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: