在 Q KDB+ 中使用 EACH 循环

Loop with EACH in Q KDB+

我有股票交易数据库(名称 "TRADES"),我尝试了很长时间来制作一个简单的循环(具有 EACH 函数),它将所有高于预定义的数量相加每个 ISIN 的数量阈值。数据如下所示:

q) select TIME, PRICE, QUANTITY from TRADES where ISIN=`IT123

TIME    PRICE QUANTITY
8:58:05 9.47    66
9:00:09 9.47    55
9:00:56 9.48    107
9:01:06 9.49    7
9:01:33 9.50    9
9:03:11 9.07    200
9:06:27 9.07    100
9:07:46 9.12    65...

首先,我为一个 ISIN 尝试此代码:

q) myquant: ([] qu: 1 + til 100) //pre-define quantities from 1 to 100

q) f:{[x] (select sum QUANTITY from TRADES where ISIN=`IT123, QUANTITY> x)}

q) f each myquant.qu //use function EACH for all x that are in myquant

然后我得到一些象形文字...可能是因为列表指定错误?

我还需要为数据库中的所有 ISIN(即 "EACH distinct ISIN")做这些计算。

非常感谢您的提前帮助。

给定一些 trades:

q)show trades:flip`isin`time`price`quantity!100?/:(`US5949181045`US38259P5089`US0378331005;24t;100f;100)
    isin         time         price    quantity
    -------------------------------------------
    US5949181045 18:45:28.487 60.91539 12
    US5949181045 04:35:02.468 98.30794 62
    US0378331005 23:39:20.774 75.43122 18
    US38259P5089 09:37:08.266 38.13679 37
    US0378331005 12:09:01.385 3.112646 17
    ..

对于范围从 0 到 100 的 minQty

q)raze {[minQty] select sum quantity by isin,minQty:minQty  from trades where quantity>minQty} each til 100
    isin         minQty| quantity
    -------------------| --------
    US0378331005 0     | 1537
    US38259P5089 0     | 1767
    US5949181045 0     | 1435
    US0378331005 1     | 1537
    US38259P5089 1     | 1767
    ..

结果给出每个 isin 的总数量,其中数量 > 给定的 minQty

几个选项:

Sol1:

  q) s1:{[mqty]`mqty xasc ungroup select mqty,quantity:sum @/:quantity where each quantity>/:mqty by isin from trades}

  q) s1 myquant.qu

Sol2:

扩展 MdSalih 解决方案以处理没有行符合数量条件的情况

  q) s2:{a:ungroup select minQty:x ,quantity:0 by isin from trades;
         b:raze {[minQty] select sum quantity by isin,minQty:minQty from trades where quantity>minQty} each x;
         `minQty xasc a lj b }


  q)s2 myquant.qu

编辑(对于 ISIN 分区目录):

如果您将 ISIN 作为不是 int 的分区键(正如您在评论中的示例所看到的那样),那么 kdb 将不会将其识别为分区数据库。

更多详细信息:http://code.kx.com/q4m3/14_Introduction_to_Kdb+/#1432-partition-domain

您必须手动加载 columns/tables 并进行计算。一种解决方案是:

   q) src_path:"C:\q\"
   q) raze {[isin;mqty]a:get hsym `$src_path,isin,"\trades\quantity";flip `isin`mqty`quantity!count[mqty]#/:(enlist isin;mqty;sum @/:a where each a>/:(),mqty)}[;myquant.qu] each ("ISIN01";"ISIN02")