首页 > 编程知识 正文

ARIMA模型Python应用用法介绍

时间:2023-11-22 16:39:06 阅读:292691 作者:DBWC

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模型的应用和实现,为更广泛的时间序列数据处理提供基础。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。