Search code examples
kdb

How do I apply function to all columns in KDB?


I've got a table of minute return data.

To squash it to daily data, I'm currently doing:

select sum XLK, sum XLE, sum XLY, sum BTAL, sum BND, sum GLD, sum UVXY, sum SPY by t.date from r

Is there a way I can not repeat the sum?


Solution

  • You can avoid repeating sum by using functional form. First step is to parse the statement to create a parse tree, which gives the form your expression needs to take.

    q)parse"select sum XLK, sum XLE, sum XLY, sum BTAL, sum BND, sum GLD, sum UVXY, sum SPY by t.date from r"
    ?
    `r
    ()
    (,`date)!,`t.date
    `XLK`XLE`XLY`BTAL`BND`GLD`UVXY`SPY!((sum;`XLK);(sum;`XLE);(sum;`XLY);(sum;`BTAL);(sum;`BND);(sum;`GLD);(sum;`UVXY);(sum;`SPY))
    

    That information can then be used to create the equivalent functional form.

    ?[r;();enlist[`date]!enlist`t.date;{x!sum,/:x}`XLK`XLE`XLY`BTAL`BND`GLD`UVXY`SPY]