Time for action – computing the Simple Moving Average
The moving average is easy enough to compute with a few loops and the mean()
function, but NumPy has a better alternative—the convolve()
function. The SMA is, after all, nothing more than a convolution with equal weights or, if you like, unweighted.
Note
Convolution is a mathematical operation on two functions defined as the integral of the product of the two functions after one of the functions is reversed and shifted.
Convolution is described on Wikipedia at https://en.wikipedia.org/wiki/Convolution. Khan Academy also has a tutorial on convolution at https://www.khanacademy.org/math/differential-equations/laplace-transform/convolution-integral/v/introduction-to-the-convolution.
Use the following steps to compute the SMA:
Use the
ones()
function to create an array of sizeN
and elements initialized to1
, and then, divide the array byN
to give us the weights:N = 5 weights = np.ones(N) / N print("Weights", weights)
For
N = 5
, this gives us...