Python实现ARIMA模型:时间序列分析与预测

本文将介绍如何使用Python构建ARIMA模型,对时间序列数据进行分析和预测。我们将提供完整的代码示例,涵盖以下步骤:

  1. 数据读取和准备2. 平稳性检验3. 差分处理4. 模型定阶5. 模型拟合6. 模型评估和可视化

代码示例pythonimport pandas as pdimport matplotlib.pyplot as pltfrom statsmodels.tsa.stattools import adfullerfrom statsmodels.tsa.arima.model import ARIMA

读取数据data = pd.read_excel('D:\M_hua\text.xlsx', index_col=0, header=None, skiprows=[0])data = data.astype(float)

平稳性检验def check_stationarity(series): result = adfuller(series) print('ADF检验结果:') print('ADF Statistic:', result[0]) print('p-value:', result[1]) print('Critical Values:') for key, value in result[4].items(): print(f'{key}: {value}')

查看原始数据的平稳性print('原始数据的平稳性检验结果:')check_stationarity(data.iloc[:, 0])

进行差分处理diff_data = data.diff().dropna()

查看差分后数据的平稳性print('一阶差分后数据的平稳性检验结果:')check_stationarity(diff_data.iloc[:, 0])

确定差分次数diff_count = 1

定界过程order_aic_bic = []for p in range(3): for q in range(3): try: model = ARIMA(data, order=(p, diff_count, q)) result = model.fit() order_aic_bic.append((p, q, result.aic, result.bic)) except: continue

输出定界过程结果(按AIC排序)order_aic_bic.sort(key=lambda x: x[2])print('定界过程结果(按AIC排序):')for order in order_aic_bic: print(f'Order: {order[0]}, {diff_count}, {order[1]}, AIC: {order[2]}, BIC: {order[3]}')

构建ARIMA模型,并拟合数据best_order = order_aic_bic[0][:2]model = ARIMA(data, order=best_order)result = model.fit()

输出模型系数print('模型系数:')print(result.summary().tables[1])

可视化拟合结果plt.plot(data, label='原始数据')plt.plot(result.fittedvalues, color='red', label='拟合结果')plt.legend()plt.show()

代码说明

  1. 数据读取和准备: 使用pandas读取Excel数据,并将其转换为浮点型。2. 平稳性检验: 使用ADF检验判断时间序列数据的平稳性。3. 差分处理: 如果数据非平稳,则进行差分处理使其平稳。4. 模型定阶: 通过循环遍历不同的p、q值,并比较AIC、BIC值,确定ARIMA模型的最佳阶数。5. 模型拟合: 使用最佳阶数构建ARIMA模型,并使用历史数据进行拟合。6. 模型评估和可视化: 输出模型系数,并将拟合结果可视化。

总结

本文介绍了如何使用Python构建ARIMA模型进行时间序列分析和预测。代码示例涵盖了数据准备、平稳性检验、差分、定阶、模型拟合、可视化等关键步骤。你可以根据自己的数据和需求对代码进行调整和优化。

Python实现ARIMA模型:时间序列分析与预测

原文地址: https://www.cveoy.top/t/topic/bJNa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录