克隆策略

    {"Description":"实验创建于2018/10/16","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-1442:instruments","SourceOutputPortId":"-1483:data_1"},{"DestinationInputPortId":"-298:input_1","SourceOutputPortId":"-165:data"},{"DestinationInputPortId":"-1483:input_1","SourceOutputPortId":"-165:data"},{"DestinationInputPortId":"-307:features","SourceOutputPortId":"-173:data"},{"DestinationInputPortId":"-307:input_data","SourceOutputPortId":"-298:data_1"},{"DestinationInputPortId":"-1442:options_data","SourceOutputPortId":"-307:data"}],"ModuleNodes":[{"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 \n date_time = data.current_dt # 日期时间(timestamp格式)\n date = date_time.strftime('%Y-%m-%d') # 日期(str格式)\n \n if date not in context.DATE: # 用于判断是否是新的一天\n context.DATE.append(date)\n context.trading_counts = 0 # 每日开始的时候初始化该字段\n \n \n instrument_symbol = context.future_symbol(context.instruments[0]) # 交易标的\n curr_position = context.portfolio.positions[instrument_symbol].amount # 持仓数量\n price = data.current(instrument_symbol, 'price')\n \n try:\n upperline = context.indicator_df.ix[date]['upperline']\n lowerline = context.indicator_df.ix[date]['lowerline']\n except KeyError as e:\n return \n\n \n # 交易逻辑\n # 卖平\n if curr_position > 0 and price <= lowerline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:\n order(instrument_symbol, -1*abs(curr_position), position_effect='close')\n print(date_time, '卖平!','交易前持仓:',curr_position, price ,lowerline)\n \n # 买平\n elif curr_position < 0 and price >= upperline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:\n order(instrument_symbol, 1*abs(curr_position), position_effect='open') \n print(date_time, '买平!', '交易前持仓:',curr_position, price , upperline)\n \n # 买开\n if curr_position == 0 and price >= upperline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:\n order(instrument_symbol, 1, position_effect='open')\n context.trading_counts += 1\n print(date_time, '买开!','交易前持仓:',curr_position, price ,upperline)\n \n # 卖开 \n elif curr_position == 0 and price <= lowerline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:\n order(instrument_symbol, -1, position_effect='open') \n context.trading_counts += 1\n print(date_time, '卖开!','交易前持仓:',curr_position, price ,lowerline)\n \n \n \n \n # 每日收盘,日终平仓\n curr_position = context.portfolio.positions[instrument_symbol].amount # 持仓数量\n \n if date_time.hour == 14 and date_time.minute == 55:\n if curr_position >0:\n order(instrument_symbol, -1*abs(curr_position), position_effect='close')\n print(date_time, '收盘,卖平!', '交易前持仓:',curr_position)\n \n elif curr_position <0:\n order(instrument_symbol, 1*abs(curr_position), position_effect='close')\n print(date_time, '收盘,买平!', '交易前持仓:',curr_position)\n\n\n \n \n \n ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass","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')\n \n # 设置手续费\n #context.set_commission(futures_commission=PerContract(cost={'RB':(0.000045, 0.000045, 0.000045)}))\n #context.set_margin('RB', 0.07)\n \n \n context.DATE = list()\n context.max_trade_cnt = 3 # 每日最大交易次数不超过3次\n context.indicator_df = context.options['data'].read_df().set_index('date')\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":"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":"20000","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"minute","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,"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 \n data = input_1.read_pickle()\n \n start_date= data['start_date']\n end_date = data['end_date']\n contracts = data['instruments']\n \n ds1 = DataSource.write_pickle({'start_date':start_date, 'end_date':end_date, 'instruments':contracts})\n \n return Outputs(data_1=ds1)\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":1,"Comment":"整理成证券代码列表模块","CommentCollapsed":false},{"Id":"-165","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2018-03-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2018-06-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"RB1810.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":"-165"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-165","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"Comment":"","CommentCollapsed":true},{"Id":"-173","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"HH=ts_max(high, 10)\nHC=ts_max(close, 10)\nLC=ts_min(close,10)\nLL=ts_min(low,10)\nRange=max(HH-LC,HC-LL)\nupperline=open+shift(0.1*Range,1)\nlowerline=open-shift(0.1*Range,1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-173"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-173","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"Comment":"","CommentCollapsed":true},{"Id":"-298","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 start_date=input_1.read_pickle()['start_date']\n end_date=input_1.read_pickle()['end_date']\n ins=input_1.read_pickle()['instruments']\n df = DataSource('bar1d_CN_FUTURE').read(instruments=ins,start_date=start_date,end_date=end_date,fields=['open','close','high','low','settle'])\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':1}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-298"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-298"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-298"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-298","OutputType":null},{"Name":"data_2","NodeId":"-298","OutputType":null},{"Name":"data_3","NodeId":"-298","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":6,"Comment":"读取价量数据以方便进行指标计算","CommentCollapsed":false},{"Id":"-307","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":"-307"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-307"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-307","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"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='-1442' Position='308.7632141113281,89.95791149139404,200,200'/><NodePosition Node='-1483' Position='128.07630157470703,-157.73946380615234,200,200'/><NodePosition Node='-165' Position='228.40264892578125,-409.392053604126,200,200'/><NodePosition Node='-173' Position='636.9293212890625,-351.7491455078125,200,200'/><NodePosition Node='-298' Position='410.092041015625,-248.70529174804688,200,200'/><NodePosition Node='-307' Position='489.05792236328125,-92.01841831207275,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 [36]:
    # 本代码由可视化策略环境自动生成 2019年6月15日 15:36
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m6_run_bigquant_run(input_1, input_2, input_3,before_days):
        start_date=input_1.read_pickle()['start_date']
        end_date=input_1.read_pickle()['end_date']
        ins=input_1.read_pickle()['instruments']
        df = DataSource('bar1d_CN_FUTURE').read(instruments=ins,start_date=start_date,end_date=end_date,fields=['open','close','high','low','settle'])
        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 m6_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,before_days):
        
        
        data = input_1.read_pickle()
        
        start_date= data['start_date']
        end_date = data['end_date']
        contracts = data['instruments']
        
        ds1 = DataSource.write_pickle({'start_date':start_date, 'end_date':end_date, 'instruments':contracts})
     
        return Outputs(data_1=ds1)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m1_post_run_bigquant_run(outputs):
        return outputs
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m3_handle_data_bigquant_run(context, data):
         
        
        date_time = data.current_dt # 日期时间(timestamp格式)
        date = date_time.strftime('%Y-%m-%d') # 日期(str格式)
        
        if date not in context.DATE: # 用于判断是否是新的一天
            context.DATE.append(date)
            context.trading_counts = 0 # 每日开始的时候初始化该字段
            
         
        instrument_symbol = context.future_symbol(context.instruments[0]) # 交易标的
        curr_position = context.portfolio.positions[instrument_symbol].amount # 持仓数量
        price = data.current(instrument_symbol, 'price')
        
        try:
            upperline = context.indicator_df.ix[date]['upperline']
            lowerline = context.indicator_df.ix[date]['lowerline']
        except KeyError as e:
            return 
    
         
        # 交易逻辑
        # 卖平
        if curr_position > 0  and price <= lowerline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:
            order(instrument_symbol, -1*abs(curr_position), position_effect='close')
            print(date_time, '卖平!','交易前持仓:',curr_position, price ,lowerline)
       
         # 买平
        elif  curr_position < 0 and price >= upperline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:
            order(instrument_symbol, 1*abs(curr_position),  position_effect='open') 
            print(date_time, '买平!', '交易前持仓:',curr_position, price , upperline)
            
        # 买开
        if curr_position == 0 and price >= upperline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:
            order(instrument_symbol, 1, position_effect='open')
            context.trading_counts += 1
            print(date_time, '买开!','交易前持仓:',curr_position, price ,upperline)
        
        # 卖开 
        elif  curr_position == 0 and price <= lowerline and date_time.hour<14 and context.trading_counts<context.max_trade_cnt:
            order(instrument_symbol, -1, position_effect='open') 
            context.trading_counts += 1
            print(date_time, '卖开!','交易前持仓:',curr_position, price ,lowerline)
            
        
            
            
        # 每日收盘,日终平仓
        curr_position = context.portfolio.positions[instrument_symbol].amount # 持仓数量
         
        if date_time.hour == 14 and date_time.minute == 55:
            if curr_position >0:
                order(instrument_symbol, -1*abs(curr_position), position_effect='close')
                print(date_time, '收盘,卖平!', '交易前持仓:',curr_position)
                
            elif curr_position <0:
                order(instrument_symbol, 1*abs(curr_position), position_effect='close')
                print(date_time, '收盘,买平!', '交易前持仓:',curr_position)
    
    
            
            
            
            
    # 回测引擎:准备数据,只执行一次
    def m3_prepare_bigquant_run(context):
        pass
    # 回测引擎:初始化函数,只执行一次
    def m3_initialize_bigquant_run(context):
       # 设置是否是结算模式
        context.set_need_settle(False)
        # 设置最大杠杆
        #context.set_max_leverage(1, 'fill_amap')
        
        # 设置手续费
        #context.set_commission(futures_commission=PerContract(cost={'RB':(0.000045, 0.000045, 0.000045)}))
        #context.set_margin('RB', 0.07)
        
         
        context.DATE = list()
        context.max_trade_cnt = 3 # 每日最大交易次数不超过3次
        context.indicator_df = context.options['data'].read_df().set_index('date')
         
        
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m3_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m2 = M.instruments.v2(
        start_date='2018-03-01',
        end_date='2018-06-01',
        market='CN_STOCK_A',
        instrument_list='RB1810.SHF',
        max_count=0
    )
    
    m6 = M.cached.v3(
        input_1=m2.data,
        run=m6_run_bigquant_run,
        post_run=m6_post_run_bigquant_run,
        input_ports='',
        params='{\'before_days\':1}',
        output_ports='',
        m_cached=False
    )
    
    m1 = M.cached.v3(
        input_1=m2.data,
        run=m1_run_bigquant_run,
        post_run=m1_post_run_bigquant_run,
        input_ports='',
        params='{\'before_days\':60}',
        output_ports=''
    )
    
    m4 = M.input_features.v1(
        features="""HH=ts_max(high, 10)
    HC=ts_max(close, 10)
    LC=ts_min(close,10)
    LL=ts_min(low,10)
    Range=max(HH-LC,HC-LL)
    upperline=open+shift(0.1*Range,1)
    lowerline=open-shift(0.1*Range,1)
    
    """
    )
    
    m5 = M.derived_feature_extractor.v3(
        input_data=m6.data_1,
        features=m4.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m3 = M.trade.v4(
        instruments=m1.data_1,
        options_data=m5.data,
        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=20000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='minute',
        price_type='后复权',
        product_type='期货',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    • 收益率9.69%
    • 年化收益率44.76%
    • 基准收益率-3.49%
    • 阿尔法0.34
    • 贝塔-0.18
    • 夏普比率1.55
    • 胜率0.5
    • 盈亏比1.01
    • 收益波动率23.7%
    • 信息比率0.11
    • 最大回撤7.37%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-6b826c4c44614eed96f3d2388bf03193"}/bigcharts-data-end