季节性自回归集成移动平均模型(SARIMA)代码
时间: 2023-06-25 14:04:53 浏览: 58
下面是一个简单的SARIMA模型的示例代码:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX
# Load data
data = pd.read_csv('data.csv', index_col=0, parse_dates=[0])
data = data.asfreq('D')
# Split data into training and testing sets
train = data.loc['2010-01-01':'2018-12-31']
test = data.loc['2019-01-01':]
# Define and fit SARIMA model
model = SARIMAX(train, order=(2, 1, 2), seasonal_order=(1, 1, 1, 12))
results = model.fit()
# Make predictions
predictions = results.predict(start='2019-01-01', end='2020-12-31')
# Plot actual vs predicted values
plt.plot(test)
plt.plot(predictions)
plt.legend(['Actual', 'Predicted'])
plt.show()
```
在这个例子中,我们首先加载时间序列数据,并将其转换为每天的频率。然后,我们将数据拆分为训练集和测试集,并将SARIMA模型拟合到训练数据中。最后,我们使用拟合模型进行预测,并绘制实际值和预测值的比较图。
在SARIMA模型中,`order`参数是一个三元组(p, d, q),其中p表示自回归项的数量,d表示差分的次数,q表示移动平均项的数量。另外,`seasonal_order`参数是一个四元组(P, D, Q, s),其中P、D和Q与前面的参数类似,但是它们适用于季节性分量,并且s表示季节性的周期性。在这个例子中,我们使用了(2, 1, 2)和(1, 1, 1, 12)作为模型参数。
最后,我们使用`predict()`方法进行预测,并将结果与测试数据进行比较。