kdb+

row-wise ema of several columns


In kdb+ let's say I have a table t such that

show t:([] rnk1: 1 2; rnk2: 3 4);
rnk1 rnk2
---------
1    3   
2    4 

I can calculate the row-wise average avg of the two columns as:

show update r:avg[(rnk1;rnk2)] from t;
show ![t;();0b;(enlist`r)!enlist (avg;(enlist;`rnk1;`rnk2))]; / alternative functional form
rnk1 rnk2 r
-----------
1    3    2
2    4    3

However, I can't seem to able to compute the row-wise exponential moving average ema using a similar approach

alpha:0.5;
show update r:ema[alpha;(rnk1;rnk2)] from t;
show ![t;();0b;(enlist`r)!enlist (ema;`alpha;(enlist;`rnk1;`rnk2))

'rank

which errors out. How do i find the row-wise ema above?


Solution

  • You need to flip the rnk columns in order to align them row-wise and call each ':

    q)ema[0.5;1 3]
    1 2f
    q)ema[0.5;2 4]
    2 3f
    q)update r:ema'[0.5;flip(rnk1;rnk2)]from t
    rnk1 rnk2 r
    -------------
    1    3    1 2
    2    4    2 3
    q)![t;();0b;enlist[`r]!enlist(ema';0.5;(flip;(enlist;`rnk1;`rnk2)))]
    rnk1 rnk2 r
    -------------
    1    3    1 2
    2    4    2 3