Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – smoothing with the hanning() function


We will use the hanning() function to smooth arrays of stock returns, as shown in the following steps:

  1. Call the hanning() function to compute weights for a certain length window (in this example 8) as follows:

    N = 8
    weights = np.hanning(N)
    print("Weights", weights)

    The weights are as follows:

    Weights [ 0.          0.1882551   0.61126047  0.95048443  0.95048443  0.61126047
      0.1882551   0.        ]
    
  2. Calculate the stock returns for the BHP and VALE quotes using convolve() with normalized weights:

    bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True)
    bhp_returns = np.diff(bhp) / bhp[ : -1]
    smooth_bhp = np.convolve(weights/weights.sum(), bhp_returns)[N-1:-N+1]
    
    vale = np.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True)
    vale_returns = np.diff(vale) / vale[ : -1]
    smooth_vale = np.convolve(weights/weights.sum(), vale_returns)[N-1:-N+1]
  3. Plot with matplotlib using this code:

    t = np.arange(N - 1, len(bhp_returns))
    plt.plot...