Time for action – smoothing stock prices with the Blackman window

Let's smooth the close prices from the small AAPL stock prices data file:

  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 = 5
    window = np.blackman(N)
    smoothed = np.convolve(window/window.sum(),
      closes, mode='same')
  2. Plot the smoothed prices with matplotlib. In this example, we will omit the first five data points and the last five data points. The reason for this is that there is a strong boundary effect:
    plt.plot(smoothed[N:-N], lw=2, label="smoothed") plt.plot(closes[N:-N], label="closes") plt.legend(loc='best') ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.