年化42.86%,比基准的12.86高出不少,回撤才9.43%,还是比较稳健的。
策略核心代码如下:我们使用KNN算法,大家可以考虑替换成SVM,或者树模型lightGBM。
class MLTrainOnceStrategy(Strategy): price_delta = .004 # 0.4% def init(self): # Init our model, a kNN classifier self.clf = KNeighborsClassifier(7) # Train the classifier in advance on the first N_TRAIN examples df = self.data.df.iloc[:N_TRAIN] X, y = get_clean_Xy(df) self.clf.fit(X, y) # Plot y for inspection self.I(get_y, self.data.df, name='y_true') # Prepare empty, all-NaN forecast indicator self.forecasts = self.I(lambda: np.repeat(np.nan, len(self.data)), name='forecast') def next(self): # Skip the training, in-sample data if len(self.data) < N_TRAIN: return # Proceed only with out-of-sample data. Prepare some variables high, low, close = self.data.High, self.data.Low, self.data.Close current_time = self.data.index[-1] # Forecast the next movement X = get_X(self.data.df.iloc[-1:]) forecast = self.clf.predict(X)[0] # Update the plotted "forecast" indicator self.forecasts[-1] = forecast # If our forecast is upwards and we don't already hold a long position # place a long order for 20% of available account equity. Vice versa for short. # Also set target take-profit and stop-loss prices to be one price_delta # away from the current closing price. upper, lower = close[-1] * (1 + np.r_[1, -1] * self.price_delta) if forecast == 1 and not self.position.is_long: self.buy(size=.2, tp=upper, sl=lower) elif forecast == -1 and not self.position.is_short: self.sell(size=.2, tp=lower, sl=upper) # Additionally, set aggressive stop-loss on trades that have been open # for more than two days for trade in self.trades: if current_time - trade.entry_time > pd.Timedelta('2 days'): if trade.is_long: trade.sl = max(trade.sl, low) else: trade.sl = min(trade.sl, high)
数据格式如下,同代码一起打包已经发布至星球:
请大家前往星球下载:
代码说明:
本周我们深度调研了vnpy, ctpbee, backtesting,还看了pyalgotrade。
结合之前的backtrader, pybroker和qlib。
quantlab2.x的底层引擎之前是pybroker,3.0引用了大量的backtesting的代码,原因如下:
1、pybroker做空部分不好理解,对于后续接实盘带来麻烦,这块需要重写。
2、vnpy和ctpbee的设计思路,回测引擎与实盘过于“追求相似”,各种send_order和order_request。其实从回测切换到实盘,从onbar开始解耦就好了。
实盘我们还会使用ctpbee的部分代码。
吾日三省吾身
在高度不确定的当下,没有人可以预测未来,更不用说资本市场。
但我们仍然可以做很多事情。
反脆弱的系统设计,所谓“守正出奇”。
寻找“局部”最优解,持续迭代,总能突破。
这是当下的力量。
我们能拥用的只有当下。
往你能掌控的最优的步骤,多走一步,看到更多的信息,得到进一步的反馈,再优化我们的系统。
发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/103607
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!