Weighted Moving Average with numpy.convolve

I am writing a moving average function that uses the convolve function in numpy, which should be equivalent ( weighted moving average ). When my weights are equal (as in a simple arithmetic mean), 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 the weighted average

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

instead (for the same data) 3,667,4,667,5,667,6,667, ... I expect, I will get

 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. I would really like to use convolve for WMA, as well as MA, since it does a code cleaner (the same code, different weights), and otherwise I think that I will have to iterate over all the data and accept the fragments.

Any ideas on this behavior?

+9
python math numpy
Oct 10
source share
1 answer

What you want is convolution np.correlate , the second argument is inverted basically, so your expected result will be with np.convolve(data, w[::-1], 'valid') .

+14
Oct 10 '12 at 11:18
source share



All Articles