克隆策略
In [2]:
start_date = '2016-01-01'
end_date = '2017-09-14'
instrument = D.instruments(start_date=start_date, end_date=end_date)
df =D.history_data(instrument, start_date, end_date, ['high', 'low','price_limit_status' ,'amount'])
raw_df = df[(df['price_limit_status']==3)&(df['high']==df['low'])&(df['amount']>=10000)]   # 选出一字涨停的股票
result = raw_df.groupby('date').apply(lambda df: list(df['instrument']))  # 整理出每日一字涨停的股票列表
In [5]:
def initialize(context):
    context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5)) # 设置手续费
    context.hold_days = dict()
    context.max_hold = 25  # 一共持有25个股票
def handle_data(context, data):
    dt = data.current_dt.strftime('%Y-%m-%d')
    stock_hold_now = [equity.symbol for equity in context.portfolio.positions]  # 目前持有的股票
    # 当日买入股票列表 
    try:
        buy = result.ix[dt] 
    except KeyError as e:
        buy = []
    weight = 1 / context.max_hold  # 先采取固定比例 
    for st in buy:  # 达到买入条件就买入
        sid = context.symbol(st)
        cur_position = context.portfolio.positions[sid].amount
        if cur_position == 0 and data.can_trade(sid):
            order_target_percent(sid, weight)
            context.hold_days[st] = context.trading_day_index     # 记录买入时间
    for st in stock_hold_now:   # 持仓大于1天就卖出
        sid = context.symbol(st)
        cur_position = context.portfolio.positions[sid].amount
        if cur_position > 0 and data.can_trade(sid) and context.trading_day_index - context.hold_days[st] > 1:
             order_target_percent(sid, 0)     
m = M.trade.v2(  # 执行回测
    instruments=instrument,
    start_date=start_date,
    end_date=end_date,
    initialize=initialize,
    handle_data=handle_data,
    order_price_field_buy='open',
    order_price_field_sell='open',
    capital_base=20000000,
    benchmark='000300.INDX',
)
[2017-09-15 17:38:40.251471] INFO: bigquant: backtest.v7 开始运行..
[2017-09-15 17:39:24.190981] INFO: Performance: Simulated 417 trading days out of 417.
[2017-09-15 17:39:24.192149] INFO: Performance: first open: 2016-01-04 14:30:00+00:00
[2017-09-15 17:39:24.193045] INFO: Performance: last close: 2017-09-14 19:00:00+00:00
  • 收益率-73.97%
  • 年化收益率-55.67%
  • 基准收益率2.65%
  • 阿尔法-0.59
  • 贝塔0.29
  • 夏普比率-3.2
  • 收益波动率18.76%
  • 信息比率-2.59
  • 最大回撤74.09%
[2017-09-15 17:39:26.704450] INFO: bigquant: backtest.v7 运行完成[46.45298s].