🚀 AI 一键生成 qmt 策略代码
立即体验

qmt 平台如何使用 get_date_location 快速查找特定日期对应的 K 线索引号?

qmt | 发布时间: 2026/7/22
以下内容由 EasyQuant 生成。

问题描述

请根据以下 SEO 主题生成完整页面内容:

Title: qmt 快速定位 K 线:get_date_location 接口用法

Question: qmt 怎么用 get_date_location 查找特定日期对应的 K 线索引号?

解决方案

qmt 快速定位 K 线:get_date_location 接口用法

在编写 QMT(Quantitative Multi-strategy Trading)量化策略时,我们经常需要根据具体的日期(如某个历史事件发生日、财报公布日等)去获取当时 K 线的索引号(barpos),以便提取该时间点前后的行情数据或进行逻辑判断。QMT 提供了 ContextInfo.get_date_location() 接口来完美解决这一需求。


1. 接口定义与参数说明

用法

ContextInfo.get_date_location(strdate)

参数

  • strdate (string): 目标日期,格式为 'yyyymmdd',例如 '20170711'

返回值

  • number: 对应 K 线的索引号(从 0 开始)。

边界返回值规则

  1. 小于最早日期:如果给定的日期 strdate 小于当前图 K 线对应的最早日期,结果返回 0
  2. 大于最新日期:如果给定的日期 strdate 大于当前图 K 线对应的最新日期,结果返回最新 K 线的索引号(即 ContextInfo.time_tick_size - 1)。

2. 核心代码示例

以下是一个简单的 Python 策略示例,展示了如何在 handlebar 中获取指定日期 '20170711' 对应的 K 线索引,并获取该 K 线的收盘价。

#encoding:gbk

def init(ContextInfo):
    # 设定基础股票池
    ContextInfo.set_universe(['600000.SH'])

def handlebar(ContextInfo):
    # 仅在最后一根 Bar 运行一次,避免重复打印
    if ContextInfo.is_last_bar():
        target_date = '20170711'
        
        # 获取指定日期对应的 K 线索引号
        pos = ContextInfo.get_date_location(target_date)
        print(f"日期 {target_date} 对应的 K 线索引号为: {pos}")
        
        # 结合 get_history_data 获取该位置的收盘价
        # 注意:get_history_data 返回的是整个序列,我们可以通过索引 pos 获取当时的数据
        close_data = ContextInfo.get_history_data(ContextInfo.time_tick_size, '1d', 'close')
        stock_code = '600000.SH'
        
        if stock_code in close_data and len(close_data[stock_code]) > pos:
            target_close = close_data[stock_code][pos]
            print(f"{stock_code} 在 {target_date} 的收盘价为: {target_close}")

3. 常见应用场景

  • 事件驱动策略:当获取到某一历史特定事件日期时,通过 get_date_location 定位到该 K 线,进而分析事件发生后 N 天内的股价走势。
  • 多周期数据对齐:在日线与分钟线混合策略中,通过日期时间戳快速对齐不同频段的数据源。
  • 回测区间限定:在特定历史区间内进行局部指标计算,避免全量计算以提升回测速度。