3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在量化对冲交易中,将**期现基差(Basis)与价格动量(Momentum)**相结合,能够在基差处于合理或极端区间时,借助动量信号精准择时进行建仓或平仓,从而提升期现套利与趋势对冲策略的风险收益比。
本文将基于国信 QMT 平台的 Python API,为您详细介绍如何在 QMT 中构建并运行该策略。
基差率计算:
$$\text{基差率} = \frac{\text{现货价格 (如沪深300指数 000300.SH)} - \text{期货价格 (如 IF 主力合约)}}{\text{现货价格}}$$
当基差率大于设定阈值时,说明期货折价较高(贴水),具有对冲或套利安全边际。
动量信号判定:
在对冲标的(或现货指数)出现明确动量突破(例如 20 日动量正向突破或收盘价突破均线)时,触发对冲建仓信号。
交易执行:
请在 QMT 【策略开发】- 选择 Python 模型进行编写:
#coding:gbk
import numpy as np
def init(ContextInfo):
# 1. 设定资金账号与交易标的
ContextInfo.account = '6000000248' # 请替换为您的实盘/虚拟期货/股票账号
ContextInfo.set_account(ContextInfo.account)
ContextInfo.index_code = '000300.SH' # 现货基准(沪深300)
ContextInfo.future_code = 'IF00.IF' # 股指期货主力合约
# 设置股票池
ContextInfo.set_universe([ContextInfo.index_code, ContextInfo.future_code])
# 2. 策略参数设置
ContextInfo.basis_threshold = 0.005 # 基差率门槛 (0.5%)
ContextInfo.momentum_period = 20 # 动量周期
ContextInfo.trade_lots = 1 # 下单手手数
# 全局状态控制
ContextInfo.has_position = False
print("策略初始化完成:基于期现基差与动量信号的趋势对冲策略")
def handlebar(ContextInfo):
# 保证只在最新的 barPos 执行逻辑或逐 Bar 计算
d = ContextInfo.barpos
if d < ContextInfo.momentum_period:
return
# 获取主力合约代码
real_future = ContextInfo.get_main_contract(ContextInfo.future_code)
if not real_future:
return
# 获取行情数据(现货指数与期货主力)
index_data = ContextInfo.get_market_data_ex(['close'], [ContextInfo.index_code], period='1d', count=ContextInfo.momentum_period + 1)
future_data = ContextInfo.get_market_data_ex(['close'], [real_future], period='1d', count=2)
if ContextInfo.index_code not in index_data or real_future not in future_data:
return
index_closes = index_data[ContextInfo.index_code]['close'].values
future_close = future_data[real_future]['close'].values[-1]
index_close = index_closes[-1]
# 1. 计算基差率 (现货 - 期货) / 现货
basis_rate = (index_close - future_close) / index_close
# 2. 计算动量信号 (当前价格对比 20 日前价格的涨跌幅)
momentum = (index_close - index_closes[0]) / index_closes[0]
# 3. 交易信号判定
# 买入对冲条件:基差率大于阈值(贴水足够大)且现货呈现正向动量
if not ContextInfo.has_position:
if basis_rate > ContextInfo.basis_threshold and momentum > 0:
print(f"[信号触发-建仓] 当前基差率: {basis_rate:.4f}, 20日动量: {momentum:.4f}")
# 期货卖出开仓 (opType=3, orderType=1101 为单股单账号股/手下单, prType=5 为最新价)
passorder(3, 1101, ContextInfo.account, real_future, 5, -1, ContextInfo.trade_lots, 'BasisMomStrategy', 1, 'Build_Short_Future', ContextInfo)
ContextInfo.has_position = True
# 平仓条件:基差收敛(基差率小于0)或动量转负
else:
if basis_rate < 0 or momentum < -0.01:
print(f"[信号触发-平仓] 当前基差率: {basis_rate:.4f}, 20日动量: {momentum:.4f}")
# 期货买入平仓,优先平今 (opType=8)
passorder(8, 1101, ContextInfo.account, real_future, 5, -1, ContextInfo.trade_lots, 'BasisMomStrategy', 1, 'Close_Short_Future', ContextInfo)
ContextInfo.has_position = False
ContextInfo.get_main_contract(codemarket):IF.IF 或 IF00.IF)在当前时刻的主力合约代码,自动解决期货合约换月问题。ContextInfo.get_market_data_ex(...):passorder(...):opType=3 代表期货卖出开仓,opType=8 代表平空(优先平今),配合 quickTrade=1 可实现信号生成时即时触发委托下单。