Skip to content

Instantly share code, notes, and snippets.

@rianoc
Created December 7, 2021 10:07
Show Gist options
  • Save rianoc/1d72168e512e43f35633a96714327d26 to your computer and use it in GitHub Desktop.
Save rianoc/1d72168e512e43f35633a96714327d26 to your computer and use it in GitHub Desktop.
Kdb+ window join with rename for multiple aggregations

https://code.kx.com/q/ref/wj/

When permforming wj out of box multiple aggregations requires the user to perform positional renaming to tidy up the result.

Instead a helper can be created:

wjr:{[f;w;c;t;q]
 if[not 99h~type q[1];
    :f[w;c;t;q]];
 r:f[w;c;t;q[0],value q[1]];
 (cols[t],key q[1]) xcol r
 };

//Operate the same as standard wj/wj1 if last param structure match expected as per https://code.kx.com/q/ref/wj/
//Standard: wj[w; c; t; (q; (f0;c0); (f1;c1))]
//New feature: wj[w; c; t; (q;`n0`n1!((f0;c0);(f1;c1)))]
//Passing dictionary the keys will be used to name returned data columns
wjRename:wjr[wj]
wj1Rename:wjr[wj1]

Data for example:

trade: flip `sym`time`price!(`JPM`JPM`JPM;09:30:01 09:30:04 09:30:08;120 123 121)
quote: flip `sym`time`ask`bid!(`JPM`JPM`JPM`JPM`JPM`JPM`JPM`JPM`JPM`JPM;`s#09:30:00 09:30:01 09:30:01 09:30:03 09:30:05 09:30:05 09:30:06 09:30:06 09:30:06 09:30:07;96 100 99 99 100 108 95 103 108 95;99 92 109 102 99 100 104 96 97 94)

Example in use:

wjRename[trade[`time]-/:5 0;`sym`time;trade;(quote;`avg_ask`avg_bid`max_ask`max_bid!((avg;`ask);(avg;`bid);(max;`ask);(max;`bid)))]

Output:

sym time     price avg_ask  avg_bid  max_ask max_bid
----------------------------------------------------
JPM 09:30:01 120   98.33333 100      100     109    
JPM 09:30:04 123   98.5     100.5    100     109    
JPM 09:30:08 121   101.1429 98.85714 108     104   
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment