复制链接
克隆策略

    {"description":"实验创建于2023/5/1","graph":{"edges":[{"to_node_id":"-464:input_data","from_node_id":"-456:data"},{"to_node_id":"-209:options_data","from_node_id":"-464:data"},{"to_node_id":"-209:instruments","from_node_id":"-161:data"}],"nodes":[{"node_id":"-209","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 # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0001, sell_cost=0.0011, 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":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n # 获取数据\n print(\"here\")\n buy_sell_data_df = context.options['data'].read_df()\n print(buy_sell_data_df.head())\n\n # 按日期过滤得到今日的预测数据\n today = data.current_dt.strftime('%Y%m%d')\n buy_sell_data = buy_sell_data[buy_sell_data_df.deal_date == today]\n \n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰\n sell_stocks = buy_sell_data[buy_sell_data['deal_action']=='sell']\n if len(sell_stocks) > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n for stock_code in sell_stocks['stock_code']:\n context.order_target(context.symbol(stock_code), 0) \n print(f\"日期:{today} - 卖出股票: {stock_code}\")\n\n # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票\n buy_stocks = buy_sell_data[buy_sell_data['deal_action']=='buy']\n if len(buy_stocks) > 0:\n for volumn, stock_code in zip(buy_stocks['deal_volume'], buy_stocks['stock_code']):\n context.order(context.symbol(stock_code), volumn)\n print(f\"日期:{today} - 买入股票: {stock_code} - 数量:{volumn}\")","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":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":"000300.HIX","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-209"},{"name":"options_data","node_id":"-209"},{"name":"history_ds","node_id":"-209"},{"name":"benchmark_ds","node_id":"-209"},{"name":"trading_calendar","node_id":"-209"}],"output_ports":[{"name":"raw_perf","node_id":"-209"}],"cacheable":false,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-456","module_id":"BigQuantSpace.datahub_load_file.datahub_load_file-v2","parameters":[{"name":"file_path","value":"# Python 动态生成文件路径\ndef bigquant_run():\n # 示例代码如下。在这里编写您的代码\n # 如果不需要动态生成路径,直接返回path即可\n # import datetime\n # import os\n # base_path = \"/var/app/data/datahub\"\n # data_path = os.path.join(base_path, \"bigcrawler\")\n # date = datetime.datetime.now().strftime(\"%Y%m%d\")\n # file_path = os.path.join(data_path, \"{}.csv\".format(date))\n # return file_path\n\n return \"stock_transaction.csv\"\n","type":"Literal","bound_global_parameter":null},{"name":"file_type","value":"csv","type":"Literal","bound_global_parameter":null},{"name":"csv_delimiter","value":",","type":"Literal","bound_global_parameter":null},{"name":"other_parameters","value":"{}","type":"Literal","bound_global_parameter":null},{"name":"h5_data_key","value":"data","type":"Literal","bound_global_parameter":null}],"input_ports":[],"output_ports":[{"name":"data","node_id":"-456"}],"cacheable":false,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"-464","module_id":"BigQuantSpace.datahub_handler_column.datahub_handler_column-v1","parameters":[{"name":"handler","value":"# Python 代码处理数据\ndef bigquant_run(data):\n # 示例代码如下。在这里编写您的代码\n # data[\"test\"] = \"t1\"\n data['stock_code'] = data['stock_code'].str.replace(\"SH\",\"SHA\").str.replace(\"SZ\",\"SZA\")\n return data\n","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-464"}],"output_ports":[{"name":"data","node_id":"-464"}],"cacheable":false,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-161","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2002-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2002-12-31","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":"-161"}],"output_ports":[{"name":"data","node_id":"-161"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-209' Position='356,302,200,200'/><node_position Node='-456' Position='195,16,200,200'/><node_position Node='-464' Position='344,122,200,200'/><node_position Node='-161' Position='36,124,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [3]:
    # 本代码由可视化策略环境自动生成 2023年5月1日 15:26
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 动态生成文件路径
    def m2_file_path_bigquant_run():
        # 示例代码如下。在这里编写您的代码
        # 如果不需要动态生成路径,直接返回path即可
        # import datetime
        # import os
        # base_path = "/var/app/data/datahub"
        # data_path = os.path.join(base_path, "bigcrawler")
        # date = datetime.datetime.now().strftime("%Y%m%d")
        # file_path = os.path.join(data_path, "{}.csv".format(date))
        # return file_path
    
        return "stock_transaction.csv"
    
    # Python 代码处理数据
    def m3_handler_bigquant_run(data):
        # 示例代码如下。在这里编写您的代码
        # data["test"] = "t1"
        data['stock_code'] = data['stock_code'].str.replace("SH","SHA").str.replace("SZ","SZA")
        return data
    
    # 回测引擎:初始化函数,只执行一次
    def m1_initialize_bigquant_run(context):
        
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0001, sell_cost=0.0011, 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
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m1_handle_data_bigquant_run(context, data):
        
        # 获取数据
        print("here")
        buy_sell_data_df = context.options['data'].read_df()
        print(buy_sell_data_df.head())
    
        # 按日期过滤得到今日的预测数据
        today = data.current_dt.strftime('%Y%m%d')
        buy_sell_data = buy_sell_data[buy_sell_data_df.deal_date == today]
        
    
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
        sell_stocks = buy_sell_data[buy_sell_data['deal_action']=='sell']
        if len(sell_stocks) > 0:
            equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
            for stock_code in sell_stocks['stock_code']:
                context.order_target(context.symbol(stock_code), 0) 
                print(f"日期:{today} - 卖出股票: {stock_code}")
    
        # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票
        buy_stocks = buy_sell_data[buy_sell_data['deal_action']=='buy']
        if len(buy_stocks) > 0:
            for volumn, stock_code in zip(buy_stocks['deal_volume'], buy_stocks['stock_code']):
                context.order(context.symbol(stock_code), volumn)
                print(f"日期:{today} - 买入股票: {stock_code} - 数量:{volumn}")
    # 回测引擎:准备数据,只执行一次
    def m1_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m1_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m2 = M.datahub_load_file.v2(
        file_path=m2_file_path_bigquant_run,
        file_type='csv',
        csv_delimiter=',',
        other_parameters='{}',
        h5_data_key='data'
    )
    
    m3 = M.datahub_handler_column.v1(
        input_data=m2.data,
        handler=m3_handler_bigquant_run
    )
    
    m4 = M.instruments.v2(
        start_date='2002-01-01',
        end_date='2002-12-31',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m1 = M.trade.v4(
        instruments=m4.data,
        options_data=m3.data,
        start_date='',
        end_date='',
        initialize=m1_initialize_bigquant_run,
        handle_data=m1_handle_data_bigquant_run,
        prepare=m1_prepare_bigquant_run,
        before_trading_start=m1_before_trading_start_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.HIX'
    )
    

    读取数据(文件) 数据统计 (前 1233 行) </font></font>

    ID deal_action stock_code deal_price deal_volume deal_cost deal_date remark
    count(Nan) 0 0 0 0 0 0 0 1233
    type int64 object object float64 int64 float64 int64 float64

    读取数据(文件) 数据预览 (前 5 行) </font></font>

    ID deal_action stock_code deal_price deal_volume deal_cost deal_date remark
    0 72491 buy 000682.SZ 74.60 300 5.45 20020104 NaN
    1 72492 buy 600177.SH 32.01 700 5.45 20020104 NaN
    2 72493 buy 600019.SH 3.85 6400 5.49 20020104 NaN
    3 72494 buy 000717.SZ 9.19 2700 5.50 20020104 NaN
    4 72495 buy 600126.SH 13.65 1800 5.49 20020104 NaN

    数据处理(自定义) 数据统计 (前 1233 行) </font></font>

    ID deal_action stock_code deal_price deal_volume deal_cost deal_date remark
    count(Nan) 0 0 0 0 0 0 0 1233
    type int64 object object float64 int64 float64 int64 float64

    数据处理(自定义) 数据预览 (前 5 行) </font></font>

    ID deal_action stock_code deal_price deal_volume deal_cost deal_date remark
    0 72491 buy 000682.SZA 74.60 300 5.45 20020104 NaN
    1 72492 buy 600177.SHA 32.01 700 5.45 20020104 NaN
    2 72493 buy 600019.SHA 3.85 6400 5.49 20020104 NaN
    3 72494 buy 000717.SZA 9.19 2700 5.50 20020104 NaN
    4 72495 buy 600126.SHA 13.65 1800 5.49 20020104 NaN
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-3-8fc58c782096> in <module>
         95 )
         96 
    ---> 97 m1 = M.trade.v4(
         98     instruments=m4.data,
         99     options_data=m3.data,
    
    TypeError: object of type 'NoneType' has no len()