Search code examples
kdb

Calculating the weighted moving average of 2 lists using a set window


If I have two lists:

a:1 2 3 4;
b:10 20 30 40;

I want to sum the product of the two lists within a window of 2. So the result set should be:

10 50 130 250

For example, to get the result of 130 it would be (2*20)+(3*30) = 130

sums 2 mavg '(a*b)

seems to get me part way there, but the window of 2 isn't being applied. I've tried experimenting with sum, sums, sum each, wavg, mavg, etc. and I am completely stuck. Could anyone help? Thanks!


Solution

  • Alternatively you could use the adverb each prior:

    q)+':[a*b]
    

    However this will only work with a window size of 2 and if your data contains null values this needs to be padded with 0:

    q)+':[0^a*b2]
    

    On a positive note it is faster than using msum in this situation.

    q)\ts:1000000 +':[0^a*b2]
    940 1264
    q)\ts:1000000 2 msum a*b2
    1556 1104