Time for action – smoothing stock prices with the Blackman window

Let's smooth the close prices from the small AAPL stock prices data file. Perform the following steps to do so:

  1. Load the data into a NumPy array. Call the NumPy blackman function to form a window and then use this window to smooth the price signal.
    closes=np.loadtxt('AAPL.csv', delimiter=',', usecols=(6,), converters={1:datestr2num}, unpack=True)
    N = int(sys.argv[1])
    window = np.blackman(N)
    smoothed = np.convolve(window/window.sum(),
      closes, mode='same')
  2. Plot the smoothed prices with Matplotlib. We will omit the first five and the last five data points in this example. The reason for this is that there is a strong boundary effect.
    plot(smoothed[N:-N], lw=2, label="smoothed")
    plot(closes[N:-N], label="closes")
    legend(loc='best')
    show()

    The closing prices of AAPL smoothed with the Blackman window should appear, as follows:

    Time for action – smoothing stock prices with the Blackman window

What just happened?

We plotted the closing price of AAPL from our sample data file that was smoothed using the Blackman window with the NumPy blackman function (see plot_blackman.py).

import numpy as np
from matplotlib.pyplot import plot, show, legend
from matplotlib.dates import datestr2num
import sys


closes=np.loadtxt('AAPL.csv', delimiter=',', usecols=(6,), converters={1:datestr2num}, unpack=True)
N = int(sys.argv[1])
window = np.blackman(N)
smoothed = np.convolve(window/window.sum(), closes, mode='same')
plot(smoothed[N:-N], lw=2, label="smoothed")
plot(closes[N:-N], label="closes")
legend(loc='best')
show()
..................Content has been hidden....................

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