import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 设置合适的字体,确保matplotlib可以显示中文
font_path = 'C:/Windows/Fonts/simsun.ttc'  # 修改为你系统中合适的字体路径
font_prop = FontProperties(fname=font_path, size=12)

# 读取数据
data = pd.read_excel('D:\M_hua\text.xlsx')
print(data.columns)

# 将时间列作为时间索引
data.set_index('time', inplace=True)


# 查看原始数据的平稳性
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])

# 绘制原始数据图
plt.plot(data.index, data.values, label='原始数据')
plt.legend(prop=font_prop)
plt.xlabel('时间', fontproperties=font_prop)
plt.ylabel('数据', fontproperties=font_prop)
plt.title('原始数据', fontproperties=font_prop)
plt.savefig('原始数据.png')
plt.show()

# 进行差分处理,直至平稳
diff_count = 0

while not adfuller(data.iloc[:, 0])[1] < 0.05:
    diff_count += 1
    diff_data = data.diff().dropna()

    # 绘制差分后数据图
    plt.figure()
    plt.plot(diff_data.index, diff_data.values, label=f'差分{diff_count}阶数据')
    plt.legend(prop=font_prop)
    plt.xlabel('时间', fontproperties=font_prop)
    plt.ylabel('数据', fontproperties=font_prop)
    plt.title(f'差分{diff_count}阶数据', fontproperties=font_prop)
    plt.savefig(f'差分{diff_count}阶数据.png')
    plt.show()

    # 绘制差分后数据的ACF和PACF
    plt.figure(figsize=(8, 6))
    ax1 = plt.subplot(211)
    ax2 = plt.subplot(212)
    plot_acf(diff_data.values.squeeze(), ax=ax1, lags=20)
    plot_pacf(diff_data.values.squeeze(), ax=ax2, lags=20)
    ax1.set_xlabel('滞后', fontproperties=font_prop)
    ax1.set_ylabel('ACF', fontproperties=font_prop)
    ax2.set_xlabel('滞后', fontproperties=font_prop)
    ax2.set_ylabel('PACF', fontproperties=font_prop)
    ax1.set_title(f'差分{diff_count}阶数据的ACF', fontproperties=font_prop)
    ax2.set_title(f'差分{diff_count}阶数据的PACF', fontproperties=font_prop)
    plt.tight_layout()
    plt.savefig(f'差分{diff_count}阶数据的ACF和PACF.png')
    plt.show()

    # 更新数据
    data = diff_data
Python时间序列分析:ARIMA模型实战

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

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