设置回测基准期货案例

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

(iQuant) #1
克隆策略

    {"Description":"实验创建于2018/10/16","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-1442:instruments","SourceOutputPortId":"-25:data"},{"DestinationInputPortId":"-1483:input_1","SourceOutputPortId":"-25:data"},{"DestinationInputPortId":"-136:input_1","SourceOutputPortId":"-25:data"},{"DestinationInputPortId":"-1473:features","SourceOutputPortId":"-1468:data"},{"DestinationInputPortId":"-1632:input_data","SourceOutputPortId":"-1473:data"},{"DestinationInputPortId":"-1473:input_data","SourceOutputPortId":"-1483:data_1"},{"DestinationInputPortId":"-1442:options_data","SourceOutputPortId":"-1632:data"},{"DestinationInputPortId":"-1442:benchmark_ds","SourceOutputPortId":"-136:data_1"}],"ModuleNodes":[{"Id":"-25","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-11-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2018-05-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_FUTURE","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"RU1809.SHF","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-25"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-25","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1442","ModuleId":"BigQuantSpace.trade.trade-v4","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 buy_condition=context.buy_condition[today]\n sell_condition=context.sell_condition[today]\n \n instrument = context.future_symbol(context.instruments[0]) # 交易标的\n curr_po=context.portfolio.positions[instrument] # 组合持仓\n curr_position = curr_po.amount # 持仓数量\n \n\n # 交易逻辑\n if buy_condition>0 and data.can_trade(instrument): # 开多,下单数量20手\n order_target(instrument, 20)\n print(today,'平空开多')\n \n elif sell_condition>0 and data.can_trade(instrument):# 开空,下单数量20手\n order_target(instrument, -20)\n print(today,'平多开空')","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n df = context.options['data'].read_df()\n df['date']=df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n df.set_index('date',inplace=True)\n context.buy_condition=df['buy_condition']\n context.sell_condition=df['sell_condition']\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 设置是否是结算模式\n context.set_need_settle(False)\n # 设置最大杠杆\n context.set_max_leverage(1, 'fill_amap')","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":"0","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":"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":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1442"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1442","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1468","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where((close-(mean(close,20)-2*std(close,20)))/(4*std(close,20))>=1,1,0)\nsell_condition=where((close-(mean(close,20)-2*std(close,20)))/(4*std(close,20))<=0,1,0)\n\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-1468"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1468","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1473","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":"-1473"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1473"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1473","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1483","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3,before_days):\n # 示例代码如下。在这里编写您的代码\n start_date=(pd.to_datetime(input_1.read_pickle()['start_date']) - datetime.timedelta(days=before_days)).strftime('%Y-%m-%d')\n end_date=input_1.read_pickle()['end_date']\n instruments=input_1.read_pickle()['instruments']\n fields=['open','high','low','close']\n df = DataSource('bar1d_CN_FUTURE').read(instruments,start_date,end_date,fields)\n df['adjust_factor']=1.0\n data_1 = DataSource.write_df(df)\n return Outputs(data_1=data_1, data_2=None, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{'before_days':60}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-1483"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-1483"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-1483"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-1483","OutputType":null},{"Name":"data_2","NodeId":"-1483","OutputType":null},{"Name":"data_3","NodeId":"-1483","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1632","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-1632"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1632","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-136","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n # 示例代码如下。在这里编写您的代码\n start = input_1.read_pickle()['start_date']\n end = input_1.read_pickle()['end_date']\n bm = DataSource('bar1d_CN_FUTURE').read(instruments=['RU8888.SHF'],start_date=start,end_date=end)\n bm.index = range(len(bm)) \n data_1 = DataSource.write_df(bm)\n return Outputs(data_1=data_1)","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-136"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-136"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-136"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-136","OutputType":null},{"Name":"data_2","NodeId":"-136","OutputType":null},{"Name":"data_3","NodeId":"-136","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"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='-25' Position='-240,14,200,200'/><NodePosition Node='-1442' Position='210,482,200,200'/><NodePosition Node='-1468' Position='259,28,200,200'/><NodePosition Node='-1473' Position='213,237,200,200'/><NodePosition Node='-1483' Position='-17,124,200,200'/><NodePosition Node='-1632' Position='151,342,200,200'/><NodePosition Node='-136' Position='490,356,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 [3]:
    # 本代码由可视化策略环境自动生成 2019年3月9日 16:10
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m4_run_bigquant_run(input_1, input_2, input_3,before_days):
        # 示例代码如下。在这里编写您的代码
        start_date=(pd.to_datetime(input_1.read_pickle()['start_date']) - datetime.timedelta(days=before_days)).strftime('%Y-%m-%d')
        end_date=input_1.read_pickle()['end_date']
        instruments=input_1.read_pickle()['instruments']
        fields=['open','high','low','close']
        df = DataSource('bar1d_CN_FUTURE').read(instruments,start_date,end_date,fields)
        df['adjust_factor']=1.0
        data_1 = DataSource.write_df(df)
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m4_post_run_bigquant_run(outputs):
        return outputs
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m1_run_bigquant_run(input_1, input_2, input_3):
        # 示例代码如下。在这里编写您的代码
        start = input_1.read_pickle()['start_date']
        end = input_1.read_pickle()['end_date']
        bm = DataSource('bar1d_CN_FUTURE').read(instruments=['RU8888.SHF'],start_date=start,end_date=end)
        bm.index = range(len(bm)) 
        data_1 = DataSource.write_df(bm)
        return Outputs(data_1=data_1)
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m1_post_run_bigquant_run(outputs):
        return outputs
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m3_handle_data_bigquant_run(context, data):
        # 获取当日指标数据
        today = data.current_dt.strftime('%Y-%m-%d') # 当前交易日期
        buy_condition=context.buy_condition[today]
        sell_condition=context.sell_condition[today]
        
        instrument = context.future_symbol(context.instruments[0]) # 交易标的
        curr_po=context.portfolio.positions[instrument] # 组合持仓
        curr_position = curr_po.amount  # 持仓数量
             
    
        # 交易逻辑
        if buy_condition>0 and data.can_trade(instrument): # 开多,下单数量20手
            order_target(instrument,  20)
            print(today,'平空开多')
                
        elif  sell_condition>0 and data.can_trade(instrument):# 开空,下单数量20手
            order_target(instrument, -20)
            print(today,'平多开空')
    # 回测引擎:准备数据,只执行一次
    def m3_prepare_bigquant_run(context):
        df = context.options['data'].read_df()
        df['date']=df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
        df.set_index('date',inplace=True)
        context.buy_condition=df['buy_condition']
        context.sell_condition=df['sell_condition']
    
    # 回测引擎:初始化函数,只执行一次
    def m3_initialize_bigquant_run(context):
       # 设置是否是结算模式
        context.set_need_settle(False)
        # 设置最大杠杆
        context.set_max_leverage(1, 'fill_amap')
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m3_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m2 = M.instruments.v2(
        start_date='2017-11-01',
        end_date='2018-05-01',
        market='CN_FUTURE',
        instrument_list='RU1809.SHF',
        max_count=0
    )
    
    m4 = M.cached.v3(
        input_1=m2.data,
        run=m4_run_bigquant_run,
        post_run=m4_post_run_bigquant_run,
        input_ports='',
        params='{\'before_days\':60}',
        output_ports=''
    )
    
    m1 = M.cached.v3(
        input_1=m2.data,
        run=m1_run_bigquant_run,
        post_run=m1_post_run_bigquant_run,
        input_ports='',
        params='{}',
        output_ports=''
    )
    
    m5 = M.input_features.v1(
        features="""
    # #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    buy_condition=where((close-(mean(close,20)-2*std(close,20)))/(4*std(close,20))>=1,1,0)
    sell_condition=where((close-(mean(close,20)-2*std(close,20)))/(4*std(close,20))<=0,1,0)
    
    """
    )
    
    m6 = M.derived_feature_extractor.v3(
        input_data=m4.data_1,
        features=m5.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m7 = M.dropnan.v1(
        input_data=m6.data
    )
    
    m3 = M.trade.v4(
        instruments=m2.data,
        options_data=m7.data,
        benchmark_ds=m1.data_1,
        start_date='',
        end_date='',
        handle_data=m3_handle_data_bigquant_run,
        prepare=m3_prepare_bigquant_run,
        initialize=m3_initialize_bigquant_run,
        before_trading_start=m3_before_trading_start_bigquant_run,
        volume_limit=0,
        order_price_field_buy='open',
        order_price_field_sell='open',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='期货',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    2017-11-02 平空开多
    2017-11-06 平空开多
    2017-11-07 平空开多
    2017-11-13 平空开多
    2017-12-04 平空开多
    2018-01-23 平多开空
    2018-01-24 平多开空
    2018-01-30 平多开空
    2018-01-31 平多开空
    2018-02-01 平多开空
    2018-02-06 平多开空
    2018-03-20 平多开空
    2018-03-21 平多开空
    2018-03-22 平多开空
    2018-03-23 平多开空
    2018-03-26 平多开空
    2018-03-27 平多开空
    
    • 收益率41.86%
    • 年化收益率108.41%
    • 基准收益率-16.95%
    • 阿尔法1.0
    • 贝塔0.26
    • 夏普比率1.44
    • 胜率0.0
    • 盈亏比0.0
    • 收益波动率62.25%
    • 信息比率0.12
    • 最大回撤23.82%

    【宽客学院】设置回测基准