复制链接
克隆策略

策略名称

小市值策略

策略思想

每月月初买入市值最小的30只股票并且成交额满足一定条件的股票,持有至下个月月初再调仓,等权重买,无单只股票仓位上限控制、无止盈止损。

    {"description":"实验创建于2023/2/10","graph":{"edges":[{"to_node_id":"-17:instruments","from_node_id":"-6:data"},{"to_node_id":"-41:instruments","from_node_id":"-6:data"},{"to_node_id":"-17:features","from_node_id":"-14:data"},{"to_node_id":"-24:input_ds","from_node_id":"-17:data"},{"to_node_id":"-32:input_data","from_node_id":"-24:sorted_data"},{"to_node_id":"-41:options_data","from_node_id":"-32:data"}],"nodes":[{"node_id":"-6","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2015-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2018-11-01","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-6"}],"output_ports":[{"name":"data","node_id":"-6"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-14","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"market_cap_float_0\namount_0","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-14"}],"output_ports":[{"name":"data","node_id":"-14"}],"cacheable":true,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"-17","module_id":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":90,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-17"},{"name":"features","node_id":"-17"}],"output_ports":[{"name":"data","node_id":"-17"}],"cacheable":true,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-24","module_id":"BigQuantSpace.sort.sort-v5","parameters":[{"name":"sort_by","value":"market_cap_float_0","type":"Literal","bound_global_parameter":null},{"name":"group_by","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"keep_columns","value":"--","type":"Literal","bound_global_parameter":null},{"name":"ascending","value":"True","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_ds","node_id":"-24"},{"name":"sort_by_ds","node_id":"-24"}],"output_ports":[{"name":"sorted_data","node_id":"-24"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-32","module_id":"BigQuantSpace.filter.filter-v3","parameters":[{"name":"expr","value":"amount_0 > 10000","type":"Literal","bound_global_parameter":null},{"name":"output_left_data","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-32"}],"output_ports":[{"name":"data","node_id":"-32"},{"name":"left_data","node_id":"-32"}],"cacheable":true,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-41","module_id":"BigQuantSpace.trade.trade-v4","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"initialize","value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n from zipline.finance.commission import PerOrder\n # 加载股票指标数据,数据继承自m6模块\n context.indicator_data = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n \n # 设置股票数量\n context.stock_num = 30\n \n # 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次\n context.rebalance_days = 22\n \n # 如果策略运行中,需要将数据进行保存,可以借用extension这个对象,类型为dict\n # 比如当前运行的k线的索引,比如个股持仓天数、买入均价\n if 'index' not in context.extension:\n context.extension['index'] = 0\n \n \n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n \n context.extension['index'] += 1\n # 不在换仓日就return,相当于后面的代码只会一个月运行一次,买入的股票会持有1个月\n if context.extension['index'] % context.rebalance_days != 0:\n return \n \n # 当前的日期\n date = data.current_dt.strftime('%Y-%m-%d')\n \n cur_data = context.indicator_data[context.indicator_data['date'] == date]\n # 根据日期获取调仓需要买入的股票的列表\n stock_to_buy = list(cur_data.instrument[:context.stock_num])\n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表\n stock_hold_now = [equity.symbol for equity in context.portfolio.positions]\n # 继续持有的股票:调仓时,如果买入的股票已经存在于目前的持仓里,那么应继续持有\n no_need_to_sell = [i for i in stock_hold_now if i in stock_to_buy]\n # 需要卖出的股票\n stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]\n \n # 卖出\n for stock in stock_to_sell:\n # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态\n # 如果返回真值,则可以正常下单,否则会出错\n # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式\n\n if data.can_trade(context.symbol(stock)):\n # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,\n # 即卖出全部股票,可参考回测文档\n context.order_target_percent(context.symbol(stock), 0)\n \n # 如果当天没有买入的股票,就返回\n if len(stock_to_buy) == 0:\n return\n\n # 等权重买入 \n weight = 1 / len(stock_to_buy)\n \n # 买入\n for stock in stock_to_buy:\n if data.can_trade(context.symbol(stock)):\n # 下单使得某只股票的持仓权重达到weight,因为\n # weight大于0,因此是等权重买入\n context.order_target_percent(context.symbol(stock), weight)\n ","type":"Literal","bound_global_parameter":null},{"name":"prepare","value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"volume_limit","value":0.025,"type":"Literal","bound_global_parameter":null},{"name":"order_price_field_buy","value":"open","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_sell","value":"open","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":1000000,"type":"Literal","bound_global_parameter":null},{"name":"auto_cancel_non_tradable_orders","value":"True","type":"Literal","bound_global_parameter":null},{"name":"data_frequency","value":"daily","type":"Literal","bound_global_parameter":null},{"name":"price_type","value":"后复权","type":"Literal","bound_global_parameter":null},{"name":"product_type","value":"股票","type":"Literal","bound_global_parameter":null},{"name":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-41"},{"name":"options_data","node_id":"-41"},{"name":"history_ds","node_id":"-41"},{"name":"benchmark_ds","node_id":"-41"},{"name":"trading_calendar","node_id":"-41"}],"output_ports":[{"name":"raw_perf","node_id":"-41"}],"cacheable":false,"seq_num":6,"comment":"回测","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-6' Position='45,51,200,200'/><node_position Node='-14' Position='450,48,200,200'/><node_position Node='-17' Position='231,182,200,200'/><node_position Node='-24' Position='241,281,200,200'/><node_position Node='-32' Position='238,372,200,200'/><node_position Node='-41' Position='210,463,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [2]:
    # 本代码由可视化策略环境自动生成 2023年5月24日 17:27
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
     
    # 显式导入 BigQuant 相关 SDK 模块
    from bigdatasource.api import DataSource
    from biglearning.api import M
    from biglearning.api import tools as T
    from biglearning.module2.common.data import Outputs
    
    # 回测引擎:初始化函数,只执行一次
    def m6_initialize_bigquant_run(context):
        from zipline.finance.commission import PerOrder
        # 加载股票指标数据,数据继承自m6模块
        context.indicator_data = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        
        # 设置股票数量
        context.stock_num = 30
        
        # 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次
        context.rebalance_days = 22
        
        # 如果策略运行中,需要将数据进行保存,可以借用extension这个对象,类型为dict
        # 比如当前运行的k线的索引,比如个股持仓天数、买入均价
        if 'index' not in context.extension:
            context.extension['index'] = 0
     
        
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m6_handle_data_bigquant_run(context, data):
        
        
        context.extension['index'] += 1
        # 不在换仓日就return,相当于后面的代码只会一个月运行一次,买入的股票会持有1个月
        if  context.extension['index'] % context.rebalance_days != 0:
            return 
        
        # 当前的日期
        date = data.current_dt.strftime('%Y-%m-%d')
        
        cur_data = context.indicator_data[context.indicator_data['date'] == date]
        # 根据日期获取调仓需要买入的股票的列表
        stock_to_buy = list(cur_data.instrument[:context.stock_num])
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
        stock_hold_now = [equity.symbol for equity in context.portfolio.positions]
        # 继续持有的股票:调仓时,如果买入的股票已经存在于目前的持仓里,那么应继续持有
        no_need_to_sell = [i for i in stock_hold_now if i in stock_to_buy]
        # 需要卖出的股票
        stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]
      
        # 卖出
        for stock in stock_to_sell:
            # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态
            # 如果返回真值,则可以正常下单,否则会出错
            # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式
    
            if data.can_trade(context.symbol(stock)):
                # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,
                #   即卖出全部股票,可参考回测文档
                context.order_target_percent(context.symbol(stock), 0)
        
        # 如果当天没有买入的股票,就返回
        if len(stock_to_buy) == 0:
            return
    
        # 等权重买入 
        weight =  1 / len(stock_to_buy)
        
        # 买入
        for stock in stock_to_buy:
            if data.can_trade(context.symbol(stock)):
                # 下单使得某只股票的持仓权重达到weight,因为
                # weight大于0,因此是等权重买入
                context.order_target_percent(context.symbol(stock), weight)
     
    # 回测引擎:准备数据,只执行一次
    def m6_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m6_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2015-01-01',
        end_date='2018-11-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m2 = M.input_features.v1(
        features="""market_cap_float_0
    amount_0"""
    )
    
    m3 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m2.data,
        start_date='',
        end_date='',
        before_start_days=90
    )
    
    m4 = M.sort.v5(
        input_ds=m3.data,
        sort_by='market_cap_float_0',
        group_by='instrument',
        keep_columns='--',
        ascending=True
    )
    
    m5 = M.filter.v3(
        input_data=m4.sorted_data,
        expr='amount_0 > 10000',
        output_left_data=False
    )
    
    m6 = M.trade.v4(
        instruments=m1.data,
        options_data=m5.data,
        start_date='',
        end_date='',
        initialize=m6_initialize_bigquant_run,
        handle_data=m6_handle_data_bigquant_run,
        prepare=m6_prepare_bigquant_run,
        before_trading_start=m6_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=''
    )
    
    [2023-05-24 17:27:53.679074] INFO moduleinvoker: instruments.v2 开始运行..
    
    INFO:moduleinvoker:instruments.v2 开始运行..
    
    [2023-05-24 17:27:54.010044] INFO moduleinvoker: instruments.v2 运行完成[0.331038s].
    
    INFO:moduleinvoker:instruments.v2 运行完成[0.331038s].
    
    [2023-05-24 17:27:54.019959] INFO moduleinvoker: input_features.v1 开始运行..
    
    INFO:moduleinvoker:input_features.v1 开始运行..
    
    [2023-05-24 17:27:54.027414] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 17:27:54.030312] INFO moduleinvoker: input_features.v1 运行完成[0.010387s].
    
    INFO:moduleinvoker:input_features.v1 运行完成[0.010387s].
    
    [2023-05-24 17:27:54.064918] INFO moduleinvoker: general_feature_extractor.v7 开始运行..
    
    INFO:moduleinvoker:general_feature_extractor.v7 开始运行..
    
    [2023-05-24 17:27:54.757303] INFO 基础特征抽取: 年份 2014, 特征行数=141569
    
    INFO:基础特征抽取:年份 2014, 特征行数=141569
    
    [2023-05-24 17:27:55.468782] INFO 基础特征抽取: 年份 2015, 特征行数=569698
    
    INFO:基础特征抽取:年份 2015, 特征行数=569698
    
    [2023-05-24 17:27:56.214688] INFO 基础特征抽取: 年份 2016, 特征行数=641546
    
    INFO:基础特征抽取:年份 2016, 特征行数=641546
    
    [2023-05-24 17:27:57.044757] INFO 基础特征抽取: 年份 2017, 特征行数=743233
    
    INFO:基础特征抽取:年份 2017, 特征行数=743233
    
    [2023-05-24 17:27:57.710133] INFO 基础特征抽取: 年份 2018, 特征行数=672348
    
    INFO:基础特征抽取:年份 2018, 特征行数=672348
    
    [2023-05-24 17:27:57.815551] INFO 基础特征抽取: 总行数: 2768394
    
    INFO:基础特征抽取:总行数: 2768394
    
    [2023-05-24 17:27:57.826940] INFO moduleinvoker: general_feature_extractor.v7 运行完成[3.762037s].
    
    INFO:moduleinvoker:general_feature_extractor.v7 运行完成[3.762037s].
    
    [2023-05-24 17:27:57.843588] INFO moduleinvoker: sort.v5 开始运行..
    
    INFO:moduleinvoker:sort.v5 开始运行..
    
    [2023-05-24 17:28:07.514004] INFO moduleinvoker: sort.v5 运行完成[9.670394s].
    
    INFO:moduleinvoker:sort.v5 运行完成[9.670394s].
    
    [2023-05-24 17:28:07.532198] INFO moduleinvoker: filter.v3 开始运行..
    
    INFO:moduleinvoker:filter.v3 开始运行..
    
    [2023-05-24 17:28:07.549278] INFO filter: 使用表达式 amount_0 > 10000 过滤
    
    INFO:filter:使用表达式 amount_0 > 10000 过滤
    
    [2023-05-24 17:28:11.977530] INFO filter: 过滤 /data, 2768343/0/2768394
    
    INFO:filter:过滤 /data, 2768343/0/2768394
    
    [2023-05-24 17:28:12.013380] INFO moduleinvoker: filter.v3 运行完成[4.481152s].
    
    INFO:moduleinvoker:filter.v3 运行完成[4.481152s].
    
    [2023-05-24 17:28:12.092951] INFO moduleinvoker: backtest.v8 开始运行..
    
    INFO:moduleinvoker:backtest.v8 开始运行..
    
    [2023-05-24 17:28:12.098740] INFO backtest: biglearning backtest:V8.6.3
    
    INFO:backtest:biglearning backtest:V8.6.3
    
    [2023-05-24 17:28:12.101384] INFO backtest: product_type:stock by specified
    
    INFO:backtest:product_type:stock by specified
    
    [2023-05-24 17:28:12.203448] INFO moduleinvoker: cached.v2 开始运行..
    
    INFO:moduleinvoker:cached.v2 开始运行..
    
    [2023-05-24 17:28:31.924733] INFO backtest: 读取股票行情完成:4079789
    
    INFO:backtest:读取股票行情完成:4079789
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/generic.py:2605: PerformanceWarning: 
    your performance may suffer as PyTables will pickle object types that it cannot
    map directly to c-types [inferred_type->mixed,key->block3_values] [items->Index(['instrument', 'suspended', 'name'], dtype='object')]
    
      pytables.to_hdf(
    
    [2023-05-24 17:28:34.887773] INFO moduleinvoker: cached.v2 运行完成[22.684263s].
    
    INFO:moduleinvoker:cached.v2 运行完成[22.684263s].
    
    [2023-05-24 17:28:55.278900] INFO backtest: algo history_data=DataSource(bbed37c95e234720b8060373e3eee835T)
    
    INFO:backtest:algo history_data=DataSource(bbed37c95e234720b8060373e3eee835T)
    
    [2023-05-24 17:28:55.285280] INFO algo: TradingAlgorithm V1.8.9
    
    INFO:algo:TradingAlgorithm V1.8.9
    
    [2023-05-24 17:29:09.951617] INFO algo: trading transform...
    
    INFO:algo:trading transform...
    /usr/local/python3/lib/python3.8/site-packages/empyrical/stats.py:710: RuntimeWarning: divide by zero encountered in divide
      np.divide(
    /var/app/enabled/bigline/zipline/data/us_equity_pricing.py:990: FutureWarning: Indexing a timezone-naive DatetimeIndex with a timezone-aware datetime is deprecated and will raise KeyError in a future version.  Use a timezone-naive object instead.
      return df.loc[dt, field]
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/indexing.py:1124: FutureWarning: Indexing a timezone-naive DatetimeIndex with a timezone-aware datetime is deprecated and will raise KeyError in a future version.  Use a timezone-naive object instead.
      return self._get_label(key, axis=axis)
    
    [2023-05-24 17:29:13.151669] WARNING Performance: maybe_close_position no price for asset:Equity(1593 [000024.SZA]), field:price, dt:2015-12-30 15:00:00+00:00
    
    WARNING:Performance:maybe_close_position no price for asset:Equity(1593 [000024.SZA]), field:price, dt:2015-12-30 15:00:00+00:00
    
    [2023-05-24 17:29:18.309195] INFO Performance: Simulated 934 trading days out of 934.
    
    INFO:Performance:Simulated 934 trading days out of 934.
    
    [2023-05-24 17:29:18.312387] INFO Performance: first open: 2015-01-05 09:30:00+00:00
    
    INFO:Performance:first open: 2015-01-05 09:30:00+00:00
    
    [2023-05-24 17:29:18.315226] INFO Performance: last close: 2018-11-01 15:00:00+00:00
    
    INFO:Performance:last close: 2018-11-01 15:00:00+00:00
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/generic.py:2605: PerformanceWarning: 
    your performance may suffer as PyTables will pickle object types that it cannot
    map directly to c-types [inferred_type->mixed,key->block5_values] [items->Index(['positions', 'transactions', 'orders', 'LOG', 'TRA_FAC', 'POS_FAC',
           'period_label'],
          dtype='object')]
    
      pytables.to_hdf(
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/generic.py:2605: PerformanceWarning: 
    your performance may suffer as PyTables will pickle object types that it cannot
    map directly to c-types [inferred_type->mixed,key->block2_values] [items->Index(['instrument', 'suspended', 'name'], dtype='object')]
    
      pytables.to_hdf(
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/indexing.py:1637: SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame
    
    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
      self._setitem_single_block(indexer, value, name)
    [2023-05-24 17:29:30.431793] INFO: bigcharts.impl.render:render.py:407:render_chart Data is None, skip loading it to chart.
    
    • 收益率1.83%
    • 年化收益率0.49%
    • 基准收益率-10.09%
    • 阿尔法0.04
    • 贝塔0.88
    • 夏普比率0.06
    • 胜率0.82
    • 盈亏比2.07
    • 收益波动率29.42%
    • 信息比率0.01
    • 最大回撤55.58%
    日期 时间 股票代码 股票名称 买/卖 数量 成交价 总成本 交易佣金
    Loading... (need help?)
    日期 股票代码 股票名称 持仓均价 收盘价 股数 持仓价值 收益
    Loading... (need help?)
    时间 级别 内容
    Loading... (need help?)
    [2023-05-24 17:29:31.128297] INFO moduleinvoker: backtest.v8 运行完成[79.035337s].
    
    INFO:moduleinvoker:backtest.v8 运行完成[79.035337s].
    
    [2023-05-24 17:29:31.132140] INFO moduleinvoker: trade.v4 运行完成[79.103531s].
    
    INFO:moduleinvoker:trade.v4 运行完成[79.103531s].