Search code examples
kdbq-lang

How to generate datatable by iterating through multiple lists? (KDB)


I have a function quotes[ticker;startDate;endDate], and a function indexConstituents[index;startDate;endDate] that yield the below:

daterange: 2017.12.05,2017.12.06;

quotes'[AAPL;daterange]

date        time    sym    price
2017.12.05  09:45   AAPL   101.20
2017.12.06  09:45   AAPL   102.30

quotes'[GOOG;daterange]

date        time    sym    price
2017.12.05  10:00   GOOG   800.50

quotes'[BBRY;daterange]

date        time    sym    price
2017.12.06  11:15   BBRY   02.10

and

indexConstituents'[DJIA;daterange]

date        sym    shares   divisor
2017.12.05  AAPL   20       2
2017.12.05  GOOG   5        1
2017.12.06  AAPL   10       1.5
2017.12.06  BBRY   100      1

I need a way to run the indexConstituents function as normal to yield a list of constituents over a set of days (as in the second table above), then fetch the data from table 1 for each constituent. Finally, I need to join the data from both tables to yield the below:

data:
date       time     sym    price    shares    divisor
2017.12.05 09:45    AAPL   101.20   20        2
2017.12.06 09:45    AAPL   101.30   10        1.5
2017.12.05 10:00    GOOG   800.50   5         1
2017.12.06 11:15    BBRY   02.10    200       1

Code for the first two tables:

([] date:2017.12.05,2017.12.06; time:09:45,09:45; sym:`AAPL,`AAPL; price:101.20,102.30)

([] date:2017.12.05,2017.12.05,2017.12.06,2017.12.06; sym:`AAPL,`GOOG,`AAPL,`BBRY; shares:20f,5f,10f,100f; divisor:2f,1f,1.5f,1f)

Solution

  • I think the best approach is to assign the resultant table from indexConstituents'[DJIA;daterange] to a variable, so that we can then pull out the sym column and apply distinct to it.

    You can then use that list of syms as your first argument to the quotes.

    Finally join the two resultant tables together.

    idx:indexConstituents'[DJIA;daterange];
    q:quotes\:/:[distinct idx`sym;daterange];
    q lj 2!idx
    

    Hope this helps!