回测没问题,因子分析时出错

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

(Shadowder) #1
克隆策略

    {"Description":"实验创建于2019/1/21","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-60:instruments","SourceOutputPortId":"-5:data"},{"DestinationInputPortId":"-370:instruments","SourceOutputPortId":"-5:data"},{"DestinationInputPortId":"-648:input_data","SourceOutputPortId":"-60:data"},{"DestinationInputPortId":"-540:input_ds","SourceOutputPortId":"-519:data"},{"DestinationInputPortId":"-139:input_data","SourceOutputPortId":"-540:data"},{"DestinationInputPortId":"-519:input_data","SourceOutputPortId":"-546:data"},{"DestinationInputPortId":"-370:options_data","SourceOutputPortId":"-576:sorted_data"},{"DestinationInputPortId":"-98:user_factor_data","SourceOutputPortId":"-576:sorted_data"},{"DestinationInputPortId":"-546:input_data","SourceOutputPortId":"-648:data"},{"DestinationInputPortId":"-60:features","SourceOutputPortId":"-13:data"},{"DestinationInputPortId":"-546:features","SourceOutputPortId":"-13:data"},{"DestinationInputPortId":"-576:input_ds","SourceOutputPortId":"-139:data"},{"DestinationInputPortId":"-519:features","SourceOutputPortId":"-142:data"},{"DestinationInputPortId":"-98:features","SourceOutputPortId":"-108:data"}],"ModuleNodes":[{"Id":"-5","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2012-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"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":"-5"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-60","ModuleId":"BigQuantSpace.general_feature_extractor_vx1.general_feature_extractor_vx1-v1","ModuleParameters":[{"Name":"start_date","Value":"2012-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-60"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-60"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-60","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-519","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":"-519"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-519"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-519","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-540","ModuleId":"BigQuantSpace.select_columns.select_columns-v3","ModuleParameters":[{"Name":"columns","Value":"date,instrument,degree","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"reverse_select","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-540"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"columns_ds","NodeId":"-540"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-540","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-546","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":"-546"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-546"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-546","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-576","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"degree","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-576"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-576"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-576","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":20,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-370","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\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0003, min_cost=0))\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 回测引擎:每日数据处理函数,每天执行一次\n today = data.current_dt.strftime('%Y-%m-%d') # 日期\n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表和对应的最新市值\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 记录用于买入股票的可用现金\n cash_for_buy = context.portfolio.cash\n \n # 获取当日符合买入/卖出条件的股票列表\n try:\n buy_stock = context.daily_buy_stock[today] # 当日符合买入条件的股票\n except:\n buy_stock=[]\n try:\n sell_stock = context.daily_sell_stock[today] # 当日符合卖出条件的股票\n except:\n sell_stock = []\n\n # 需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [i for i in stock_hold_now if i in sell_stock]\n # 需要买入的股票:没有持仓且符合买入条件的股票\n stock_to_buy = [i for i in buy_stock if i not in stock_hold_now]\n # 卖出\n for instrument in stock_to_sell:\n # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态\n # 如果返回真值,则可以正常下单,否则会出错\n # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式\n if data.can_trade(context.symbol(instrument)):\n # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,即卖出全部股票,可参考回测文档\n context.order_target_percent(context.symbol(instrument), 0)\n # 开盘卖出后所得资金可用来买入股票,更新当日可用现金\n cash_for_buy += stock_hold_now[instrument]\n \n # 如果当天没有买入的股票,就返回\n if len(stock_to_buy) == 0:\n return\n \n # 买入\n count=0\n for instrument in stock_to_buy:\n if data.can_trade(context.symbol(instrument)):\n count=count+1\n # 利用当日可用现金使用等资金比例下单买入\n for instrument in stock_to_buy:\n cash = cash_for_buy / count\n if data.can_trade(context.symbol(instrument)):\n current_price = data.current(context.symbol(instrument), 'price')\n amount = math.floor(cash / current_price)\n context.order(context.symbol(instrument), amount)","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n df = context.options['data'].read_df()\n # 函数:求满足开仓条件的股票列表\n def open_pos_con(df):\n return list(df.instrument)[:200]\n\n # 函数:求满足平仓条件的股票列表\n def close_pos_con(df):\n return list(df.instrument)[200:]\n \n # 每日买入股票的数据框\n context.daily_buy_stock= df.groupby('date').apply(open_pos_con)\n # 每日卖出股票的数据框\n context.daily_sell_stock= df.groupby('date').apply(close_pos_con) \n \n \n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":"","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":"100000","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":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-370"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-370"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-370"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-370"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-370"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-370","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":21,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-648","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-648"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-648","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-13","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\n#(close_0-close_1)/close_1\nstock_return=return_0-1\nbenchmark_return=group_sum(date, return_0-1)/group_sum(date,1)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-13"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-13","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-139","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-139"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-139","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-142","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\ndegree=correlation(benchmark_return,stock_return,60)-1/group_sum(date,1)","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-142"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-142","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-98","ModuleId":"BigQuantSpace.factorlens.factorlens-v1","ModuleParameters":[{"Name":"title","Value":"因子分析: {factor_name}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"2012-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"rebalance_period","Value":"6","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"stock_pool","Value":"全部","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"quantile_count","Value":"5","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"commission_rate","Value":"0.003","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_price_limit_stocks","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_st_stocks","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_new_stocks","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"neutralization","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E8%A1%8C%E4%B8%9A%22%2C%22displayValue%22%3A%22%E8%A1%8C%E4%B8%9A%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E5%B8%82%E5%80%BC%22%2C%22displayValue%22%3A%22%E5%B8%82%E5%80%BC%22%2C%22selected%22%3Atrue%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-98"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"user_factor_data","NodeId":"-98"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-98","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-108","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\ndegree\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-108"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-108","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"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='-5' Position='-432,-94,200,200'/><NodePosition Node='-60' Position='-436,58,200,200'/><NodePosition Node='-519' Position='-454,497,200,200'/><NodePosition Node='-540' Position='-439,656,200,200'/><NodePosition Node='-546' Position='-461,337,200,200'/><NodePosition Node='-576' Position='-426,901,200,200'/><NodePosition Node='-370' Position='-481,1083,200,200'/><NodePosition Node='-648' Position='-442,171,200,200'/><NodePosition Node='-13' Position='-95,-85,200,200'/><NodePosition Node='-139' Position='-433,786,200,200'/><NodePosition Node='-142' Position='-136,347,200,200'/><NodePosition Node='-98' Position='81,1040,200,200'/><NodePosition Node='-108' Position='369,860,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 [97]:
    # 本代码由可视化策略环境自动生成 2020年2月2日 01:26
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m21_initialize_bigquant_run(context):
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0003, min_cost=0))
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m21_handle_data_bigquant_run(context, data):
        # 回测引擎:每日数据处理函数,每天执行一次
        today = data.current_dt.strftime('%Y-%m-%d') # 日期
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表和对应的最新市值
        stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        # 记录用于买入股票的可用现金
        cash_for_buy = context.portfolio.cash
        
        # 获取当日符合买入/卖出条件的股票列表
        try:
            buy_stock = context.daily_buy_stock[today]  # 当日符合买入条件的股票
        except:
            buy_stock=[]
        try:
            sell_stock = context.daily_sell_stock[today]  # 当日符合卖出条件的股票
        except:
            sell_stock = []
    
        # 需要卖出的股票:已有持仓中符合卖出条件的股票
        stock_to_sell = [i for i in stock_hold_now if i in sell_stock]
        # 需要买入的股票:没有持仓且符合买入条件的股票
        stock_to_buy = [i for i in buy_stock if i not in stock_hold_now]
        # 卖出
        for instrument in stock_to_sell:
            # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态
            # 如果返回真值,则可以正常下单,否则会出错
            # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式
            if data.can_trade(context.symbol(instrument)):
                # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,即卖出全部股票,可参考回测文档
                context.order_target_percent(context.symbol(instrument), 0)
                # 开盘卖出后所得资金可用来买入股票,更新当日可用现金
                cash_for_buy += stock_hold_now[instrument]
                
        # 如果当天没有买入的股票,就返回
        if len(stock_to_buy) == 0:
            return
        
        # 买入
        count=0
        for instrument in stock_to_buy:
            if data.can_trade(context.symbol(instrument)):
                count=count+1
            # 利用当日可用现金使用等资金比例下单买入
        for instrument in stock_to_buy:
            cash = cash_for_buy / count
            if data.can_trade(context.symbol(instrument)):
                current_price = data.current(context.symbol(instrument), 'price')
                amount = math.floor(cash / current_price)
                context.order(context.symbol(instrument), amount)
    # 回测引擎:准备数据,只执行一次
    def m21_prepare_bigquant_run(context):
        # 加载预测数据
        df = context.options['data'].read_df()
        # 函数:求满足开仓条件的股票列表
        def open_pos_con(df):
            return list(df.instrument)[:200]
    
        # 函数:求满足平仓条件的股票列表
        def close_pos_con(df):
            return list(df.instrument)[200:]
        
        # 每日买入股票的数据框
        context.daily_buy_stock= df.groupby('date').apply(open_pos_con)
        # 每日卖出股票的数据框
        context.daily_sell_stock= df.groupby('date').apply(close_pos_con)    
        
        
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m21_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m5 = M.instruments.v2(
        start_date='2012-01-01',
        end_date='2019-12-31',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m10 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    #(close_0-close_1)/close_1
    stock_return=return_0-1
    benchmark_return=group_sum(date, return_0-1)/group_sum(date,1)
    """
    )
    
    m6 = M.general_feature_extractor_vx1.v1(
        instruments=m5.data,
        features=m10.data,
        start_date='2012-01-01',
        end_date='2019-12-31',
        before_start_days=120
    )
    
    m12 = M.dropnan.v1(
        input_data=m6.data
    )
    
    m17 = M.derived_feature_extractor.v3(
        input_data=m12.data,
        features=m10.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m2 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    degree=correlation(benchmark_return,stock_return,60)-1/group_sum(date,1)"""
    )
    
    m4 = M.derived_feature_extractor.v3(
        input_data=m17.data,
        features=m2.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m9 = M.select_columns.v3(
        input_ds=m4.data,
        columns='date,instrument,degree',
        reverse_select=False
    )
    
    m1 = M.dropnan.v1(
        input_data=m9.data
    )
    
    m20 = M.sort.v4(
        input_ds=m1.data,
        sort_by='degree',
        group_by='date',
        keep_columns='--',
        ascending=False
    )
    
    m21 = M.trade.v4(
        instruments=m5.data,
        options_data=m20.sorted_data,
        start_date='',
        end_date='',
        initialize=m21_initialize_bigquant_run,
        handle_data=m21_handle_data_bigquant_run,
        prepare=m21_prepare_bigquant_run,
        before_trading_start=m21_before_trading_start_bigquant_run,
        order_price_field_buy='open',
        order_price_field_sell='open',
        capital_base=100000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='真实价格',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    m11 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    degree
    """
    )
    
    m3 = M.factorlens.v1(
        features=m11.data,
        user_factor_data=m20.sorted_data,
        title='因子分析: {factor_name}',
        start_date='2012-01-01',
        end_date='2019-12-31',
        rebalance_period=6,
        stock_pool='全部',
        quantile_count=5,
        commission_rate=0.003,
        drop_price_limit_stocks=True,
        drop_st_stocks=True,
        drop_new_stocks=True,
        neutralization=['行业', '市值']
    )
    

    因子分析(factorlens)使用错误,你可以:

    1.一键查看文档

    2.一键搜索答案

    Traceback (most recent call last):
      File "module2/common/moduleinvoker.py", line 209, in biglearning.module2.common.moduleinvoker._invoke_with_cache
      File "module2/common/moduleinvoker.py", line 166, in biglearning.module2.common.moduleinvoker._module_run
      File "module2/modules/factorlens/v1/__init__.py", line 72, in biglearning.module2.modules.factorlens.v1.__init__.bigquant_run
      File "impl/alpha_performance.py", line 287, in bigalpha.impl.alpha_performance.AlphaPerformance.batch_process
      File "impl/alpha_performance.py", line 267, in bigalpha.impl.alpha_performance.AlphaPerformance._process_factors
      File "impl/alpha_performance.py", line 245, in bigalpha.impl.alpha_performance.AlphaPerformance._process
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/alpha_performance.py", line 179, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper
      File "impl/options/neutralization_option.py", line 90, in bigalpha.impl.options.neutralization_option.NeutralizationOption.process
      File "impl/expression.py", line 350, in bigexpr.impl.expression.evaluate
      File "impl/expression.py", line 183, in bigexpr.impl.expression.__evaluate_ast
      File "impl/functions.py", line 1102, in bigexpr.impl.functions.UserFunctions.neutralize
      File "/usr/local/python3/lib/python3.5/site-packages/pandas/core/groupby.py", line 805, in apply
        return self._python_apply_general(f)
      File "/usr/local/python3/lib/python3.5/site-packages/pandas/core/groupby.py", line 809, in _python_apply_general
        self.axis)
      File "/usr/local/python3/lib/python3.5/site-packages/pandas/core/groupby.py", line 1969, in apply
        res = f(group)
      File "impl/functions.py", line 1100, in bigexpr.impl.functions.UserFunctions.neutralize._resid
      File "/usr/local/python3/lib/python3.5/site-packages/numpy/linalg/linalg.py", line 2236, in lstsq
        x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj)
    ValueError: On entry to DLASCL parameter number 4 had an illegal value
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/usr/local/python3/lib/python3.5/site-packages/logbook/handlers.py", line 213, in handle
        self.emit(record)
      File "/usr/local/python3/lib/python3.5/site-packages/logbook/handlers.py", line 839, in emit
        self.perform_rollover()
      File "/usr/local/python3/lib/python3.5/site-packages/logbook/handlers.py", line 828, in perform_rollover
        self.stream.close()
    AttributeError: 'NoneType' object has no attribute 'close'
    Logged from file <ipython-input-97-39716ecb6f49>, line 101
    
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-97-39716ecb6f49> in <module>()
         99     drop_st_stocks=True,
        100     drop_new_stocks=True,
    --> 101     neutralization=['行业', '市值']
        102 )
    
    ValueError: On entry to DLASCL parameter number 4 had an illegal value

    [2020-02-02 00:56:19.489331] INFO: bigquant: instruments.v2 开始运行…

    [2020-02-02 00:56:19.657340] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:19.659062] INFO: bigquant: instruments.v2 运行完成[0.169736s].

    [2020-02-02 00:56:19.661438] INFO: bigquant: input_features.v1 开始运行…

    [2020-02-02 00:56:19.793401] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:19.795531] INFO: bigquant: input_features.v1 运行完成[0.134075s].

    [2020-02-02 00:56:19.824859] INFO: bigquant: general_feature_extractor_vx1.v1 开始运行…

    [2020-02-02 00:56:19.871348] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:19.873544] INFO: bigquant: general_feature_extractor_vx1.v1 运行完成[0.048697s].

    [2020-02-02 00:56:19.876939] INFO: bigquant: dropnan.v1 开始运行…

    [2020-02-02 00:56:19.904043] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:19.906384] INFO: bigquant: dropnan.v1 运行完成[0.029428s].

    [2020-02-02 00:56:19.909729] INFO: bigquant: derived_feature_extractor.v3 开始运行…

    [2020-02-02 00:56:19.944349] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:19.946021] INFO: bigquant: derived_feature_extractor.v3 运行完成[0.036298s].

    [2020-02-02 00:56:19.948199] INFO: bigquant: input_features.v1 开始运行…

    [2020-02-02 00:56:20.050510] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:20.052175] INFO: bigquant: input_features.v1 运行完成[0.103966s].

    [2020-02-02 00:56:20.054981] INFO: bigquant: derived_feature_extractor.v3 开始运行…

    [2020-02-02 00:56:20.134952] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:20.136605] INFO: bigquant: derived_feature_extractor.v3 运行完成[0.081618s].

    [2020-02-02 00:56:20.140904] INFO: bigquant: select_columns.v3 开始运行…

    [2020-02-02 00:56:20.180673] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:20.182198] INFO: bigquant: select_columns.v3 运行完成[0.04129s].

    [2020-02-02 00:56:20.184350] INFO: bigquant: dropnan.v1 开始运行…

    [2020-02-02 00:56:20.264491] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:20.266427] INFO: bigquant: dropnan.v1 运行完成[0.082064s].

    [2020-02-02 00:56:20.268450] INFO: bigquant: sort.v4 开始运行…

    [2020-02-02 00:56:20.308519] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:20.311493] INFO: bigquant: sort.v4 运行完成[0.043012s].

    [2020-02-02 00:56:20.314156] INFO: bigquant: input_features.v1 开始运行…

    [2020-02-02 00:56:20.344646] INFO: bigquant: 命中缓存

    [2020-02-02 00:56:20.346467] INFO: bigquant: input_features.v1 运行完成[0.032323s].

    [2020-02-02 00:56:20.348743] INFO: bigquant: factorlens.v1 开始运行…

    [2020-02-02 00:56:24.110237] INFO: 因子分析: batch_process start

    [2020-02-02 00:56:24.111993] INFO: 因子分析: load_instruments 2012-01-01, 2019-12-31

    [2020-02-02 00:56:31.815636] INFO: 因子分析: load_instruments, 3805 rows.

    [2020-02-02 00:56:31.819638] INFO: 因子分析: StockPool.before_load_general_feature_data

    [2020-02-02 00:56:31.821043] INFO: 因子分析: DropSTStocks.before_load_general_feature_data

    [2020-02-02 00:56:31.822200] INFO: 因子分析: DropNewStocks.before_load_general_feature_data

    [2020-02-02 00:56:31.823345] INFO: 因子分析: Neutralization.before_load_general_feature_data

    [2020-02-02 00:56:31.824808] INFO: 因子分析: Industry.before_load_general_feature_data

    [2020-02-02 00:56:31.826031] INFO: 因子分析: PBRatio.before_load_general_feature_data

    [2020-02-02 00:56:31.827078] INFO: 因子分析: Turnover.before_load_general_feature_data

    [2020-02-02 00:56:31.828082] INFO: 因子分析: MarketCap.before_load_general_feature_data

    [2020-02-02 00:56:31.829104] INFO: 因子分析: load_general_feature_data, load data

    [2020-02-02 01:00:29.041510] INFO: 因子分析: RebalancePeriod.after_load_general_feature_data

    [2020-02-02 01:00:36.488695] INFO: 因子分析: load_general_feature_data, 5356117 rows.

    [2020-02-02 01:00:36.490961] INFO: 因子分析: load_derived_feature_data, 5356117 rows, 15 columns.

    [2020-02-02 01:00:36.492211] INFO: 因子分析: process, degree

    [2020-02-02 01:00:36.494121] INFO: 因子分析: calculate_factor, degree

    [2020-02-02 01:00:36.529676] INFO: 因子分析: calculate_factor, done

    [2020-02-02 01:00:36.531309] INFO: 因子分析: QuantileReturns.before_process

    [2020-02-02 01:00:36.532745] INFO: 因子分析: IC.before_process

    [2020-02-02 01:00:36.534659] INFO: 因子分析: Turnover.before_process

    [2020-02-02 01:00:36.663382] INFO: 因子分析: process metrics, start …

    [2020-02-02 01:00:39.631868] INFO: 因子分析: process, 5007296/5356117 rows …

    [2020-02-02 01:00:39.634047] INFO: 因子分析: BacktestInterval.process, 0.000s

    [2020-02-02 01:00:39.635980] INFO: 因子分析: StockPool.process, 0.000s

    [2020-02-02 01:00:39.637428] INFO: 因子分析: DropSTStocks.process, 0.000s

    [2020-02-02 01:00:39.638912] INFO: 因子分析: DropPriceLimitStocks.process, 0.000s

    [2020-02-02 01:00:39.640510] INFO: 因子分析: DropNewStocks.process, 0.000s

    [2020-02-02 01:00:39.642045] INFO: 因子分析: QuantileCount.process, 0.000s

    [2020-02-02 01:00:39.643425] INFO: 因子分析: CommissionRates.process, 0.000s

    [2020-02-02 01:00:41.699232] INFO: 因子分析: Normalization.process, 2.054s

    [2020-02-02 01:05:18.206095] ERROR: bigquant: module name: factorlens, module version: v1, trackeback: Traceback (most recent call last): ValueError: On entry to DLASCL parameter number 4 had an illegal value

    因子分析(factorlens)使用错误,你可以:

    1.一键查看文档

    2.一键搜索答案

    Traceback (most recent call last): File “module2/common/moduleinvoker.py”, line 209, in biglearning.module2.common.moduleinvoker._invoke_with_cache File “module2/common/moduleinvoker.py”, line 166, in biglearning.module2.common.moduleinvoker._module_run File “module2/modules/factorlens/v1/init.py”, line 72, in biglearning.module2.modules.factorlens.v1.init.bigquant_run File “impl/alpha_performance.py”, line 287, in bigalpha.impl.alpha_performance.AlphaPerformance.batch_process File “impl/alpha_performance.py”, line 267, in bigalpha.impl.alpha_performance.AlphaPerformance._process_factors File “impl/alpha_performance.py”, line 245, in bigalpha.impl.alpha_performance.AlphaPerformance._process File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 164, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/alpha_performance.py”, line 179, in bigalpha.impl.alpha_performance.AlphaPerformance._process_helper File “impl/options/neutralization_option.py”, line 90, in bigalpha.impl.options.neutralization_option.NeutralizationOption.process File “impl/expression.py”, line 350, in bigexpr.impl.expression.evaluate File “impl/expression.py”, line 183, in bigexpr.impl.expression.__evaluate_ast File “impl/functions.py”, line 1102, in bigexpr.impl.functions.UserFunctions.neutralize File “/usr/local/python3/lib/python3.5/site-packages/pandas/core/groupby.py”, line 805, in apply return self._python_apply_general(f) File “/usr/local/python3/lib/python3.5/site-packages/pandas/core/groupby.py”, line 809, in _python_apply_general self.axis) File “/usr/local/python3/lib/python3.5/site-packages/pandas/core/groupby.py”, line 1969, in apply res = f(group) File “impl/functions.py”, line 1100, in bigexpr.impl.functions.UserFunctions.neutralize._resid File “/usr/local/python3/lib/python3.5/site-packages/numpy/linalg/linalg.py”, line 2236, in lstsq x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj) ValueError: On entry to DLASCL parameter number 4 had an illegal value During handling of the above exception, another exception occurred: Traceback (most recent call last): File “/usr/local/python3/lib/python3.5/site-packages/logbook/handlers.py”, line 213, in handle self.emit(record) File “/usr/local/python3/lib/python3.5/site-packages/logbook/handlers.py”, line 839, in emit self.perform_rollover() File “/usr/local/python3/lib/python3.5/site-packages/logbook/handlers.py”, line 828, in perform_rollover self.stream.close() AttributeError: ‘NoneType’ object has no attribute ‘close’ Logged from file <ipython-input-97-39716ecb6f49>, line 101

    --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-97-39716ecb6f49> in <module>() 99 drop_st_stocks=True, 100 drop_new_stocks=True, --> 101 neutralization=[‘行业’, ‘市值’] 102 ) ValueError: On entry to DLASCL parameter number 4 had an illegal value


    (iQuant) #2

    收到您的提问,已提交至策略工程师,会尽快为您回复。


    (cash01) #3

    错误解决了吗?