- 数据来源: R语言自带 Nile 数据集(尼罗河流量)
- 分析工具:R-3.5.0 & Rstudio-1.1.453
#清理环境,加载包
rm(list=ls())
library(forecast)
library(tseries)
#趋势查看
plot(Nile)

#平稳性检验
#自相关图
acf(Nile)

#偏相关图
pacf(Nile)

#也可以直接用tsdisplay查看
tsdisplay(Nile)

#单位根检验
adf.test(Nile)

- 从自相关图上看,自相关系数没有快速衰减为0,呈拖尾,单位根检验进一步验证,存在单位根,所以序列为非平稳序列
#做序列差分
#可以用ndiffs判断需要做几阶差分
ndiffs(Nile)

#做一阶差分,然后再进行检验
Nile_diff=diff(Nile,1)
plot(Nile_diff)

acf(Nile_diff)

pacf(Nile_diff)

adf.test(Nile_diff)

#建立模型
(mod=arima(Nile,order=c(0,1,1),method='ML'))

#auto.arima通过选取AIC和BIC最小来选取模型,与根据acf和pacf图建立的模型进行比较
(mod_auto=auto.arima(Nile))

# 残差正态性检验
qqnorm(mod$residuals)
qqline(mod$residuals)

qqnorm(mod_auto$residuals)
qqline(mod_auto$residuals)

# 残差白噪检验
Box.test(mod$residuals,type='Ljung-Box')

Box.test(mod_auto$residuals,type='Ljung-Box')

- 根据检验结果来看,还是选择根据acf图和pacf图建立的模型比较好
# 进行预测
(pre=forecast(mod,5))

plot(Nile,col='pink')
par(new=T)
plot(pre,col='green')

plot(pre,col='green')
