3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在进行跨品种、跨市场交易(如股票与股指期货套利、商品期货与行业板块对冲)时,不同市场的交易日历往往存在差异。例如:
如果直接按 K 线索引(barpos)进行计算,会导致数据错位,产生严重的“未来函数”或逻辑错误。因此,必须使用 QMT 的 get_trading_dates 接口获取真实的交易日历,并对齐时间轴。
get_trading_datesContextInfo.get_trading_dates(stockcode, start_date, end_date, count, period)
'600000.SH' 或 'IF00.IF')。'YYYYMMDD'。若不为空,则 count 参数失效。'YYYYMMDD',默认为当前 bar 的时间。start_date 为空时生效,表示获取 end_date 往前数 count 个交易日。'1d'(日线)、'1m'(1分钟线)等。返回一个包含时间字符串的 list。若周期为日线,返回格式如 ['20231001', '20231002', ...];若为分钟线,返回格式如 ['20231001093000', ...]。
以下源码展示了如何在 init 初始化阶段获取股票和期货的交易日历,通过 Python 的集合(Set)求交集,找出共同的交易日,并在 handlebar 中排除非共同交易日。
#coding:gbk
def init(ContextInfo):
# 1. 定义需要对齐的股票和期货标的
ContextInfo.stock = '600000.SH' // 浦发银行
ContextInfo.future = 'IF00.IF' // 沪深300股指期货连续
# 2. 设定获取交易日历的时间范围
start_time = '20230101'
end_time = '20231231'
# 3. 分别获取股票和期货的交易日历列表
# 注:count参数在start_time不为空时无效,传入1作为占位符
stock_calendar = ContextInfo.get_trading_dates(ContextInfo.stock, start_time, end_time, 1, '1d')
future_calendar = ContextInfo.get_trading_dates(ContextInfo.future, start_time, end_time, 1, '1d')
# 4. 利用集合求交集,获取共同交易日,并重新排序
common_dates = list(set(stock_calendar).intersection(set(future_calendar)))
common_dates.sort()
# 将对齐后的交易日历存入全局变量
ContextInfo.common_dates = common_dates
print(f"股票交易天数: {len(stock_calendar)}")
print(f"期货交易天数: {len(future_calendar)}")
print(f"对齐后的共同交易天数: {len(ContextInfo.common_dates)}")
def handlebar(ContextInfo):
# 1. 获取当前主图 K 线的时间戳并转换为 YYYYMMDD 格式
raw_time = ContextInfo.get_bar_timetag(ContextInfo.barpos)
current_date = timetag_to_datetime(raw_time, '%Y%m%d')
# 2. 排除非共同交易日
if current_date not in ContextInfo.common_dates:
# 如果当前日期不是共同交易日,则跳过不执行交易逻辑
return
# 3. 执行对齐后的多市场交易策略逻辑
print(f"【对齐交易日】当前日期 {current_date} 满足对齐条件,开始执行策略...")
# 在此编写您的双市场套利或对冲逻辑
get_trading_dates 之前,请务必通过 QMT 客户端的 “数据管理” 功能,完整下载对应品种及对应周期的历史行情数据,否则可能获取到空列表。'1m')上对齐,由于期货有夜盘而股票没有,交集法会自动过滤掉期货的夜盘数据,只保留日盘重合的分钟 Bar。handlebar 的驱动次数,提高回测效率。