🚀 AI 一键生成 joinquant 策略代码
立即体验

JoinQuant 平台如何根据品种代码动态获取最新期货主力合约?

joinquant | 发布时间: 2026/8/3
以下内容由 EasyQuant 生成。

问题描述

请根据以下 SEO 主题生成完整页面内容:

Title: joinquant 期货主力合约获取:get_dominant_future API 详细使用教程

Question: joinquant 如何根据品种代码动态获取最新的主力合约?

解决方案

JoinQuant 期货主力合约获取:get_dominant_future API 详细使用教程

在期货量化交易中,由于单个期货合约存在到期交割限制,策略通常需要跟踪连续的主力合约。JoinQuant(聚宽)平台提供了 get_dominant_future 函数,帮助开发者动态获取指定品种在当前交易日的主力合约代码。


一、聚宽主力合约定义规则

  1. 拼接规则:如果某合约持仓量连续 2 天为同一个品种中最大的(金融期货限定主力只从最近的两个合约中选取),且该合约相对于当前主力合约为远期合约,系统会自动将其切换为新的主力合约。
  2. 更新时间:主力合约基于 T-2 和 T-1 日的持仓量计算,在 T-1 日晚上(即 T 日夜盘开始前)完成切换,不会在日内进行主力合约切换。
  3. 交易注意:主力连续合约代码(如 IF9999.CCFXRB9999.XSGE)仅用于行情展示与回测数据获取,不能直接对其下单。交易时必须通过 get_dominant_future 获取具体的真实合约代码(如 IF2309.CCFX)。

二、get_dominant_future API 详解

函数签名

get_dominant_future(underlying_symbol, date=None)

参数说明

  • underlying_symbol (str): 期货合约品种代码。例如:
    • 'IF' (沪深300股指期货)
    • 'RB' (螺纹钢)
    • 'CU' (沪铜)
    • 'A' (豆一)
  • date (str / datetime.date / datetime.datetime, 可选): 查询日期。
    • 在回测/模拟盘中:默认为当前逻辑时间 context.current_dt
    • 在研究环境中:默认为最新日期。

返回值

  • 返回指定品种在该日期对应的真实可交易合约代码(字符串),例如 'IF1608.CCFX'

三、代码示例

1. 研究环境基础用法

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)

2. 回测/模拟盘中的实战策略应用

在策略中,可以在每日开盘前(如 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}")

四、常见问题与注意事项

  1. 非法品种代码报错
    传入的 underlying_symbol 必须是品种大写字母代码(如 'RB'),不能带有交易所后缀或数字(例如传入 'RB9999''RB.XSGE' 均会导致错误)。

  2. 移仓换月处理
    当检测到 get_dominant_future 返回的合约代码发生变更时,投资者需在策略逻辑中自行实现平掉旧合约仓位并建立新合约仓位的平翻/换月操作。

  3. 数据获取配套
    获取到主力合约代码后,可将其作为参数传入 get_priceget_barsorder 等标准 API 中获取行情和执行交易。