開始使用免費開始

使用 AR 模型進行預測

除了上一題你已經做過的模型參數估計外,你也可以使用 statsmodels 進行樣本內與樣本外的預測。樣本內預測是指用截至某一點的資料來預測下一個觀測值;樣本外預測則是預測未來任意多個觀測值。你可以使用 plot_predict() 函式來繪製預測結果。你需要提供預測的起點與終點,終點可以是在資料集結束之後的任意多個觀測點。

對於 DataFrame simulated_data_1 中的模擬資料,且 $\small \phi=0.9$,你將繪製樣本外的預測以及其信賴區間。

本練習屬於課程

Python 中的時間序列分析

檢視課程

練習說明

  • 匯入類別 ARIMA,並匯入函式 plot_predict
  • 使用 DataFrame simulated_data_1 的模擬資料與模型的 (p,d,q) 次數(此處為 AR(1)),建立一個名為 modARIMA 類別實例:order=(1,0,0)
  • .fit() 方法擬合模型 mod,並將結果儲存到名為 res 的結果物件
  • 繪製從第 950 筆資料開始的樣本內預測圖
  • 使用 plot_predict() 函式,從資料結束的第 1000 筆開始,到第 1010 筆為止,繪製樣本外的預測與信賴區間

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import the ARIMA and plot_predict from statsmodels
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_predict

# Forecast the first AR(1) model
mod = ARIMA(___, order=___)
res = mod.fit()

# Plot the data and the forecast
fig, ax = plt.subplots()
simulated_data_1.loc[950:].plot(ax=ax)
plot_predict(res, start=___, end=___, ax=ax)
plt.show()
編輯並執行程式碼