ARIMA(自回歸移動平均模型)是一種時序分析常用的模型,廣泛應用於股票、經濟等領域。本文將從多個方面詳細闡述ARIMA模型的Python實現方式。
一、ARIMA模型是什麼?
ARIMA模型是對時間序列數據進行建模和分析的一種方法。ARIMA本質上是一種泛化的自回歸模型(AR)和移動平均模型(MA)的組合,其中,時間序列數據中的“自相關”和“平移”是兩個關鍵因素。
在ARIMA模型中,我們可以將時間序列數據看做是具有無窮自相關性和移動平均性質的數據,而這些特性需要經過處理才能使得序列成為平穩序列。ARIMA模型就是通過一定的參數來調整這些自相關和平移的特性,得出預測結果。
二、Python實現ARIMA模型
1. 安裝相關庫
pip install numpy
pip install pandas
pip install matplotlib
pip install pmdarima
2. 數據處理
首先,我們需要對時間序列數據進行處理。這裡以股票數據為例,使用pandas庫讀取csv文件,並進行處理。
import pandas as pd
import numpy as np
df = pd.read_csv('stock_data.csv', parse_dates=['Date'])
df.set_index('Date', inplace=True)
df.head(10)
上述代碼中,parse_dates參數用於將csv文件中的日期數據轉換為Python的datetime格式,將日期數據設置為索引。
3. 數據可視化
可視化數據可以幫助我們更好地理解數據的特性和規律。使用matplotlib庫繪製收盤價的折線圖。
import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
plt.plot(df['Close'], label='Close Price history')
plt.title('Stock data')
plt.xlabel('Date')
plt.ylabel('Close Price (USD)')
plt.show()
4. ARIMA模型建立
此時,我們需要評估時間序列數據是否為平穩時間序列。
可以使用平穩性檢驗的方法來判斷時間序列數據是否為平穩序列。可以採用ADF(Augmented Dickey-Fuller)檢驗,在pmdarima庫中,可以使用adfuller()方法進行檢驗。
from pmdarima.arima.utils import ndiffs
from statsmodels.tsa.stattools import adfuller
# estimate number of differencing terms
kpss_diffs = ndiffs(df['Close'], alpha=0.05, test='kpss', max_d=6)
adf_diffs = ndiffs(df['Close'], alpha=0.05, test='adf', max_d=6)
# calculate ADF test statistic
adf_test = adfuller(df['Close'], maxlag=30, autolag=None)
p_value = adf_test[1]
print('KPSS Test: estimated number of differences =', kpss_diffs)
print('ADF Test: estimated number of differences =', adf_diffs)
print('p-value of ADF test =', p_value)
如果ADF檢驗的p-value小於0.05,那麼我們可以得到一個平穩序列,因此可以進行下一步操作。
ARIMA模型需要用一個參數元組(p,d,q)表示,其中,p表示自回歸項數,d表示差分項數,q表示移動平均項數,因此我們需要通過ACF(自相關函數)和PACF(偏自相關函數)圖來判斷p和q的值,通過pmdarima庫中的區域搜索方法來確定參數值。
from pmdarima.arima import auto_arima
model = auto_arima(df['Close'], start_p=1, start_q=1, max_p=3, max_q=3,
start_P=0, seasonal=False, d=1, trace=True, error_action='ignore',
suppress_warnings=True, stepwise=True)
model.summary()
上述代碼中,使用的是pmdarima庫中的auto_arima()方法,根據參數傳入的初始值和範圍等參數,返回最優的ARIMA模型。
5. 模型擬合和預測
可以使用ARIMA模型進行擬合和預測。擬合和預測的代碼如下:
from statsmodels.tsa.arima_model import ARIMA
train_data = df['Close'][:int(len(df)*0.8)]
test_data = df['Close'][int(len(df)*0.8):]
model = ARIMA(train_data, order=(1,1,1))
fitted_model = model.fit(disp=-1)
print(fitted_model.summary())
# Forecast
fc, se, conf = fitted_model.forecast(len(test_data), alpha=0.05) # 95% conf
# Make as pandas series
fc_series = pd.Series(fc, index=test_data.index)
lower_series = pd.Series(conf[:, 0], index=test_data.index)
upper_series = pd.Series(conf[:, 1], index=test_data.index)
plt.figure(figsize=(10,6))
plt.plot(train_data, label='training')
plt.plot(test_data, label='actual')
plt.plot(fc_series, label='forecast')
plt.fill_between(lower_series.index, lower_series, upper_series,
color='k', alpha=.15)
plt.title('Forecast vs Actuals')
plt.legend(loc='upper left', fontsize=8)
plt.show()
模型擬合和預測的圖形化結果如下圖所示。
三、總結
本文從四個方面詳細講解了ARIMA模型在Python中的實現方法,包括數據處理、數據可視化、模型建立和模型預測。通過對股票數據的ARIMA模型的實現,可以更好的理解ARIMA模型的應用和實現,為更廣泛的時間序列數據處理提供基礎。
原創文章,作者:GKATV,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/375244.html