時間序列分析:ARIMA模型
概述
ARIMA 是用於單變數時間序列資料預測的最廣泛使用方法之一
優點:模型十分簡單,只需要內生變數而不需要藉助其他外生變數
缺點:要求時序資料是穩定的;本質上只能捕捉線性關係,不能捕捉非線性關係
資料處理
1、匯入資料,視覺化觀察資料趨勢,並劃分測試集和訓練集
tsdata
=
pd
。
read_csv
(
‘timeseries。csv’
,
index_col
=
‘date’
,
parse_dates
=
[
‘date’
])
tsdata
。
revenue
。
plot
()
plt
。
show
()
ts_train
=
tsdate
。
loc
[
‘2020-02-16’
:
‘2020-03-06’
]
ts_test
=
tsdata
。
loc
[
‘2020-03-07’
:]
2、平穩性檢驗:單位根檢驗 ADF test
因為時間序列預測基於未來序列的統計特徵(均值、方差、協方差等)與現有序列相同,即這些統計特徵獨立於時間
H0: 單位根存在,序列不平穩。當 p-value<0。05, 拒絕原假設,時間序列平穩
from
statsmodels。tsa。stattools
import
adfuller
results
=
adfuller
(
tsdata
[
‘revenue’
])
(
results
[
1
])
#返回p-value
3、若不平穩,使時間序列平穩化:d 階差分
from
statsmodels。graphics。tsaplots
import
plot_acf
plot_acf
(
tsdata
[
‘revenue’
],
alpha
=
0。05
,
lags
=
20
)
tsdata
[
‘revenue’
]
=
tsdata
[
‘revenue’
]
。
diff
(
4
)
。
dropna
()
#一個週期的lags數
tsdata
[
‘revenue’
]
=
tsdata
[
‘revenue’
]
。
diff
()
。
dropna
()
#若仍有置信區間外的autocorrelation,繼續差分
4、純隨機性檢驗(白噪聲檢驗)
白噪聲無法預測,因為所有自相關接近零
from
statsmodels。stats。diagnostic
import
acorr_ljungbox
accor_ljungbox
(
tsdata
[
‘revenue’
],
lags
=
1
)[
1
]
#返回p-value,小於0。05則不是白噪音
建模預測
ARIMA
1、計算自相關係數ACF和偏相關係數PACF,對模型定階
AR模型是自迴歸模型,其基本假設是當前的序列值取決於它之前的值,且存在一定滯後
p 值可從PACF圖的最大滯後點來大致判斷,q 值可從ACF圖的最大滯後點來大致判斷
from
statsmodels。graphics。tsaplots
import
plot_acf
,
plot_pacf
plot_acf
(
tsdata
[
‘revenue’
],
alpha
=
0。05
,
lags
=
20
)
plot_pacf
(
tsdata
[
‘revenue’
],
alpha
=
0。05
,
lags
=
20
)
也可以遍歷搜尋AIC和BIC最小的引數組合
AIC和BIC都是量統計模型擬合優良性的一種標準,且引入了對模型引數過多過複雜的懲罰項,避免過擬合(BIC的懲罰項比AIC的大,還考慮了樣本數量過多)
pmax
=
int
(
len
(
tsdata
[
‘revenue’
])
/
10
)
qmax
=
int
(
len
(
tsdata
[
‘revenue’
])
/
10
)
bic_matrix
=
[]
for
p
in
range
(
pmax
+
1
):
tmp
=
[]
for
q
in
range
(
qmax
+
1
):
try
:
#存在部分報錯,所以用try來跳過報錯
tmp
。
append
(
ARIMA
(
data
,
(
p
,
1
,
q
))
。
fit
()
。
bic
)
except
:
tmp
。
append
(
None
)
bic_matrix
。
append
(
tmp
)
bic_matrix
=
pd
。
DataFrame
(
bic_matrix
)
p
,
q
=
bic_matrix
。
stack
()
。
idxmin
()
#用stack展平
((
p
,
q
)
2、由 d, p, q 得到ARIMA模型
model
=
ARIMA
(
tsdata
[
‘revenue’
],
order
=
(
p
,
d
,
q
))
。
fit
()
(
model
。
summary
())
#給出模型結果報告
model
。
plot_fit
()
#對模型擬合效果進行視覺化
model
。
predict
(
start
=
‘
2019
-
04
-
01
’
,
end
=
‘
2019
-
12
-
04
’
)
model
。
plot_predict
(
start
=
‘
2019
-
04
-
01
’
,
end
=
‘
2019
-
12
-
04
’
)
plt
。
show
()
SARIMA
由於ARIMA不支援對具有季節性元件的時間序列直接建模,SARIMA 引入四個季節性引數 P D Q s,使用等於季節數的滯後差異來消除加性季節效應
P為AR模型中季節分量的階數,等於PACF圖中顯著滯後的數量
D為季節性整合階數,取值等於1或0,表示是否應用季節差分
Q為MA模型中季節分量的階數,等於ACF圖中顯著滯後的數量
s為季節週期的長度值
model
=
SARIMA
(
tsdata
[
‘revenue’
],
order
=
(
p
,
d
,
q
),
seasonal_order
=
(
P
,
D
,
Q
,
s
))
。
fit
()
ARIMAX
引入外部資訊來增強 ARIMA 模型的預測能力
exog表示引入的變數
model
=
ARIMA
(
tsdata
[
‘revenue’
],
order
=
(
p
,
d
,
q
),
exog
=
tsdata
[
‘cost’
])
。
fit
()
模型評估
1、用 MAE 衡量模型精度,MAE越小越好
results
=
ARIMA
()
。
fit
()
mae
=
np
。
mean
(
np
。
abs
(
results
。
resid
))
2、檢視殘差,檢驗模型對資料的擬合程度
Prob(Q)為H0 殘差無correlation的p-value,Prob(JB)為H0 殘差正態分佈的p-value
model
=
ARIMA
()
。
fit
()
model
。
summary
()