So this recipe is a short example on how to compute moving averages using a sliding window over an array. Let's get started.
import numpy as np
Let's pause and look at these imports. Numpy is generally helpful in data manipulation while working with arrays. It also helps in performing mathematical operation.
def moving_average(a, n) : test = np.cumsum(a, dtype=float) test[n:] = test[n:] - test[:-n] return test[n - 1:] / n
We have a defined a function that helps in returning moving average. It uses cumulative sum for calculation of the same.
We have send a array of size 20 and then calling the moving_average function, defined earlier, simply printing away the output.
Once we run the above code snippet, we will see:
array([ 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17.])