克隆策略
In [1]:
#读取基金数据
instruments=['510330.HOF']
df = DataSource('bar1d_CN_FUND').read(instruments)
history_ds = DataSource.write_df(df)
#设置开始日期,结束日期
start_date = '2018-01-04'
end_date = '2018-10-01'

# 策略比较参考标准,以沪深300为例
benchmark = '000300.SHA'

capital_base = 1000000

# 2. 策略主体函数
# 初始化虚拟账户状态,只在第一个交易日运行
def initialize(context):
    #记录策略运行天数
    context.index = 0
    #短均线参数
    context.short_period = 5
    #长均线参数
    context.long_period = 10

# 策略交易逻辑,每个交易日运行一次
def handle_data(context, data):
    today = data.current_dt.strftime('%Y-%m-%d')
    #更新策略运行天数
    context.index += 1
    if context.index <= context.long_period:
        return
    
    for instr in instruments:
        # 将标的转化为equity格式
        sid = context.symbol(instr)
        # 短周期均线值
        short_mavg = data.history(sid, 'price', context.short_period, '1d').mean()
        # 长周期均线值
        long_mavg = data.history(sid, 'price', context.long_period, '1d').mean()
        # 账户持仓
        cur_pos = context.portfolio.positions[sid].amount

        # 策略逻辑部分
        # 空仓状态下,短周期均线上穿(大于)长周期均线形成金叉,买入股票,且该股票可以交易
        # 持仓状态下,短周期均线下穿(小于)长周期均线形成死叉,卖出股票,且该股票可以交易
        if short_mavg > long_mavg and cur_pos == 0:
            context.order_target_percent(sid, 1)
        elif short_mavg < long_mavg and cur_pos > 0:
            context.order_target_percent(sid, 0)



# 3. 启动回测
# 策略回测接口: https://bigquant.com/docs/module_trade.html
m = M.trade.v4(
    instruments=['510330.HOF'],
    start_date=start_date,
    end_date=end_date,
    initialize=initialize,
    history_ds = history_ds,
    before_trading_start=None,
    handle_data=handle_data,
    # 买入订单以开盘价成交
    order_price_field_buy='open',
    m_deps=np.random.randn(),
    order_price_field_sell='open',
    capital_base=capital_base,
    benchmark=benchmark,
    volume_limit=0.25,
    product_type='stock',
)
[2018-10-18 09:52:42.888558] INFO: bigquant: backtest.v8 开始运行..
[2018-10-18 09:52:42.895186] INFO: bigquant: biglearning backtest:V8.1.0
[2018-10-18 09:52:42.896070] INFO: bigquant: product_type:stock by specified
[2018-10-18 09:52:42.897818] INFO: bigquant: 其它市场:{'HOF'}
[2018-10-18 09:52:42.992033] INFO: algo: TradingAlgorithm V1.3.2
[2018-10-18 09:52:44.802375] INFO: Performance: Simulated 181 trading days out of 181.
[2018-10-18 09:52:44.803449] INFO: Performance: first open: 2018-01-04 09:30:00+00:00
[2018-10-18 09:52:44.804309] INFO: Performance: last close: 2018-09-28 15:00:00+00:00
  • 收益率-11.06%
  • 年化收益率-15.06%
  • 基准收益率-16.36%
  • 阿尔法-0.13
  • 贝塔0.24
  • 夏普比率-1.89
  • 胜率0.18
  • 盈亏比0.17
  • 收益波动率9.94%
  • 信息比率0.03
  • 最大回撤17.02%
[2018-10-18 09:52:45.553203] INFO: bigquant: backtest.v8 运行完成[2.664664s].