超参搜索报错

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

(hooou) #1
克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-128:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-96:sort_by_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-103:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-121:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1933:instrument_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-96:input_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-181:input_data","SourceOutputPortId":"-121:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-128:data"},{"DestinationInputPortId":"-128:input_data","SourceOutputPortId":"-181:data"},{"DestinationInputPortId":"-421:options_data","SourceOutputPortId":"-96:sorted_data"},{"DestinationInputPortId":"-1933:prediction_ds","SourceOutputPortId":"-96:sorted_data"},{"DestinationInputPortId":"-121:features","SourceOutputPortId":"-103:data"},{"DestinationInputPortId":"-421:instruments","SourceOutputPortId":"-1933:data_1"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"#rank(market_cap_float_0)\n#rank_turn_5\n#((close_0-open_0)/((high_0-low_0)+.001))\nclose_9/close_0\n","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":3,"IsPartOfPartialRun":null,"Comment":"在这里输入因子","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2018-02-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-09-17","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","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":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"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":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-121","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-121"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-121"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-121","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-128","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-128"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-128"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-128","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-181","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"st_status_0==0","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_left_data","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-181"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-181","OutputType":null},{"Name":"left_data","NodeId":"-181","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":26,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-96","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-96"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-96"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-96","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"传统选股,基于规则打分,选择靠前的股票","CommentCollapsed":false},{"Id":"-103","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"st_status_0\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-103"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-103","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"用于过滤ST股票的特征","CommentCollapsed":false},{"Id":"-152","ModuleId":"BigQuantSpace.comments.comments-v1","ModuleParameters":[],"InputPortsInternal":[],"OutputPortsInternal":[],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"AI","CommentCollapsed":false},{"Id":"-153","ModuleId":"BigQuantSpace.comments.comments-v1","ModuleParameters":[],"InputPortsInternal":[],"OutputPortsInternal":[],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"传统方法","CommentCollapsed":false},{"Id":"-421","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n print('------------ 传统方法/升序方向 ------------')\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 1\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 1\n context.options['hold_days'] = 1\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.options['hold_days']\n cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)\n cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])\n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy_instruments):\n cash = cash_for_buy * buy_cash_weights[i]\n if cash > max_cash_per_instrument - positions.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions.get(instrument, 0)\n if cash > 0:\n context.order_value(context.symbol(instrument), cash)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\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":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-421"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-421","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1933","ModuleId":"BigQuantSpace.filter_instruments_with_predictions.filter_instruments_with_predictions-v3","ModuleParameters":[{"Name":"count","Value":"5","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instrument_ds","NodeId":"-1933"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"prediction_ds","NodeId":"-1933"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-1933","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-12267","ModuleId":"BigQuantSpace.hyper_parameter_search.hyper_parameter_search-v1","ModuleParameters":[{"Name":"param_grid_builder","Value":"def bigquant_run():\n param_grid = {}\n # 在这里设置需要调优的参数备选\n param_grid['m3.features'] =[\"((close_0-low_0)-(high_0-close_0))/(high_0-close_0)\",\n\"(high_0-low_0+high_1-low_1+high_2-low_2)/close_0\",\n\"mean(close_0,6)/close_0\"]\n \n # param_grid['m6.number_of_trees'] = [5, 10, 20]\n\n return param_grid\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"scoring","Value":"def bigquant_run(result):\n #m19.raw_perf.read_df()['algorithm_period_return'][-1]\n #m19.read_raw_perf()['algorithm_period_return'][-1]\n #m19.read_raw_perf()['sharpe'].tail(1)[0]\n score = result.get('m19').read_raw_perf()['sharpe'].tail(1)[0]\n return score\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"search_algorithm","Value":"网格搜索","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"search_iterations","Value":10,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"workers","Value":"3","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"worker_distributed_run","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"worker_silent","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"run_now","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"bq_graph","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"bq_graph_port","NodeId":"-12267"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-12267"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-12267"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-12267"}],"OutputPortsInternal":[{"Name":"result","NodeId":"-12267","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":2,"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='532,-192,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='945,25,200,200'/><NodePosition Node='-86' Position='524,716,200,200'/><NodePosition Node='-121' Position='595,266,200,200'/><NodePosition Node='-128' Position='471,597,200,200'/><NodePosition Node='-181' Position='635,416,200,200'/><NodePosition Node='-96' Position='821,844,200,200'/><NodePosition Node='-103' Position='512,-12,200,200'/><NodePosition Node='-152' Position='-37,-103,200,200'/><NodePosition Node='-153' Position='995,-97,200,200'/><NodePosition Node='-421' Position='565,1102,200,200'/><NodePosition Node='-1933' Position='463,932,200,200'/><NodePosition Node='-12267' Position='61,113,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 [1]:
    # 本代码由可视化策略环境自动生成 2019年9月19日 18:48
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m19_initialize_bigquant_run(context):
        print('------------ 传统方法/升序方向 ------------')
        # 加载预测数据
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        stock_count = 1
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 1
        context.options['hold_days'] = 1
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
    
        # 1. 资金分配
        # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
        # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
        is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
        cash_avg = context.portfolio.portfolio_value / context.options['hold_days']
        cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
        cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
        if not is_staging and cash_for_sell > 0:
            equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
            instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                    lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
            # print('rank order for sell %s' % instruments)
            for instrument in instruments:
                context.order_target(context.symbol(instrument), 0)
                cash_for_sell -= positions[instrument]
                if cash_for_sell <= 0:
                    break
    
        # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
        buy_cash_weights = context.stock_weights
        buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
        max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
        for i, instrument in enumerate(buy_instruments):
            cash = cash_for_buy * buy_cash_weights[i]
            if cash > max_cash_per_instrument - positions.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
                cash = max_cash_per_instrument - positions.get(instrument, 0)
            if cash > 0:
                context.order_value(context.symbol(instrument), cash)
    
    # 回测引擎:准备数据,只执行一次
    def m19_prepare_bigquant_run(context):
        pass
    
    
    g = T.Graph({
    
        'm3': 'M.input_features.v1',
        'm3.features': """#rank(market_cap_float_0)
    #rank_turn_5
    #((close_0-open_0)/((high_0-low_0)+.001))
    close_9/close_0
    """,
    
        'm1': 'M.input_features.v1',
        'm1.features_ds': T.Graph.OutputPort('m3.data'),
        'm1.features': """st_status_0
    """,
    
        'm9': 'M.instruments.v2',
        'm9.start_date': T.live_run_param('trading_date', '2018-02-01'),
        'm9.end_date': T.live_run_param('trading_date', '2019-09-17'),
        'm9.market': 'CN_STOCK_A',
        'm9.instrument_list': '',
        'm9.max_count': 0,
    
        'm17': 'M.general_feature_extractor.v7',
        'm17.instruments': T.Graph.OutputPort('m9.data'),
        'm17.features': T.Graph.OutputPort('m1.data'),
        'm17.start_date': '',
        'm17.end_date': '',
        'm17.before_start_days': 30,
    
        'm26': 'M.filter.v3',
        'm26.input_data': T.Graph.OutputPort('m17.data'),
        'm26.expr': 'st_status_0==0',
        'm26.output_left_data': False,
    
        'm18': 'M.derived_feature_extractor.v3',
        'm18.input_data': T.Graph.OutputPort('m26.data'),
        'm18.features': T.Graph.OutputPort('m3.data'),
        'm18.date_col': 'date',
        'm18.instrument_col': 'instrument',
        'm18.drop_na': False,
        'm18.remove_extra_columns': False,
    
        'm14': 'M.dropnan.v1',
        'm14.input_data': T.Graph.OutputPort('m18.data'),
    
        'm7': 'M.sort.v4',
        'm7.input_ds': T.Graph.OutputPort('m14.data'),
        'm7.sort_by_ds': T.Graph.OutputPort('m3.data'),
        'm7.sort_by': '--',
        'm7.group_by': 'date',
        'm7.keep_columns': 'date,instrument',
        'm7.ascending': True,
    
        'm6': 'M.filter_instruments_with_predictions.v3',
        'm6.instrument_ds': T.Graph.OutputPort('m9.data'),
        'm6.prediction_ds': T.Graph.OutputPort('m7.sorted_data'),
        'm6.count': 5,
    
        'm19': 'M.trade.v4',
        'm19.instruments': T.Graph.OutputPort('m6.data_1'),
        'm19.options_data': T.Graph.OutputPort('m7.sorted_data'),
        'm19.start_date': '',
        'm19.end_date': '',
        'm19.initialize': m19_initialize_bigquant_run,
        'm19.handle_data': m19_handle_data_bigquant_run,
        'm19.prepare': m19_prepare_bigquant_run,
        'm19.volume_limit': 0.025,
        'm19.order_price_field_buy': 'open',
        'm19.order_price_field_sell': 'close',
        'm19.capital_base': 1000000,
        'm19.auto_cancel_non_tradable_orders': True,
        'm19.data_frequency': 'daily',
        'm19.price_type': '后复权',
        'm19.product_type': '股票',
        'm19.plot_charts': True,
        'm19.backtest_only': False,
        'm19.benchmark': '000300.SHA',
    
        'm5': 'M.comments.v1',
    
        'm13': 'M.comments.v1',
    })
    
    # g.run({})
    
    
    def m2_param_grid_builder_bigquant_run():
        param_grid = {}
        # 在这里设置需要调优的参数备选
        param_grid['m3.features'] =["((close_0-low_0)-(high_0-close_0))/(high_0-close_0)",
    "(high_0-low_0+high_1-low_1+high_2-low_2)/close_0",
    "mean(close_0,6)/close_0"]
        
        # param_grid['m6.number_of_trees'] = [5, 10, 20]
    
        return param_grid
    
    def m2_scoring_bigquant_run(result):
        #m19.raw_perf.read_df()['algorithm_period_return'][-1]
        #m19.read_raw_perf()['algorithm_period_return'][-1]
        #m19.read_raw_perf()['sharpe'].tail(1)[0]
        score = result.get('m19').read_raw_perf()['sharpe'].tail(1)[0]
        return score
    
    
    m2 = M.hyper_parameter_search.v1(
        param_grid_builder=m2_param_grid_builder_bigquant_run,
        scoring=m2_scoring_bigquant_run,
        search_algorithm='网格搜索',
        search_iterations=10,
        workers=3,
        worker_distributed_run=True,
        worker_silent=True,
        run_now=True,
        bq_graph=g
    )
    
    Fitting 1 folds for each of 3 candidates, totalling 3 fits
    [Parallel(n_jobs=3)]: Using backend ThreadingBackend with 3 concurrent workers.
    [CV] m3.features=((close_0-low_0)-(high_0-close_0))/(high_0-close_0) .
    [CV] m3.features=(high_0-low_0+high_1-low_1+high_2-low_2)/close_0 ....
    [CV] m3.features=mean(close_0,6)/close_0 .............................
    
    ('error_help error: ', AttributeError("'NoneType' object has no attribute 'get'",))
    [CV]  m3.features=(high_0-low_0+high_1-low_1+high_2-low_2)/close_0, score=-inf, total=  18.4s
    [Parallel(n_jobs=3)]: Done   1 tasks      | elapsed:   18.4s
    
    ('error_help error: ', AttributeError("'NoneType' object has no attribute 'get'",))
    [CV] .. m3.features=mean(close_0,6)/close_0, score=-inf, total=  34.7s
    ('error_help error: ', AttributeError("'NoneType' object has no attribute 'get'",))
    [CV]  m3.features=((close_0-low_0)-(high_0-close_0))/(high_0-close_0), score=-inf, total=  34.8s
    [Parallel(n_jobs=3)]: Done   3 out of   3 | elapsed:   34.8s remaining:    0.0s
    [Parallel(n_jobs=3)]: Done   3 out of   3 | elapsed:   34.8s finished
    
    ('error_help error: ', AttributeError("'NoneType' object has no attribute 'get'",))
    
    In [14]:
    #m19.raw_perf.read_df()['algorithm_period_return'][-1]
    #m19.read_raw_perf()['algorithm_period_return'][-1]
    #m19.read_raw_perf()['sharpe'].tail(1)[0]
    
    In [1]:
    import numpy as np
    import pandas as p
    #print(m2.result.best_params_,"\n",m2.result.best_score_)
    #print(m2.result.cv_results_)
    e=m2.result.cv_results_
    matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]]);
    #test_dict_df = pd.DataFrame(e)
    test_dict_df = pd.DataFrame(data=e,columns=['param_m3.features','mean_test_score'])
    test_dict_df=test_dict_df.set_index('param_m3.features')
    b=test_dict_df.sort_values(by='mean_test_score',ascending=False)
    test_dict_df
    
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-1-225a5603f942> in <module>()
          3 #print(m2.result.best_params_,"\n",m2.result.best_score_)
          4 #print(m2.result.cv_results_)
    ----> 5 e=m2.result.cv_results_
          6 matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]]);
          7 #test_dict_df = pd.DataFrame(e)
    
    NameError: name 'm2' is not defined
    In [ ]:
    #m19.raw_perf.read_df()['algorithm_period_return'][-1]
    
    In [ ]:
     
    

    (达达) #2

    并行作业数1

    克隆策略

      {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-128:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-96:sort_by_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-103:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-121:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1933:instrument_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-96:input_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-181:input_data","SourceOutputPortId":"-121:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-128:data"},{"DestinationInputPortId":"-128:input_data","SourceOutputPortId":"-181:data"},{"DestinationInputPortId":"-421:options_data","SourceOutputPortId":"-96:sorted_data"},{"DestinationInputPortId":"-1933:prediction_ds","SourceOutputPortId":"-96:sorted_data"},{"DestinationInputPortId":"-121:features","SourceOutputPortId":"-103:data"},{"DestinationInputPortId":"-421:instruments","SourceOutputPortId":"-1933:data_1"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"#rank(market_cap_float_0)\n#rank_turn_5\n#((close_0-open_0)/((high_0-low_0)+.001))\nclose_9/close_0","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":3,"IsPartOfPartialRun":null,"Comment":"在这里输入因子","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2018-02-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-09-17","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","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":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"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":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-121","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-121"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-121"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-121","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-128","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-128"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-128"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-128","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-181","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"st_status_0==0","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_left_data","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-181"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-181","OutputType":null},{"Name":"left_data","NodeId":"-181","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":26,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-96","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-96"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-96"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-96","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"传统选股,基于规则打分,选择靠前的股票","CommentCollapsed":false},{"Id":"-103","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"st_status_0\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-103"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-103","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"用于过滤ST股票的特征","CommentCollapsed":false},{"Id":"-421","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n print('------------ 传统方法/升序方向 ------------')\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 1\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 1\n context.options['hold_days'] = 1\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.options['hold_days']\n cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)\n cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])\n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy_instruments):\n cash = cash_for_buy * buy_cash_weights[i]\n if cash > max_cash_per_instrument - positions.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions.get(instrument, 0)\n if cash > 0:\n context.order_value(context.symbol(instrument), cash)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\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":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-421"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-421"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-421","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1933","ModuleId":"BigQuantSpace.filter_instruments_with_predictions.filter_instruments_with_predictions-v3","ModuleParameters":[{"Name":"count","Value":"5","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instrument_ds","NodeId":"-1933"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"prediction_ds","NodeId":"-1933"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-1933","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-12267","ModuleId":"BigQuantSpace.hyper_parameter_search.hyper_parameter_search-v1","ModuleParameters":[{"Name":"param_grid_builder","Value":"def bigquant_run():\n param_grid = {}\n # 在这里设置需要调优的参数备选\n param_grid['m3.features'] =[\"((close_0-low_0)-(high_0-close_0))/(high_0-close_0)\",\n\"(high_0-low_0+high_1-low_1+high_2-low_2)/close_0\",\n\"mean(close_0,6)/close_0\"]\n \n # param_grid['m6.number_of_trees'] = [5, 10, 20]\n\n return param_grid\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"scoring","Value":"def bigquant_run(result):\n #m19.raw_perf.read_df()['algorithm_period_return'][-1]\n #m19.read_raw_perf()['algorithm_period_return'][-1]\n #m19.read_raw_perf()['sharpe'].tail(1)[0]\n score = result.get('m19').read_raw_perf()['sharpe'].tail(1)[0]\n return score\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"search_algorithm","Value":"网格搜索","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"search_iterations","Value":10,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"workers","Value":"1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"worker_distributed_run","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"worker_silent","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"run_now","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"bq_graph","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"bq_graph_port","NodeId":"-12267"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-12267"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-12267"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-12267"}],"OutputPortsInternal":[{"Name":"result","NodeId":"-12267","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":2,"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='532,-192,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='945,25,200,200'/><NodePosition Node='-86' Position='524,717.8731079101562,200,200'/><NodePosition Node='-121' Position='595,266,200,200'/><NodePosition Node='-128' Position='471,597,200,200'/><NodePosition Node='-181' Position='635,416,200,200'/><NodePosition Node='-96' Position='821,845.8731079101562,200,200'/><NodePosition Node='-103' Position='512,-12,200,200'/><NodePosition Node='-421' Position='565,1102,200,200'/><NodePosition Node='-1933' Position='463,932,200,200'/><NodePosition Node='-12267' Position='61,113,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 [1]:
      # 本代码由可视化策略环境自动生成 2019年9月20日 09:15
      # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
      
      
      # 回测引擎:初始化函数,只执行一次
      def m19_initialize_bigquant_run(context):
          print('------------ 传统方法/升序方向 ------------')
          # 加载预测数据
          context.ranker_prediction = context.options['data'].read_df()
      
          # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
          context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
          # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
          # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
          stock_count = 1
          # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
          context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])
          # 设置每只股票占用的最大资金比例
          context.max_cash_per_instrument = 1
          context.options['hold_days'] = 1
      
      # 回测引擎:每日数据处理函数,每天执行一次
      def m19_handle_data_bigquant_run(context, data):
          # 按日期过滤得到今日的预测数据
          ranker_prediction = context.ranker_prediction[
              context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
      
          # 1. 资金分配
          # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
          # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
          is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
          cash_avg = context.portfolio.portfolio_value / context.options['hold_days']
          cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
          cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
          positions = {e.symbol: p.amount * p.last_sale_price
                       for e, p in context.perf_tracker.position_tracker.positions.items()}
      
          # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
          if not is_staging and cash_for_sell > 0:
              equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
              instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                      lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
              # print('rank order for sell %s' % instruments)
              for instrument in instruments:
                  context.order_target(context.symbol(instrument), 0)
                  cash_for_sell -= positions[instrument]
                  if cash_for_sell <= 0:
                      break
      
          # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
          buy_cash_weights = context.stock_weights
          buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
          max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
          for i, instrument in enumerate(buy_instruments):
              cash = cash_for_buy * buy_cash_weights[i]
              if cash > max_cash_per_instrument - positions.get(instrument, 0):
                  # 确保股票持仓量不会超过每次股票最大的占用资金量
                  cash = max_cash_per_instrument - positions.get(instrument, 0)
              if cash > 0:
                  context.order_value(context.symbol(instrument), cash)
      
      # 回测引擎:准备数据,只执行一次
      def m19_prepare_bigquant_run(context):
          pass
      
      
      g = T.Graph({
      
          'm3': 'M.input_features.v1',
          'm3.features': """#rank(market_cap_float_0)
      #rank_turn_5
      #((close_0-open_0)/((high_0-low_0)+.001))
      close_9/close_0""",
      
          'm1': 'M.input_features.v1',
          'm1.features_ds': T.Graph.OutputPort('m3.data'),
          'm1.features': """st_status_0
      """,
      
          'm9': 'M.instruments.v2',
          'm9.start_date': T.live_run_param('trading_date', '2018-02-01'),
          'm9.end_date': T.live_run_param('trading_date', '2019-09-17'),
          'm9.market': 'CN_STOCK_A',
          'm9.instrument_list': '',
          'm9.max_count': 0,
      
          'm17': 'M.general_feature_extractor.v7',
          'm17.instruments': T.Graph.OutputPort('m9.data'),
          'm17.features': T.Graph.OutputPort('m1.data'),
          'm17.start_date': '',
          'm17.end_date': '',
          'm17.before_start_days': 30,
      
          'm26': 'M.filter.v3',
          'm26.input_data': T.Graph.OutputPort('m17.data'),
          'm26.expr': 'st_status_0==0',
          'm26.output_left_data': False,
      
          'm18': 'M.derived_feature_extractor.v3',
          'm18.input_data': T.Graph.OutputPort('m26.data'),
          'm18.features': T.Graph.OutputPort('m3.data'),
          'm18.date_col': 'date',
          'm18.instrument_col': 'instrument',
          'm18.drop_na': False,
          'm18.remove_extra_columns': False,
      
          'm14': 'M.dropnan.v1',
          'm14.input_data': T.Graph.OutputPort('m18.data'),
      
          'm7': 'M.sort.v4',
          'm7.input_ds': T.Graph.OutputPort('m14.data'),
          'm7.sort_by_ds': T.Graph.OutputPort('m3.data'),
          'm7.sort_by': '--',
          'm7.group_by': 'date',
          'm7.keep_columns': 'date,instrument',
          'm7.ascending': True,
      
          'm6': 'M.filter_instruments_with_predictions.v3',
          'm6.instrument_ds': T.Graph.OutputPort('m9.data'),
          'm6.prediction_ds': T.Graph.OutputPort('m7.sorted_data'),
          'm6.count': 5,
      
          'm19': 'M.trade.v4',
          'm19.instruments': T.Graph.OutputPort('m6.data_1'),
          'm19.options_data': T.Graph.OutputPort('m7.sorted_data'),
          'm19.start_date': '',
          'm19.end_date': '',
          'm19.initialize': m19_initialize_bigquant_run,
          'm19.handle_data': m19_handle_data_bigquant_run,
          'm19.prepare': m19_prepare_bigquant_run,
          'm19.volume_limit': 0.025,
          'm19.order_price_field_buy': 'open',
          'm19.order_price_field_sell': 'close',
          'm19.capital_base': 1000000,
          'm19.auto_cancel_non_tradable_orders': True,
          'm19.data_frequency': 'daily',
          'm19.price_type': '后复权',
          'm19.product_type': '股票',
          'm19.plot_charts': True,
          'm19.backtest_only': False,
          'm19.benchmark': '000300.SHA',
      })
      
      # g.run({})
      
      
      def m2_param_grid_builder_bigquant_run():
          param_grid = {}
          # 在这里设置需要调优的参数备选
          param_grid['m3.features'] =["((close_0-low_0)-(high_0-close_0))/(high_0-close_0)",
      "(high_0-low_0+high_1-low_1+high_2-low_2)/close_0",
      "mean(close_0,6)/close_0"]
          
          # param_grid['m6.number_of_trees'] = [5, 10, 20]
      
          return param_grid
      
      def m2_scoring_bigquant_run(result):
          #m19.raw_perf.read_df()['algorithm_period_return'][-1]
          #m19.read_raw_perf()['algorithm_period_return'][-1]
          #m19.read_raw_perf()['sharpe'].tail(1)[0]
          score = result.get('m19').read_raw_perf()['sharpe'].tail(1)[0]
          return score
      
      
      m2 = M.hyper_parameter_search.v1(
          param_grid_builder=m2_param_grid_builder_bigquant_run,
          scoring=m2_scoring_bigquant_run,
          search_algorithm='网格搜索',
          search_iterations=10,
          workers=1,
          worker_distributed_run=True,
          worker_silent=True,
          run_now=True,
          bq_graph=g
      )
      
      Fitting 1 folds for each of 3 candidates, totalling 3 fits
      [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
      [CV] m3.features=((close_0-low_0)-(high_0-close_0))/(high_0-close_0) .
      [CV]  m3.features=((close_0-low_0)-(high_0-close_0))/(high_0-close_0), score=-0.2138862676305877, total=  26.5s
      [Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:   26.6s remaining:    0.0s
      [CV] m3.features=(high_0-low_0+high_1-low_1+high_2-low_2)/close_0 ....
      [CV]  m3.features=(high_0-low_0+high_1-low_1+high_2-low_2)/close_0, score=-5.073401855632176, total=  21.1s
      [Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:   47.9s remaining:    0.0s
      [CV] m3.features=mean(close_0,6)/close_0 .............................
      [CV]  m3.features=mean(close_0,6)/close_0, score=-0.4025051979794357, total=  16.3s
      [Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:  1.1min remaining:    0.0s
      [Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:  1.1min finished
      
      In [2]:
      #m19.raw_perf.read_df()['algorithm_period_return'][-1]
      #m19.read_raw_perf()['algorithm_period_return'][-1]
      #m19.read_raw_perf()['sharpe'].tail(1)[0]
      
      In [3]:
      import numpy as np
      import pandas as p
      #print(m2.result.best_params_,"\n",m2.result.best_score_)
      #print(m2.result.cv_results_)
      e=m2.result.cv_results_
      matrix = numpy.array([[3,6,9,11],[2,4,8,10],[1,5,7,9]]);
      #test_dict_df = pd.DataFrame(e)
      test_dict_df = pd.DataFrame(data=e,columns=['param_m3.features','mean_test_score'])
      test_dict_df=test_dict_df.set_index('param_m3.features')
      b=test_dict_df.sort_values(by='mean_test_score',ascending=False)
      test_dict_df
      
      Out[3]:
      mean_test_score
      param_m3.features
      ((close_0-low_0)-(high_0-close_0))/(high_0-close_0) -0.213886
      (high_0-low_0+high_1-low_1+high_2-low_2)/close_0 -5.073402
      mean(close_0,6)/close_0 -0.402505
      In [ ]:
      #m19.raw_perf.read_df()['algorithm_period_return'][-1]
      
      In [ ]: