3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT 回测或模型运行中,如果需要根据一个具体的日期字符串找到该日期在当前主图 K 线数据中的索引位置(即第几根 K 线),可以使用 ContextInfo.get_date_location() 函数。
以下是该函数的详细用法说明和示例代码。
该函数用于获取给定日期对应的 K 线索引号。
index = ContextInfo.get_date_location(strdate)
'yyyymmdd'(例如 '20230105')。根据 API 文档说明:
以下代码展示了如何在 init 方法中查找特定日期的索引,并通过 get_bar_timetag 验证该索引对应的时间戳。
# -*- coding: gbk -*-
def init(ContextInfo):
# 1. 设定一个目标日期,格式为 'yyyymmdd'
target_date = '20220601'
# 2. 调用 get_date_location 获取索引
# 注意:ContextInfo 必须包含行情数据,通常在回测模式或有主图数据时有效
k_index = ContextInfo.get_date_location(target_date)
print(f"目标日期 {target_date} 对应的 K 线索引为: {k_index}")
# 3. 验证:根据获取的索引反查时间戳
# get_bar_timetag 返回的是毫秒级时间戳
timetag = ContextInfo.get_bar_timetag(k_index)
# 将时间戳转换为可读格式进行对比
import time
# 毫秒转秒
time_struct = time.localtime(timetag / 1000)
readable_date = time.strftime("%Y%m%d", time_struct)
print(f"索引 {k_index} 对应的实际 K 线日期为: {readable_date}")
def handlebar(ContextInfo):
pass
'yyyymmdd' 格式,不要带横杠或冒号(如 '2022-01-01' 可能会导致解析错误或不准确,建议使用 '20220101')。Q: 如果输入的日期是停牌日或者周末,get_date_location 会报错吗?
A: 不会报错。如果输入的日期没有对应的 K 线(例如停牌或非交易日),函数通常会返回该日期之前最近的一根 K 线的索引,或者根据 API 的边界逻辑处理,不会抛出异常。
Q: 这个函数可以在 handlebar 中使用吗?
A: 可以。虽然示例是在 init 中演示的,但在 handlebar 中同样可以使用该函数来动态查找某个历史日期的位置,用于计算历史区间的指标。
Q: 如何判断返回的索引是否有效?
A: 可以结合 ContextInfo.time_tick_size(当前图 K 线总数)来判断。如果返回的索引等于 ContextInfo.time_tick_size - 1,说明日期可能超过了当前数据的最大范围;如果返回 0,说明日期可能早于数据的开始时间。