原文策略源码如下:
导入函数库
from jqdata import *
import talib
from math import isnan
def initialize(context):
# 设置参数
set_parameter(context)
# 设定基准银华日利,在多品种的回测当中基准没有参考意义
set_benchmark(‘511880.XSHG’)
# 开启动态复权模式(真实价格)
set_option(‘use_real_price’, True)
# 过滤掉order系列API产生的比error级别低的log
log.set_level(‘order’, ‘error’)
### 期货相关设定 ###
# 设定账户为金融账户
set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type=‘futures’)])
# 期货类每笔交易时的手续费是:买入时万分之1,卖出时万分之1,平今仓为万分之1
set_order_cost(OrderCost(open_commission=0.0001, close_commission=0.0001,close_today_commission=0.0001), type=‘index_futures’)
# 设定保证金比例
set_option(‘futures_margin_rate’, 0.15)
# 设置滑点(单边万5,双边千1)
set_slippage(PriceRelatedSlippage(0.001),type=‘future’)
# 开盘前运行
run_daily( before_market_open, time=‘before_open’, reference_security=get_future_code(‘RB’))
# 开盘时运行
run_weekly(market_open, 1,time=‘open’, reference_security=get_future_code(‘RB’))
run_monthly(market_open, 11,time=‘open’, reference_security=get_future_code(‘RB’))
# 交易运行
# 交易运行
run_weekly(Trade, 1, time='open', reference_security=get_future_code('RB'))
run_monthly(Trade, 11, time=‘open’, reference_security=get_future_code(‘RB’))
# 收盘后运行
run_daily( after_market_close, time='after_close', reference_security=get_future_code('RB'))
参数设置函数
def set_parameter(context):
#######变量设置########
g.LastRealPrice = {} # 最新真实合约价格字典(用于吊灯止损)
g.HighPrice = {} # 各品种最高价字典(用于吊灯止损)
g.LowPrice = {} # 各品种最低价字典(用于吊灯止损)
g.future_list = [] # 设置期货品种列表
g.TradeLots = {} # 各品种的交易手数信息
g.PriceArray = {} # 信号计算价格字典
g.Price_dict = {} # 各品种价格列表字典
g.Times = {} # 计数器(用于防止止损重入)
g.Reentry_long = False # 止损后重入标记
g.Reentry_short = False # 止损后重入标记
g.MappingReal = {} # 真实合约映射(key为symbol,value为主力合约)
g.MappingIndex = {} # 指数合约映射 (key为 symbol,value为指数合约
g.StatusTimer = {} # 当前状态计数器
g.ATR = {}
g.CurrentPrice = {}
g.Price_DaysAgo = {}
g.Momentum = {}
g.ClosePrice = {}
#######参数设置########
g.BackWindow = 15 # 回溯窗口长度
g.Range = 0.3
# 交易的期货品种信息
g.instruments = ['AL','NI','CU','PB','AG',
'RU','MA','PP','TA','L','V',
'M','P','Y','OI','C','CS','JD','SR',
'HC','J','I','SF','RB','ZC','FG']
# 价格列表初始化
set_future_list(context)
def set_future_list(context):
for ins in g.instruments:
idx = get_future_code(ins)
dom = get_dominant_future(ins)
# 填充映射字典
g.MappingIndex[ins] = idx
g.MappingReal[ins] = dom
g.StatusTimer[ins] = 0
#设置主力合约已上市的品种基本参数
if dom == ‘’:
pass
else:
if dom not in g.f