克隆策略
In [2]:
import pandas as pd
from datetime import timedelta

def my_handle_bar60m(context,bar):
    #获取当前时间、标的和预计算的信号数据
    cur_date_str =  bar.datetime
    instrument = bar.symbol
    now_data = context.mydata[(context.mydata["instrument"]==instrument)&(context.mydata["date"]==cur_date_str)]
       
    #获取持仓情况
    position = context.get_position(instrument)

    #当前没有持仓且满足开仓条件
    if(position.current_qty == 0 and now_data['signal'].iloc[0]==1):
        #等权重买入
        cash = min(context.portfolio.cash,context.portfolio.portfolio_value/len(context.ins))
        rv = context.order_value(instrument,cash,order_type=OrderType.MARKET)
        msg = "{} 买入{}  下单函数返回{}".format(cur_date_str,instrument,context.get_error_msg(rv))
        context.write_log(msg, stdout=context.PRINT) 

    #当前有持仓且满足平仓条件
    elif(position.avail_qty != 0 and now_data['signal'].iloc[0]==0):
        #有持仓则卖出    
        rv = context.order_target(instrument, 0, order_type=OrderType.MARKET)
        msg = "{} 卖出{}  下单函数返回{}".format(cur_date_str,instrument,context.get_error_msg(rv))
        context.write_log(msg, stdout=context.PRINT)
                
def initialize(context):
    """策略初始化函数,只触发一次。可以在该函数中初始化一些变量,如读取配置和全局使用数据"""
    context.PRINT = 0
    #输出关键日志
    msg = "initialize:" 
    context.write_log(msg, stdout=context.PRINT)
    
    context.ins = context.get_conf_param("instruments") #从传入参数中获取需要交易的合约
    start_date = context.get_conf_param("start_date") #从传入参数中获取开始时间
    end_date = context.get_conf_param("end_date") #从传入参数中获取结束时间
    # 订阅要交易的合约的行情
    context.subscribe(context.ins)
    #注册60分钟bar回调
    period = '60m'
    context.subscribe_bar(context.ins,period,my_handle_bar60m)
    #设置尾盘可以下单
    context.set_enable_auto_planed_order(1)
    #提前计算开平仓信号,减少回测时间
    new_start_date = (pd.to_datetime(start_date) - timedelta(days=20)).strftime("%Y-%m-%d")
    df_data = DataSource("bar1m_CN_STOCK_A").read(instruments=context.ins,start_date=new_start_date,end_date=end_date)    
    context.mydata = BarGenerator.aggregate_df(df_data, period)
    MA = 60
    def cal_ma(df):
        df['ma'] = df['close'].rolling(MA).mean()
        df['signal'] = np.where(df['close']>=df['ma'],1,0)
        return df
    context.mydata = context.mydata.groupby('instrument').apply(cal_ma)

def before_trading(context, data):
    """盘前处理,策略盘前交易函数,每日盘前触发一次。可以在该函数中一些启动前的准备,如订阅行情等"""
    # 输出关键日志
    msg = "before_trading"
    context.write_log(msg, stdout=context.PRINT)
    
def handle_order(context, order):
    """委托回报通知函数,每个订单状态有变化时会触发"""
    #输出关键日志
    msg = "handle_order data:{}".format(order.log_str())
    context.write_log(msg, stdout=context.PRINT) 
    
def handle_trade(context, trade):
    """成交回报通知函数,有成交时会触发"""
    #输出关键日志
    msg = "handle_trade data:{} ".format(trade.log_str())
    context.write_log(msg, stdout=context.PRINT) 


instruments = ["000001.SZA","600519.SHA"]
# 需要交易者传入的参数
start_date = "2021-01-01"
end_date = "2021-10-25"
strategy_setting = [
    {
        "instruments": instruments,
        'start_date': start_date,
        'end_date': end_date,
    }    
]

md = M.hfbacktest.v1(start_date=start_date, #回测开始时间
                     end_date=end_date, #回测结束时间
                     instruments=instruments, #股票列表
                     capital_base=10000000, #初始资金
                     product_type=Product.EQUITY, #交易标的为股票
                     frequency=Frequency.MINUTE,  #回测频率
                     initialize=initialize,
                     before_trading_start=before_trading,
                     handle_order=handle_order,
                     handle_trade=handle_trade,
                     plot_charts=True, #画出回测结果分析图
                     disable_cache=1, #启用缓存加速
                     show_debug_info=0, #打印debug日志
                     strategy_setting=strategy_setting, #配置参数
                     slippage_type=SlippageType.FIXED,#滑点固定模式
                     slippage_value=0.01,#买卖双向各0.01个滑点
                     stock_t1=0, #0表示回测支持当天买和卖。1表示不支持t0
                     m_deps=np.random.rand() # 模块依赖,值相同的话会命中缓存
                     )
2021-10-28 20:49:55.248628 run trading v1.7.8_sp1 
2021-10-28 20:49:55.249226 init history datas... 
2021-10-28 20:49:55.309573 init trading env... 
2021-10-28 20:50:04.620664 send_order keep pending req=OrderReq(bkt000,600519.SHA,long,open,2500,1997.0,MARKET,0,strategy_20211028), dt=2021-01-04 15:00:00 
2021-10-28 20:50:04.628486 send_order keep pending req=OrderReq(bkt000,000001.SZA,long,open,268800,18.600000381469727,MARKET,0,strategy_20211028), dt=2021-01-04 15:00:00 
2021-10-28 20:50:22.199660 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,2500,2070.0,MARKET,0,strategy_20211028), dt=2021-01-21 15:00:00 
2021-10-28 20:50:27.569638 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,2400,2089.0,MARKET,0,strategy_20211028), dt=2021-01-27 15:00:00 
2021-10-28 20:51:04.968591 send_order keep pending req=OrderReq(bkt000,000001.SZA,short,close,108375,21.600000381469727,MARKET,0,strategy_20211028), dt=2021-03-15 15:00:00 
2021-10-28 20:51:08.738979 send_order keep pending req=OrderReq(bkt000,000001.SZA,long,open,242400,21.729999542236328,MARKET,0,strategy_20211028), dt=2021-03-18 15:00:00 
2021-10-28 20:51:21.159855 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,2500,2009.0,MARKET,0,strategy_20211028), dt=2021-03-31 15:00:00 
2021-10-28 20:51:32.556414 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,1175,2021.0,MARKET,0,strategy_20211028), dt=2021-04-13 15:00:00 
2021-10-28 20:51:33.813653 send_order keep pending req=OrderReq(bkt000,600519.SHA,long,open,2400,2047.0,MARKET,0,strategy_20211028), dt=2021-04-14 15:00:00 
2021-10-28 20:51:41.794405 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,2400,2055.5,MARKET,0,strategy_20211028), dt=2021-04-22 15:00:00 
2021-10-28 20:51:59.045356 send_order keep pending req=OrderReq(bkt000,000001.SZA,short,close,3925,23.06999969482422,MARKET,0,strategy_20211028), dt=2021-05-13 15:00:00 
2021-10-28 20:52:00.636809 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,2400,2009.8499755859375,MARKET,0,strategy_20211028), dt=2021-05-14 15:00:00 
2021-10-28 20:52:00.645674 send_order keep pending req=OrderReq(bkt000,000001.SZA,long,open,215200,23.31999969482422,MARKET,0,strategy_20211028), dt=2021-05-14 15:00:00 
2021-10-28 20:52:07.794145 send_order keep pending req=OrderReq(bkt000,000001.SZA,long,open,214400,23.489999771118164,MARKET,0,strategy_20211028), dt=2021-05-21 15:00:00 
2021-10-28 20:52:09.234080 send_order keep pending req=OrderReq(bkt000,000001.SZA,short,close,52275,23.479999542236328,MARKET,0,strategy_20211028), dt=2021-05-24 15:00:00 
2021-10-28 20:52:18.922024 send_order keep pending req=OrderReq(bkt000,000001.SZA,long,open,212400,23.889999389648438,MARKET,0,strategy_20211028), dt=2021-06-02 15:00:00 
2021-10-28 20:52:20.245965 send_order keep pending req=OrderReq(bkt000,000001.SZA,short,close,199625,23.770000457763672,MARKET,0,strategy_20211028), dt=2021-06-03 15:00:00 
2021-10-28 20:52:28.045960 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,2400,2178.81005859375,MARKET,0,strategy_20211028), dt=2021-06-11 15:00:00 
2021-10-28 20:52:40.449543 send_order keep pending req=OrderReq(bkt000,000001.SZA,short,close,28125,23.360000610351562,MARKET,0,strategy_20211028), dt=2021-06-25 15:00:00 
2021-10-28 20:52:51.181323 send_order keep pending req=OrderReq(bkt000,000001.SZA,short,close,55500,22.549999237060547,MARKET,0,strategy_20211028), dt=2021-07-07 15:00:00 
2021-10-28 20:53:23.982346 send_order keep pending req=OrderReq(bkt000,600519.SHA,long,open,2800,1799.0,MARKET,0,strategy_20211028), dt=2021-08-10 15:00:00 
2021-10-28 20:53:25.290687 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,1875,1750.5,MARKET,0,strategy_20211028), dt=2021-08-11 15:00:00 
2021-10-28 20:53:47.644994 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,3000,1618.800048828125,MARKET,0,strategy_20211028), dt=2021-09-02 15:00:00 
2021-10-28 20:54:02.170080 send_order keep pending req=OrderReq(bkt000,600519.SHA,long,open,2900,1638.0699462890625,MARKET,0,strategy_20211028), dt=2021-09-16 15:00:00 
2021-10-28 20:54:04.808442 send_order keep pending req=OrderReq(bkt000,600519.SHA,short,close,1850,1637.68994140625,MARKET,0,strategy_20211028), dt=2021-09-22 15:00:00 
2021-10-28 20:54:14.430971 send_order keep pending req=OrderReq(bkt000,000001.SZA,long,open,266500,18.639999389648438,MARKET,0,strategy_20211028), dt=2021-10-08 15:00:00 
  • 收益率3.6%
  • 年化收益率4.51%
  • 基准收益率-5.47%
  • 阿尔法0.07
  • 贝塔0.46
  • 夏普比率0.18
  • 胜率0.19
  • 盈亏比1.25
  • 收益波动率19.14%
  • 信息比率0.03
  • 最大回撤17.41%
bigcharts-data-start/{"__type":"tabs","__id":"bigchart-d2c56a78d8f940feb96336cb5d42b2f5"}/bigcharts-data-end