复制链接
克隆策略
In [46]:
m3.data_1.read()
Out[46]:
date bm_1 bm_2 bm_3
0 2022-02-07 NaN NaN 4638.575195
1 2022-02-08 -0.005463 NaN 4626.436523
2 2022-02-09 0.009392 0.003878 4608.148926
3 2022-02-10 -0.002622 0.006746 4657.210938
4 2022-02-11 -0.008291 -0.010891 4617.874023
... ... ... ... ...
100 2022-07-05 -0.001444 0.005109 4505.457031
101 2022-07-06 -0.014605 -0.016028 4475.481445
102 2022-07-07 0.004409 -0.010260 4425.281250
103 2022-07-08 -0.003307 0.001088 4468.062500
104 2022-07-11 -0.016746 -0.019997 4406.147461

105 rows × 4 columns

    {"description":"实验创建于2017/8/26","graph":{"edges":[{"to_node_id":"-1870:instruments","from_node_id":"-4849:data"},{"to_node_id":"-224:instruments","from_node_id":"-4849:data"},{"to_node_id":"-4862:instruments","from_node_id":"-4849:data"},{"to_node_id":"-4663:input_1","from_node_id":"-4849:data"},{"to_node_id":"-6998:input_data","from_node_id":"-4862:data"},{"to_node_id":"-4679:data1","from_node_id":"-2687:data"},{"to_node_id":"-2687:input_data","from_node_id":"-6998:data"},{"to_node_id":"-1870:options_data","from_node_id":"-61:sorted_data"},{"to_node_id":"-4673:input_ds","from_node_id":"-4663:data_1"},{"to_node_id":"-4673:columns_ds","from_node_id":"-4663:data_2"},{"to_node_id":"-4663:input_2","from_node_id":"-4668:data"},{"to_node_id":"-189:data2","from_node_id":"-4673:data"},{"to_node_id":"-61:input_ds","from_node_id":"-4679:data"},{"to_node_id":"-224:features","from_node_id":"-148:data"},{"to_node_id":"-189:data1","from_node_id":"-224:data"},{"to_node_id":"-4679:data2","from_node_id":"-189:data"},{"to_node_id":"-6998:features","from_node_id":"-112:data"},{"to_node_id":"-4862:features","from_node_id":"-112:data"}],"nodes":[{"node_id":"-4849","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2022-06-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-07-11","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":"-4849"}],"output_ports":[{"name":"data","node_id":"-4849"}],"cacheable":false,"seq_num":11,"comment":"","comment_collapsed":true},{"node_id":"-4862","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":"20","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-4862"},{"name":"features","node_id":"-4862"}],"output_ports":[{"name":"data","node_id":"-4862"}],"cacheable":false,"seq_num":12,"comment":"","comment_collapsed":true},{"node_id":"-2687","module_id":"BigQuantSpace.chinaa_stock_filter.chinaa_stock_filter-v1","parameters":[{"name":"index_constituent_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22displayValue%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"board_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22displayValue%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E7%A7%91%E5%88%9B%E6%9D%BF%22%2C%22displayValue%22%3A%22%E7%A7%91%E5%88%9B%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"industry_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22displayValue%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22displayValue%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22displayValue%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22displayValue%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22displayValue%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22displayValue%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22displayValue%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22displayValue%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22displayValue%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22displayValue%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22displayValue%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22displayValue%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22displayValue%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22displayValue%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%87%87%E6%8E%98%22%2C%22displayValue%22%3A%22%E9%87%87%E6%8E%98%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%92%A2%E9%93%81%22%2C%22displayValue%22%3A%22%E9%92%A2%E9%93%81%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22displayValue%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22displayValue%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22displayValue%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"st_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22displayValue%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22ST%22%2C%22displayValue%22%3A%22ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22*ST%22%2C%22displayValue%22%3A%22*ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22displayValue%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"delist_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%80%80%E5%B8%82%22%2C%22displayValue%22%3A%22%E9%80%80%E5%B8%82%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%9D%9E%E9%80%80%E5%B8%82%22%2C%22displayValue%22%3A%22%E9%9D%9E%E9%80%80%E5%B8%82%22%2C%22selected%22%3Atrue%7D%5D%7D","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":"-2687"}],"output_ports":[{"name":"data","node_id":"-2687"},{"name":"left_data","node_id":"-2687"}],"cacheable":false,"seq_num":13,"comment":"","comment_collapsed":true},{"node_id":"-6998","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":"-6998"},{"name":"features","node_id":"-6998"}],"output_ports":[{"name":"data","node_id":"-6998"}],"cacheable":false,"seq_num":14,"comment":"","comment_collapsed":true},{"node_id":"-61","module_id":"BigQuantSpace.sort.sort-v5","parameters":[{"name":"sort_by","value":"lr","type":"Literal","bound_global_parameter":null},{"name":"group_by","value":"date","type":"Literal","bound_global_parameter":null},{"name":"keep_columns","value":"--","type":"Literal","bound_global_parameter":null},{"name":"ascending","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_ds","node_id":"-61"},{"name":"sort_by_ds","node_id":"-61"}],"output_ports":[{"name":"sorted_data","node_id":"-61"}],"cacheable":false,"seq_num":17,"comment":"","comment_collapsed":true},{"node_id":"-1870","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 = 3\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n # 每只股票的权重平均分配\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.33\n context.hold_days = 10\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\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 # 赚30%就止赢\n if (stock_market_price - stock_cost ) / stock_cost>= 0.7: \n context.order_target_percent(context.symbol(i),0) \n current_stopwin_stock.append(i)\n print('日期:',date,'股票:',i,'出现止盈状况')\n #-------------------------------------------止赢模块END---------------------------------------------\n\n \n #------------------------------------------止损模块START--------------------------------------------\n date = data.current_dt.strftime('%Y-%m-%d') \n equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}\n # 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断\n current_stoploss_stock = [] \n if len(equities) > 0:\n for i in equities.keys():\n stock_market_price = data.current(context.symbol(i), 'price') # 最新市场价格\n last_sale_date = equities[i].last_sale_date # 上次交易日期\n delta_days = data.current_dt - last_sale_date \n hold_days = delta_days.days # 持仓天数\n # 建仓以来的最高价\n highest_price_since_buy = data.history(context.symbol(i), 'high', hold_days, '1d').max()\n # 确定止损位置\n stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.2\n record('止损位置', stoploss_line)\n # 如果价格下穿止损位置\n if stock_market_price < stoploss_line:\n context.order_target_percent(context.symbol(i), 0) \n current_stoploss_stock.append(i)\n print('日期:', date , '股票:', i, '出现止损状况')\n #-------------------------------------------止损模块END--------------------------------------------------\n #-------------------------- START: ST和退市股卖出 --------------------- \n st_stock_list = []\n for instrument in positions.keys():\n try:\n instrument_name = ranker_prediction[ranker_prediction.instrument==instrument].name.values[0]\n # 如果股票状态变为了st或者退市 则卖出\n if 'ST' in instrument_name or '退' in instrument_name:\n if instrument in stock_sold:\n continue\n if data.can_trade(context.symbol(instrument)):\n context.order_target(context.symbol(instrument), 0)\n st_stock_list.append(instrument)\n cash_for_sell -= positions[instrument]\n except:\n continue\n if st_stock_list!=[]:\n print(today,'持仓出现st股/退市股',st_stock_list,'进行卖出处理') \n stock_sold += st_stock_list\n\n #-------------------------- END: ST和退市股卖出 --------------------- \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.portfolio.positions.items()}\n\n # 记录用于买入股票的可用现金,因为是早盘卖股票,需要记录卖出的股票市值并在买入下单前更新可用现金;\n # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用\n cash_for_buy = context.portfolio.cash \n \n try:\n buy_stock = list(ranker_prediction[ranker_prediction.buy_condition>0].instrument) # 当日符合买入条件的股票\n except:\n buy_stock=[]\n try:\n sell_stock = list(context.daily_sell_stock[ranker_prediction.sell_condition>0].instrument) # 当日符合卖出条件的股票\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 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 # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.hold_days # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.hold_days\n cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)\n cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n \n \n\n # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票\n ranker_prediction = ranker_prediction[ranker_prediction.buy_condition>=1]\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction.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","type":"Literal","bound_global_parameter":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)","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"","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":"-1870"},{"name":"options_data","node_id":"-1870"},{"name":"history_ds","node_id":"-1870"},{"name":"benchmark_ds","node_id":"-1870"},{"name":"trading_calendar","node_id":"-1870"}],"output_ports":[{"name":"raw_perf","node_id":"-1870"}],"cacheable":false,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-4663","module_id":"BigQuantSpace.index_feature_extract.index_feature_extract-v3","parameters":[{"name":"before_days","value":"120","type":"Literal","bound_global_parameter":null},{"name":"index","value":"000300.HIX","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_1","node_id":"-4663"},{"name":"input_2","node_id":"-4663"}],"output_ports":[{"name":"data_1","node_id":"-4663"},{"name":"data_2","node_id":"-4663"}],"cacheable":false,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-4668","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# return_0\nbm_1=close/shift(close,1)-1\n# return_1\nbm_2=close/shift(close,2)-1\n\nbm_3=open","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-4668"}],"output_ports":[{"name":"data","node_id":"-4668"}],"cacheable":false,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-4673","module_id":"BigQuantSpace.select_columns.select_columns-v3","parameters":[{"name":"columns","value":"date,bm_1,bm_2,bm_3","type":"Literal","bound_global_parameter":null},{"name":"reverse_select","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_ds","node_id":"-4673"},{"name":"columns_ds","node_id":"-4673"}],"output_ports":[{"name":"data","node_id":"-4673"}],"cacheable":false,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-4679","module_id":"BigQuantSpace.join.join-v3","parameters":[{"name":"on","value":"date,instrument","type":"Literal","bound_global_parameter":null},{"name":"how","value":"left","type":"Literal","bound_global_parameter":null},{"name":"sort","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"data1","node_id":"-4679"},{"name":"data2","node_id":"-4679"}],"output_ports":[{"name":"data","node_id":"-4679"}],"cacheable":false,"seq_num":6,"comment":"","comment_collapsed":true},{"node_id":"-148","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nname","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-148"}],"output_ports":[{"name":"data","node_id":"-148"}],"cacheable":false,"seq_num":7,"comment":"","comment_collapsed":true},{"node_id":"-224","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"instruments_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":"-224"},{"name":"features","node_id":"-224"}],"output_ports":[{"name":"data","node_id":"-224"}],"cacheable":false,"seq_num":9,"comment":"","comment_collapsed":true},{"node_id":"-189","module_id":"BigQuantSpace.join.join-v3","parameters":[{"name":"on","value":"date","type":"Literal","bound_global_parameter":null},{"name":"how","value":"left","type":"Literal","bound_global_parameter":null},{"name":"sort","value":"True","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"data1","node_id":"-189"},{"name":"data2","node_id":"-189"}],"output_ports":[{"name":"data","node_id":"-189"}],"cacheable":false,"seq_num":10,"comment":"","comment_collapsed":true},{"node_id":"-112","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"amout_zf=amount_0/amount_1\nzhangf=(close_0-open_0)/close_1\nzhangf_max=max((close_0-open_0)/open_0,(close_0-close_1)/close_1)\n\npriceHighb10=close_0/ts_max(close_0,10)\npriceLow10=close_0/ts_min(close_0,10)\n\npriceHighb30=close_0/ts_max(close_0,30)\npriceLow30=close_0/ts_min(close_0,30)\n\nhpb10=ts_max(close_0,10)/ts_min(close_0,10)\n\nzt=where(price_limit_status_0==3,1,0)\nzt_num=group_sum(date,zt)\nzt_shouyi=where(shift(zt,1),1,0)\nmean_ztshouyi=group_sum(date,zt_shouyi)/shift(zt_num,1)\n\n# my1=where((zs_return_0>1)&(zs_return_1<1)&(zs_open<1.0025)&(shift(priceLow10,1)==1)&(return_1>0.96)&(abs(open_0/close_1-1.03)<0.01)&(zhangf>0)&(amount_zf<2)&(priceLow30<1.08,1,0)\n# my2=where((shift(zt_num,2)<=90)&(shift(mean_ztshouyi,1)>1)&(zs_return_0<1.005)&(shift(hpb10,3)<1.1)&(ts_max(return_3,120)>1.2)&(shift(zt,2)==1)&(ts_max(high_0,2)/close_0>1.05)&(rpiceLow10<1.2)&(abs(close_0/close_2-1)<0.02)&(zhangf>0),1,0)\n\n# my=max(my1,my2)\n# buy_condition=where(my>0,1,0)\n# sell_condition=where(my>1,1,0)","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-112"}],"output_ports":[{"name":"data","node_id":"-112"}],"cacheable":true,"seq_num":8,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-4849' Position='518,-29,200,200'/><node_position Node='-4862' Position='98,159,200,200'/><node_position Node='-2687' Position='233,519,200,200'/><node_position Node='-6998' Position='230,375,200,200'/><node_position Node='-61' Position='427,950,200,200'/><node_position Node='-1870' Position='358,1188,200,200'/><node_position Node='-4663' Position='1006,242,200,200'/><node_position Node='-4668' Position='1038,-12,200,200'/><node_position Node='-4673' Position='1039,382,200,200'/><node_position Node='-4679' Position='481,719,200,200'/><node_position Node='-148' Position='561,160,200,200'/><node_position Node='-224' Position='710,339,200,200'/><node_position Node='-189' Position='763,460,200,200'/><node_position Node='-112' Position='205,-5,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [4]:
    # 本代码由可视化策略环境自动生成 2022年7月15日 11:16
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m1_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 = 3
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[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.33
        context.hold_days = 10
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m1_handle_data_bigquant_run(context, data):
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
     #------------------------------------------止赢模块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') 
                # 赚30%就止赢
                if (stock_market_price - stock_cost ) / stock_cost>= 0.7:   
                    context.order_target_percent(context.symbol(i),0)     
                    current_stopwin_stock.append(i)
                    print('日期:',date,'股票:',i,'出现止盈状况')
        #-------------------------------------------止赢模块END---------------------------------------------
    
           
             #------------------------------------------止损模块START--------------------------------------------
        date = data.current_dt.strftime('%Y-%m-%d')  
        equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
        # 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
        current_stoploss_stock = [] 
        if len(equities) > 0:
            for i in equities.keys():
                stock_market_price = data.current(context.symbol(i), 'price')  # 最新市场价格
                last_sale_date = equities[i].last_sale_date   # 上次交易日期
                delta_days = data.current_dt - last_sale_date  
                hold_days = delta_days.days # 持仓天数
                # 建仓以来的最高价
                highest_price_since_buy = data.history(context.symbol(i), 'high', hold_days, '1d').max()
                # 确定止损位置
                stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.2
                record('止损位置', stoploss_line)
                # 如果价格下穿止损位置
                if stock_market_price < stoploss_line:
                    context.order_target_percent(context.symbol(i), 0)     
                    current_stoploss_stock.append(i)
                    print('日期:', date , '股票:', i, '出现止损状况')
        #-------------------------------------------止损模块END--------------------------------------------------
         #-------------------------- START: ST和退市股卖出 ---------------------  
        st_stock_list = []
        for instrument in positions.keys():
            try:
                instrument_name = ranker_prediction[ranker_prediction.instrument==instrument].name.values[0]
                # 如果股票状态变为了st或者退市 则卖出
                if 'ST' in instrument_name or '退' in instrument_name:
                    if instrument in stock_sold:
                        continue
                    if data.can_trade(context.symbol(instrument)):
                        context.order_target(context.symbol(instrument), 0)
                        st_stock_list.append(instrument)
                        cash_for_sell -= positions[instrument]
            except:
                continue
        if st_stock_list!=[]:
            print(today,'持仓出现st股/退市股',st_stock_list,'进行卖出处理')    
            stock_sold += st_stock_list
    
        #-------------------------- END: ST和退市股卖出 --------------------- 
         # 获取今日的日期
        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.portfolio.positions.items()}
    
        # 记录用于买入股票的可用现金,因为是早盘卖股票,需要记录卖出的股票市值并在买入下单前更新可用现金;
        # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用
        cash_for_buy = context.portfolio.cash    
        
        try:
            buy_stock = list(ranker_prediction[ranker_prediction.buy_condition>0].instrument) # 当日符合买入条件的股票
        except:
            buy_stock=[]
        try:
            sell_stock = list(context.daily_sell_stock[ranker_prediction.sell_condition>0].instrument)  # 当日符合卖出条件的股票
        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:
                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]
        
        # 1. 资金分配
        # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
        # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
        is_staging = context.trading_day_index < context.hold_days # 是否在建仓期间(前 hold_days 天)
        cash_avg = context.portfolio.portfolio_value / context.hold_days
        cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
        cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        
        
    
        # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票
        ranker_prediction = ranker_prediction[ranker_prediction.buy_condition>=1]
        buy_cash_weights = context.stock_weights
        buy_instruments = list(ranker_prediction.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 m1_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)
    
    m11 = M.instruments.v2(
        start_date='2022-06-01',
        end_date='2022-07-11',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0,
        m_cached=False
    )
    
    m4 = M.input_features.v1(
        features="""# return_0
    bm_1=close/shift(close,1)-1
    # return_1
    bm_2=close/shift(close,2)-1
    
    bm_3=open""",
        m_cached=False
    )
    
    m3 = M.index_feature_extract.v3(
        input_1=m11.data,
        input_2=m4.data,
        before_days=120,
        index='000300.HIX',
        m_cached=False
    )
    
    m5 = M.select_columns.v3(
        input_ds=m3.data_1,
        columns_ds=m3.data_2,
        columns='date,bm_1,bm_2,bm_3',
        reverse_select=False,
        m_cached=False
    )
    
    m7 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    name""",
        m_cached=False
    )
    
    m9 = M.use_datasource.v1(
        instruments=m11.data,
        features=m7.data,
        datasource_id='instruments_CN_STOCK_A',
        start_date='',
        end_date='',
        m_cached=False
    )
    
    m10 = M.join.v3(
        data1=m9.data,
        data2=m5.data,
        on='date',
        how='left',
        sort=True,
        m_cached=False
    )
    
    m8 = M.input_features.v1(
        features="""amout_zf=amount_0/amount_1
    zhangf=(close_0-open_0)/close_1
    zhangf_max=max((close_0-open_0)/open_0,(close_0-close_1)/close_1)
    
    priceHighb10=close_0/ts_max(close_0,10)
    priceLow10=close_0/ts_min(close_0,10)
    
    priceHighb30=close_0/ts_max(close_0,30)
    priceLow30=close_0/ts_min(close_0,30)
    
    hpb10=ts_max(close_0,10)/ts_min(close_0,10)
    
    zt=where(price_limit_status_0==3,1,0)
    zt_num=group_sum(date,zt)
    zt_shouyi=where(shift(zt,1),1,0)
    mean_ztshouyi=group_sum(date,zt_shouyi)/shift(zt_num,1)
    
    # my1=where((zs_return_0>1)&(zs_return_1<1)&(zs_open<1.0025)&(shift(priceLow10,1)==1)&(return_1>0.96)&(abs(open_0/close_1-1.03)<0.01)&(zhangf>0)&(amount_zf<2)&(priceLow30<1.08,1,0)
    # my2=where((shift(zt_num,2)<=90)&(shift(mean_ztshouyi,1)>1)&(zs_return_0<1.005)&(shift(hpb10,3)<1.1)&(ts_max(return_3,120)>1.2)&(shift(zt,2)==1)&(ts_max(high_0,2)/close_0>1.05)&(rpiceLow10<1.2)&(abs(close_0/close_2-1)<0.02)&(zhangf>0),1,0)
    
    # my=max(my1,my2)
    # buy_condition=where(my>0,1,0)
    # sell_condition=where(my>1,1,0)"""
    )
    
    m12 = M.general_feature_extractor.v7(
        instruments=m11.data,
        features=m8.data,
        start_date='',
        end_date='',
        before_start_days=20,
        m_cached=False
    )
    
    m14 = M.derived_feature_extractor.v3(
        input_data=m12.data,
        features=m8.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={},
        m_cached=False
    )
    
    m13 = M.chinaa_stock_filter.v1(
        input_data=m14.data,
        index_constituent_cond=['全部'],
        board_cond=['上证主板', '深证主板', '创业板'],
        industry_cond=['全部'],
        st_cond=['正常'],
        delist_cond=['非退市'],
        output_left_data=False,
        m_cached=False
    )
    
    m6 = M.join.v3(
        data1=m13.data,
        data2=m10.data,
        on='date,instrument',
        how='left',
        sort=False,
        m_cached=False
    )
    
    m17 = M.sort.v5(
        input_ds=m6.data,
        sort_by='lr',
        group_by='date',
        keep_columns='--',
        ascending=False,
        m_cached=False
    )
    
    m1 = M.trade.v4(
        instruments=m11.data,
        options_data=m17.sorted_data,
        start_date='',
        end_date='',
        initialize=m1_initialize_bigquant_run,
        handle_data=m1_handle_data_bigquant_run,
        prepare=m1_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.HIX'
    )