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 – 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 SMA 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.

Convolution is described on Wikipedia at https://en.wikipedia.org/wiki/Convolution. Khan Academy also has a tutorial on convolution at https://www.khanacademy.org/math/differential-equations/laplace-transform/convolution-integral/v/introduction-to-the-convolution.

Use the following steps to compute the SMA:

  1. Use the ones() function to create an array of size N and elements initialized to 1, and then, divide the array by N to give us the weights:

    N = 5
    weights = np.ones(N) / N
    print("Weights", weights)

    For N = 5, this gives us...