Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between rows in KDB/Q

Tags:

kdb+

I'm new to KDB/Q and have a question around getting the difference between two (not necessarily adjacent) rows.

I have only one table, which looks like the below:

q)tickers:`ibm`bac`dis`gs`ibm`gs`dis`bac
q)pxs:100 50 30 250 110 240 45 48
q)dates:2013.05.01 2013.01.05 2013.02.03 2013.02.11 2013.06.17 2013.06.21 2013.04.24 2013.01.06

q)trades:([tickers;dates];pxs)
q)trades
tickers dates     | pxs
------------------| ---
ibm     2013.05.01| 100
bac     2013.01.05| 50
dis     2013.02.03| 30
gs      2013.02.11| 250
ibm     2013.06.17| 110
gs      2013.06.21| 240
dis     2013.04.24| 45
bac     2013.01.06| 48

I would like to be able to have a either another column in the table that stores the difference between the current and the previous price, or another structure similar in structure. The key question that the resulting needs to answer is "by how much did the stock change compared to the previous time a price was recorded?"

So far I've tried something along the lines of:

select tickers, dates, pxs - pxs(dates bin (exec dates from trades where tickers = trades.tickers)) from trades

which doesn't really work (at all). Definitely due to trying to do SQL-like queries and having a row-oriented mindset.

Please find below an exemple of the sought after answer:

q)trades: do magic with trades
q)trades
tickers dates     | pxs | delta
------------------| --- | -----
ibm     2013.05.01| 100 | 0
bac     2013.01.05| 50  | 0
dis     2013.02.03| 30  | 0
gs      2013.02.11| 250 | 0
ibm     2013.06.17| 110 | 10
gs      2013.06.21| 240 | -10
dis     2013.04.24| 45  | 15
bac     2013.01.06| 48  | -2

Thanks for your help, Dan

like image 251
user1158959 Avatar asked Jul 30 '26 11:07

user1158959


1 Answers

q)update delta:{0,1_deltas x}pxs by tickers from trades
   tickers dates     | pxs delta
   ------------------| ---------
   ibm     2013.05.01| 100 0
   bac     2013.01.05| 50  0
   dis     2013.02.03| 30  0
   gs      2013.02.11| 250 0
   ibm     2013.06.17| 110 10
   gs      2013.06.21| 240 -10
   dis     2013.04.24| 45  15
   bac     2013.01.06| 48  -2
like image 188
MdSalih Avatar answered Aug 04 '26 16:08

MdSalih



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!