How To Calculate Moving Averages (MA) Using C++?

15 minutes read

Moving Averages (MA) are commonly used in statistical analysis to smooth out fluctuations in data and identify trends over time. In C++, calculating moving averages involves taking the average of a specified number of data points in a series and updating the average as new data points are added.


To calculate a simple moving average, you would create an array or vector to store the data points and a variable to store the moving average. Then, you would iterate through the data points, summing up the values for the specified number of points and dividing by that number to calculate the average. As new data points are added, you would update the moving average by removing the oldest data point from the sum and adding the new data point.


There are different types of moving averages, including simple moving averages, weighted moving averages, and exponential moving averages, each with different formulas for calculating the average. Depending on the type of moving average you want to calculate, you would use the appropriate formula in your C++ program.


Overall, calculating moving averages in C++ involves keeping track of a specified number of data points, updating the average as new data points are added, and choosing the type of moving average that best fits your data analysis needs.

Best Software Development Books of 2024

1
Clean Code: A Handbook of Agile Software Craftsmanship

Rating is 5 out of 5

Clean Code: A Handbook of Agile Software Craftsmanship

2
Mastering API Architecture: Design, Operate, and Evolve API-Based Systems

Rating is 4.9 out of 5

Mastering API Architecture: Design, Operate, and Evolve API-Based Systems

3
Developing Apps With GPT-4 and ChatGPT: Build Intelligent Chatbots, Content Generators, and More

Rating is 4.8 out of 5

Developing Apps With GPT-4 and ChatGPT: Build Intelligent Chatbots, Content Generators, and More

4
The Software Engineer's Guidebook: Navigating senior, tech lead, and staff engineer positions at tech companies and startups

Rating is 4.7 out of 5

The Software Engineer's Guidebook: Navigating senior, tech lead, and staff engineer positions at tech companies and startups

5
Software Engineering for Absolute Beginners: Your Guide to Creating Software Products

Rating is 4.6 out of 5

Software Engineering for Absolute Beginners: Your Guide to Creating Software Products

6
A Down-To-Earth Guide To SDLC Project Management: Getting your system / software development life cycle project successfully across the line using PMBOK adaptively.

Rating is 4.5 out of 5

A Down-To-Earth Guide To SDLC Project Management: Getting your system / software development life cycle project successfully across the line using PMBOK adaptively.

7
Code: The Hidden Language of Computer Hardware and Software

Rating is 4.4 out of 5

Code: The Hidden Language of Computer Hardware and Software

8
Fundamentals of Software Architecture: An Engineering Approach

Rating is 4.3 out of 5

Fundamentals of Software Architecture: An Engineering Approach

9
C# & C++: 5 Books in 1 - The #1 Coding Course from Beginner to Advanced (2023) (Computer Programming)

Rating is 4.2 out of 5

C# & C++: 5 Books in 1 - The #1 Coding Course from Beginner to Advanced (2023) (Computer Programming)


What is a moving average convergence divergence (MACD) and how to calculate it using C++?

The Moving Average Convergence Divergence (MACD) is a popular technical indicator that is used to identify trends in the price movements of an asset. It is calculated by subtracting the 26-period exponential moving average (EMA) from the 12-period EMA.


Here is an example C++ code to calculate the MACD for a given set of price data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
#include <cmath>

double calculateEMA(const std::vector<double>& data, int period) {
    double sum = 0;
    for (int i = 0; i < period; i++) {
        sum += data[i];
    }
    double ema = sum / period;

    for (int i = period; i < data.size(); i++) {
        ema = ((data[i] - ema) * 2 / (period + 1)) + ema;
    }

    return ema;
}

int main() {
    std::vector<double> prices = {100.0, 105.0, 110.0, 115.0, 120.0, 125.0, 130.0, 135.0, 140.0, 145.0, 150.0, 155.0};

    int shortPeriod = 12;
    int longPeriod = 26;

    double shortEMA = calculateEMA(prices, shortPeriod);
    double longEMA = calculateEMA(prices, longPeriod);

    double macd = shortEMA - longEMA;

    std::cout << "MACD: " << macd << std::endl;

    return 0;
}


In this code, we first define a function calculateEMA to calculate the exponential moving average for a given period. We then calculate the short and long EMAs using the 12-period and 26-period data respectively. Finally, we subtract the long EMA from the short EMA to get the MACD value.


You can adjust the input price data and periods as needed to calculate the MACD for your specific requirements.


What is a volume-adjusted moving average (VAMA) and how to calculate it using C++?

A volume-adjusted moving average (VAMA) is a type of moving average that takes into account the volume of trades along with the price data. It aims to give more weight to periods with higher trading volume, as it is believed that high volume periods are more significant in terms of price movement.


To calculate VAMA using C++, you can follow these steps:

  1. Define the period length for the moving average (e.g., 20 periods).
  2. Define two arrays to store the price and volume data.
  3. Calculate the sum of price*volume for each period.
  4. Calculate the sum of volume for each period.
  5. Divide the sum of price*volume by the sum of volume to get the VAMA value for each period.


Here is a sample code snippet in C++ that demonstrates how to calculate VAMA:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <vector>

// Function to calculate VAMA
void calculateVAMA(std::vector<double>& prices, std::vector<int>& volumes, int period) {
    if (prices.size() != volumes.size()) {
        std::cout << "Error: Price and volume data should have the same size" << std::endl;
        return;
    }

    std::vector<double> vama;

    for (int i = period - 1; i < prices.size(); i++) {
        double sumPriceVolume = 0;
        double sumVolume = 0;

        for (int j = i - period + 1; j <= i; j++) {
            sumPriceVolume += prices[j] * volumes[j];
            sumVolume += volumes[j];
        }

        double vamaValue = sumPriceVolume / sumVolume;
        vama.push_back(vamaValue);
    }

    // Print VAMA values
    for (int i = 0; i < vama.size(); i++) {
        std::cout << "VAMA[" << i << "]: " << vama[i] << std::endl;
    }
}

int main() {
    std::vector<double> prices = {100, 105, 110, 115, 120};
    std::vector<int> volumes = {1000, 1500, 2000, 2500, 3000};
    int period = 3;

    calculateVAMA(prices, volumes, period);

    return 0;
}


In this code snippet, we first define sample price and volume data and a period length for the moving average. We then call the calculateVAMA function, which calculates the VAMA values for each period and prints them out. You can modify the input data and period length as needed for your specific use case.


What is a triangular moving average (TMA) and how to calculate it using C++?

A triangular moving average (TMA) is a type of moving average that gives equal weight to all data points within a specified time period. It is calculated by taking the average of the values within a triangular window centered around the current data point.


To calculate a TMA using C++, you can follow these steps:

  1. Define an array to store the data points.
  2. Define the length of the triangular window (e.g. 5 data points on either side of the current data point).
  3. Iterate over the data points and calculate the TMA for each point by finding the sum of the values within the triangular window and dividing by the number of data points.
  4. Store the TMA values in a new array or print them out directly.


Here is a sample code snippet to calculate the TMA using C++:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>

std::vector<float> calculateTMA(const std::vector<float>& data, int windowSize) {
    std::vector<float> tmaValues;

    for (int i = 0; i < data.size(); i++) {
        float sum = 0;
        int count = 0;

        for (int j = i - windowSize; j <= i + windowSize; j++) {
            if (j >= 0 && j < data.size()) {
                sum += data[j];
                count++;
            }
        }

        float tma = sum / count;
        tmaValues.push_back(tma);
    }

    return tmaValues;
}

int main() {
    std::vector<float> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int windowSize = 2;

    std::vector<float> tmaValues = calculateTMA(data, windowSize);

    for (float val : tmaValues) {
        std::cout << val << " ";
    }

    return 0;
}


In this code, the calculateTMA function takes the input data array and the window size as parameters, and it returns a vector containing the calculated TMA values. The main function then calls this function with sample data and window size, and prints out the resulting TMA values.


What is an exponential moving average (EMA) and how to calculate it using C++?

An exponential moving average (EMA) is a type of moving average that is similar to a simple moving average, but gives more weight to the most recent data points. This makes EMAs more responsive to recent price changes compared to simple moving averages.


To calculate an EMA using C++, you can use the following formula:


EMA(t) = (Price(t) * k) + (EMA(t-1) * (1 - k))


where:

  • EMA(t) is the EMA value at period t
  • Price(t) is the price at period t
  • k is the smoothing factor, which can be calculated as 2 / (N + 1), where N is the number of periods
  • EMA(t-1) is the EMA value at the previous period


Here's a simple C++ code snippet to calculate an EMA:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>

double calculateEMA(const std::vector<double>& prices, int periods) {
    double k = 2.0 / (periods + 1);
    double ema = prices[0];

    for (int i = 1; i < prices.size(); i++) {
        ema = (prices[i] * k) + (ema * (1 - k));
    }

    return ema;
}

int main() {
    std::vector<double> prices = {100, 105, 110, 115, 120};
    int periods = 5;

    double ema = calculateEMA(prices, periods);

    std::cout << "EMA: " << ema << std::endl;

    return 0;
}


In this code, we define a function calculateEMA that takes a vector of prices and the number of periods as input, and calculates the EMA using the formula mentioned above. We then calculate the EMA for a sample set of prices and print the result.


How to calculate a Winton composite moving average (WCMA) using C++?

To calculate a Winton composite moving average (WCMA) using C++, you can follow these steps:

  1. Define the period length for the WCMA (e.g. 10 days).
  2. Create an array to store the data points for the time series.
  3. Calculate the exponential moving average (EMA) for each data point using the formula:
1
EMA = (Close - EMA_previous) * (2 / (period + 1)) + EMA_previous;


  1. Calculate the WCMA by averaging the EMAs for each data point in the period:
1
WCMA = sum(EMA) / period;


Here is a sample C++ code snippet for calculating WCMA for a given time series:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>

double calculateWCMA(std::vector<double> data, int period) {
    double sumEMA = 0.0;
    double WCMA;

    // Calculate EMA for each data point
    for (int i = 0; i < data.size(); i++) {
        double EMA = data[i];
        sumEMA += EMA;
    }

    // Calculate WCMA
    WCMA = sumEMA / period;

    return WCMA;
}

int main() {
    std::vector<double> data = {50.0, 55.0, 60.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0};
    int period = 10;

    double WCMA = calculateWCMA(data, period);
    std::cout << "WCMA: " << WCMA << std::endl;

    return 0;
}


You can input your own data points and period length to calculate the WCMA for your specific time series.


How to calculate a Hull moving average (HMA) using C++?

To calculate a Hull moving average (HMA) using C++, you can follow these steps:

  1. First, you need to define the period for the HMA. The period is usually determined based on the time frame of the prices you are analyzing.
  2. Next, you need to initialize three different weighted moving averages (WMAs) based on the period - short term, medium term, and long term.
  3. Calculate the half-length of the period by taking the square root of the period and rounding it to the nearest whole number.
  4. Calculate the WMA for the short term, medium term, and long term using the formulas:
  • Short term WMA: WMA = (WMA[(period/2)] * (period/2)) + WMA[price] - WMA[(period)]
  • Medium term WMA: WMA = (WMA[period] * period) - (WMA[period/2] * (period/2)) + WMA[price] - WMA[period]
  • Long term WMA: WMA = (WMA[sqrt(period)] * sqrt(period)) - (WMA[period] * period) + WMA[price] - WMA[sqrt(period)]
  1. Finally, calculate the Hull moving average using the formula:


HMA = 2 * WMA[short term] - WMA[medium term]


Here is an example C++ code snippet to calculate the Hull moving average (HMA) for a given set of prices:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>

double calculateWMA(const std::vector<double>& prices, int period) {
    double sum = 0;
    for (int i = 0; i < period; i++) {
        sum += prices[i];
    }
    return sum / period;
}

double calculateHMA(const std::vector<double>& prices, int period) {
    int halfLength = std::round(std::sqrt(period));
    double shortTermWMA = calculateWMA(prices, period/2);
    double mediumTermWMA = calculateWMA(prices, period);
    double longTermWMA = calculateWMA(prices, halfLength);

    return 2 * shortTermWMA - mediumTermWMA;
}

int main() {
    std::vector<double> prices = {100, 105, 110, 115, 120, 125, 130, 135, 140, 145};
    int period = 5;

    double hma = calculateHMA(prices, period);

    std::cout << "Hull Moving Average: " << hma << std::endl;

    return 0;
}


This code calculates the Hull moving average for a set of price data using a period of 5. You can modify the prices vector and period variable to match your specific data and period requirements.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

Trading with Moving AveragesMoving averages are popular indicators used in technical analysis to identify trends and potential trading opportunities. The moving average line smooths out price fluctuations and helps traders to focus on the overall trend.When tr...
A Triangular Moving Average (TMA) is a type of moving average commonly used in technical analysis to smooth out price data over a specified period. It is similar to other moving averages such as the Simple Moving Average (SMA) or the Exponential Moving Average...
The Percentage Price Oscillator (PPO) is a technical indicator used in technical analysis to measure and visualize the percentage difference between two moving averages. It helps traders and investors identify potential buying and selling opportunities by anal...