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 simple moving average 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.
Use the following steps to compute the simple moving average:
Use the
ones
function to create an array of sizeN
and elements initialized to1
; then, divide the array byN
to give us the weights, as follows:N = int(sys.argv[1]) weights = np.ones(N) / N print "Weights", weights
For N = 5, this code gives us the following output:
Weights [ 0.2 0.2 0.2 0.2 0.2]
Now call the
convolve
function with the following weights:c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True) sma = np.convolve(weights...