Book Image

Learning NumPy Array

By : Ivan Idris
Book Image

Learning NumPy Array

By: Ivan Idris

Overview of this book

Table of Contents (14 chapters)
Learning NumPy Array
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Moving averages


Moving averages are tools commonly used to analyze time-series data. A moving average defines a window of previously seen data that is averaged each time the window slides forward one period. The different types of moving average differ essentially in the weights used for averaging. The exponential moving average, for instance, has exponentially decreasing weights with time. This means that older values have less influence than newer values, which is sometimes desirable.

We can express an equal-weight strategy for the simple moving average as follows in the NumPy code:

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

A simple moving average uses equal weights which, in code, looks as follows:

def sma(arr, n):
   weights = np.ones(n) / n

   return np.convolve(weights, arr)[n-1:-n+1]

The following code plots the simple moving average for the 11- and 22-year sunspot cycle:

import numpy as np
import sys
import matplotlib.pyplot as plt

data = np.loadtxt(sys.argv...