import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.arima_model import ARIMA
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
我们将使用包含特定日期飞机乘客数量的数据集。
df = pd.read_csv('air.csv', parse_dates = ['Month'], index_col = ['Month'])
df.head()
plt.xlabel('Date')
plt.ylabel('Number of air passengers')
plt.plot(df)
在建立模型之前,我们必须确保时间序列是平稳的。有两种主要方法可以确定给定时间序列是否平稳。
滚动统计:绘制滚动平均值和滚动标准差。如果时间序列随时间保持恒定(用肉眼观察线条是否笔直且平行于 x 轴),则时间序列是平稳的。
增强迪基-富勒检验:如果 p 值较低(根据原假设)并且 1%、5%、10% 置信区间的临界值尽可能接近增强迪基-富勒统计,则时间序列被视为平稳。
result = adfuller(df['Passengers'])
print('ADF Statistic: {}'.format(result[0]))
print('p-value: {}'.format(result[1]))
print('Critical Values:')
for key, value in result[4].items():
print('\t{}: {}'.format(key, value))
获取因变量的对数是降低滚动平均值增加速率的简单方法。
df_log = np.log(df)
plt.plot(df_log)
让我们创建一个函数来运行两个测试,以确定给定的时间序列是否平稳。
def get_stationarity(timeseries):
rolling_mean = timeseries.rolling(window=12).mean()
rolling_std = timeseries.rolling(window=12).std()
original = plt.plot(timeseries, color='blue', label='Original')
mean = plt.plot(rolling_mean, color='red', label='Rolling Mean')
std = plt.plot(rolling_std, color='black', label='Rolling Std')
plt.legend(loc='best')
plt.title('Rolling Mean & Standard Deviation')
plt.show(block=False)
result = adfuller(timeseries['Passengers'])
print('ADF Statistic: {}'.format(result[0]))
print('p-value: {}'.format(result[1]))
print('Critical Values:')
for key, value in result[4].items():
print('\t{}: {}'.format(key, value))