13

I'm writing a moving average function that uses the convolve function in numpy, which should be equivalent to a (weighted moving average). 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

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

Any ideas about this behavior?

Dr. Andrew
  • 2,532
  • 3
  • 26
  • 42

1 Answers1

20

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

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
seberg
  • 8,785
  • 2
  • 31
  • 30
  • 1
    thanks I see. And I also did not know that [::-1] will reverse an array/list. That is extremely useful information! – Dr. Andrew Oct 10 '12 at 11:59
  • 2
    As a mere comment, `np.cumsum(np.ones(numdays,dtype=float),axis=0)` is a very complex way to get `np.arange(numdays)+1.` or `np.np.arange(1., numdays+1.)`. – Ramon Crehuet Jul 21 '16 at 12:42