Skip to content

Programming idioms

Q expressions that solve some common programming problems.

How do I extract regular time series from observed quotes?

Generate sample quotes with the kx.datagen.capmkts module, and keep the quotes for three symbols:

q)([getInMemoryTables]): use `kx.datagen.capmkts
q)(trade; quote): 2#getInMemoryTables[]
q)quote: update `time$time from select time,sym,bid,ask from quote where sym in `AAPL`GOOG`IBM
q)quote
time         sym  bid    ask
-------------------------------
09:30:00.000 GOOG 245.49 245.71
09:30:02.421 IBM  285.96 286.05
09:30:05.451 IBM  285.96 286.05
09:30:05.822 IBM  285.96 286.05
09:30:07.729 IBM  285.86 286.05
09:30:09.991 GOOG 245.56 245.62
...

To extract the last observation of each one-second period:

q)`second xasc select last bid,last last ask by sym, time.second from select from quote
sym  second  | bid    ask
-------------| -------------
GOOG 09:30:00| 245.49 245.71
IBM  09:30:02| 285.96 286.05
IBM  09:30:05| 285.96 286.05
IBM  09:30:07| 285.86 286.05
GOOG 09:30:09| 245.56 245.62
IBM  09:30:10| 285.65 285.84
GOOG 09:30:11| 245.5  245.56
IBM  09:30:13| 285.68 285.87
..

However, this solution skips periods with no observations. In the table generated for this page, GOOG has no observations at 09:30:01 to 09:30:08, or at 09:30:10.

A better solution is to use aj, which fills each second with the latest earlier observation:

q)res: aj[`sym`time;([]sym:`AAPL`IBM`GOOG) cross ([]time:09:30:00+til `int$(16:00:00 - 09:30:00)); update `second$time from quote]
q)select from res where sym=`GOOG, time within 09:30:09 09:30:12
sym  time     bid    ask
---------------------------
GOOG 09:30:09 245.56 245.62
GOOG 09:30:10 245.56 245.62
GOOG 09:30:11 245.5  245.56
GOOG 09:30:12 245.5  245.56

How do I calculate vwap series?

Use xbar and wavg:

q)aapl: select from trade where sym=`AAPL,size>0
q)select vwap:size wavg price by 5 xbar time.minute from aapl
minute| vwap
------| --------
09:30 | 256.1467
09:40 | 258.16
09:45 | 258.4638
10:05 | 260.3
10:35 | 263.02
10:45 | 263.21
10:55 | 263.9
11:00 | 264.89
..

Q for Mortals §9.13.4 Meaty Queries

How do I extract regular-size vwap series?

A quick solution is to use xbar with the running sum of size to average over each period:

q)t:select time,price,size from trade where sym=`AAPL
q)select time:last time ,vwap: size wavg price by g:500 xbar sums size from t
g    | time                 vwap
-----| -----------------------------
0    | 0D10:39:42.923444577 258.28
500  | 0D11:33:21.418210502 264.9105
1000 | 0D12:24:58.838196835 269.1622
1500 | 0D13:52:18.062257875 273.9903
2000 | 0D15:33:16.008235746 278.8997
2500 | 0D15:59:36.297840840 284.5561

However, this solution only approximates regular trade series. The last trade of each period can overflow the requested size (500 in the examples), and the overflowing amount isn't used in the following period. This query shows the problem:

q)update total:sum each size from select time:last time,vwap: size wavg price,size by g:500 xbar sums size from t
g    | time                 vwap     size                                total
-----| -----------------------------------------------------------------------
0    | 0D10:39:42.923444577 258.28   44 90 37 55 84 90 46 52             498
500  | 0D11:33:21.418210502 264.9105 95 83 75 12 13 13 15 72 96 14       488
1000 | 0D12:24:58.838196835 269.1622 23 36 73 72 32 24 95 36 70 10 22    493
1500 | 0D13:52:18.062257875 273.9903 68 82 44 20 62 55 13 64 27 50       485
2000 | 0D15:33:16.008235746 278.8997 50 29 19 91 34 10 57 38 29 68 26 29 480
2500 | 0D15:59:36.297840840 284.5561 65 11 68 97 49 54                   344

A more precise but more elaborate solution splits the edge trades into two parts, so that each bar sums to the requested size:

rvwap : { [t;size_par]
 // add the bucket and the total size
 t:update bar:size_par xbar tot from update tot:sums size from t;
 // get the indices where the bar changes
 ind:where differ t`bar;
 // re-index t, and sort (duplicate the rows where the bucket changes)
 t:t asc (til count t),ind;
 // shift all the indices due to the table now being larger
 ind:ind+til count ind;
 // update the size in the first trade of the new window and modify the bar
 t:update size:size-tot-bar,bar:size_par xbar tot-size from t where i in ind;
 // update the size in the second trade of the new window
 t:update size:tot-bar from t where i in 1+ind;
 // calculate stats
 select last time,price:size wavg price,sum size by bar from t
 }

q)rvwap[t;500]
bar  | time                 price    size
-----| ----------------------------------
0    | 0D10:45:00.803669914 258.2997 500
500  | 0D11:34:02.010266565 264.9878 500
1000 | 0D12:35:23.895050075 269.3442 500
1500 | 0D14:02:59.459125175 274.2482 500
2000 | 0D15:49:31.801973985 279.6089 500
2500 | 0D15:59:36.297840840 284.7109 288

How do I apply a function to a sequence sliding window?

Use the Scan iterator to build a moving list that adds one item at a time from the original table, and the _ Drop operator to discard older values.

This example calculates the moving average for a sliding window of 3 items. The second parameter sets the window size.

q)swin:{[f;w;s] f each { 1_x,y }\[w#0;s]}
q)swin[avg; 3; til 10]
0 0.33333333 1 2 3 4 5 6 7 8
q)// trace the sliding window
q)swin[0N!; 3; til 10]
0 0 0
0 0 1
0 1 2
1 2 3
2 3 4
3 4 5
..

A different approach uses prev and inserts 0N at the beginning of the window instead of 0:

q)swin2:fwv:{x/'[flip reverse prev\[y-1;z]]}
q)swin2[avg;3;til 10]
0 0.5 1 2 3 4 5 6 7 8
q)swin2[::;3;til 10]
    0
  0 1
0 1 2
1 2 3
2 3 4
3 4 5
..

swin2:fwv finds all the windows using prev and Converge. To find windows of size 3:

q)prev\[2;x:3 5 7 2 4 3 7]
3 5 7 2 4 3 7
  3 5 7 2 4 3
    3 5 7 2 4
q)flip reverse prev\[2;x]
    3 
  3 5
3 5 7
5 7 2
7 2 4
2 4 3
4 3 7
q)max each flip prev\[2;x]
3 5 7 7 7 4 7
q)(3 mmax x)~max each flip prev\[2;x]
1b

A third function, m, is more memory efficient:

q)m:{last{(a;x 1;x[2],z y x[1]+a:1+x 0)}[;z;x]/[n:count z;(0-y;til y;())]}

For larger windows, time and space may matter:

q)\ts swin[max;1000;10000?10]
71 82473552
q)\ts 1000 mmax 10000?10
76 524592
q)\ts m[max;1000;10000?10]
205 401984
q)\ts fwv[max;1000;10000?10]
491 213061888

Compare a smaller window:

q)\ts w mmax v
1 393440
q)\ts fwv[f:max;w:10;v:10000?10]
6 2656576
q)\ts swin[f;w;v]
12 1702416
q)\ts m[f;w;v]
50 262784

To get the index of the maximum in each window:

q)w:{(til[count z]-m)+x each flip reverse prev\[m:y-1;z]}
q)x w[{x?max x};3;x]
3 5 7 7 7 4 7

This is useful for addressing other lists:

q)update top:date w[{x?max x};3;volume] from ([]date:2000.01.01+til 7;volume:x)
date       volume top
----------------------------
2000.01.01 3      2000.01.01
2000.01.02 5      2000.01.02
2000.01.03 7      2000.01.03
2000.01.04 2      2000.01.03
2000.01.05 4      2000.01.03
2000.01.06 3      2000.01.05
2000.01.07 7      2000.01.07