# 回测起始时间
start_date = '2017-11-01'
# 回测结束时间
end_date = '2018-04-01'
# 策略比较参考标准
benchmark = 'BTC_USDT.HBI'
# 交易标的
instruments = ['BTC_USDT.HBI']
# 起始资金
capital_base = 1000000
# 初始化虚拟账户状态,只在第一个交易日运行
def initialize(context):
# context.set_commission是设置手续费,这里作演示不考虑手续费,股票的手续费设置如下,作为参考。
# context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
#短均线参数
context.short_period = 5
#长均线参数
context.long_period = 20
def handle_data(context, data):
# 当前支持的K线数量还达不到长均线时直接返回
if context.trading_day_index < context.long_period:
return
# 投资标的字符串格式
instr = instruments[0]
# 将标的转化为equity格式
sid = context.symbol(instr)
# 最新价格
price = data.current(sid, 'price')
# 短周期均线值
short_mavg = data.history(sid, 'price', context.short_period, '1d').mean()
# 长周期均线值
long_mavg = data.history(sid, 'price', context.long_period, '1d').mean()
# 账户资金
cash = context.portfolio.cash;
# 账户持仓
cur_pos = context.portfolio.positions[sid].amount
# 策略逻辑部分
# 空仓状态下,短周期均线上穿(大于)长周期均线形成金叉,且该股票可以交易,买入
# 持仓状态下,短周期均线下穿(小于)长周期均线形成死叉,且该股票可以交易,卖出
if (short_mavg > long_mavg and cur_pos == 0 and data.can_trade(sid)):
context.order_target_percent(sid,1)
elif (short_mavg < long_mavg and cur_pos > 0 and data.can_trade(sid)):
context.order_target_percent(sid, 0)
# history_ds=DataSource('bar1d_HBI').read(instruments,start='2017-05-01', end=end_date)
# benchmark_ds = DataSource('bar1d_HBI').read([benchmark],start='2017-05-01', end=end_date)
m = M.trade.v4(
instruments=instruments,
start_date=start_date,
end_date=end_date,
initialize=initialize,
handle_data=handle_data,
# 买入的时候,假设以次日开盘价成交
order_price_field_buy='open',
# 卖出的时候,假设以次日开盘价成交
order_price_field_sell='close',
capital_base=capital_base+1,
)
[2020-05-07 10:46:03.755892] INFO: moduleinvoker: backtest.v8 开始运行..
[2020-05-07 10:46:03.759677] INFO: backtest: biglearning backtest:V8.3.4
[2020-05-07 10:46:03.760604] INFO: backtest: product_type:stock by specified
[2020-05-07 10:46:03.899798] INFO: moduleinvoker: cached.v2 开始运行..
[2020-05-07 10:46:03.962969] INFO: backtest: 读取加密货币行情完成:158
[2020-05-07 10:46:03.993782] INFO: moduleinvoker: cached.v2 运行完成[0.093973s].
[2020-05-07 10:46:04.000884] INFO: algo: TradingAlgorithm V1.6.7
[2020-05-07 10:46:04.024974] INFO: algo: trading transform...
[2020-05-07 10:46:04.877964] INFO: Performance: Simulated 152 trading days out of 152.
[2020-05-07 10:46:04.879045] INFO: Performance: first open: 2017-11-01 00:00:00+00:00
[2020-05-07 10:46:04.879867] INFO: Performance: last close: 2018-04-01 23:59:00+00:00
[2020-05-07 10:46:05.589739] INFO: moduleinvoker: backtest.v8 运行完成[1.833857s].
[2020-05-07 10:46:05.590874] INFO: moduleinvoker: trade.v4 运行完成[3.290596s].