简体   繁体   English

加权移动平均线与numpy.convolve

[英]weighted moving average with numpy.convolve

I'm writing a moving average function that uses the convolve function in numpy, which should be equivalent to a ( weighted moving average ). 我正在写一个移动平均函数,它使用numpy中的convolve函数,它应该等于a( 加权移动平均值 )。 When my weights are all equal (as in a simple arithmatic average), it works fine: 当我的权重都相等时(如简单的算术平均值),它可以正常工作:

data = numpy.arange(1,11)
numdays = 5
w = [1.0/numdays]*numdays
numpy.convolve(data,w,'valid')

gives

array([ 3.,  4.,  5.,  6.,  7.,  8.])

However, when I try to use a weighted average 但是,当我尝试使用加权平均值时

w = numpy.cumsum(numpy.ones(numdays,dtype=float),axis=0); w = w/numpy.sum(w)

instead of the (for the same data) 3.667,4.667,5.667,6.667,... I expect, I get 而不是(对于相同的数据)3.667,4.667,5.667,6.667,...我希望,我得到

array([ 2.33333333,  3.33333333,  4.33333333,  5.33333333,  6.33333333,
        7.33333333])

If I remove the 'valid' flag, I don't even see the correct values. 如果我删除'valid'标志,我甚至看不到正确的值。 I would really like to use convolve for the WMA as well as MA as it makes the code cleaner (same code, different weights) and otherwise I think I'll have to loop through all the data and take slices. 我真的想使用卷积为WMA和MA,因为它使代码更清晰(相同的代码,不同的权重),否则我认为我将不得不遍历所有数据并采取切片。

Any ideas about this behavior? 关于这种行为的任何想法?

你想要的是卷积中的np.correlate第二个参数基本上被反转,所以你的预期结果将是np.convolve(data, w[::-1], 'valid')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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