简体   繁体   中英

Weighted two sided moving average for time series python

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:

在此处输入图像描述

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:

在此处输入图像描述

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!

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.   ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM