以天为时间间隔的ARIMA预测模型Python代码
时间: 2023-11-19 14:44:17 浏览: 204
ARIMA时间序列预测模型Python代码
下面是以天为时间间隔的ARIMA预测模型Python代码的示例:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
# 读取数据
df = pd.read_csv('data.csv')
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
# 检查数据是否平稳
def test_stationarity(timeseries):
# 计算移动平均和移动标准差
rolmean = timeseries.rolling(window=30).mean()
rolstd = timeseries.rolling(window=30).std()
# 绘制移动平均和移动标准差
plt.figure(figsize=(10, 5))
orig = plt.plot(timeseries, color='blue', label='Original')
mean = plt.plot(rolmean, color='red', label='Rolling Mean')
std = plt.plot(rolstd, color='black', label='Rolling Std')
plt.legend(loc='best')
plt.title('Rolling Mean & Standard Deviation')
plt.show()
# 进行Dickey-Fuller检验
from statsmodels.tsa.stattools import adfuller
print('Results of Dickey-Fuller Test:')
dftest = adfuller(timeseries, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used'])
for key, value in dftest[4].items():
dfoutput['Critical Value (%s)' % key] = value
print(dfoutput)
# 先进行一次差分,使其变为平稳序列
ts_diff = df.diff(1)
ts_diff = ts_diff.dropna()
# 检查平稳性
test_stationarity(ts_diff)
# 绘制ACF和PACF图
plot_acf(ts_diff)
plot_pacf(ts_diff)
plt.show()
# 建立ARIMA模型,选取最优的p、d和q的值
model = ARIMA(df, order=(1, 1, 1))
results = model.fit(disp=-1)
print(results.summary())
# 预测未来30天的数据
forecast = results.forecast(steps=30)
print(forecast)
```
上述代码中,我们首先读取了一个带有日期列的CSV文件,并将其设置为索引。然后,我们定义了一个函数来检查数据的平稳性。接下来,我们对数据进行了一次差分,使其成为平稳序列,然后检查了其平稳性并绘制了ACF和PACF图。最后,我们建立了ARIMA模型并进行预测。
阅读全文