Moving Average
Moving Average
A Finite Impulse Response Filter, or Moving Average is an example of a low-pass filter typically used in signal
processing. In its most basic form it’s simply used to smooth data. Its true purpose is to smooth out short-term
fluctuations and highlight longer-term trends or cycles. When used without any specific connection to time, a
moving average filters out the higher frequency components.
float sample;
sample = 0.0;
sample += data[i];
return (sample/period);
The period selected depends on the type of movement of interest, such as short, intermediate, or long term. If
the data is not centered around the mean, a simple moving average lags behind the latest datum point by half
the sample width. An SMA can also be disproportionately influenced by old datum points dropping out or new
data coming in.
An exponential moving average, or exponentially weighted moving average, is a type of impulse response filter
that applies weighting factors which decrease exponentially.
float accumulator;
return(accumulator);
}
In this example, we use an “accumulator” variable, which, as each sample is evaluated is updated with the new
value. The function requires a constant “alpha” that is between 0 and 1, where the effect of a given sample only
lasts for the requisite period.
Finally, you can approximate a rolling average by applying a weighted average on your input stream. This way,
you don’t need to maintain a large array of values. However, since it’s an approximation, it’s value will not
exactly match a true rolling average.
float sma;
int period;
sma += vew_value;
sma /= period;
return sma;
The following chart demonstrates the 3 types of moving averages on a sample data set. The SMA has a period
of 7, the exponential average uses an alpha of 0.4, and the approximate-rolling average uses a period of 5.