为什么自动交易时出错呢?

策略分享
标签: #<Tag:0x00007fcf67f435d8>

(ZjFy) #1
克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:options_data","SourceOutputPortId":"-86:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nclose_0\nlow_0\nmean(close_0,5)\nmean(close_0,10)\nmean(close_0,20)\nmean(close_0,40)\nmean(close_0,120)","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2018-06-13","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"600036.SHA\n000651.SZA\n600887.SHA\n000423.SZA\n002415.SZA\n000848.SZA\n002507.SZA\n600600.SHA\n601888.SHA\n000538.SZA\n600048.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-70","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-76","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v2","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-81","ModuleId":"BigQuantSpace.trade.trade-v3","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n today=data.current_dt.strftime('%Y-%m-%d')\n # 从context中读取已经获取的数据\n data_all=context.data_all\n # 有的个股当日停牌,选出当日未停牌的股票作为股票池\n instruments=list(data_all[data_all.date==today].instrument)\n # 获取当日的数据\n data_today=data_all[data_all.date==today] \n\n # 每天买入的股票量buy_num\n buy_num = 0\n # 操作 \n for k in instruments:\n \n sid = context.symbol(k) # 字符型股票代码转化成BigQuant回测引擎所需的股票代码\n price = data.current(sid, 'price') # 最新价格 \n mavg_10 = data_today[data_today.instrument==k]['mean(close_0,10)'].values[0]\n close_0 = data_today[data_today.instrument==k]['close_0'].values[0] \n cur_position = context.portfolio.positions[sid].amount # 持仓 \n cash = context.portfolio.cash # 现金\n \n # 卖出逻辑 - 上轨\n if close_0 > mavg_10 * 1.05 and cur_position > 0 and data.can_trade(sid): \n context.order_target_percent(sid, 0)\n # 买入逻辑 - 下轨\n elif close_0 < mavg_10 * 0.95 and cur_position == 0 and data.can_trade(sid) and buy_num<1: \n context.order(sid, np.floor(cash/price/100) * 100)\n buy_num=buy_num+1 \n ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n df = context.options['data'].read_df().reset_index()\n df['date'] = df['date'].apply(lambda x : x.strftime('%Y-%m-%d'))\n\n context.instruments=df.instrument.unique()\n context.data_all=df[['date','instrument','mean(close_0,10)','close_0']]\n #ss=context.data_all","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"后复权","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"amount_integer","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,19,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1074,119,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-70' Position='1078,234,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-76' Position='1076,325,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-81' Position='1036,545,200,200'/><NodePosition Node='-86' Position='1078,418,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":true}
    In [14]:
    # 本代码由可视化策略环境自动生成 2018年6月20日 08:18
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    close_0
    low_0
    mean(close_0,5)
    mean(close_0,10)
    mean(close_0,20)
    mean(close_0,40)
    mean(close_0,120)"""
    )
    
    m2 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2015-01-01'),
        end_date=T.live_run_param('trading_date', '2018-06-13'),
        market='CN_STOCK_A',
        instrument_list="""600036.SHA
    000651.SZA
    600887.SHA
    000423.SZA
    002415.SZA
    000848.SZA
    002507.SZA
    600600.SHA
    601888.SHA
    000538.SZA
    600048.SHA""",
        max_count=0
    )
    
    m3 = M.general_feature_extractor.v6(
        instruments=m2.data,
        features=m1.data,
        start_date='',
        end_date='',
        before_start_days=200
    )
    
    m4 = M.derived_feature_extractor.v2(
        input_data=m3.data,
        features=m1.data,
        date_col='date',
        instrument_col='instrument'
    )
    
    m6 = M.dropnan.v1(
        input_data=m4.data
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m5_handle_data_bigquant_run(context, data):
        
        today=data.current_dt.strftime('%Y-%m-%d')
        # 从context中读取已经获取的数据
        data_all=context.data_all
        # 有的个股当日停牌,选出当日未停牌的股票作为股票池
        instruments=list(data_all[data_all.date==today].instrument)
        # 获取当日的数据
        data_today=data_all[data_all.date==today]    
    
        # 每天买入的股票量buy_num
        buy_num = 0
        # 操作   
        for k in instruments:
            
            sid = context.symbol(k) # 字符型股票代码转化成BigQuant回测引擎所需的股票代码
            price = data.current(sid, 'price') # 最新价格        
            mavg_10 = data_today[data_today.instrument==k]['mean(close_0,10)'].values[0]
            close_0 =  data_today[data_today.instrument==k]['close_0'].values[0]        
            cur_position = context.portfolio.positions[sid].amount # 持仓    
            cash = context.portfolio.cash # 现金
            
            # 卖出逻辑 - 上轨
            if close_0 > mavg_10 * 1.05 and cur_position > 0 and data.can_trade(sid):  
                context.order_target_percent(sid, 0)
            # 买入逻辑 - 下轨
            elif close_0 < mavg_10 * 0.95 and cur_position == 0 and data.can_trade(sid) and buy_num<1: 
                context.order(sid, np.floor(cash/price/100) * 100)
                buy_num=buy_num+1        
       
    # 回测引擎:准备数据,只执行一次
    def m5_prepare_bigquant_run(context):
        # 加载预测数据
        df = context.options['data'].read_df().reset_index()
        df['date'] = df['date'].apply(lambda x : x.strftime('%Y-%m-%d'))
    
        context.instruments=df.instrument.unique()
        context.data_all=df[['date','instrument','mean(close_0,10)','close_0']]
        #ss=context.data_all
    # 回测引擎:初始化函数,只执行一次
    def m5_initialize_bigquant_run(context):
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    
    m5 = M.trade.v3(
        instruments=m2.data,
        options_data=m6.data,
        start_date='',
        end_date='',
        handle_data=m5_handle_data_bigquant_run,
        prepare=m5_prepare_bigquant_run,
        initialize=m5_initialize_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='open',
        capital_base=1000000,
        benchmark='000300.SHA',
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        plot_charts=True,
        backtest_only=False,
        amount_integer=False
    )
    
    [2018-06-14 17:26:47.459461] INFO: bigquant: input_features.v1 开始运行..
    [2018-06-14 17:26:47.475722] INFO: bigquant: 命中缓存
    [2018-06-14 17:26:47.477971] INFO: bigquant: input_features.v1 运行完成[0.019917s].
    [2018-06-14 17:26:47.500151] INFO: bigquant: instruments.v2 开始运行..
    [2018-06-14 17:26:47.504481] INFO: bigquant: 命中缓存
    [2018-06-14 17:26:47.505395] INFO: bigquant: instruments.v2 运行完成[0.005277s].
    [2018-06-14 17:26:47.546718] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2018-06-14 17:26:47.549344] INFO: bigquant: 命中缓存
    [2018-06-14 17:26:47.550273] INFO: bigquant: general_feature_extractor.v6 运行完成[0.003581s].
    [2018-06-14 17:26:47.564879] INFO: bigquant: derived_feature_extractor.v2 开始运行..
    [2018-06-14 17:26:47.568398] INFO: bigquant: 命中缓存
    [2018-06-14 17:26:47.570053] INFO: bigquant: derived_feature_extractor.v2 运行完成[0.005187s].
    [2018-06-14 17:26:47.579174] INFO: bigquant: dropnan.v1 开始运行..
    [2018-06-14 17:26:47.583173] INFO: bigquant: 命中缓存
    [2018-06-14 17:26:47.584294] INFO: bigquant: dropnan.v1 运行完成[0.005156s].
    [2018-06-14 17:26:47.737800] INFO: bigquant: backtest.v7 开始运行..
    [2018-06-14 17:26:47.742374] INFO: bigquant: 命中缓存
    
    • 收益率318.89%
    • 年化收益率53.68%
    • 基准收益率7.21%
    • 阿尔法0.51
    • 贝塔0.83
    • 夏普比率1.49
    • 胜率0.844
    • 盈亏比1.238
    • 收益波动率33.04%
    • 信息比率2.02
    • 最大回撤28.9%
    [2018-06-14 17:26:52.836419] INFO: bigquant: backtest.v7 运行完成[5.09863s].
    

    (达达) #2

    您是说模拟实盘没有发出信号么?


    (ZjFy) #3

    [2018-06-21 03:30:05.802414] INFO: forward_test: last record: None
    [2018-06-21 03:30:05.806265] INFO: forward_test: today record: None
    [2018-06-21 03:30:05.809384] INFO: forward_test: first record: None
    [2018-06-21 03:30:05.959500] INFO: algo: set price type:backward_adjusted
    [2018-06-21 03:30:06.033674] ERROR: forward_test: hit Exception, e The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    Traceback (most recent call last):
    File “”, line 254, in run
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

    ValueError Traceback (most recent call last)
    in ()
    111 plot_charts=True,
    112 backtest_only=False,
    –> 113 amount_integer=False
    114 )

    /var/app/enabled/biglearning/module2/common/modulemanagerv2.py in call(self, **kwargs)

    /var/app/enabled/biglearning/module2/common/moduleinvoker.py in module_invoke(name, version, kwargs)

    /var/app/enabled/biglearning/module2/common/moduleinvoker.py in _invoke_with_cache(module, kwargs, module_cache_key, name, version)

    /var/app/enabled/biglearning/module2/common/moduleinvoker.py in _module_run(module, kwargs)

    /var/app/enabled/biglearning/module2/modules/trade/v3/init.py in bigquant_run(start_date, end_date, handle_data, instruments, prepare, initialize, before_trading_start, volume_limit, order_price_field_buy, order_price_field_sell, capital_base, benchmark, auto_cancel_non_tradable_orders, data_frequency, price_type, plot_charts, backtest_only, options_data, options, amount_integer, m_meta_kwargs)

    /var/app/enabled/biglearning/module2/modules/trade/v3/init.py in do_live_run(env)

    /var/app/enabled/biglearning/module2/common/modulemanagerv2.py in call(self, **kwargs)

    /var/app/enabled/biglearning/module2/common/moduleinvoker.py in module_invoke(name, version, kwargs)

    /var/app/enabled/biglearning/module2/common/moduleinvoker.py in _invoke_with_cache(module, kwargs, module_cache_key, name, version)

    /var/app/enabled/biglearning/module2/common/moduleinvoker.py in _module_run(module, kwargs)

    /var/app/enabled/biglearning/module2/modules/forward_test/v5/init.py in run(self)

    /var/app/enabled/biglearning/module2/modules/forward_test/v5/init.py in run(self)

    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


    (达达) #4

    context.instruments=df.instrument.unique()这句改成context.instruments=list(df.instrument.unique()),传入的必须是list


    (ZjFy) #5

    好的,我今天改下 试试,只有等星期一 才能看到结果吧