-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

NumPy Beginner's Guide
By :

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.
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 size N
and elements initialized to 1
; then, divide the array by N
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...
Change the font size
Change margin width
Change background colour