# ARIMA 时间序列1: 差分, ACF, PACF

27 篇文章 3 订阅

## ARIMA

ARIMA(p，d，q)模型全称为差分自回归移动平均模型
(Autoregressive Integrated Moving Average Model,简记ARIMA).

• p：趋势自回归阶数。
• d：趋势差分阶数。
• q：趋势移动平均阶数。

## ACF 与 PACF

• 自相关函数ACF 还包含了其他变量的影响
• 偏自相关系数PACF 是严格这两个变量之间的相关性
• ARIMA(p，d，q)阶数确定：
• AR (p ) 看PACF
MA(q ) 看ACF

## 实例: 美国消费者信心指数

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style = 'whitegrid', context = 'poster')
%matplotlib inline



sns.set(style = 'ticks', context = 'poster')

sentiment_select = Sentiment.loc['2004' : '2016']
sentiment_select.plot(figsize = (12, 8))
plt.legend(bbox_to_anchor = (1.25, 0.5))
plt.title('Comsumer Sentiment')
sns.despine()


#### 差分

sentiment_select['diff_1'] = sentiment_select['UMCSENT'].diff(1) # 一阶差分
sentiment_select['diff_2'] = sentiment_select['diff_1'].diff(1) # 二阶差分

sentiment_select.plot(subplots = True, figsize = (18, 18))


del sentiment_select['diff_2']
del sentiment_select['diff_1']
print(type(sentiment_select))


#### ACF 与 PACF

import statsmodels.api as sm
# import statsmodels.formula.api as smf
import statsmodels.tsa.api as smt

fig = plt.figure(figsize = (12, 8))

sm.graphics.tsa.plot_acf(sentiment_select, lags=20, ax=ax1)
ax1.xaxis.set_ticks_position('top')

sm.graphics.tsa.plot_pacf(sentiment_select, lags=20, ax=ax2)
ax2.xaxis.set_ticks_position('bottom')
fig.tight_layout()


# 散点图也可以表示

lags = 9
ncols = 3
nrows = int(np.ceil(lags / ncols))

fig, axes = plt.subplots(ncols=ncols, nrows=nrows, figsize=(4*ncols, 4*nrows))

for ax,lag in zip(axes.flat, np.arange(1, lags+1, 1)):
lag_str = 't-{}'.format(lag)
X = (pd.concat([sentiment_select, sentiment_select.shift(-lag)], axis=1,
keys=['y'] + [lag_str]).dropna())
X.plot(ax = ax, kind = 'scatter', y = 'y', x = lag_str)
corr = X.corr().as_matrix()[0][1]
ax.set_ylabel('Original')
ax.set_title('Lag: {} (corr={:.2f})'.format(lag_str, corr))
ax.set_aspect('equal')
sns.despine()
fig.tight_layout()


# 更直观展示

def tsplot(y, lags=None, title='', figsize=(14, 10)):
fig = plt.figure(figsize = figsize)
layout = (2, 2)
ts_ax = plt.subplot2grid(layout, (0, 0))
hist_ax = plt.subplot2grid(layout, (0, 1))
acf_ax = plt.subplot2grid(layout, (1, 0))
pacf_ax = plt.subplot2grid(layout, (1, 1))

y.plot(ax = ts_ax)
ts_ax.set_title(title)

y.plot(ax = hist_ax, kind = 'hist', bins = 30)
hist_ax.set_title('Histogram')

smt.graphics.plot_acf(y, lags=lags, ax=acf_ax)
smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax)
[ax.set_xlim(0) for ax in [acf_ax, pacf_ax]]
plt.tight_layout()
return ts_ax, acf_ax, pacf_ax

tsplot(sentiment_select, title = 'Consumer Sentiment', lags = 36)


• 2
点赞
• 0
评论
• 33
收藏
• 一键三连
• 扫一扫，分享海报

07-15 2086
05-29 7001
04-28 4万+
01-30 6673
07-07 3万+
12-11 2万+
06-28
07-16 2万+
01-21 105
08-18 4万+
08-18
08-19