ファイナンス機械学習:ラベリング 練習問題 メタラベルの利用 移動平均とランダムフォレストモデル

前記事の移動平均線のクロスにより、サイドを決め、それを執行するか否かのメタラベルをつけた。

 これをランダムフォレストモデルに入れて、トレードするかしないかの訓練を行う。
 特徴量は、一次モデルで使用した長期移動平均と短期移動平均、収益、日次ボラティリティとする。
 再現性のため、random_state=0と固定してある。

from sklearn.model_selection import train_test_split

X = pd.DataFrame(
    {'long': ddfSMA.long,
     'short':ddfSMA.short,
     'rtn':ddf_rtn,
     'vol': daily_vol,
     'side': SMATPevents['side']}).dropna()
X = X[~X.index.duplicated(keep='first')]
y=SMAlabels['bin'].values.astype(int)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, shuffle=False)

from sklearn.ensemble import RandomForestClassifier

n_estimator = 400
rf = RandomForestClassifier(max_depth=2, n_estimators=n_estimator,
                            criterion='entropy',random_state=0)
rf.fit(X_train, y_train)

y_pred = rf.predict(X_test)

 ここで、性能指標と混合行列を描く。

from sklearn.metrics import confusion_matrix

print(classification_report(y_true=y_test, y_pred=y_pred))
confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)

fig, ax = plt.subplots(figsize=(2.5, 2.5))
ax.matshow(confmat, cmap=plt.cm.Blues, alpha=0.3)
for i in range(confmat.shape[0]):
    for j in range(confmat.shape[1]):
        ax.text(x=j, y=i, s=confmat[i, j], va='center', ha='center')

plt.xlabel('Predicted label')
plt.ylabel('True label')

plt.tight_layout()
plt.show()

accuracy = (y_test == y_pred).sum() / y_test.shape[0]
print('Accuracy: ', round(accuracy, 4))


この、True Label(メタラベル)と予想ラベルが共に1となったのが、真の陽性で、取引を行うタイミングであるから、この操作を入れて、混合行列と性能指標、精度を計算し直す。

FinalPrediction = (y_pred & y_test)
print('Meta Label Metrics: ')
print(classification_report(y_true=y_test, y_pred=FinalPrediction))
print('Confusion Matrix')

confmat=confusion_matrix(y_test, FinalPrediction)
fig, ax = plt.subplots(figsize=(2.5, 2.5))
ax.matshow(confmat, cmap=plt.cm.Blues, alpha=0.3)
for i in range(confmat.shape[0]):
    for j in range(confmat.shape[1]):
        ax.text(x=j, y=i, s=confmat[i, j], va='center', ha='center')

plt.xlabel('Predicted label')
plt.ylabel('True label')

plt.tight_layout()
plt.show()
accuracy = (y_test == FinalPrediction).sum() / y_test.shape[0]
print('Accuracy: ', round(accuracy, 4))
メタラベルをフィルタリングした時の混合行列と正確度

 ここでは、ランダムフォレストのパラメータであるmax_depthとn_estimatersはグリッドサーチからスコアの良いものを選んで採用した。
 ドルバーを変えて行った結果の、二次モデルのROCカーブは以下の通りである。

この記事が気に入ったらサポートをしてみませんか?