3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在编写 QMT(Quantitative Multi-strategy Trading)量化策略时,我们经常需要根据具体的日期(如某个历史事件发生日、财报公布日等)去获取当时 K 线的索引号(barpos),以便提取该时间点前后的行情数据或进行逻辑判断。QMT 提供了 ContextInfo.get_date_location() 接口来完美解决这一需求。
ContextInfo.get_date_location(strdate)
strdate (string): 目标日期,格式为 'yyyymmdd',例如 '20170711'。number: 对应 K 线的索引号(从 0 开始)。strdate 小于当前图 K 线对应的最早日期,结果返回 0。strdate 大于当前图 K 线对应的最新日期,结果返回最新 K 线的索引号(即 ContextInfo.time_tick_size - 1)。以下是一个简单的 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}")
get_date_location 定位到该 K 线,进而分析事件发生后 N 天内的股价走势。