背景:
03年到19年第一季度分季度的数据,13年之前只有传统汽车的销量,13年之后是传统汽车+新能源汽车的销量,需要预测未来三期传统汽车的销量
数据链接:
具体的实现过程:
#loda data
data = pd.read_excel("/Users/jackwang/downloads/时序数据.xlsx")
data.head()
数据格式转换
data = data[['日期','传统汽车销量']]
for i in range(data.shape[0]):
if data.loc[i,'日期'][-2:] == 'Q1':
data.loc[i,'日期'] = data.loc[i,'日期'][:4] + '-02'
elif data.loc[i,'日期'][-2:] == 'Q2':
data.loc[i,'日期'] = data.loc[i,'日期'][:4] + '-05'
elif data.loc[i,'日期'][-2:] == 'Q3':
data.loc[i,'日期'] = data.loc[i,'日期'][:4] + '-08'
elif data.loc[i,'日期'][-2:] == 'Q4':
data.loc[i,'日期'] = data.loc[i,'日期'][:4] + '-11'
#拆分训练数据和测试数据
train = data[:56]
test = data[56:]
#将数据转换为datatime 序列
train['Timestamp'] = pd.to_datetime(train['Timestamp'], format='%Y-%m')
train.index = train['Timestamp']
test['Timestamp'] = pd.to_datetime(test['日期'],format='%Y-%m')
test.index = test['Timestamp']
#可视化展示
train.传统汽车销量.plot(figsize=(15,8), title= 'Q_SALE', fontsize=14)
test.传统汽车销量.plot(figsize=(15,8), title= 'Q_SALE', fontsize=14)
plt.show()
#平稳性校验
fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot(211)
fig = sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=ax1)
ax2 = fig.add_subplot(212)
fig = sm.graphics.tsa.plot_pacf(dta, lags=40, ax=ax2)
模型训练及结果预测:
arma_mod20 = sm.tsa.ARMA(dta, (2,0)).fit(disp=False)
arma_mod30 = sm.tsa.ARMA(dta, (3,0)).fit(disp=False)
print(arma_mod20.aic, arma_mod20.bic, arma_mod20.hqic)
# In[128]:
print(arma_mod30.params)
# In[129]:
sm.stats.durbin_watson(arma_mod30.resid.values)
# In[130]:
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
ax = arma_mod30.resid.plot(ax=ax);
# In[131]:
resid = arma_mod30.resid
# In[133]:
from scipy import stats
stats.normaltest(resid)
# In[135]:
from statsmodels.graphics.api import qqplot
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
fig = qqplot(resid, line='q', ax=ax, fit=True)
# In[136]:
fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot(211)
fig = sm.graphics.tsa.plot_acf(resid.values.squeeze(), lags=40, ax=ax1)
ax2 = fig.add_subplot(212)
fig = sm.graphics.tsa.plot_pacf(resid, lags=40, ax=ax2)
# In[137]:
r,q,p = sm.tsa.acf(resid.values.squeeze(), fft=True, qstat=True)
data = np.c_[range(1,41), r[1:], q, p]
table = pd.DataFrame(data, columns=['lag', "AC", "Q", "Prob(>Q)"])
print(table.set_index('lag'))
# In[138]:
predict_sunspots = arma_mod30.predict('2019', '2020', dynamic=True)
print(predict_sunspots)
fig, ax = plt.subplots(figsize=(12, 8))
ax = dta.plot(ax=ax)
fig = arma_mod30.plot_predict('2019', '2020', dynamic=True, ax=ax, plot_insample=False)
预测结果展示:
结果可视化:
参考:
https://www.statsmodels.org/stable/examples/notebooks/generated/tsa_arma_0.html
https://cloud.tencent.com/developer/article/1059136
https://www.codercto.com/a/35980.html