克隆策略
In [2]:
import talib
import numpy as np
def initialize(context):
    # 设置是否是结算模式
    context.set_need_settle(False)
    # 设置最大杠杆
    context.set_max_leverage(1,'fill_amap')
    # 设置参数
    context.window = 20
def handle_data(context, data):
    
    if context.trading_day_index < context.window : # 在形成均线后才开始交易
        return
    
    today = data.current_dt.strftime('%Y-%m-%d') # 当前交易日期

    instrument = context.future_symbol(context.instruments[0]) # 交易标的
    curr_po = context.portfolio.positions[instrument] # 组合持仓
    curr_position = curr_po.amount # 持仓数量
    price = data.current(instrument, 'price') # 当前价格
    
    # 计算20天内最高价、最低价
    high_price = data.history(instrument, 'price', context.window, '1d').max()
    low_price = data.history(instrument, 'price', context.window, '1d').min()
    # 交易逻辑
    if price >= high_price and data.can_trade(instrument):
        context.order_target(instrument, 20) # 买入开仓
        print(today, curr_position, '买入开仓')
    elif price <= low_price and data.can_trade(instrument):
        context.order_target(instrument, -20) # 卖出开仓
        print(today, curr_position, '卖出开仓')
#启动回测
#策略回测接口: https://bigquant.com/docs/module_trade.html
m = M.trade.v3(
    instruments= ['RU1809.SHF'],
    start_date='2017-11-01',
    end_date='2018-06-01',
    initialize=initialize,
    handle_data=handle_data,
    # 买入订单以开盘价成交
    order_price_field_buy='open',
    # 卖出订单以开盘价成交
    order_price_field_sell='open',
    capital_base=1000000,
    benchmark='RU1809.SHF',
    m_deps=np.random.rand()
)
[2018-08-01 16:36:59.078118] INFO: bigquant: backtest.v7 开始运行..
[2018-08-01 16:36:59.087901] INFO: bigquant: biglearning backtest:V7.1.2
[2018-08-01 16:37:01.025092] INFO: algo: TradingAlgorithm V1.2.2
2017-12-04 0 买入开仓
2018-01-19 20 卖出开仓
2018-01-23 -20 卖出开仓
2018-01-24 -20 卖出开仓
2018-01-30 -20 卖出开仓
2018-01-31 -20 卖出开仓
2018-02-01 -20 卖出开仓
2018-02-06 -20 卖出开仓
2018-02-08 -20 卖出开仓
2018-03-19 -20 卖出开仓
2018-03-20 -20 卖出开仓
2018-03-21 -20 卖出开仓
2018-03-22 -20 卖出开仓
2018-03-23 -20 卖出开仓
2018-03-26 -20 卖出开仓
2018-04-04 -20 卖出开仓
2018-04-16 -20 卖出开仓
2018-04-17 -20 卖出开仓
[2018-08-01 16:37:02.539673] INFO: Performance: Simulated 143 trading days out of 143.
[2018-08-01 16:37:02.541444] INFO: Performance: first open: 2017-10-31 21:00:00+00:00
[2018-08-01 16:37:02.542713] INFO: Performance: last close: 2018-06-01 15:00:00+00:00
  • 收益率34.26%
  • 年化收益率68.06%
  • 基准收益率-16.99%
  • 阿尔法0.39
  • 贝塔-0.63
  • 夏普比率1.29
  • 胜率0.5
  • 盈亏比2.86
  • 收益波动率45.94%
  • 信息比率0.1
  • 最大回撤18.91%
[2018-08-01 16:37:03.257349] INFO: bigquant: backtest.v7 运行完成[4.179289s].