投資のためのデータサイエンス

個人の投資活動に役立つデータ分析にまつわる話題を綴ります。

Pythonで学ぶ統計学(10):予測のための時系列データの統計モデル化(ARIMAモデル)(その2)

前回紹介したARIMAモデルを実際の時系列データの予測に適用するpythonコードを紹介します。
時系列データの統計モデルによる予測は、現在では機械学習の一手法として紹介されることがほとんどとなっています。
ここでは機械学習コンペのサイトKaggleにあるデータを用いてARIMAモデルによる予測を行うコードを記述します。
ARMAあるいはARIMAモデルは、statsmodel.tsa.arima_modelからライブラリをインポートして使います。ARやMAの次数の高いモデルはエラーとなって計算できないようです。
学習の方法は、ある一定の長さの系列を用いてモデルを推定し、それを用いて1時点先を予測する「ウォークフォワード」という方式で順次予測を行い、平均二乗誤差の平方根(RMSE)で精度を評価しています。

# ウォークフォワード法によるARIMAモデルの予測
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_squared_error
from math import sqrt
# データセットの読み込み
# https://www.kaggle.com/bulentsiyah/for-simple-exercises-time-series-forecasting
df1 = pd.read_csv('Alcohol_Sales.csv',index_col=0,parse_dates=True)
df2 = df1.rename(columns={'S4248SM144NCEN':'alcohol_sales'})
# 訓練データ(2/3)とテストデータ(1/3)に分ける
X = df2.values
size = int(len(X) * 0.66)
train, test = X[0:size], X[size:len(X)]
history = [x for x in train] # モデル当てはめデータの作成
predictions = list() # 空リスト
# ウォークフォワード法
for t in range(len(test)):
    model = ARIMA(history, order=(2,1,1))
    model_fit = model.fit()
    output = model_fit.forecast()
    yhat = output[0]
    predictions.append(yhat) # 予測値をリストに加える
    obs = test[t]
    history.append(obs) # 観測値データを1時点追加する
    history = history[1:len(history)] # 観測値データの先頭を削除する
#	print('predicted=%f, expected=%f' % (yhat, obs))
# 予測誤差の評価
rmse = sqrt(mean_squared_error(test, predictions))
print('Test RMSE: %.3f' % rmse)
# 実績値と予測値のプロット
plt.plot(test)
plt.plot(predictions, color='red')
plt.title('ARIMA model prediction')
plt.show()

f:id:nicjps230:20210112174322p:plain