【宽客学院】零基础小白可以学习的AI量化课程

用户成长系列
ai量化培训
标签: #<Tag:0x00007fcf6bdbfc58> #<Tag:0x00007fcf6bdbfaf0>

(iQuant) #1

AI量化是未来趋势,金融机构对量化方向的人才求贤若渴,存在大量的人才缺失。对于金融知识一片空白的小白来说,难以听懂量化中专业的术语。因此,BigQuant整理了一套适合金融小白的培训课程,精心挑选量化中所需要具备的金融基础知识,为大家打开金融世界的一扇门。点击下方的视频来学习吧!(视频会持续更新!)

更多的知识需要个人不断地积累和沉淀,有什么不懂的就来问小Q吧!


(iQuant) #2

[量化学院-新手专区]BigQuant新手指南
(iQuant) #3

(iQuant) #4

课程相关案例及源代码

1.1量化数据研究

克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-2229:input_data","SourceOutputPortId":"-215:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2019-03-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-03-01","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\npe_ttm_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,"Comment":"","CommentCollapsed":true},{"Id":"-215","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":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"Comment":"","CommentCollapsed":true},{"Id":"-2229","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-2229"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2229","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"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-8' Position='210.27316284179688,93.27317810058594,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='547,90,200,200'/><NodePosition Node='-215' Position='375.54632568359375,188,200,200'/><NodePosition Node='-2229' Position='407.6291809082031,274.0049743652344,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 [8]:
    # 本代码由可视化策略环境自动生成 2019年7月13日 14:00
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2019-03-01',
        end_date='2019-03-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    pe_ttm_0
    """
    )
    
    m15 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m2 = M.dropnan.v1(
        input_data=m15.data
    )
    

    1.2因子构建

    克隆策略

      {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-2538:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-03-01","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na_label","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"cast_label_int","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"Comment":"","CommentCollapsed":true},{"Id":"-2538","ModuleId":"BigQuantSpace.standardlize.standardlize-v8","ModuleParameters":[{"Name":"columns_input","Value":"['label']","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2538"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2538"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2538","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"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-8' Position='211,64,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='201.23858642578125,215.8096466064453,200,200'/><NodePosition Node='-2538' Position='213.19903564453125,419.6730651855469,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年7月13日 14:07
      # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
      
      
      m1 = M.instruments.v2(
          start_date='2016-01-01',
          end_date='2016-03-01',
          market='CN_STOCK_A',
          instrument_list='',
          max_count=0
      )
      
      m2 = M.advanced_auto_labeler.v2(
          instruments=m1.data,
          label_expr="""# #号开始的表示注释
      # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
      # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
      #   添加benchmark_前缀,可使用对应的benchmark数据
      # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
      
      # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
      shift(close, -5) / shift(open, -1)
      """,
          start_date='',
          end_date='',
          benchmark='000300.SHA',
          drop_na_label=True,
          cast_label_int=True
      )
      
      m3 = M.standardlize.v8(
          input_1=m2.data,
          columns_input=['label']
      )
      

      2.1 固定买卖周期逻辑

      克隆策略

        {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:model"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-250:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-250:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-238:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na_label","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"cast_label_int","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nreturn_5\nreturn_10\nreturn_20\navg_amount_0/avg_amount_5\navg_amount_5/avg_amount_20\nrank_avg_amount_0/rank_avg_amount_5\nrank_avg_amount_5/rank_avg_amount_10\nrank_return_0\nrank_return_5\nrank_return_10\nrank_return_0/rank_return_5\nrank_return_5/rank_return_10\npe_ttm_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":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","ModuleId":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v5","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":30,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":20,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"}],"OutputPortsInternal":[{"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"feature_gains","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","ModuleId":"BigQuantSpace.join.join-v3","ModuleParameters":[{"Name":"on","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"how","Value":"inner","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"sort","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data1","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","ModuleId":"BigQuantSpace.stock_ranker_predict.stock_ranker_predict-v5","ModuleParameters":[{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-01-01","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","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":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","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":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","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":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","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":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-250","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 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 = 5\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 = 0.2\n context.options['hold_days'] = 3\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+1 < 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, cash_avg)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n\n # 2. 持有固定天数卖出\n #----------------------------START:持有固定交易日天数卖出---------------------------\n today = data.current_dt.strftime('%Y-%m-%d')\n # 不是建仓期(在前hold_days属于建仓期)\n if not is_staging:\n equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}\n for instrument in equities:\n sid = equities[instrument].sid # 交易标的\n # 今天和上次交易的时间相隔hold_days就全部卖出\n dt = pd.to_datetime(D.trading_days(end_date = today).iloc[-context.options['hold_days']+1].values[0])\n if pd.to_datetime(equities[instrument].last_sale_date.strftime('%Y-%m-%d')) <= dt and data.can_trade(context.symbol(instrument)):\n context.order_target_percent(sid, 0)\n #--------------------------------END:持有固定天数卖出---------------------------\n\n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票,这里要过滤掉已经持仓的股票否则last_sale_date会被再次买入覆盖\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction[~ranker_prediction.instrument.isin(positions)].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":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-250"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-250","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"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-8' Position='211,64,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='70,183,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,21,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-43' Position='638,561,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='906,647,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1074,127,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='376,467,200,200'/><NodePosition Node='-86' Position='1078,418,200,200'/><NodePosition Node='-215' Position='381,188,200,200'/><NodePosition Node='-222' Position='385,280,200,200'/><NodePosition Node='-231' Position='1078,236,200,200'/><NodePosition Node='-238' Position='1081,327,200,200'/><NodePosition Node='-250' Position='1006.32568359375,802.9885864257812,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":false}
        In [24]:
        # 本代码由可视化策略环境自动生成 2019年9月19日 16:25
        # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
        
        
        # 回测引擎:初始化函数,只执行一次
        def m19_initialize_bigquant_run(context):
            # 加载预测数据
            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 = 5
            # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[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 = 0.2
            context.options['hold_days'] = 3
        
        # 回测引擎:每日数据处理函数,每天执行一次
        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+1 < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
            cash_avg = context.portfolio.portfolio_value / (context.options['hold_days'])
            cash_for_buy = min(context.portfolio.cash, cash_avg)
            positions = {e.symbol: p.amount * p.last_sale_price
                         for e, p in context.portfolio.positions.items()}
        
            # 2. 持有固定天数卖出
            #----------------------------START:持有固定交易日天数卖出---------------------------
            today = data.current_dt.strftime('%Y-%m-%d')
            # 不是建仓期(在前hold_days属于建仓期)
            if not is_staging:
                equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
                for instrument in equities:
                    sid = equities[instrument].sid  # 交易标的
                    # 今天和上次交易的时间相隔hold_days就全部卖出
                    dt = pd.to_datetime(D.trading_days(end_date = today).iloc[-context.options['hold_days']+1].values[0])
                    if  pd.to_datetime(equities[instrument].last_sale_date.strftime('%Y-%m-%d')) <= dt and data.can_trade(context.symbol(instrument)):
                        context.order_target_percent(sid, 0)
            #--------------------------------END:持有固定天数卖出---------------------------
        
            # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票,这里要过滤掉已经持仓的股票否则last_sale_date会被再次买入覆盖
            buy_cash_weights = context.stock_weights
            buy_instruments = list(ranker_prediction[~ranker_prediction.instrument.isin(positions)].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
        
        
        m1 = M.instruments.v2(
            start_date='2010-01-01',
            end_date='2015-01-01',
            market='CN_STOCK_A',
            instrument_list='',
            max_count=0
        )
        
        m2 = M.advanced_auto_labeler.v2(
            instruments=m1.data,
            label_expr="""# #号开始的表示注释
        # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
        # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
        #   添加benchmark_前缀,可使用对应的benchmark数据
        # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
        
        # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
        shift(close, -5) / shift(open, -1)
        
        # 极值处理:用1%和99%分位的值做clip
        clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
        
        # 将分数映射到分类,这里使用20个分类
        all_wbins(label, 20)
        
        # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
        where(shift(high, -1) == shift(low, -1), NaN, label)
        """,
            start_date='',
            end_date='',
            benchmark='000300.SHA',
            drop_na_label=True,
            cast_label_int=True
        )
        
        m3 = M.input_features.v1(
            features="""# #号开始的表示注释
        # 多个特征,每行一个,可以包含基础特征和衍生特征
        return_5
        return_10
        return_20
        avg_amount_0/avg_amount_5
        avg_amount_5/avg_amount_20
        rank_avg_amount_0/rank_avg_amount_5
        rank_avg_amount_5/rank_avg_amount_10
        rank_return_0
        rank_return_5
        rank_return_10
        rank_return_0/rank_return_5
        rank_return_5/rank_return_10
        pe_ttm_0
        """
        )
        
        m15 = M.general_feature_extractor.v7(
            instruments=m1.data,
            features=m3.data,
            start_date='',
            end_date='',
            before_start_days=0
        )
        
        m16 = M.derived_feature_extractor.v3(
            input_data=m15.data,
            features=m3.data,
            date_col='date',
            instrument_col='instrument',
            drop_na=False,
            remove_extra_columns=False
        )
        
        m7 = M.join.v3(
            data1=m2.data,
            data2=m16.data,
            on='date,instrument',
            how='inner',
            sort=False
        )
        
        m13 = M.dropnan.v1(
            input_data=m7.data
        )
        
        m6 = M.stock_ranker_train.v5(
            training_ds=m13.data,
            features=m3.data,
            learning_algorithm='排序',
            number_of_leaves=30,
            minimum_docs_per_leaf=1000,
            number_of_trees=20,
            learning_rate=0.1,
            max_bins=1023,
            feature_fraction=1,
            m_lazy_run=False
        )
        
        m9 = M.instruments.v2(
            start_date=T.live_run_param('trading_date', '2015-01-01'),
            end_date=T.live_run_param('trading_date', '2017-01-01'),
            market='CN_STOCK_A',
            instrument_list='',
            max_count=0
        )
        
        m17 = M.general_feature_extractor.v7(
            instruments=m9.data,
            features=m3.data,
            start_date='',
            end_date='',
            before_start_days=0
        )
        
        m18 = M.derived_feature_extractor.v3(
            input_data=m17.data,
            features=m3.data,
            date_col='date',
            instrument_col='instrument',
            drop_na=False,
            remove_extra_columns=False
        )
        
        m14 = M.dropnan.v1(
            input_data=m18.data
        )
        
        m8 = M.stock_ranker_predict.v5(
            model=m6.model,
            data=m14.data,
            m_lazy_run=False
        )
        
        m19 = M.trade.v4(
            instruments=m9.data,
            options_data=m8.predictions,
            start_date='',
            end_date='',
            initialize=m19_initialize_bigquant_run,
            handle_data=m19_handle_data_bigquant_run,
            prepare=m19_prepare_bigquant_run,
            volume_limit=0.025,
            order_price_field_buy='open',
            order_price_field_sell='close',
            capital_base=1000000,
            auto_cancel_non_tradable_orders=True,
            data_frequency='daily',
            price_type='真实价格',
            product_type='股票',
            plot_charts=True,
            backtest_only=False,
            benchmark='000300.SHA'
        )
        
        设置测试数据集,查看训练迭代过程的NDCG
        bigcharts-data-start/{"__id":"bigchart-28cd2240310243b2bf633f9c8f4dfe28","__type":"tabs"}/bigcharts-data-end
        • 收益率418.09%
        • 年化收益率133.84%
        • 基准收益率-6.33%
        • 阿尔法0.92
        • 贝塔0.96
        • 夏普比率2.14
        • 胜率0.6
        • 盈亏比0.96
        • 收益波动率42.58%
        • 信息比率0.2
        • 最大回撤48.58%
        bigcharts-data-start/{"__id":"bigchart-de2d674fa952460db9c8f8d748db85b7","__type":"tabs"}/bigcharts-data-end

        3.1 股票配对交易策略

        克隆策略

        配对交易策略

          {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-836:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-3301:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-836:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-3041:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-3041:options_data","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-3301:input_data","SourceOutputPortId":"-836:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-3301:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nclose_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":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2018-10-28","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"601328.SHA\n601998.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-836","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":"300","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-836"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-836"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-836","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-3041","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 today = data.current_dt.strftime('%Y-%m-%d')\n zscore_today =context.zscore.ix[today]\n #获取股票的列表\n stocklist=context.instruments\n # 转换成回测引擎所需要的symbol格式\n symbol_1 = context.symbol(stocklist[0]) \n symbol_2 = context.symbol(stocklist[1]) \n\n # 持仓\n cur_position_1 = context.portfolio.positions[symbol_1].amount\n cur_position_2 = context.portfolio.positions[symbol_2].amount\n \n # 交易逻辑\n # 如果zscore大于上轨(>1),则价差会向下回归均值,因此需要买入股票x,卖出股票y\n if zscore_today > 1 and cur_position_1 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2): \n context.order_target_percent(symbol_2, 0)\n context.order_target_percent(symbol_1, 1)\n print(today, '全仓买入:',stocklist[0])\n \n # 如果zscore小于下轨(<-1),则价差会向上回归均值,因此需要买入股票y,卖出股票x\n elif zscore_today < -1 and cur_position_2 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2): \n context.order_target_percent(symbol_1, 0) \n context.order_target_percent(symbol_2, 1)\n print(today, '全仓买入:',stocklist[1])\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_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context,data):\n # 加载股票历史数据\n df = context.options['data'].read_df()\n df['date'] = df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n today = data.current_dt.strftime('%Y-%m-%d')\n # 获取前240个自然日的数据\n start_date = (pd.to_datetime(data.current_dt)-datetime.timedelta(days=240)).strftime('%Y-%m-%d')\n stock_data = df[df.date <= today]\n # 由于可能上市天数不同,对缺失值填充处理\n prices_df=pd.pivot_table(stock_data, values='close_0', index=['date'], columns=['instrument'])\n prices_df.fillna(method='ffill',inplace=True)\n \n x = prices_df[context.instruments[0]] # 股票1\n y = prices_df[context.instruments[1]] # 股票2\n \n # 线性回归两个股票的股价 y=ax+b\n from pyfinance import ols\n model = ols.OLS(y=y, x=x)\n \n def zscore(series):\n return (series - series.mean()) / np.std(series)\n \n # 计算 y-a*x 序列的zscore值序列\n zscore_calcu = zscore(y-model.beta*x)\n context.zscore=zscore_calcu","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"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":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-3041"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-3041","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-3301","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":"-3301"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-3301"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-3301","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"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='1306,105,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='812,113,200,200'/><NodePosition Node='-86' Position='1079,397,200,200'/><NodePosition Node='-836' Position='1079,236,200,200'/><NodePosition Node='-3041' Position='999,558,200,200'/><NodePosition Node='-3301' Position='1088,305,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 [7]:
          # 本代码由可视化策略环境自动生成 2019年6月21日 13:50
          # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
          
          
          # 回测引擎:每日数据处理函数,每天执行一次
          def m3_handle_data_bigquant_run(context, data):
              today = data.current_dt.strftime('%Y-%m-%d')
              zscore_today =context.zscore.ix[today]
              #获取股票的列表
              stocklist=context.instruments
              # 转换成回测引擎所需要的symbol格式
              symbol_1 = context.symbol(stocklist[0]) 
              symbol_2 = context.symbol(stocklist[1])  
          
              # 持仓
              cur_position_1 = context.portfolio.positions[symbol_1].amount
              cur_position_2 = context.portfolio.positions[symbol_2].amount
                 
              # 交易逻辑
              # 如果zscore大于上轨(>1),则价差会向下回归均值,因此需要买入股票x,卖出股票y
              if zscore_today > 1 and cur_position_1 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2):  
                  context.order_target_percent(symbol_2, 0)
                  context.order_target_percent(symbol_1, 1)
                  print(today, '全仓买入:',stocklist[0])
                  
              # 如果zscore小于下轨(<-1),则价差会向上回归均值,因此需要买入股票y,卖出股票x
              elif zscore_today < -1 and cur_position_2 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2):  
                  context.order_target_percent(symbol_1, 0)  
                  context.order_target_percent(symbol_2, 1)
                  print(today, '全仓买入:',stocklist[1])
           
                    
          
          # 回测引擎:准备数据,只执行一次
          def m3_prepare_bigquant_run(context):
              pass
          # 回测引擎:初始化函数,只执行一次
          def m3_initialize_bigquant_run(context):
              # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
              context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
          # 回测引擎:准备数据,只执行一次
          def m3_before_trading_start_bigquant_run(context,data):
              # 加载股票历史数据
              df = context.options['data'].read_df()
              df['date'] = df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
              today = data.current_dt.strftime('%Y-%m-%d')
              # 获取前240个自然日的数据
              start_date = (pd.to_datetime(data.current_dt)-datetime.timedelta(days=240)).strftime('%Y-%m-%d')
              stock_data = df[df.date <= today]
              # 由于可能上市天数不同,对缺失值填充处理
              prices_df=pd.pivot_table(stock_data, values='close_0', index=['date'], columns=['instrument'])
              prices_df.fillna(method='ffill',inplace=True)
              
              x = prices_df[context.instruments[0]] # 股票1
              y = prices_df[context.instruments[1]] # 股票2
              
              # 线性回归两个股票的股价 y=ax+b
              from pyfinance import ols
              model = ols.OLS(y=y, x=x)
           
              def zscore(series):
                  return (series - series.mean()) / np.std(series)
              
              # 计算 y-a*x 序列的zscore值序列
              zscore_calcu = zscore(y-model.beta*x)
              context.zscore=zscore_calcu
          
          m1 = M.input_features.v1(
              features="""# #号开始的表示注释
          # 多个特征,每行一个,可以包含基础特征和衍生特征
          close_0
          """
          )
          
          m2 = M.instruments.v2(
              start_date=T.live_run_param('trading_date', '2015-01-01'),
              end_date=T.live_run_param('trading_date', '2018-10-28'),
              market='CN_STOCK_A',
              instrument_list="""601328.SHA
          601998.SHA""",
              max_count=0
          )
          
          m7 = M.general_feature_extractor.v7(
              instruments=m2.data,
              features=m1.data,
              start_date='',
              end_date='',
              before_start_days=300
          )
          
          m4 = M.derived_feature_extractor.v3(
              input_data=m7.data,
              features=m1.data,
              date_col='date',
              instrument_col='instrument',
              drop_na=False,
              remove_extra_columns=False,
              user_functions={}
          )
          
          m6 = M.dropnan.v1(
              input_data=m4.data
          )
          
          m3 = M.trade.v4(
              instruments=m2.data,
              options_data=m6.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.025,
              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=''
          )
          
          2015-01-05 全仓买入: 601328.SHA
          2015-06-01 全仓买入: 601998.SHA
          2015-07-08 全仓买入: 601328.SHA
          2015-08-31 全仓买入: 601998.SHA
          2015-11-18 全仓买入: 601328.SHA
          2016-06-06 全仓买入: 601998.SHA
          
          2016-11-28 全仓买入: 601328.SHA
          2017-04-19 全仓买入: 601998.SHA
          
          2018-02-05 全仓买入: 601328.SHA
          
          2018-09-14 全仓买入: 601998.SHA
          
          • 收益率54.33%
          • 年化收益率12.48%
          • 基准收益率-10.19%
          • 阿尔法0.15
          • 贝塔0.74
          • 夏普比率0.44
          • 胜率0.67
          • 盈亏比0.69
          • 收益波动率30.75%
          • 信息比率0.04
          • 最大回撤40.63%
          bigcharts-data-start/{"__id":"bigchart-56cff1c73cbc45268d29cd7a4da5d1ce","__type":"tabs"}/bigcharts-data-end

          3.2 双均线策略+固定百分比止损

          克隆策略

          双均线策略+固定百分比止损

            {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-50:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-57:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-50:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-102:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-102:options_data","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-57:input_data","SourceOutputPortId":"-50:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-57:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where(mean(close_0,5)>mean(close_0,20),1,0)\nsell_condition=where(mean(close_0,5)<mean(close_0,20),1,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":false,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"600519.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-50","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":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-50"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-50"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-50","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-57","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":"-57"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-57"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-57","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-102","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.0013, min_cost=5))\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n #------------------------------------------止损模块START------------------------------------------- #\n date = data.current_dt.strftime('%Y-%m-%d')\n positions = {e.symbol: p.cost_basis for e, p in context.portfolio.positions.items()}\n # 新建当日止赢股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断\n current_stopwin_stock = [] \n if len(positions) > 0:\n for i in positions.keys():\n stock_cost = positions[i] \n stock_market_price = data.current(context.symbol(i), 'price') \n # 赚10%止盈\n if stock_market_price / stock_cost -1 > 0.1: \n context.order_target_percent(context.symbol(i),0) \n current_stopwin_stock.append(i)\n print('日期:',date,'股票:',i,'出现上涨10%,触发止盈')\n #-------------------------------------------止损模块END---------------------------------------------#\n\n\n\n\n # 1. 获取今日的日期\n today = data.current_dt.strftime('%Y-%m-%d')\n \n # 2. 获取目前持仓的股票和最新市值\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price for e, p in context.portfolio.positions.items()} \n \n # 3. 获取当前账户可用现金\n cash_for_buy = context.portfolio.cash\n \n # 4. 获取当日的买卖信号股票列表\n try:\n buy_stock = context.daily_stock_buy[today]\n except:\n buy_stock=[] # 如果没有符合条件的股票,就设置为空\n \n try:\n sell_stock = context.daily_stock_sell[today]\n except:\n sell_stock=[] # 如果没有符合条件的股票,就设置为空 \n \n # 5. 确认需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]\n \n # 6. 执行卖出操作\n if len(stock_to_sell)>0:\n for instrument in stock_to_sell:\n # 如果股票已经在止盈列表中,则跳过卖出操作\n if instrument in current_stopwin_stock:\n continue\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 当前持仓\n if cur_position > 0 and data.can_trade(sid):\n context.order_target_percent(sid, 0) # 全部卖出\n # 根据卖出的股票市值更新可用现金:\n cash_for_buy += stock_hold_now[instrument]\n \n # 7. 执行买入操作\n if len(buy_stock)>0:\n weight = 1/len(buy_stock) # 每只股票的比重为等资金比例持有\n for instrument in buy_stock:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 当前持仓\n if data.can_trade(sid) and cur_position==0:\n context.order_target_value(sid, weight*cash_for_buy) # 按可用现金等比例买入","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n df = context.options['data'].read_df()\n\n # 函数:求满足开仓条件的股票列表\n def open_pos_con(df):\n return list(df[df['buy_condition']>0].instrument)\n\n # 函数:求满足平仓条件的股票列表\n def close_pos_con(df):\n return list(df[df['sell_condition']>0].instrument)\n\n # 每日买入股票的数据框\n context.daily_stock_buy= df.groupby('date').apply(open_pos_con)\n # 每日卖出股票的数据框\n context.daily_stock_sell= df.groupby('date').apply(close_pos_con)","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":"1000000","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"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":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-102"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-102","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,19.007720947265625,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1072,123,200,200'/><NodePosition Node='-86' Position='1077,418,200,200'/><NodePosition Node='-50' Position='1078,232,200,200'/><NodePosition Node='-57' Position='1076,327,200,200'/><NodePosition Node='-102' Position='1048,529,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 [5]:
            # 本代码由可视化策略环境自动生成 2019年9月19日 17:23
            # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
            
            
            # 回测引擎:初始化函数,只执行一次
            def m3_initialize_bigquant_run(context):
            
                # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
                context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
            
            # 回测引擎:每日数据处理函数,每天执行一次
            def m3_handle_data_bigquant_run(context, data):
                
             #------------------------------------------止损模块START------------------------------------------- #
                date = data.current_dt.strftime('%Y-%m-%d')
                positions = {e.symbol: p.cost_basis  for e, p in context.portfolio.positions.items()}
                # 新建当日止赢股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
                current_stopwin_stock = [] 
                if len(positions) > 0:
                    for i in positions.keys():
                        stock_cost = positions[i] 
                        stock_market_price = data.current(context.symbol(i), 'price') 
                        # 赚10%止盈
                        if stock_market_price / stock_cost -1 > 0.1:   
                            context.order_target_percent(context.symbol(i),0)     
                            current_stopwin_stock.append(i)
                            print('日期:',date,'股票:',i,'出现上涨10%,触发止盈')
             #-------------------------------------------止损模块END---------------------------------------------#
            
            
            
            
                # 1. 获取今日的日期
                today = data.current_dt.strftime('%Y-%m-%d')
                
                # 2. 获取目前持仓的股票和最新市值
                stock_hold_now = {e.symbol: p.amount * p.last_sale_price for e, p in context.portfolio.positions.items()} 
                
                # 3. 获取当前账户可用现金
                cash_for_buy = context.portfolio.cash
                
                # 4. 获取当日的买卖信号股票列表
                try:
                    buy_stock = context.daily_stock_buy[today]
                except:
                    buy_stock=[]  # 如果没有符合条件的股票,就设置为空
                
                try:
                    sell_stock = context.daily_stock_sell[today]
                except:
                    sell_stock=[] # 如果没有符合条件的股票,就设置为空 
                    
                # 5. 确认需要卖出的股票:已有持仓中符合卖出条件的股票
                stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]
                
                # 6. 执行卖出操作
                if len(stock_to_sell)>0:
                    for instrument in stock_to_sell:
                        # 如果股票已经在止盈列表中,则跳过卖出操作
                        if instrument in current_stopwin_stock:
                            continue
                        sid = context.symbol(instrument) # 将标的转化为equity格式
                        cur_position = context.portfolio.positions[sid].amount # 当前持仓
                        if cur_position > 0 and data.can_trade(sid):
                            context.order_target_percent(sid, 0) # 全部卖出
                            # 根据卖出的股票市值更新可用现金:
                            cash_for_buy += stock_hold_now[instrument]
                
                # 7. 执行买入操作
                if len(buy_stock)>0:
                    weight = 1/len(buy_stock)  # 每只股票的比重为等资金比例持有
                    for instrument in buy_stock:
                        sid = context.symbol(instrument) # 将标的转化为equity格式
                        cur_position = context.portfolio.positions[sid].amount # 当前持仓
                        if  data.can_trade(sid) and cur_position==0:
                            context.order_target_value(sid, weight*cash_for_buy) # 按可用现金等比例买入
            # 回测引擎:准备数据,只执行一次
            def m3_prepare_bigquant_run(context):
                # 加载预测数据
                df = context.options['data'].read_df()
            
                # 函数:求满足开仓条件的股票列表
                def open_pos_con(df):
                    return list(df[df['buy_condition']>0].instrument)
            
                # 函数:求满足平仓条件的股票列表
                def close_pos_con(df):
                    return list(df[df['sell_condition']>0].instrument)
            
                # 每日买入股票的数据框
                context.daily_stock_buy= df.groupby('date').apply(open_pos_con)
                # 每日卖出股票的数据框
                context.daily_stock_sell= df.groupby('date').apply(close_pos_con)
            
            m1 = M.input_features.v1(
                features="""# #号开始的表示注释
            # 多个特征,每行一个,可以包含基础特征和衍生特征
            buy_condition=where(mean(close_0,5)>mean(close_0,20),1,0)
            sell_condition=where(mean(close_0,5)<mean(close_0,20),1,0)""",
                m_cached=False
            )
            
            m2 = M.instruments.v2(
                start_date=T.live_run_param('trading_date', '2016-01-01'),
                end_date=T.live_run_param('trading_date', '2017-01-01'),
                market='CN_STOCK_A',
                instrument_list='600519.SHA',
                max_count=0
            )
            
            m7 = M.general_feature_extractor.v7(
                instruments=m2.data,
                features=m1.data,
                start_date='',
                end_date='',
                before_start_days=200,
                m_cached=False
            )
            
            m8 = M.derived_feature_extractor.v3(
                input_data=m7.data,
                features=m1.data,
                date_col='date',
                instrument_col='instrument',
                drop_na=False,
                remove_extra_columns=False
            )
            
            m6 = M.dropnan.v1(
                input_data=m8.data
            )
            
            m3 = M.trade.v4(
                instruments=m2.data,
                options_data=m6.data,
                start_date='',
                end_date='',
                initialize=m3_initialize_bigquant_run,
                handle_data=m3_handle_data_bigquant_run,
                prepare=m3_prepare_bigquant_run,
                volume_limit=0.025,
                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=''
            )
            
            日期: 2016-03-03 股票: 600519.SHA 出现上涨10%,触发止盈
            日期: 2016-06-03 股票: 600519.SHA 出现上涨10%,触发止盈
            日期: 2016-07-05 股票: 600519.SHA 出现上涨10%,触发止盈
            
            • 收益率28.16%
            • 年化收益率29.21%
            • 基准收益率-11.28%
            • 阿尔法0.29
            • 贝塔0.3
            • 夏普比率1.2
            • 胜率0.56
            • 盈亏比3.01
            • 收益波动率20.66%
            • 信息比率0.09
            • 最大回撤10.38%
            bigcharts-data-start/{"__type":"tabs","__id":"bigchart-98dd58eca2ef47d28cebe0c77f0b82b4"}/bigcharts-data-end

            3.3 多因子选股

            克隆策略

              {"Description":"实验创建于2019/4/24","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-64:input_ds","SourceOutputPortId":"-6:data"},{"DestinationInputPortId":"-6:instruments","SourceOutputPortId":"-21:data"},{"DestinationInputPortId":"-43:instruments","SourceOutputPortId":"-21:data"},{"DestinationInputPortId":"-43:options_data","SourceOutputPortId":"-30:data"},{"DestinationInputPortId":"-6:features","SourceOutputPortId":"-35:data"},{"DestinationInputPortId":"-30:input_data","SourceOutputPortId":"-64:data_1"}],"ModuleNodes":[{"Id":"-6","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":90,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-6"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-6"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-6","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-21","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-04-23","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":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-21"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-21","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-30","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"pb_lf_0 < 1.5 & pe_ttm_0 < 15 & amount_0 > 0 & pb_lf_0 > 0 & pe_ttm_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":"-30"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-30","OutputType":null},{"Name":"left_data","NodeId":"-30","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-35","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"pb_lf_0\npe_ttm_0\namount_0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-35"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-35","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-43","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 # 1. 按每个K线递增,记录策略运行天数\n context.extension['index'] += 1\n \n # 2. 每隔22个交易日进行换仓\n if context.extension['index'] % context.rebalance_days != 1:\n return \n \n # 3. 买入股票列表\n stock_to_buy = context.daily_stock_buy.ix[ata.current_dt.strftime('%Y-%m-%d')]\n \n # 4. 当前持仓列表 \n stock_hold_now = [equity.symbol for equity in context.portfolio.positions]\n\n # 5. 卖出股票列表 \n stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]\n \n # 6. 执行卖出\n for stock in stock_to_sell:\n if data.can_trade(context.symbol(stock)):\n context.order_target_percent(context.symbol(stock), 0)\n \n # 7. 执行买入\n if len(stock_to_buy)>0: \n weight = 1 / len(stock_to_buy) # 等权重\n for instrument in stock_to_buy:\n if data.can_trade(context.symbol(instrument)):\n context.order_target_percent(context.symbol(instrument), weight)","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载股票指标数据,数据继承自m4模块\n context.indicator_data = context.options['data'].read_df()\n\n # 设置股票数量\n context.stock_num = 30\n \n def open_pos_con(df):\n return list(df.instrument)[:context.stock_num]\n \n # 计算每日股票买入列表\n context.daily_stock_buy = context.indicator_data.groupby('date').apply(open_pos_con)\n \n # 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次\n context.rebalance_days = 22\n \n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n \n # 设置交易费用,买入是万三,卖出是千分之1.3,如果不足5元按5元算\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n \n # 如果策略运行中,需要将数据(比如运行天数)进行保存,可以借用extension这个对象,类型为dict\n if 'index' not in context.extension:\n context.extension['index'] = 0","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"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":"-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-43"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-43","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-64","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"pe_ttm_0,pb_lf_0","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-64"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-64"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-64","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"按多个因子进行排序","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='-6' Position='197.74703979492188,108.72286987304688,200,200'/><NodePosition Node='-21' Position='7.024139404296875,22.698776245117188,200,200'/><NodePosition Node='-30' Position='202.10845947265625,251.40960693359375,200,200'/><NodePosition Node='-35' Position='329.6506652832031,19.144546508789062,200,200'/><NodePosition Node='-43' Position='118.91571044921875,334.2048034667969,200,200'/><NodePosition Node='-64' Position='197.65066528320312,177.7108154296875,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年6月20日 18:29
              # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
              
              
              # 回测引擎:每日数据处理函数,每天执行一次
              def m2_handle_data_bigquant_run(context, data):
                  
                  # 1. 按每个K线递增,记录策略运行天数
                  context.extension['index']  += 1
                  
                  # 2. 每隔22个交易日进行换仓
                  if context.extension['index'] % context.rebalance_days != 1:
                      return 
                  
                  # 3. 买入股票列表
                  stock_to_buy = context.daily_stock_buy.ix[ata.current_dt.strftime('%Y-%m-%d')]
                  
                  # 4. 当前持仓列表    
                  stock_hold_now = [equity.symbol for equity in context.portfolio.positions]
              
                  # 5. 卖出股票列表 
                  stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]
                  
                  # 6. 执行卖出
                  for stock in stock_to_sell:
                      if data.can_trade(context.symbol(stock)):
                          context.order_target_percent(context.symbol(stock), 0)
                          
                  # 7. 执行买入
                  if len(stock_to_buy)>0: 
                      weight = 1 / len(stock_to_buy) # 等权重
                      for  instrument in stock_to_buy:
                          if data.can_trade(context.symbol(instrument)):
                              context.order_target_percent(context.symbol(instrument), weight)
              # 回测引擎:准备数据,只执行一次
              def m2_prepare_bigquant_run(context):
                  # 加载股票指标数据,数据继承自m4模块
                  context.indicator_data = context.options['data'].read_df()
              
                   # 设置股票数量
                  context.stock_num = 30
                  
                  def open_pos_con(df):
                      return list(df.instrument)[:context.stock_num]
                  
                  # 计算每日股票买入列表
                  context.daily_stock_buy = context.indicator_data.groupby('date').apply(open_pos_con)
                  
                  # 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次
                  context.rebalance_days = 22
                  
              
              # 回测引擎:初始化函数,只执行一次
              def m2_initialize_bigquant_run(context):
                  
                  # 设置交易费用,买入是万三,卖出是千分之1.3,如果不足5元按5元算
                  context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
                  
                  # 如果策略运行中,需要将数据(比如运行天数)进行保存,可以借用extension这个对象,类型为dict
                  if 'index' not in context.extension:
                      context.extension['index'] = 0
              
              m3 = M.instruments.v2(
                  start_date='2015-01-01',
                  end_date='2019-04-23',
                  market='CN_STOCK_A',
                  instrument_list=''
              )
              
              m5 = M.input_features.v1(
                  features="""pb_lf_0
              pe_ttm_0
              amount_0"""
              )
              
              m1 = M.general_feature_extractor.v7(
                  instruments=m3.data,
                  features=m5.data,
                  start_date='',
                  end_date='',
                  before_start_days=90
              )
              
              m6 = M.sort.v4(
                  input_ds=m1.data,
                  sort_by='pe_ttm_0,pb_lf_0',
                  group_by='date',
                  keep_columns='--',
                  ascending=True
              )
              
              m4 = M.filter.v3(
                  input_data=m6.data_1,
                  expr='pb_lf_0 < 1.5 & pe_ttm_0 < 15 & amount_0 > 0 & pb_lf_0 > 0 & pe_ttm_0 > 0',
                  output_left_data=False
              )
              
              m2 = M.trade.v4(
                  instruments=m3.data,
                  options_data=m4.data,
                  start_date='',
                  end_date='',
                  handle_data=m2_handle_data_bigquant_run,
                  prepare=m2_prepare_bigquant_run,
                  initialize=m2_initialize_bigquant_run,
                  volume_limit=0.025,
                  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=''
              )
              
              • 收益率86.33%
              • 年化收益率16.13%
              • 基准收益率13.73%
              • 阿尔法0.12
              • 贝塔0.84
              • 夏普比率0.6
              • 胜率0.45
              • 盈亏比2.44
              • 收益波动率25.28%
              • 信息比率0.05
              • 最大回撤30.73%
              bigcharts-data-start/{"__type":"tabs","__id":"bigchart-5f61ccbd3ede4c17bafaa4c9263c96b1"}/bigcharts-data-end

              3.4 双均线策略

              克隆策略

              双均线策略

                {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-50:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-57:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-50:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-102:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-102:options_data","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-57:input_data","SourceOutputPortId":"-50:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-57:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where(mean(close_0,5)>mean(close_0,20),1,0)\nsell_condition=where(mean(close_0,5)<mean(close_0,20),1,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":false,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"600519.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-50","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":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-50"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-50"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-50","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-57","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":"-57"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-57"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-57","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-102","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 # 1. 获取今日的日期\n today = data.current_dt.strftime('%Y-%m-%d')\n \n # 2. 获取目前持仓的股票和最新市值\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price for e, p in context.portfolio.positions.items()} \n \n # 3. 获取当前账户可用现金\n cash_for_buy = context.portfolio.cash\n \n # 4. 获取当日的买卖信号股票列表\n try:\n buy_stock = context.daily_stock_buy[today]\n except:\n buy_stock=[] # 如果没有符合条件的股票,就设置为空\n \n try:\n sell_stock = context.daily_stock_sell[today]\n except:\n sell_stock=[] # 如果没有符合条件的股票,就设置为空 \n \n # 5. 确认需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]\n \n # 6. 执行卖出操作\n if len(stock_to_sell)>0:\n for instrument in stock_to_sell:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 当前持仓\n if cur_position > 0 and data.can_trade(sid):\n context.order_target_percent(sid, 0) \n # 根据卖出的股票市值更新可用现金;\n cash_for_buy += stock_hold_now[instrument]\n \n # 7. 执行买入操作\n if len(buy_stock)>0:\n weight = 1/len(buy_stock) # 每只股票的比重为等资金比例持有\n for instrument in buy_stock:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 当前持仓\n if data.can_trade(sid) and cur_position==0:\n context.order_target_value(sid, weight*cash_for_buy) # 按可用现金等比例买入","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n df = context.options['data'].read_df()\n\n # 函数:求满足开仓条件的股票列表\n def open_pos_con(df):\n return list(df[df['buy_condition']>0].instrument)\n\n # 函数:求满足平仓条件的股票列表\n def close_pos_con(df):\n return list(df[df['sell_condition']>0].instrument)\n\n # 每日买入股票的数据框\n context.daily_stock_buy= df.groupby('date').apply(open_pos_con)\n # 每日卖出股票的数据框\n context.daily_stock_sell= df.groupby('date').apply(close_pos_con)","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n \n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))","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":"close","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":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-102"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-102"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-102","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":3,"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='1165,136,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='868,91,200,200'/><NodePosition Node='-86' Position='1078,418,200,200'/><NodePosition Node='-50' Position='1071,238,200,200'/><NodePosition Node='-57' Position='1076,327,200,200'/><NodePosition Node='-102' Position='972,505,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 [37]:
                # 本代码由可视化策略环境自动生成 2019年6月20日 15:59
                # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
                
                
                # 回测引擎:每日数据处理函数,每天执行一次
                def m3_handle_data_bigquant_run(context, data):
                    # 1. 获取今日的日期
                    today = data.current_dt.strftime('%Y-%m-%d')
                    
                    # 2. 获取目前持仓的股票和最新市值
                    stock_hold_now = {e.symbol: p.amount * p.last_sale_price for e, p in context.portfolio.positions.items()} 
                    
                    # 3. 获取当前账户可用现金
                    cash_for_buy = context.portfolio.cash
                    
                    # 4. 获取当日的买卖信号股票列表
                    try:
                        buy_stock = context.daily_stock_buy[today]
                    except:
                        buy_stock=[]  # 如果没有符合条件的股票,就设置为空
                    
                    try:
                        sell_stock = context.daily_stock_sell[today]
                    except:
                        sell_stock=[] # 如果没有符合条件的股票,就设置为空 
                        
                    # 5. 确认需要卖出的股票:已有持仓中符合卖出条件的股票
                    stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]
                    
                    # 6. 执行卖出操作
                    if len(stock_to_sell)>0:
                        for instrument in stock_to_sell:
                            sid = context.symbol(instrument) # 将标的转化为equity格式
                            cur_position = context.portfolio.positions[sid].amount # 当前持仓
                            if cur_position > 0 and data.can_trade(sid):
                                context.order_target_percent(sid, 0) 
                                # 根据卖出的股票市值更新可用现金;
                                cash_for_buy += stock_hold_now[instrument]
                    
                    # 7. 执行买入操作
                    if len(buy_stock)>0:
                        weight = 1/len(buy_stock)  # 每只股票的比重为等资金比例持有
                        for instrument in buy_stock:
                            sid = context.symbol(instrument) # 将标的转化为equity格式
                            cur_position = context.portfolio.positions[sid].amount # 当前持仓
                            if  data.can_trade(sid) and cur_position==0:
                                context.order_target_value(sid, weight*cash_for_buy) # 按可用现金等比例买入
                # 回测引擎:准备数据,只执行一次
                def m3_prepare_bigquant_run(context):
                    # 加载预测数据
                    df = context.options['data'].read_df()
                
                    # 函数:求满足开仓条件的股票列表
                    def open_pos_con(df):
                        return list(df[df['buy_condition']>0].instrument)
                
                    # 函数:求满足平仓条件的股票列表
                    def close_pos_con(df):
                        return list(df[df['sell_condition']>0].instrument)
                
                    # 每日买入股票的数据框
                    context.daily_stock_buy= df.groupby('date').apply(open_pos_con)
                    # 每日卖出股票的数据框
                    context.daily_stock_sell= df.groupby('date').apply(close_pos_con)
                # 回测引擎:初始化函数,只执行一次
                def m3_initialize_bigquant_run(context):
                 
                    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
                    context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
                
                m1 = M.input_features.v1(
                    features="""# #号开始的表示注释
                # 多个特征,每行一个,可以包含基础特征和衍生特征
                buy_condition=where(mean(close_0,5)>mean(close_0,20),1,0)
                sell_condition=where(mean(close_0,5)<mean(close_0,20),1,0)""",
                    m_cached=False
                )
                
                m2 = M.instruments.v2(
                    start_date=T.live_run_param('trading_date', '2016-01-01'),
                    end_date=T.live_run_param('trading_date', '2017-01-01'),
                    market='CN_STOCK_A',
                    instrument_list='600519.SHA',
                    max_count=0
                )
                
                m7 = M.general_feature_extractor.v7(
                    instruments=m2.data,
                    features=m1.data,
                    start_date='',
                    end_date='',
                    before_start_days=200,
                    m_cached=False
                )
                
                m8 = M.derived_feature_extractor.v3(
                    input_data=m7.data,
                    features=m1.data,
                    date_col='date',
                    instrument_col='instrument',
                    drop_na=False,
                    remove_extra_columns=False
                )
                
                m6 = M.dropnan.v1(
                    input_data=m8.data
                )
                
                m3 = M.trade.v4(
                    instruments=m2.data,
                    options_data=m6.data,
                    start_date='',
                    end_date='',
                    handle_data=m3_handle_data_bigquant_run,
                    prepare=m3_prepare_bigquant_run,
                    initialize=m3_initialize_bigquant_run,
                    volume_limit=0.025,
                    order_price_field_buy='close',
                    order_price_field_sell='close',
                    capital_base=1000000,
                    auto_cancel_non_tradable_orders=True,
                    data_frequency='daily',
                    price_type='后复权',
                    product_type='股票',
                    plot_charts=True,
                    backtest_only=False,
                    benchmark=''
                )
                
                • 收益率40.57%
                • 年化收益率42.15%
                • 基准收益率-11.28%
                • 阿尔法0.38
                • 贝塔0.3
                • 夏普比率1.59
                • 胜率0.67
                • 盈亏比3.01
                • 收益波动率21.81%
                • 信息比率0.12
                • 最大回撤11.05%
                bigcharts-data-start/{"__type":"tabs","__id":"bigchart-712f0f11151f472d97bd3a10ef466e4c"}/bigcharts-data-end