General pivot function provided at http://code.kx.com/q/cookbook/pivoting-tables/ goes:
piv:{[t;k;p;v;f;g]
v:(),v;
G:group flip k!(t:.Q.v t)k;
F:group flip p!t p;
count[k]!g[k;P;C]xcols 0!key[G]!flip(C:f[v]P:flip value flip key F)!raze
{[i;j;k;x;y]
a:count[x]#x 0N;
a[y]:x y;
b:count[x]#0b;
b[y]:1b;
c:a i;
c[k]:first'[a[j]@'where'[b j]];
c}[I[;0];I J;J:where 1<>count'[I:value G]]/:\:[t v;value F]}
given that f
and g
are defined as
f:{[v;P]`$raze each string raze P[;0],'/:v,/:\:P[;1]}
g:{[k;P;c]k,(raze/)flip flip each 5 cut'10 cut raze reverse 10 cut asc c}
Now this example works (see the above link how table q
is defined):
piv[`q;`date`sym`time;`side`level;`price`size;f;g]
date sym time | Bprice0 Bsize0 Aprice0 Asize0 Bprice1 Bsize1 ..
----------------------------| -----------------------------------------------..
2009.01.05 milg 09:30:00.187| 93.56285 29 ..
2009.01.05 milg 09:30:15.798| ..
2009.01.05 milg 09:30:30.627| ..
In my case, I would like to pivot by sym
(each column different symbol) and key by date
(each row different date), values being last price
(each cell last price for a given date and symbol).
This naive call doesn't work:
piv[`q;`date;`sym;`price;f;g]
How to redefine f
and g
functions to be able to get a table of last price for each distinct date and each symbol, yielding something like this?
date | syma symb symc
-----------| ----------------------
2009.01.05 | 93.56 8.5 566.1
2009.01.06 | 93.6 8.0 564.2
2009.01.07 | 9.0
2009.01.08 | 94.05 560.3