3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在期货量化交易中,由于单个期货合约存在到期交割限制,策略通常需要跟踪连续的主力合约。JoinQuant(聚宽)平台提供了 get_dominant_future 函数,帮助开发者动态获取指定品种在当前交易日的主力合约代码。
IF9999.CCFX、RB9999.XSGE)仅用于行情展示与回测数据获取,不能直接对其下单。交易时必须通过 get_dominant_future 获取具体的真实合约代码(如 IF2309.CCFX)。get_dominant_future(underlying_symbol, date=None)
'IF' (沪深300股指期货)'RB' (螺纹钢)'CU' (沪铜)'A' (豆一)context.current_dt。'IF1608.CCFX'。from jqdata import *
# 获取当前最新的螺纹钢主力合约
dominant_rb = get_dominant_future('RB')
print("当前螺纹钢主力合约:", dominant_rb)
# 查询历史特定日期(如2023年5月10日)的沪深300股指期货主力合约
historical_if = get_dominant_future('IF', date='2023-05-10')
print("2023-05-10 沪深300主力合约:", historical_if)
在策略中,可以在每日开盘前(如 08:30)动态获取最新的主力合约并订阅其 Tick/Bar 数据:
import jqdata
def initialize(context):
# 设置交易账户为期货账户
init_cash = context.portfolio.starting_cash
set_subportfolios([SubPortfolioConfig(cash=init_cash, type='futures')])
# 标的品种:螺纹钢
g.symbol = 'RB'
g.current_dominant = None
# 每日开盘前运行主力合约更新函数
run_daily(before_market_open, time='08:30', reference_security='RB9999.XSGE')
def before_market_open(context):
# 动态获取当日主力合约
new_dominant = get_dominant_future(g.symbol)
# 检查是否发生移仓换月
if new_dominant != g.current_dominant:
log.info(f"主力合约切换:原合约 {g.current_dominant} -> 新合约 {new_dominant}")
g.current_dominant = new_dominant
log.info(f"今日运行主力合约为:{g.current_dominant}")
def handle_data(context, data):
# 使用动态获取的主力合约进行下单操作
symbol_code = g.current_dominant
# 获取过去5日收盘价
hist = attribute_history(symbol_code, 5, '1d', ['close'])
ma5 = hist['close'].mean()
current_price = data[symbol_code].close
# 简单的突破买入逻辑
if current_price > ma5 * 1.01 and context.portfolio.positions[symbol_code].total_amount == 0:
# 开多仓 1 手
order(symbol_code, 1, side='long')
log.info(f"开多仓:{symbol_code}")
非法品种代码报错
传入的 underlying_symbol 必须是品种大写字母代码(如 'RB'),不能带有交易所后缀或数字(例如传入 'RB9999' 或 'RB.XSGE' 均会导致错误)。
移仓换月处理
当检测到 get_dominant_future 返回的合约代码发生变更时,投资者需在策略逻辑中自行实现平掉旧合约仓位并建立新合约仓位的平翻/换月操作。
数据获取配套
获取到主力合约代码后,可将其作为参数传入 get_price、get_bars 或 order 等标准 API 中获取行情和执行交易。