Time for action – calculating the exponential moving average

Given an array, the exp function calculates the exponential of each array element. For example, look at the following code:

x = np.arange(5)
print "Exp", np.exp(x)

It gives the following output:

Exp [  1.           2.71828183   7.3890561   20.08553692  54.59815003]

The linspace function takes, as parameters, a start and a stop and optionally an array size. It returns an array of evenly spaced numbers. The following is an example:

print "Linspace", np.linspace(-1, 0, 5)

This will give us the following output:

Linspace [-1.   -0.75 -0.5  -0.25  0.  ]

Let's calculate the exponential moving average for our data:

  1. Now, back to the weights—calculate them with exp and linspace.
    N = int(sys.argv[1])
    weights = np.exp(np.linspace(-1., 0., N))
  2. Normalize the weights. The ndarray object has a sum method that we will use.
    weights /= weights.sum()
    print "Weights", weights

    For N = 5, we get the following weights:

    Weights [ 0.11405072  0.14644403  0.18803785  0.24144538  0.31002201]
  3. After that, it's easy going—we just use the convolve function that we learned about in the simple moving average tutorial. We will also plot the results.
    c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
    ema = 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, ema, lw=2.0)
    show()

    That gives this nice chart where, again, the close price is the thin jagged line and the exponential moving average is the smooth thick line:

    Time for action – calculating the exponential moving average

What just happened?

We calculated the exponential moving average of the close price. First, we computed exponentially decreasing weights with the exp and linspace functions. linspace gave us an array with evenly spaced elements, and then, we calculated the exponential for these numbers. We called the ndarray sum method in order to normalize the weights. After that, we applied the convolve trick that we learned in the simple moving average tutorial (see ema.py).

import numpy as np
import sys
from matplotlib.pyplot import plot
from matplotlib.pyplot import show

x = np.arange(5)
print "Exp", np.exp(x)
print "Linspace", np.linspace(-1, 0, 5)

N = int(sys.argv[1])


weights = np.exp(np.linspace(-1., 0., N))
weights /= weights.sum()
print "Weights", weights

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)
ema = 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, ema, 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
18.225.11.98