3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
AdaptiveMA(自适应移动平均线),最著名的是考夫曼自适应移动平均线(Kaufman's Adaptive Moving Average, 简称 KAMA)。与传统的简单移动平均线(SMA)或指数移动平均线(EMA)不同,AdaptiveMA 能够根据市场的波动率自动调整其平滑系数。
期货多品种则是指将该策略同时应用于多个相关性较低的期货品种(如黑色系、化工、农产品、贵金属等)。
下面我们将利用 JoinQuant 的 API,编写一个基础的 AdaptiveMA 期货多品种策略框架。
# 导入聚宽函数库
import jqdata
import numpy as np
import pandas as pd
import talib
def initialize(context):
# 设定基准
set_benchmark('000300.XSHG')
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 过滤掉 order 系列 API 产生的比 error 级别低的 log
log.set_level('order', 'error')
# 初始化期货账户
init_cash = context.portfolio.starting_cash
set_subportfolios([SubPortfolioConfig(cash=init_cash, type='futures')])
# 定义要交易的期货品种代码 (螺纹钢, 橡胶, 白银)
g.symbols = ['RB', 'RU', 'AG']
# KAMA 参数
g.timeperiod = 10
# 每天 14:50 运行交易逻辑 (尾盘判断)
run_daily(trade_logic, time='14:50', reference_security='RB9999.XSGE')
def trade_logic(context):
for symbol in g.symbols:
# 获取当前品种的主力合约
dominant_contract = get_dominant_future(symbol, context.current_dt.date())
if not dominant_contract:
continue
# 获取历史收盘价数据
# 获取比 timeperiod 更多的数据以确保 talib 能够计算出有效值
bars = get_bars(dominant_contract, count=g.timeperiod * 3, unit='1d', fields=['close'], include_now=True)
if len(bars) < g.timeperiod * 3:
continue
close_prices = bars['close']
# 使用 TA-Lib 计算 KAMA (考夫曼自适应均线)
kama_values = talib.KAMA(close_prices, timeperiod=g.timeperiod)
# 获取最新价格和最新的 KAMA 值
current_price = close_prices[-1]
current_kama = kama_values[-1]
prev_price = close_prices[-2]
prev_kama = kama_values[-2]
# 获取当前合约的持仓情况
long_position = context.portfolio.long_positions.get(dominant_contract, None)
short_position = context.portfolio.short_positions.get(dominant_contract, None)
long_amount = long_position.total_amount if long_position else 0
short_amount = short_position.total_amount if short_position else 0
# 交易信号判断
# 价格上穿 KAMA,看多
if prev_price <= prev_kama and current_price > current_kama:
if short_amount > 0:
# 平空
order_target(dominant_contract, 0, side='short')
if long_amount == 0:
# 开多 1 手 (实际应用中应根据资金量和波动率计算仓位)
order_target(dominant_contract, 1, side='long')
log.info(f"买入做多 {dominant_contract}")
# 价格下穿 KAMA,看空
elif prev_price >= prev_kama and current_price < current_kama:
if long_amount > 0:
# 平多
order_target(dominant_contract, 0, side='long')
if short_amount == 0:
# 开空 1 手
order_target(dominant_contract, 1, side='short')
log.info(f"卖出做空 {dominant_contract}")
timeperiod 默认通常为 10。可以通过 JoinQuant 的研究环境对不同品种进行参数遍历,寻找最优的平滑周期。