3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在期货量化交易中,临近交割月的合约会面临交易所强制平仓或大幅提高保证金的风险。因此,在策略中建立交割日监控与自动平仓风控机制至关重要。
在 ptrade 平台中,我们可以通过 get_instruments 接口获取期货合约的详细上市信息,其中包括交割日期(delivery_date)。
get_instrumentsget_instruments(contract)contract (str) - 期货合约代码,例如 'CU2112.XSGE'。contract_code:合约代码contract_name:合约名称exchange:交易所delivery_date:交割日期(格式通常为 'YYYYMMDD' 或 'YYYY-MM-DD' 的字符串)margin_rate:保证金比例以下是一个完整的 ptrade 策略示例。策略在每日盘前(before_trading_start)获取持仓期货合约的交割日期,计算当前日期距离交割日的天数。如果距离交割日小于或等于设定的安全天数 $N$(例如 5 天),则在盘中自动执行平仓操作。
import datetime
def initialize(context):
# 设置操作的期货合约池
g.security = ['CU2505.XSGE'] # 示例合约
set_universe(g.security)
# 设定风控参数:距离交割日小于等于 N 天时强制平仓
g.safe_days_limit = 5
# 记录需要强平的合约列表
g.force_close_list = []
def before_trading_start(context, data):
g.force_close_list = []
today = context.blotter.current_dt.date()
# 遍历当前持仓
for position in context.portfolio.positions.values():
sid = position.sid
# 仅对期货业务进行风控判断
if position.business_type == 'future' and (position.long_amount > 0 or position.short_amount > 0):
try:
# 获取合约信息
instrument_info = get_instruments(sid)
if instrument_info and instrument_info.delivery_date:
# 解析交割日期
deliv_date_str = instrument_info.delivery_date.replace('-', '')
delivery_date = datetime.datetime.strptime(deliv_date_str, '%Y%m%d').date()
# 计算距离交割日的剩余天数
days_to_delivery = (delivery_date - today).days
log.info("合约 %s 距离交割日 %s 还有 %d 天" % (sid, delivery_date, days_to_delivery))
# 如果进入临期危险期,加入强平名单
if days_to_delivery <= g.safe_days_limit:
g.force_close_list.append(sid)
log.warning("警告:合约 %s 已进入临期危险期,将被强制平仓!" % sid)
except Exception as e:
log.error("获取合约 %s 信息失败: %s" % (sid, str(e)))
def handle_data(context, data):
# 盘中执行强平逻辑
if g.force_close_list:
for sid in g.force_close_list:
position = get_position(sid)
# 1. 平多仓
if position.long_amount > 0:
log.info("执行风控:卖出平仓多头合约 %s,数量 %d" % (sid, position.long_amount))
sell_close(sid, position.long_amount)
# 2. 平空仓
if position.short_amount > 0:
log.info("执行风控:买入平仓空头合约 %s,数量 %d" % (sid, position.short_amount))
buy_close(sid, position.short_amount)
delivery_date 格式可能带有 -(如 2025-05-15)或不带(如 20250515)。源码中使用了 .replace('-', '') 进行兼容处理。sell_close 和 buy_close 接口的 close_today 参数设置。get_trade_days 接口进行过滤。