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:

  1. 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]
  2. Now call the 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]]
  3. From the array returned by 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:

    Time for action – computing the simple moving average

What just happened?

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()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset