如何在DolphinDB中将非均匀快照数据聚合为带会话边界与容差的分钟K线
A股快照数据聚合1分钟K线(DolphinDB实现)
核心需求回顾
- 左开右闭窗口:如
(09:30, 09:31]对应09:31的K线 - 有效交易时段:早盘
09:31~11:30、午盘13:01~15:00,共240根K线 - 延迟数据处理:11:30:02、15:00:01这类稍晚于时段结束的数据需归入对应时段最后一根K线
- 聚合指标:
stdp(LastPrice)(总体标准差)
完整实现代码
// 1. 过滤无效数据:保留符合时间范围的快照记录 filtered = select * from mock where (time(DateTime) > 09:30:00 and time(DateTime) <= 11:30:03) or (time(DateTime) > 13:00:00 and time(DateTime) <= 15:00:03) // 2. 生成正确的K线标签barTime t = time(DateTime) barTime = iif( t > 11:30:00 and t <= 11:30:03, concatDateTime(date(DateTime), 11:30:00), iif( t > 15:00:00 and t <= 15:00:03, concatDateTime(date(DateTime), 15:00:00), concatDateTime(date(DateTime), minute(t) + 1m) ) ) dataWithBar = select *, barTime from filtered // 3. 分组聚合计算目标指标 minBar = select SecurityID, barTime, stdp(LastPrice) as StdLastPrice from dataWithBar group by SecurityID, barTime // ------------------------------ // 可选:补全当日所有240根K线(含无数据的空白bar) // ------------------------------ tradeDate = date(mock.DateTime[0]) morningBars = concatDateTime(tradeDate, 09:31:00..11:30:00 by 1m) afternoonBars = concatDateTime(tradeDate, 13:01:00..15:00:00 by 1m) allBarTimes = morningBars join afternoonBars fullMinBar = select s.SecurityID, b.barTime, min(StdLastPrice) as StdLastPrice // 无数据时显示NULL,可替换为0或其他默认值 from (select distinct SecurityID from mock) as s, table(allBarTimes as barTime) as b left join minBar as m on s.SecurityID = m.SecurityID and b.barTime = m.barTime group by s.SecurityID, b.barTime
代码逻辑说明
1. 无效数据过滤
直接通过time(DateTime)提取时间部分,精准筛选:
- 早盘:仅保留
09:30:00 < 时间 <=11:30:03的数据(3秒缓冲可根据实际延迟情况调整) - 午盘:仅保留
13:00:00 < 时间 <=15:00:03的数据
一次性排除午休、超时过久(如11:30:05、15:01:30)的无效记录。
2. K线标签生成
针对时段末尾的延迟数据做特殊处理:
- 早盘延迟数据(11:30:00 < 时间 <=11:30:03):强制绑定到11:30的K线
- 午盘延迟数据(15:00:00 < 时间 <=15:00:03):强制绑定到15:00的K线
- 常规数据:通过
minute(t)+1m得到左开右闭窗口的结束时间(如09:30:03对应09:31的K线)
3. 分组聚合
按股票代码和K线时间分组,调用stdp函数计算总体标准差,直接得到目标K线数据。
可选:补全全量K线
如果需要确保每日240根K线完整(即使无快照数据),先生成当日所有有效K线的时间序列,再通过笛卡尔积+左连接补全,无数据的K线指标会显示为NULL,可根据需求替换为默认值。
内容的提问来源于stack exchange,提问作者Lambert
相关产品推荐
相关产品推荐

