Home > database >  Weighted two sided moving average for time series python
Weighted two sided moving average for time series python

Time:08-28

I have a time series and I want to get from it a weighted two sided moving average. That is, I want to create a function that takes one observation of the original time series, considers n numbers both at the left and at the right of that center value (that's why is two sided) and calculates the weighted average of that.

By weighted I mean that each value both at the left and right will be multiplied by a weight that gets smaller the further from the center observation that value is.

Once this is done for the first value I choose to have as my center, the function moves to the next one to the right and does the same, and so on.

The equation of the filter I'm trying to apply is:

enter image description here

As an example please consider the following time series:

X = [0, 0, 0, 3, 4, 5, 6, 7, 0, 0, 0]

For β = 0.5 and starting to apply the filter in the third observation, I would have:

enter image description here

But the function should be applied in an for loop that iterates over each value of X starting and finishing in the position that I want.

Thanks!

CodePudding user response:

What you're doing is called a "convolution". numpy can do this:

import numpy as np
X = np.array([0, 0, 0, 3, 4, 5, 6, 7, 0, 0, 0])
wts = np.array([.125, .25, .5, 1, .5, .25, .125])
print(np.convolve(X,wts))

Output:

[ 0.     0.     0.     0.375  1.25   3.125  7.    10.375 12.5   13.375
 11.75   5.625  2.5    0.875  0.     0.     0.   ]
  • Related