问题描述
怎么获取当前铁矿石期货的主力合约代码并买入一手?
解决方案
在聚宽(JoinQuant)中,获取铁矿石期货主力合约并买入一手主要包含以下步骤:
- 初始化期货账户:在
initialize中必须将账户类型设置为futures。 - 获取主力合约:使用
get_dominant_future('I')获取铁矿石(代码为 'I')的当前主力合约代码。 - 下单交易:使用
order函数进行开仓买入。
以下是完整的策略代码示例:
# -*- coding: utf-8 -*-
from jqdata import *
def initialize(context):
# 1. 设定账户类型为期货账户 (必须步骤,默认是股票账户无法交易期货)
# 将初始资金全部分配给期货账户
set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='futures')])
# 2. 设定基准,这里使用铁矿石主力连续合约作为基准
set_benchmark('I9999.XDCE')
# 3. 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 4. 设置手续费(可选,这里使用默认费率,实盘或精确回测建议详细设置)
# 5. 设定定时运行,例如每天开盘时运行
run_daily(trade_func, time='open')
def trade_func(context):
# 1. 获取铁矿石主力合约代码
# 铁矿石在大商所的品种代码是 'I'
# get_dominant_future 会返回当前日期的主力合约代码,例如 'I2405.XDCE'
dominant_future = get_dominant_future('I')
if dominant_future is None:
log.warn("未获取到铁矿石主力合约")
return
log.info("当前铁矿石主力合约: %s" % dominant_future)
# 2. 买入一手 (开多单)
# 为了演示,这里加一个判断:如果当前该合约没有多头持仓,则买入
# context.portfolio.long_positions 存储多头持仓信息
if dominant_future not in context.portfolio.long_positions:
log.info("账户无持仓,正在买入一手 %s" % dominant_future)
# order 函数参数说明:
# security: 标的代码
# amount: 数量(期货为手数),正数代表买入/开仓
# side: 'long' 表示做多 (默认为long,显式写出来更清晰)
order(dominant_future, 1, side='long')
else:
log.info("已有 %s 持仓,今日不操作" % dominant_future)
代码关键点说明:
set_subportfolios: 聚宽默认初始化的账户是股票账户(type='stock')。交易期货必须在initialize中显式将账户类型设置为futures,否则下单会失败。get_dominant_future('I'):'I'是铁矿石的品种代码。- 该函数会自动根据回测的当前日期返回当时的主力合约代码(如
I2309.XDCE)。
order(..., side='long'):- 期货交易需要区分方向。
side='long'表示多单(看涨),side='short'表示空单(看跌)。 amount为正数表示开仓,为负数表示平仓。这里1表示开仓买入1手。
- 期货交易需要区分方向。