import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX
# 生成示例数据:季节性时间序列
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=120, freq='M')
seasonal_component = 10 + 10 * np.sin(np.linspace(0, 3 * np.pi, 120))
data = seasonal_component + np.random.randn(120) * 2 # 叠加噪声
# 创建DataFrame
df = pd.DataFrame(data, index=dates, columns=['Value'])
# 拟合SARIMA模型 (p=1, d=1, q=1, P=1, D=1, Q=1, s=12)
model = SARIMAX(df['Value'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
sarima_result = model.fit()
# 预测未来12个月
forecast = sarima_result.get_forecast(steps=12)
forecast_index = pd.date_range(df.index[-1] + pd.DateOffset(months=1), periods=12, freq='M')
forecast_values = forecast.predicted_mean
# 可视化
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['Value'], label='Observed', color='blue')
plt.plot(forecast_index, forecast_values, label='Forecast', color='orange', linestyle='--')
plt.fill_between(forecast_index,
forecast.conf_int().iloc[:, 0],
forecast.conf_int().iloc[:, 1],
color='#FFA07A', alpha=0.3) # 使用有效的颜色代码
plt.title('SARIMA Model Forecast')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.grid(True)
plt.show()
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.