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.
Use the following steps to compute the simple moving average:
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]
convolve
function with the following weights:c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True) sma = np.convolve(weights, c)[N-1:-N+1]]
convolve
, we extracted the data in the center of size N
. The following code makes an array of time values and plots with Matplotlib
that we will be covering in a later chapter.c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True) sma = np.convolve(weights, c)[N-1:-N+1] t = np.arange(N - 1, len(c)) plot(t, c[N-1:], lw=1.0) plot(t, sma, lw=2.0) show()
In the following chart, the smooth thick line is the 5-day simple moving average and the jagged thin line is the close price:
We computed the simple moving average for the close stock price. Truly, great riches are within your reach. It turns out that the simple moving average is just a signal processing technique—a convolution with weights 1 / N, where N is the size of the moving average window. We learned that the ones
function can create an array with ones and the convolve
function calculates the convolution of a data set with specified weights (see sma.py
).
import numpy as np import sys from matplotlib.pyplot import plot from matplotlib.pyplot import show N = int(sys.argv[1]) weights = np.ones(N) / N print "Weights", weights c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True) sma = np.convolve(weights, c)[N-1:-N+1] t = np.arange(N - 1, len(c)) plot(t, c[N-1:], lw=1.0) plot(t, sma, lw=2.0) show()