Kdb+/Q中匹配交易开平仓的正确向量化实现方法问询
符合kdb+/q风格的向量化实现方案
首先定义原始表:
t: ([] close: 18 2 4 8 5 7 3 10 17; entry: 0 1 0 0 0 1 0 0 0)
步骤拆解与实现
提取开仓位置与对应开仓价
获取所有开仓行的索引和收盘价(开仓价):entryIdxs: where t.entry=1; entryPrices: t.close entryIdxs;计算每个开仓对应的首个平仓位置
对每个开仓,找到其之后第一个满足「收盘价≥开仓价+3」的行索引:exitIdxs: first each {where (t.close >= x+3) & (til count t) > y} each entryPrices, entryIdxs;这里利用
each对每一组开仓价、开仓索引做向量查询,where筛选符合条件的位置,first取首个满足条件的索引(确保每个开仓仅平仓一次)。生成平仓列并更新表
初始化全0的exits列,将计算得到的平仓位置设为1,最后更新原表:exits: count t#0; exits[exitIdxs]: 1; t: update exits:exits from t;
最终结果
执行后表t的输出与期望一致:
t
close entry exits ----------------- 18 0 0 2 1 0 4 0 0 8 0 1 5 0 0 7 1 0 3 0 0 10 0 1 17 0 0
简化写法
可以将步骤合并为更紧凑的单行实现,保持kdb+的简洁风格:
t: update exits:(count t#0)[first each {where (close >= x+3)&(til count t)>y} each close where entry=1; where entry=1]:1 from t;
内容的提问来源于stack exchange,提问作者marital_weeping
相关产品推荐
相关产品推荐

