kdb calculate percent change between rows

438 views Asked by At

i calculate percent change in 24 hour by this way that you can see below.

is there any way to get calculated percent directly from kdb by query? df should return the percent as final value.

df = q.sendSync('{[x;y]value select by x xbar DateTime.minute from trades where DateTime > .z.p-0D01, symbol=y }',30,np.string_(symbol))

start  = df.iloc[0].price
end = df.iloc[-1].price

return ((end-start)/start) * 100 ##### return -0.01152

kdb query result:

                 DateTime    side       symbol  amount     price   
0 2022-04-15 14:59:59.975  b'buy'  b'ETH-USDT'  0.0033     3035.75  
1 2022-04-15 15:29:58.889  b'buy'  b'ETH-USDT'   0.079     3035.2100
2 2022-04-15 15:32:09.050  b'buy'  b'ETH-USDT'  0.0165     3034.1599
2

There are 2 answers

1
rianoc On BEST ANSWER
first exec 100*(last[price]-price[0])%price[0] from trades where DateTime > .z.p-0D01, symbol=y
0
WSUN000 On

update PctDiff:-[price%first price;1] from trades

This query creates additional column of "percent change from start to now", and of course you need to sort the table by time first.

This query can also help if you have multiple symbols in the table and want to calculate for each sym:

update PctDiff:-[price%first price;1] by sym from trades