如何按指定时间间隔获取最新非空价格?(kdb+技术问询)
在kdb+中按指定时间间隔获取最新非空价格
给定数据表
quote:([] sym:5#`aapl; time: 08:59 09:27 09:40 09:45 09:46;price: 10 0Ni 30 40 50 )
需求说明
获取09:00至10:00之间,每15分钟间隔的最新非空价格,期望输出:
time price 09:00 10 09:15 10 09:30 10 09:45 40 10:00 50
解决方案
步骤1:过滤非空价格数据
先剔除原表中价格为空的记录,避免空值干扰后续匹配逻辑:
clean_quote: select from quote where not null price
步骤2:生成目标时间序列
根据指定的起止时间和间隔,生成需要查询的时间点集合:
start_time: 09:00 end_time: 10:00 interval: 00:15 target_times: start_time + til ((end_time - start_time) div interval + 1) * interval
执行后target_times会得到09:00 09:15 09:30 09:45 10:00。
步骤3:匹配最新记录并填充空值
用kdb+的aj(asof join)函数,为每个目标时间点匹配对应标的(sym)下、时间不晚于目标时间的最新记录;再通过fills函数向前填充空值,确保无匹配记录的时间点沿用之前的最新非空价格:
// 执行asof join匹配最新记录 aj_result: aj[`sym`time; ([] sym:count[target_times]#`aapl; time:target_times); clean_quote] // 向前填充价格空值 final_result: update price:fills price from aj_result // 筛选出需要的列 final_result: select time, price from final_result
简洁合并写法
如果需要更紧凑的代码,可将所有步骤合并为一行:
start:09:00; end:10:00; interval:00:15 select time, price:fills price from aj[`sym`time; ([] sym:count[t]#`aapl; time:t); select from quote where not null price] where t:start + til ((end-start)div interval +1)*interval
关键函数说明
aj:asof join,kdb+中匹配历史最新记录的核心函数,会为每个目标行找到sym一致且time不晚于目标时间的最近行。fills:向前填充函数,自动用前一个非空值填充当前空值,保证时间序列的价格连续性。
内容的提问来源于stack exchange,提问作者Rezzy
相关产品推荐
相关产品推荐

