克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-145:input_data","SourceOutputPortId":"-135:data"},{"DestinationInputPortId":"-135:instruments","SourceOutputPortId":"-143:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"-143:data"},{"DestinationInputPortId":"-135:features","SourceOutputPortId":"-151:data"},{"DestinationInputPortId":"-135:user_functions","SourceOutputPortId":"-52:functions"},{"DestinationInputPortId":"-84:input_data","SourceOutputPortId":"-145:data"},{"DestinationInputPortId":"-90:input_data","SourceOutputPortId":"-145:data"},{"DestinationInputPortId":"-145:features","SourceOutputPortId":"-62:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-84:data"},{"DestinationInputPortId":"-228:input_data","SourceOutputPortId":"-90:data"},{"DestinationInputPortId":"-224:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-210:training_ds","SourceOutputPortId":"-224:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"-210:model"},{"DestinationInputPortId":"-250:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-228:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-210:features","SourceOutputPortId":"-568:data"},{"DestinationInputPortId":"-250:instruments","SourceOutputPortId":"-572:data"}],"ModuleNodes":[{"Id":"-135","ModuleId":"BigQuantSpace.feature_extractor_1m.feature_extractor_1m-v1","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"90","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"workers","Value":"2","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"parallel_mode","Value":"单机","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"table_1m","Value":"level2_bar1m_CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-135"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-135"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"user_functions","NodeId":"-135"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-135","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":12,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2020-06-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2020-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":" ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"10","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":20,"Comment":"","CommentCollapsed":true},{"Id":"-151","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# 支持 np=numpy, pd=pandas, ta=talib, math 库,支持 pandas series 内建函数\n# _ 开始的表示中间变量,不会出现在最终结果中,可以用于中间复用计算结果,加快速度\n# 自定义表达式\nclose_ = close.loc[145700]\n(close*volume).sum()/volume.sum()\nvwap(close,volume)\nmean_4 = close.loc[103000]+close.loc[113000]+ close.loc[140000]+close.loc[145700] \n_ret = close.pct_change().fillna(close.iloc[0]/open.iloc[0])\n\n# 分钟收益率的各阶矩\t\nskew = _ret.skew()\nkurt = _ret.kurt()\ninday_ret = close.loc[145700]/close.loc[95900] - 1 # 日内涨跌幅累积\nlow_volume_cov = low.cov(volume) #日内成交量最低价的协方差\n \nsome_rsi = ta.RSI(close).loc[95900] # RSI技术指标\nsar = ta.SAR(high,low, 0.02, 0.2).loc[145700] # SAR抛物线转向\n\n_pvt = (_ret * volume).cumsum()\npvt = _pvt.iloc[-1] - _pvt.mean() # PVT量价趋势因子\n\n# 聪明钱指标\n_st = ((close / close.shift(1) - 1).abs() / volume.pow(0.5)).sort_values(ascending=False)\n_volume = volume[_st.index]\n_close = close[_st.index]\n_smart_money = (_volume.cumsum() / volume.sum()) >= 0.2\nsmart_money = ((_volume[_smart_money] * _close[_smart_money]).sum() / _volume[_smart_money].sum()) / ((volume * close).sum() / volume.sum())\n \n# 成交量个阶矩\nmean_v =volume.mean()\nstd_v = volume.std()\nskew_v = volume.skew()\nkurt_v =volume.kurt()\n\n# 日内最优动量\nmom1 = close.loc[103000]/close.loc[93100] - 1\nmom2 = close.loc[113000]/close.loc[103000] - 1\nmom3 = close.loc[140000]/close.loc[130100] - 1\nmom4 = close.loc[145700]/close.loc[140000] - 1\n\nopen_ = open.loc[93100]\nhigh_ = high.max() \nlow_ = low.min()\n \n# 人气指标 \n_mid = (high+low+close)/3\n_strong_sum = where(high>_mid.shift(1),high-_mid.shift(1),0).sum()\n_weak_sum = where(low<_mid.shift(1),_mid.shift(1)-low,0).sum()\ncr = _strong_sum / _weak_sum \n \n# MFI资金流向因子\n_mf = _mid * volume \n_mf_p = where(_mid>_mid.shift(1), _mf, 0)\n_mf_n = where(_mid<_mid.shift(1), -1*_mf, 0)\n_positive_mf = _mf_p.loc[100000:145700].sum()\n_negative_mf = _mf_n.loc[100000:145700].sum()\n_mr = _positive_mf/_negative_mf\nmfi = 100-(100/(1+_mr))\n\n# MACD指数平滑异同平均\n_dif = ta.EMA(close,12) - ta.EMA(close,26)\nmacd = _dif.loc[145700]\n\n# SRDM动向速度比率\n_dmz = where(high+low<high.shift(1)+low.shift(1),0,max(abs(high-high.shift(1)),abs(low-low.shift(1))))\n_dmf = where(high+low>=high.shift(1)+low.shift(1),0,max(abs(high-high.shift(1)),abs(low-low.shift(1))))\n_admz = mean(_dmz,10)\n_admf = mean(_dmf,10)\n_srdm = where(_admz>_admf,(_admz-_admf)/_admz,where(_admz==_admf,0,(_admz-_admf)/_admf))\nasrdm = mean(_srdm, 10).loc[145700]\n\n# 真正强度指数TSI\t\n_mom = close - close.shift(1)\n_mom_real = np.array(_mom,dtype='f8')\n_tsi_series = (ta.EMA(ta.EMA(_mom_real,25),13) / ta.EMA(ta.EMA(abs(_mom_real),25),13) )*100\ntsi = _tsi_series.loc[145700]\n\n# 日内大单流入\n_up_volumes = volume[_ret > 0]\nmy_mf_net_amount_l = _up_volumes.nlargest(math.floor(0.1 * len(_up_volumes))).sum()\n ","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-151"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-151","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":21,"Comment":"","CommentCollapsed":true},{"Id":"-52","ModuleId":"BigQuantSpace.feature_extractor_user_function.feature_extractor_user_function-v1","ModuleParameters":[{"Name":"name","Value":"vwap","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"func","Value":"def bigquant_run(df, close, volume):\n vwap=(close*volume).sum()/volume.sum()\n return vwap\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_functions","NodeId":"-52"}],"OutputPortsInternal":[{"Name":"functions","NodeId":"-52","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"-145","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":"def cal_m(df, amount_avg, price_chg, N):\n def get_m_rolling(s, df_1, N):\n _media_num = (N + 1)//2\n _temp = pd.Series(s).sort_values(ascending=False)\n _m_high = (df_1.iloc[_temp.iloc[:_media_num].index].price_chg + 1).cumprod().iloc[-1] - 1\n _m_low = (df_1.iloc[_temp.iloc[_media_num:].index].price_chg + 1).cumprod().iloc[-1] - 1\n return _m_high - _m_low\n return pd.rolling_apply(df.amount_avg, N, lambda x: get_m_rolling(x, df, N))\n\n# Series对象 rolling 分块求回归系数\ndef rolling_series(series, roll_period):\n series.index= range(1,len(series)+1)\n start_lst = list(series[:roll_period -1])\n rolllists = [series[1].copy()] * (roll_period - 1)\n for i in range(len(start_lst)):\n rolllists[i] = start_lst[i]\n \n for row in series.index:\n index = row\n values = series.ix[index]\n if index > roll_period - 1: # or -2 if zero-indexed\n res = []\n for i in range(index - roll_period, index):\n res.append(series.loc[i + 1]) # or i if 0-indexed\n rolllists.append(res)\n \n new_roll = []\n for li in rolllists:\n while isinstance(li[0], list):\n li = [item for sublist in li for item in sublist] # flatten nested list\n new_roll.append(li)\n return new_roll\n\ndef calcu_rnyd_ret(df, x_name, y_name, N):\n \n reg_df = pd.DataFrame({'x': rolling_series(x_name, N), 'y':rolling_series(y_name, N)})\n \n beta_lst = []\n \n for i in reg_df.index:\n \n x = pd.Series(reg_df.ix[i]['x']).fillna(0)\n y = pd.Series(reg_df.ix[i]['y']).fillna(0)\n \n from scipy import stats\n import statsmodels.api as sm\n \n beta, stockalpha, r_value, p_value, slope_std_error = stats.linregress( x, y)\n beta_lst.append(beta) \n return pd.Series(beta_lst)\n \nbigquant_run = {\n 'calcu_rnyd_ret': calcu_rnyd_ret,\n 'cal_m':cal_m\n}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-145"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-145"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-145","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"Comment":"日频因子进行加工","CommentCollapsed":false},{"Id":"-62","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"mom0 = open_/close_.shift(1)\nma_mom1 = mean(mom1,22)\nma_mom2 = mean(mom2,22)\nma_mom3 = mean(mom3,22)\nma_mom4 = mean(mom4,22)\n \n ","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-62","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":4,"Comment":"","CommentCollapsed":true},{"Id":"-84","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"data<2020-11-01","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":"-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-84","OutputType":null},{"Name":"left_data","NodeId":"-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"Comment":"","CommentCollapsed":true},{"Id":"-90","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"date>=2020-11-01","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":"-90"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-90","OutputType":null},{"Name":"left_data","NodeId":"-90","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","ModuleId":"BigQuantSpace.join.join-v3","ModuleParameters":[{"Name":"on","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"how","Value":"inner","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"sort","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data1","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"Comment":"","CommentCollapsed":true},{"Id":"-224","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-224"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-224"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-224","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"Comment":"","CommentCollapsed":true},{"Id":"-210","ModuleId":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v6","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":30,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":20,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_row_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ndcg_discount_base","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-210"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-210"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-210"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-210"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-210","OutputType":null},{"Name":"feature_gains","NodeId":"-210","OutputType":null},{"Name":"m_lazy_run","NodeId":"-210","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","ModuleId":"BigQuantSpace.stock_ranker_predict.stock_ranker_predict-v5","ModuleParameters":[{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"Comment":"","CommentCollapsed":true},{"Id":"-250","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 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.options['hold_days'] = 5\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.options['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.portfolio.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.portfolio.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities)])))\n\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票\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","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\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":"close","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":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-250"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-250","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":10,"Comment":"","CommentCollapsed":true},{"Id":"-228","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-228"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-228","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na_label","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"cast_label_int","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"Comment":"","CommentCollapsed":true},{"Id":"-568","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"(close*volume).sum()/volume.sum()\nvwap(close,volume)\nmean_4\nskew\nkurt\ninday_ret\nlow_volume_cov\nsome_rsi\nsar\npvt\nsmart_money\nmean_v\nstd_v\nskew_v\nkurt_v\nmom1\nmom2\nmom3\nmom4\nopen_\nhigh_\nlow_\ncr\nmfi\nmacd\nasrdm\ntsi\nmy_mf_net_amount_l\nmom0\nma_mom1\nma_mom2\nma_mom3\nma_mom4","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-568"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-568","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"Comment":"","CommentCollapsed":true},{"Id":"-572","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2020-11-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2020-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"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":"-572"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-572","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"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='-135' Position='237.02789306640625,-871.6541137695312,200,200'/><NodePosition Node='-143' Position='-153.0854697227478,-974.3936767578125,200,200'/><NodePosition Node='-151' Position='245.11737060546875,-1029.30029296875,200,200'/><NodePosition Node='-52' Position='529.8490295410156,-955.5726318359375,200,200'/><NodePosition Node='-145' Position='211.20281982421875,-763.8330078125,200,200'/><NodePosition Node='-62' Position='656.1412963867188,-816.6461791992188,200,200'/><NodePosition Node='-84' Position='17.300265312194824,-631.9185180664062,200,200'/><NodePosition Node='-90' Position='560.40966796875,-588,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='-99.83023166656494,-497.45526123046875,200,200'/><NodePosition Node='-224' Position='-19.166961669921875,-403.45526123046875,200,200'/><NodePosition Node='-210' Position='171,-306,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='439,-222,200,200'/><NodePosition Node='-250' Position='521.6262512207031,-126.63816833496094,200,200'/><NodePosition Node='-228' Position='361,-473,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='-235.25910186767578,-751.7410888671875,200,200'/><NodePosition Node='-568' Position='304.5726623535156,-408.2661895751953,200,200'/><NodePosition Node='-572' Position='587.0579781532288,-339.53851318359375,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 [ ]:
    # 本代码由可视化策略环境自动生成 2021年5月27日17:45
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    def m1_func_bigquant_run(df, close, volume):
        vwap=(close*volume).sum()/volume.sum()
        return vwap
    
    def cal_m(df, amount_avg, price_chg, N):
        def get_m_rolling(s, df_1, N):
            _media_num = (N + 1)//2
            _temp = pd.Series(s).sort_values(ascending=False)
            _m_high = (df_1.iloc[_temp.iloc[:_media_num].index].price_chg + 1).cumprod().iloc[-1] - 1
            _m_low = (df_1.iloc[_temp.iloc[_media_num:].index].price_chg + 1).cumprod().iloc[-1] - 1
            return _m_high - _m_low
        return pd.rolling_apply(df.amount_avg, N, lambda x: get_m_rolling(x, df, N))
    
    # Series对象 rolling 分块求回归系数
    def rolling_series(series, roll_period):
        series.index= range(1,len(series)+1)
        start_lst = list(series[:roll_period -1])
        rolllists =  [series[1].copy()] * (roll_period - 1)
        for i in range(len(start_lst)):
            rolllists[i] = start_lst[i]
        
        for row in series.index:
            index = row
            values = series.ix[index]
            if index > roll_period - 1:  # or -2 if zero-indexed
                res = []
                for i in range(index - roll_period, index):
                    res.append(series.loc[i + 1])  # or i if 0-indexed
                rolllists.append(res)
        
        new_roll = []
        for li in rolllists:
            while isinstance(li[0], list):
                li = [item for sublist in li for item in sublist]  # flatten nested list
            new_roll.append(li)
        return  new_roll
    
    def calcu_rnyd_ret(df, x_name, y_name, N):
      
        reg_df = pd.DataFrame({'x': rolling_series(x_name, N), 'y':rolling_series(y_name, N)})
        
        beta_lst = []
     
        for i in reg_df.index:
           
            x = pd.Series(reg_df.ix[i]['x']).fillna(0)
            y = pd.Series(reg_df.ix[i]['y']).fillna(0)
          
            from scipy import stats
            import statsmodels.api as sm
            
            beta, stockalpha, r_value, p_value, slope_std_error = stats.linregress( x, y)
            beta_lst.append(beta) 
        return pd.Series(beta_lst)
      
    m2_user_functions_bigquant_run = {
        'calcu_rnyd_ret': calcu_rnyd_ret,
        'cal_m':cal_m
    }
    # 回测引擎:初始化函数,只执行一次
    def m10_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.options['hold_days'] = 5
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m10_handle_data_bigquant_run(context, data):
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
    
        # 1. 资金分配
        # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
        # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
        is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
        cash_avg = context.portfolio.portfolio_value / context.options['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.portfolio.positions.items()}
    
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
        if not is_staging and cash_for_sell > 0:
            equities = {e.symbol: e for e, p in context.portfolio.positions.items()}
            instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                    lambda x: x in equities)])))
    
            for instrument in instruments:
                context.order_target(context.symbol(instrument), 0)
                cash_for_sell -= positions[instrument]
                if cash_for_sell <= 0:
                    break
    
        # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
        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 m10_prepare_bigquant_run(context):
        pass
    
    
    m20 = M.instruments.v2(
        start_date='2020-06-01',
        end_date='2020-12-31',
        market='CN_STOCK_A',
        instrument_list=' ',
        max_count=10
    )
    
    m13 = M.advanced_auto_labeler.v2(
        instruments=m20.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
    
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -5) / shift(open, -1)
    
    # 极值处理:用1%和99%分位的值做clip
    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    
    # 将分数映射到分类,这里使用20个分类
    all_wbins(label, 20)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        start_date='',
        end_date='',
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True
    )
    
    m21 = M.input_features.v1(
        features="""# 支持 np=numpy, pd=pandas, ta=talib, math 库,支持 pandas series 内建函数
    # _ 开始的表示中间变量,不会出现在最终结果中,可以用于中间复用计算结果,加快速度
    # 自定义表达式
    close_ = close.loc[145700]
    (close*volume).sum()/volume.sum()
    vwap(close,volume)
    mean_4 = close.loc[103000]+close.loc[113000]+ close.loc[140000]+close.loc[145700] 
    _ret = close.pct_change().fillna(close.iloc[0]/open.iloc[0])
    
    # 分钟收益率的各阶矩	
    skew = _ret.skew()
    kurt = _ret.kurt()
    inday_ret = close.loc[145700]/close.loc[95900] - 1  # 日内涨跌幅累积
    low_volume_cov = low.cov(volume) #日内成交量最低价的协方差
     
    some_rsi = ta.RSI(close).loc[95900] # RSI技术指标
    sar = ta.SAR(high,low, 0.02, 0.2).loc[145700] # SAR抛物线转向
    
    _pvt = (_ret * volume).cumsum()
    pvt = _pvt.iloc[-1]  -  _pvt.mean() # PVT量价趋势因子
    
    # 聪明钱指标
    _st = ((close / close.shift(1) - 1).abs() / volume.pow(0.5)).sort_values(ascending=False)
    _volume = volume[_st.index]
    _close = close[_st.index]
    _smart_money = (_volume.cumsum() / volume.sum()) >= 0.2
    smart_money = ((_volume[_smart_money] * _close[_smart_money]).sum() / _volume[_smart_money].sum()) / ((volume * close).sum() / volume.sum())
     
    # 成交量个阶矩
    mean_v =volume.mean()
    std_v = volume.std()
    skew_v = volume.skew()
    kurt_v =volume.kurt()
    
    # 日内最优动量
    mom1 = close.loc[103000]/close.loc[93100] - 1
    mom2 = close.loc[113000]/close.loc[103000] - 1
    mom3 = close.loc[140000]/close.loc[130100] - 1
    mom4 = close.loc[145700]/close.loc[140000] - 1
    
    open_ = open.loc[93100]
    high_ = high.max() 
    low_ = low.min()
     
    # 人气指标 
    _mid = (high+low+close)/3
    _strong_sum = where(high>_mid.shift(1),high-_mid.shift(1),0).sum()
    _weak_sum = where(low<_mid.shift(1),_mid.shift(1)-low,0).sum()
    cr = _strong_sum / _weak_sum 
      
    # MFI资金流向因子
    _mf = _mid * volume 
    _mf_p = where(_mid>_mid.shift(1), _mf, 0)
    _mf_n = where(_mid<_mid.shift(1), -1*_mf, 0)
    _positive_mf = _mf_p.loc[100000:145700].sum()
    _negative_mf = _mf_n.loc[100000:145700].sum()
    _mr = _positive_mf/_negative_mf
    mfi = 100-(100/(1+_mr))
    
    # MACD指数平滑异同平均
    _dif = ta.EMA(close,12) - ta.EMA(close,26)
    macd = _dif.loc[145700]
    
    # SRDM动向速度比率
    _dmz = where(high+low<high.shift(1)+low.shift(1),0,max(abs(high-high.shift(1)),abs(low-low.shift(1))))
    _dmf = where(high+low>=high.shift(1)+low.shift(1),0,max(abs(high-high.shift(1)),abs(low-low.shift(1))))
    _admz = mean(_dmz,10)
    _admf = mean(_dmf,10)
    _srdm = where(_admz>_admf,(_admz-_admf)/_admz,where(_admz==_admf,0,(_admz-_admf)/_admf))
    asrdm = mean(_srdm, 10).loc[145700]
    
    # 真正强度指数TSI	
    _mom = close - close.shift(1)
    _mom_real = np.array(_mom,dtype='f8')
    _tsi_series = (ta.EMA(ta.EMA(_mom_real,25),13) / ta.EMA(ta.EMA(abs(_mom_real),25),13) )*100
    tsi = _tsi_series.loc[145700]
    
    # 日内大单流入
    _up_volumes = volume[_ret > 0]
    my_mf_net_amount_l = _up_volumes.nlargest(math.floor(0.1 * len(_up_volumes))).sum()
     """
    )
    
    m1 = M.feature_extractor_user_function.v1(
        name='vwap',
        func=m1_func_bigquant_run
    )
    
    m12 = M.feature_extractor_1m.v1(
        instruments=m20.data,
        features=m21.data,
        user_functions=m1.functions,
        start_date='',
        end_date='',
        before_start_days=90,
        workers=2,
        parallel_mode='单机',
        table_1m='level2_bar1m_CN_STOCK_A',
        m_cached=False
    )
    
    m4 = M.input_features.v1(
        features="""mom0 = open_/close_.shift(1)
    ma_mom1 = mean(mom1,22)
    ma_mom2 = mean(mom2,22)
    ma_mom3 = mean(mom3,22)
    ma_mom4 = mean(mom4,22)
     
     """,
        m_cached=False
    )
    
    m2 = M.derived_feature_extractor.v3(
        input_data=m12.data,
        features=m4.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions=m2_user_functions_bigquant_run
    )
    
    m3 = M.filter.v3(
        input_data=m2.data,
        expr='data<2020-11-01',
        output_left_data=False
    )
    
    m6 = M.join.v3(
        data1=m13.data,
        data2=m3.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m7 = M.dropnan.v2(
        input_data=m6.data
    )
    
    m5 = M.filter.v3(
        input_data=m2.data,
        expr='date>=2020-11-01',
        output_left_data=False
    )
    
    m11 = M.dropnan.v2(
        input_data=m5.data
    )
    
    m15 = M.input_features.v1(
        features="""(close*volume).sum()/volume.sum()
    vwap(close,volume)
    mean_4
    skew
    kurt
    inday_ret
    low_volume_cov
    some_rsi
    sar
    pvt
    smart_money
    mean_v
    std_v
    skew_v
    kurt_v
    mom1
    mom2
    mom3
    mom4
    open_
    high_
    low_
    cr
    mfi
    macd
    asrdm
    tsi
    my_mf_net_amount_l
    mom0
    ma_mom1
    ma_mom2
    ma_mom3
    ma_mom4"""
    )
    
    m8 = M.stock_ranker_train.v6(
        training_ds=m7.data,
        features=m15.data,
        learning_algorithm='排序',
        number_of_leaves=30,
        minimum_docs_per_leaf=1000,
        number_of_trees=20,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1,
        data_row_fraction=1,
        ndcg_discount_base=1,
        m_lazy_run=False
    )
    
    m9 = M.stock_ranker_predict.v5(
        model=m8.model,
        data=m11.data,
        m_lazy_run=False
    )
    
    m16 = M.instruments.v2(
        start_date='2020-11-01',
        end_date='2020-12-31',
        market='CN_STOCK_A',
        instrument_list=' ',
        max_count=0
    )
    
    m10 = M.trade.v4(
        instruments=m16.data,
        options_data=m9.predictions,
        start_date='',
        end_date='',
        initialize=m10_initialize_bigquant_run,
        handle_data=m10_handle_data_bigquant_run,
        prepare=m10_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.SHA'
    )