复制链接
克隆策略

    {"description":"实验创建于2022/3/23","graph":{"edges":[{"to_node_id":"-151:instruments","from_node_id":"-115:data"},{"to_node_id":"-164:instruments","from_node_id":"-115:data"},{"to_node_id":"-135:features","from_node_id":"-130:data"},{"to_node_id":"-164:features","from_node_id":"-130:data"},{"to_node_id":"-144:input_data","from_node_id":"-135:data"},{"to_node_id":"-151:options_data","from_node_id":"-144:data"},{"to_node_id":"-135:input_data","from_node_id":"-164:data"}],"nodes":[{"node_id":"-115","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2021-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-03-25","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"002665.SZA\n# 603330.SHA","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-115"}],"output_ports":[{"name":"data","node_id":"-115"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-130","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\n\n# high_0\n# low_0\n# close_0\n\n\nk_9=ta_kdj_k(high, low, close, 9, 3)\nd_9=ta_kdj_d(high, low, close, 9, 3)\n# ta_kdj_j(hhigh_0, low_0, close_0, 18, 3)\n\n\n# ta_kdj_k(high_0, low_0, close_0, 5, 3)\n\n# ta_stoch_slowd_5_3_0_3_0_0\n\n# ta_stoch_slowd_5_3_0_3_0_0\n\n\n\n\n\n\n\n\n\n\n\n\n\n","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-130"}],"output_ports":[{"name":"data","node_id":"-130"}],"cacheable":true,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-135","module_id":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","parameters":[{"name":"date_col","value":"date","type":"Literal","bound_global_parameter":null},{"name":"instrument_col","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"drop_na","value":"False","type":"Literal","bound_global_parameter":null},{"name":"remove_extra_columns","value":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-135"},{"name":"features","node_id":"-135"}],"output_ports":[{"name":"data","node_id":"-135"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-144","module_id":"BigQuantSpace.dropnan.dropnan-v2","parameters":[],"input_ports":[{"name":"input_data","node_id":"-144"},{"name":"features","node_id":"-144"}],"output_ports":[{"name":"data","node_id":"-144"}],"cacheable":true,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-151","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 # 加载预测数据\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.hold_days = 5\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"import pandas as pd\n\n\n# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n # 按日期过滤得到今日的预测数据\n options_data = context.ranker_prediction[context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n # 标的为字符串格式\n sid = context.symbol(context.instruments[0])# 标的为字符串格式\n price = data.current(sid, 'price') # 最新价格\n cash = context.portfolio.cash # 现金\n cur_position = context.portfolio.positions[sid].amount # 持仓\n\n# rsi_short_0=options_data['ta_rsi_6'].values\n# rsi_long_0=options_data['ta_rsi_12'].values\n \n# rsi_short_1 = options_data['ta_rsi_6_1'].values\n# rsi_long_1 = options_data['ta_rsi_12_1'].values\n rsi_6 = options_data['rsi_6'].values\n rsi_14 = options_data['rsi_14'].values\n lagrsi_6=options_data['lagrsi_6'].values\n lagrsi_14=options_data['lagrsi_14'].values\n \n\n \n \n \n \n\n \n #交易逻辑\n # rsi_6 < 20--buy--signal=1, rsi>80--sell--signal=-1:\n sig1=[]\n for i in rsi_6:\n if i > 80:\n sig1.append(-1)\n elif i<20:\n sig1.append(1)\n else:\n sig1.append(0)\n \n\n \n# #rsi_6上穿rsi_14,buy--singal_2=1,rsi_6下穿rsi_14,sell--singal_2=-1 \n \n sig2=[]\n \n \n for i in range(0,len(rsi_14)):\n \n if (rsi_6[i] > rsi_14[i]) & (lagrsi_6[i]<lagrsi_14[i]):\n sig2.append(1)\n elif (rsi_6[i]< rsi_14[i] ) & (lagrsi_6[i]>lagrsi_14[i]):\n sig2.append(-1)\n else:\n sig2.append(0) \n \n# print(sig2)\n \n signal = sig1 + sig2\n for i in signal:\n if i>=1:\n context.order(sid, int(cash/price/100)*100) # 买入\n print('{}全仓买入{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))\n elif i <=-1:\n context.order_target_percent(sid, 0) # 全部卖出\n print('{}卖出{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))\n else:\n return\n \n \n# for i in rsi_6:\n# if i < 20:\n# context.order(sid, int(cash/price/100)*100) # 买入\n# print('{}全仓买入{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))\n# elif i > 80:\n# context.order_target_percent(sid, 0) # 全部卖出\n# print('{}卖出{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))\n \n# else:\n# return\n \n \n \n \n \n \n\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":"close","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":"10000","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":"000300.HIX","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-151"},{"name":"options_data","node_id":"-151"},{"name":"history_ds","node_id":"-151"},{"name":"benchmark_ds","node_id":"-151"},{"name":"trading_calendar","node_id":"-151"}],"output_ports":[{"name":"raw_perf","node_id":"-151"}],"cacheable":false,"seq_num":6,"comment":"","comment_collapsed":true},{"node_id":"-164","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"bar1d_CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-164"},{"name":"features","node_id":"-164"}],"output_ports":[{"name":"data","node_id":"-164"}],"cacheable":true,"seq_num":7,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-115' Position='176,88,200,200'/><node_position Node='-130' Position='570,121,200,200'/><node_position Node='-135' Position='526,409,200,200'/><node_position Node='-144' Position='509,527.0634765625,200,200'/><node_position Node='-151' Position='449,633,200,200'/><node_position Node='-164' Position='327,249,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [6]:
    # 本代码由可视化策略环境自动生成 2022年3月27日 22:00
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m6_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.hold_days = 5
    
    import pandas as pd
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m6_handle_data_bigquant_run(context, data):
        
        # 按日期过滤得到今日的预测数据
        options_data = context.ranker_prediction[context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        # 标的为字符串格式
        sid = context.symbol(context.instruments[0])# 标的为字符串格式
        price = data.current(sid, 'price') # 最新价格
        cash = context.portfolio.cash  # 现金
        cur_position = context.portfolio.positions[sid].amount # 持仓
    
    #     rsi_short_0=options_data['ta_rsi_6'].values
    #     rsi_long_0=options_data['ta_rsi_12'].values
        
    #     rsi_short_1 = options_data['ta_rsi_6_1'].values
    #     rsi_long_1 = options_data['ta_rsi_12_1'].values
        rsi_6 = options_data['rsi_6'].values
        rsi_14 = options_data['rsi_14'].values
        lagrsi_6=options_data['lagrsi_6'].values
        lagrsi_14=options_data['lagrsi_14'].values
        
    
        
        
        
            
    
        
        #交易逻辑
        # rsi_6 < 20--buy--signal=1, rsi>80--sell--signal=-1:
        sig1=[]
        for i in rsi_6:
            if i > 80:
                sig1.append(-1)
            elif i<20:
                sig1.append(1)
            else:
                sig1.append(0)
                
    
                
    #     #rsi_6上穿rsi_14,buy--singal_2=1,rsi_6下穿rsi_14,sell--singal_2=-1   
        
        sig2=[]
        
     
        for i in range(0,len(rsi_14)):
            
            if (rsi_6[i] > rsi_14[i]) & (lagrsi_6[i]<lagrsi_14[i]):
                sig2.append(1)
            elif (rsi_6[i]< rsi_14[i] ) & (lagrsi_6[i]>lagrsi_14[i]):
                sig2.append(-1)
            else:
                sig2.append(0) 
                
    #     print(sig2)
                
        signal = sig1 + sig2
        for i in signal:
            if i>=1:
                context.order(sid, int(cash/price/100)*100) # 买入
                print('{}全仓买入{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))
            elif i <=-1:
                context.order_target_percent(sid, 0) # 全部卖出
                print('{}卖出{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))
            else:
                return
                
                
    #     for i in rsi_6:
    #         if i < 20:
    #             context.order(sid, int(cash/price/100)*100) # 买入
    #             print('{}全仓买入{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))
    #         elif i > 80:
    #             context.order_target_percent(sid, 0) # 全部卖出
    #             print('{}卖出{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))
                
    #         else:
    #             return
      
            
            
        
            
            
    
    
    # 回测引擎:准备数据,只执行一次
    def m6_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m6_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2021-01-01',
        end_date='2022-03-25',
        market='CN_STOCK_A',
        instrument_list="""002665.SZA
    # 603330.SHA""",
        max_count=0
    )
    
    m3 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    
    # high_0
    # low_0
    # close_0
    
    
    k_9=ta_kdj_k(high, low, close, 9, 3)
    d_9=ta_kdj_d(high, low, close, 9, 3)
    # ta_kdj_j(hhigh_0, low_0, close_0, 18, 3)
    
    
    # ta_kdj_k(high_0, low_0, close_0, 5, 3)
    
    # ta_stoch_slowd_5_3_0_3_0_0
    
    # ta_stoch_slowd_5_3_0_3_0_0
    
    
    
    
    
    
    
    
    
    
    
    
    
    """
    )
    
    m7 = M.use_datasource.v1(
        instruments=m1.data,
        features=m3.data,
        datasource_id='bar1d_CN_STOCK_A',
        start_date='',
        end_date=''
    )
    
    m4 = M.derived_feature_extractor.v3(
        input_data=m7.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m5 = M.dropnan.v2(
        input_data=m4.data
    )
    
    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='close',
        capital_base=10000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='真实价格',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark='000300.HIX'
    )
    
    In [ ]: