buy_conditon里 用a股业绩报表的数据出错?

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

(lyxpayne) #1

比如: buy_condition=where(sjltz>0.2)
系统提示 WARNING: DataReader: cannot find filed [sjltz] table in field_table_map!

这种用法不正确吗? 怎样才能用a股业绩报表的数据来作为买入或者卖出条件呢?

谢谢

克隆策略

价值选股策略

版本 v1.0

目录

  • ### 价值选股策略的交易规则

  • ### 策略构建步骤

  • ### 策略的实现

正文

一、价值选股策略的交易规则

  • 每隔30个交易日,以开盘价买入当日0<PB<1.5且0<PE<15且有成交量的股票;
  • 每隔30个交易日,将不符合上述标准的持仓股票在第二天以收盘价卖出。

二、策略构建步骤

1、确定股票池和回测时间

  • 通过证券代码列表输入要回测的单只/多只股票,以及回测的起止日期

2、确定买卖条件信号

  • 在输入特征列表中通过表达式引擎定义 buy_condition=where((pb_lf_0<1.5) & (pe_ttm_0<15) & (amount_0>0) & (pb_lf_0>0) & (pe_ttm_0>0), 1, 0) 实现买入条件信号定义。
  • 通过基础特征和衍生特征抽取模块实现买卖条件指标 buy_condition 数据的抽取。
  • 通过缺失数据处理模块删去有缺失值的数据。
  • 通过排序模块实现每日股票数据按 pe_ttm_0 和 pb_lf_0 两个指标降序排列

3、确定买卖原则

  • 每隔30个交易日换仓一次;
  • 已有持仓中不满足买入条件的股票为卖出股票列表,需执行卖出操作
  • 满足买入条件且没有持仓的股票为买入股票列表,需执行买入操作
  • 满足买入条件且已有持仓的股票为调仓股票列表,需执行调整仓位操作
  • 本策略中将买入股票列表和调仓股票列表中的所有股票统一调整为等资金比例仓位。

4、模拟回测

  • 通过 trade 模块中的初始化函数定义交易手续费和滑点;
  • 通过 trade 模块中的准备函数定义 context.daily_stock_buy 变量来获取并存放每日买卖交易信号;
  • 通过 trade 模块中的主函数(handle函数)查看每日的买卖交易信号,按照买卖原则执行相应的买入/卖出/调仓操作。

三、策略的实现

可视化策略实现如下:

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-2326:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-2333:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-2326:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2171:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2333:input_data","SourceOutputPortId":"-2326:data"},{"DestinationInputPortId":"-104:input_data","SourceOutputPortId":"-2333:data"},{"DestinationInputPortId":"-2171:options_data","SourceOutputPortId":"-50:sorted_data"},{"DestinationInputPortId":"-5045:input_data","SourceOutputPortId":"-104:data"},{"DestinationInputPortId":"-50:input_ds","SourceOutputPortId":"-5045:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where(sjltz>0.2)","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":"2017-05-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-10-11","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":2,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"-2326","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":"60","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-2326"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-2326"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2326","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2333","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":"-2333"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-2333"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2333","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-50","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"sjltz","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":"-50"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-50"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-50","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2171","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\n stock_count = 20\n \n ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n #周期控制\n if context.trading_day_index % 30 != 0:#以30天(交易日)换一次仓为例\n return\n # 获取今日的日期\n today = data.current_dt.strftime('%Y-%m-%d') \n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()} \n \n # 记录用于买入股票的可用现金\n cash_for_buy = context.portfolio.cash \n \n 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 # 需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]\n # 需要买入的股票:没有持仓且符合买入条件的股票\n stock_to_buy = [ i for i in buy_stock if i not in stock_hold_now ] \n # 需要调仓的股票:已有持仓且不符合卖出条件的股票\n stock_to_adjust=[ i for i in stock_hold_now if i not in sell_stock ]\n \n # 如果有卖出信号\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 # 如果有买入信号/有持仓\n if len(stock_to_buy)+len(stock_to_adjust)>0:\n weight = 1/(len(stock_to_buy)+len(stock_to_adjust)) # 每只股票的比重为等资金比例持有\n for instrument in stock_to_buy+stock_to_adjust:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n if data.can_trade(sid):\n context.order_target_value(sid, weight*cash_for_buy) # 买入","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n history_data = context.options['data'].read_df()\n\n #获取每日买入股票列表\n context.daily_stock_buy = history_data.groupby('date').apply(lambda x:x.instrument[:30])\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":"vwap_11","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":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-2171"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-2171","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-104","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"buy_condition>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":"-104"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-104","OutputType":null},{"Name":"left_data","NodeId":"-104","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5045","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-5045"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-5045"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5045","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"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='1298,45,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='801,35,200,200'/><NodePosition Node='-2326' Position='970,185,200,200'/><NodePosition Node='-2333' Position='1135,302,200,200'/><NodePosition Node='-50' Position='1122,543,200,200'/><NodePosition Node='-2171' Position='997,646,200,200'/><NodePosition Node='-104' Position='1107,383,200,200'/><NodePosition Node='-5045' Position='1133,459,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 [2]:
    # 本代码由可视化策略环境自动生成 2020年9月1日 10:54
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m9_initialize_bigquant_run(context):
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    
        stock_count = 20
        
        
    # 回测引擎:每日数据处理函数,每天执行一次
    def m9_handle_data_bigquant_run(context, data):
         #周期控制
        if context.trading_day_index % 30 != 0:#以30天(交易日)换一次仓为例
            return
        # 获取今日的日期
        today = data.current_dt.strftime('%Y-%m-%d')  
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
        stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                          for e, p in context.perf_tracker.position_tracker.positions.items()} 
        
        # 记录用于买入股票的可用现金
        cash_for_buy = context.portfolio.cash     
        
        try:
            buy_stock = context.daily_stock_buy[today]  # 当日符合买入条件的股票
        except:
            buy_stock=[]  # 如果没有符合条件的股票,就设置为空
        
        try:
            sell_stock = context.daily_stock_sell[today]  # 当日符合卖出条件的股票
        except:
            sell_stock=[] # 如果没有符合条件的股票,就设置为空
        
        # 需要卖出的股票:已有持仓中符合卖出条件的股票
        stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]
        # 需要买入的股票:没有持仓且符合买入条件的股票
        stock_to_buy = [ i for i in buy_stock if i not in stock_hold_now ]  
        # 需要调仓的股票:已有持仓且不符合卖出条件的股票
        stock_to_adjust=[ i for i in stock_hold_now if i not in sell_stock ]
        
        # 如果有卖出信号
        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]
        
        # 如果有买入信号/有持仓
        if len(stock_to_buy)+len(stock_to_adjust)>0:
            weight = 1/(len(stock_to_buy)+len(stock_to_adjust)) # 每只股票的比重为等资金比例持有
            for instrument in stock_to_buy+stock_to_adjust:
                sid = context.symbol(instrument) # 将标的转化为equity格式
                if  data.can_trade(sid):
                    context.order_target_value(sid, weight*cash_for_buy) # 买入
    # 回测引擎:准备数据,只执行一次
    def m9_prepare_bigquant_run(context):
        # 加载预测数据
        history_data = context.options['data'].read_df()
    
        #获取每日买入股票列表
        context.daily_stock_buy = history_data.groupby('date').apply(lambda x:x.instrument[:30])
    
    
    m1 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    buy_condition=where(sjltz>0.2)"""
    )
    
    m2 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2017-05-01'),
        end_date=T.live_run_param('trading_date', '2019-10-11'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m7 = M.general_feature_extractor.v7(
        instruments=m2.data,
        features=m1.data,
        start_date='',
        end_date='',
        before_start_days=60
    )
    
    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
    )
    
    m4 = M.filter.v3(
        input_data=m8.data,
        expr='buy_condition>0',
        output_left_data=False
    )
    
    m5 = M.dropnan.v2(
        input_data=m4.data
    )
    
    m3 = M.sort.v4(
        input_ds=m5.data,
        sort_by='sjltz',
        group_by='date',
        keep_columns='--',
        ascending=True
    )
    
    m9 = M.trade.v4(
        instruments=m2.data,
        options_data=m3.sorted_data,
        start_date='',
        end_date='',
        initialize=m9_initialize_bigquant_run,
        handle_data=m9_handle_data_bigquant_run,
        prepare=m9_prepare_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='vwap_11',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    ---------------------------------------------------------------------------
    Exception                                 Traceback (most recent call last)
    <ipython-input-2-e75acc58a276> in <module>()
         88     start_date='',
         89     end_date='',
    ---> 90     before_start_days=60
         91 )
         92 
    
    Exception: no features extracted.

    (adhaha111) #2

    您好,该因子只是存在于数据表中,并没有支持在表达式引擎中,您可以先通过数据源来抽取其特征;并且您的where函数用法也不正确:
    image

    建议可以查看下因子相关文档:https://bigquant.com/docs/devbigexpr.html

    克隆策略

    价值选股策略

    版本 v1.0

    目录

    • ### 价值选股策略的交易规则

    • ### 策略构建步骤

    • ### 策略的实现

    正文

    一、价值选股策略的交易规则

    • 每隔30个交易日,以开盘价买入当日0<PB<1.5且0<PE<15且有成交量的股票;
    • 每隔30个交易日,将不符合上述标准的持仓股票在第二天以收盘价卖出。

    二、策略构建步骤

    1、确定股票池和回测时间

    • 通过证券代码列表输入要回测的单只/多只股票,以及回测的起止日期

    2、确定买卖条件信号

    • 在输入特征列表中通过表达式引擎定义 buy_condition=where((pb_lf_0<1.5) & (pe_ttm_0<15) & (amount_0>0) & (pb_lf_0>0) & (pe_ttm_0>0), 1, 0) 实现买入条件信号定义。
    • 通过基础特征和衍生特征抽取模块实现买卖条件指标 buy_condition 数据的抽取。
    • 通过缺失数据处理模块删去有缺失值的数据。
    • 通过排序模块实现每日股票数据按 pe_ttm_0 和 pb_lf_0 两个指标降序排列

    3、确定买卖原则

    • 每隔30个交易日换仓一次;
    • 已有持仓中不满足买入条件的股票为卖出股票列表,需执行卖出操作
    • 满足买入条件且没有持仓的股票为买入股票列表,需执行买入操作
    • 满足买入条件且已有持仓的股票为调仓股票列表,需执行调整仓位操作
    • 本策略中将买入股票列表和调仓股票列表中的所有股票统一调整为等资金比例仓位。

    4、模拟回测

    • 通过 trade 模块中的初始化函数定义交易手续费和滑点;
    • 通过 trade 模块中的准备函数定义 context.daily_stock_buy 变量来获取并存放每日买卖交易信号;
    • 通过 trade 模块中的主函数(handle函数)查看每日的买卖交易信号,按照买卖原则执行相应的买入/卖出/调仓操作。

    三、策略的实现

    可视化策略实现如下:

      {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-2333:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-2171:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-69:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-76:input_ds","SourceOutputPortId":"-2333:data"},{"DestinationInputPortId":"-2171:options_data","SourceOutputPortId":"-50:sorted_data"},{"DestinationInputPortId":"-5045:input_data","SourceOutputPortId":"-104:data"},{"DestinationInputPortId":"-50:input_ds","SourceOutputPortId":"-5045:data"},{"DestinationInputPortId":"-2333:input_data","SourceOutputPortId":"-69:data"},{"DestinationInputPortId":"-104:input_data","SourceOutputPortId":"-76:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where(sjltz>0.2, 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":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-05-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-10-11","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":2,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"-2333","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":"-2333"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-2333"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2333","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"Comment":"","CommentCollapsed":true},{"Id":"-50","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"sjltz","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":"-50"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-50"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-50","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"Comment":"","CommentCollapsed":true},{"Id":"-2171","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\n stock_count = 20\n \n ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n #周期控制\n if context.trading_day_index % 30 != 0:#以30天(交易日)换一次仓为例\n return\n # 获取今日的日期\n today = data.current_dt.strftime('%Y-%m-%d') \n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()} \n \n # 记录用于买入股票的可用现金\n cash_for_buy = context.portfolio.cash \n \n 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 # 需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]\n # 需要买入的股票:没有持仓且符合买入条件的股票\n stock_to_buy = [ i for i in buy_stock if i not in stock_hold_now ] \n # 需要调仓的股票:已有持仓且不符合卖出条件的股票\n stock_to_adjust=[ i for i in stock_hold_now if i not in sell_stock ]\n \n # 如果有卖出信号\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 # 如果有买入信号/有持仓\n if len(stock_to_buy)+len(stock_to_adjust)>0:\n weight = 1/(len(stock_to_buy)+len(stock_to_adjust)) # 每只股票的比重为等资金比例持有\n for instrument in stock_to_buy+stock_to_adjust:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n if data.can_trade(sid):\n context.order_target_value(sid, weight*cash_for_buy) # 买入","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n history_data = context.options['data'].read_df()\n\n #获取每日买入股票列表\n context.daily_stock_buy = history_data.groupby('date').apply(lambda x:x.instrument[:30])\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":"vwap_11","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":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-2171"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-2171"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-2171","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":9,"Comment":"","CommentCollapsed":true},{"Id":"-104","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"buy_condition>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":"-104"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-104","OutputType":null},{"Name":"left_data","NodeId":"-104","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"Comment":"","CommentCollapsed":true},{"Id":"-5045","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-5045"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-5045"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5045","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"Comment":"","CommentCollapsed":true},{"Id":"-69","ModuleId":"BigQuantSpace.use_datasource.use_datasource-v1","ModuleParameters":[{"Name":"datasource_id","Value":"results_reports_CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-69"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-69"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-69","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"Comment":"","CommentCollapsed":true},{"Id":"-76","ModuleId":"BigQuantSpace.select_columns.select_columns-v3","ModuleParameters":[{"Name":"columns","Value":"date,instrument,buy_condition","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"reverse_select","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-76"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"columns_ds","NodeId":"-76"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-76","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"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='1291.16796875,62.07996368408203,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='801,34.316802978515625,200,200'/><NodePosition Node='-2333' Position='1117.919921875,222.0657958984375,200,200'/><NodePosition Node='-50' Position='1119.950439453125,548.465576171875,200,200'/><NodePosition Node='-2171' Position='997,646,200,200'/><NodePosition Node='-104' Position='1107,383,200,200'/><NodePosition Node='-5045' Position='1122.7520751953125,457.63360595703125,200,200'/><NodePosition Node='-69' Position='990.931640625,144.11248779296875,200,200'/><NodePosition Node='-76' Position='1100.926513671875,303.98089599609375,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 [14]:
      # 本代码由可视化策略环境自动生成 2020年9月3日 09:08
      # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
      
      
      # 回测引擎:初始化函数,只执行一次
      def m9_initialize_bigquant_run(context):
      
          # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
          context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
      
          stock_count = 20
          
          
      # 回测引擎:每日数据处理函数,每天执行一次
      def m9_handle_data_bigquant_run(context, data):
           #周期控制
          if context.trading_day_index % 30 != 0:#以30天(交易日)换一次仓为例
              return
          # 获取今日的日期
          today = data.current_dt.strftime('%Y-%m-%d')  
          # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
          stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                            for e, p in context.perf_tracker.position_tracker.positions.items()} 
          
          # 记录用于买入股票的可用现金
          cash_for_buy = context.portfolio.cash     
          
          try:
              buy_stock = context.daily_stock_buy[today]  # 当日符合买入条件的股票
          except:
              buy_stock=[]  # 如果没有符合条件的股票,就设置为空
          
          try:
              sell_stock = context.daily_stock_sell[today]  # 当日符合卖出条件的股票
          except:
              sell_stock=[] # 如果没有符合条件的股票,就设置为空
          
          # 需要卖出的股票:已有持仓中符合卖出条件的股票
          stock_to_sell = [ i for i in stock_hold_now if i in sell_stock ]
          # 需要买入的股票:没有持仓且符合买入条件的股票
          stock_to_buy = [ i for i in buy_stock if i not in stock_hold_now ]  
          # 需要调仓的股票:已有持仓且不符合卖出条件的股票
          stock_to_adjust=[ i for i in stock_hold_now if i not in sell_stock ]
          
          # 如果有卖出信号
          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]
          
          # 如果有买入信号/有持仓
          if len(stock_to_buy)+len(stock_to_adjust)>0:
              weight = 1/(len(stock_to_buy)+len(stock_to_adjust)) # 每只股票的比重为等资金比例持有
              for instrument in stock_to_buy+stock_to_adjust:
                  sid = context.symbol(instrument) # 将标的转化为equity格式
                  if  data.can_trade(sid):
                      context.order_target_value(sid, weight*cash_for_buy) # 买入
      # 回测引擎:准备数据,只执行一次
      def m9_prepare_bigquant_run(context):
          # 加载预测数据
          history_data = context.options['data'].read_df()
      
          #获取每日买入股票列表
          context.daily_stock_buy = history_data.groupby('date').apply(lambda x:x.instrument[:30])
      
      
      m1 = M.input_features.v1(
          features="""# #号开始的表示注释
      # 多个特征,每行一个,可以包含基础特征和衍生特征
      buy_condition=where(sjltz>0.2, 1, 0)"""
      )
      
      m2 = M.instruments.v2(
          start_date=T.live_run_param('trading_date', '2017-05-01'),
          end_date=T.live_run_param('trading_date', '2019-10-11'),
          market='CN_STOCK_A',
          instrument_list='',
          max_count=0
      )
      
      m6 = M.use_datasource.v1(
          instruments=m2.data,
          datasource_id='results_reports_CN_STOCK_A',
          start_date='',
          end_date=''
      )
      
      m8 = M.derived_feature_extractor.v3(
          input_data=m6.data,
          features=m1.data,
          date_col='date',
          instrument_col='instrument',
          drop_na=False,
          remove_extra_columns=False
      )
      
      m7 = M.select_columns.v3(
          input_ds=m8.data,
          columns='date,instrument,buy_condition',
          reverse_select=False
      )
      
      m4 = M.filter.v3(
          input_data=m7.data,
          expr='buy_condition>0',
          output_left_data=False
      )
      
      m5 = M.dropnan.v2(
          input_data=m4.data
      )
      
      m3 = M.sort.v4(
          input_ds=m5.data,
          sort_by='sjltz',
          group_by='date',
          keep_columns='--',
          ascending=True
      )
      
      m9 = M.trade.v4(
          instruments=m2.data,
          options_data=m3.sorted_data,
          start_date='',
          end_date='',
          initialize=m9_initialize_bigquant_run,
          handle_data=m9_handle_data_bigquant_run,
          prepare=m9_prepare_bigquant_run,
          volume_limit=0.025,
          order_price_field_buy='open',
          order_price_field_sell='vwap_11',
          capital_base=1000000,
          auto_cancel_non_tradable_orders=True,
          data_frequency='daily',
          price_type='后复权',
          product_type='股票',
          plot_charts=True,
          backtest_only=False,
          benchmark=''
      )
      

      (lyxpayne) #3

      好的,谢谢。 我再研究一下。
      关于业绩报表的数据,如果用的话,能不能给我举个例子? 比如我要选择净利润增长幅度大于20%的股票?