使用R中的Arima模型预测数据

时间:2017-07-09 11:42:27

标签: r forecasting predict arima

我是R语言的初学者,我有按月收到的请求数量的月度数据列表,如何使用ARIMA模型(最佳模型)进行预测可以获得任何类型的数据。 我使用下面的代码,但我不知道结果是否正确和可靠,或者我必须更改此代码中的其他模型或简单更改。

脚本:

#Step 1: Plot Qty data as time series

data <- structure(c(3108L, 2508L, 3516L, 3828L, 3755L, 6612L, 6708L, 
  3624L, 4032L, 4104L, 3000L, 3204L, 2640L, 2124L, 1884L, 12382L, 
  1488L, 1356L, 2028L, 1764L, 1524L, 7248L, 1248L, 816L, 804L, 
  708L, 756L, 972L, 4104L, 1296L, 2268L, 588L, 768L, 792L, 744L, 
  1680L, 684L, 2052L, 672L, 492L, 744L, 768L, 828L, 936L, 840L, 
  5364L, 408L, 528L, 60L, 612L, 684L, 852L, 756L, 972L),
  .Tsp = c(2013, 2017.41666666667, 12), class = "ts")    

plot(data, xlab='Years', ylab = ' Qty ')


# Step 2: Difference data to make data stationary on mean (remove trend)
plot(diff(data),ylab='Differenced Qty')

#Step 3: log transform data to make data stationary on variance
plot(log10(data),ylab='Log (Qty)')

#Step 4: Difference log transform data to make data stationary on both mean and variance
plot(diff(log10(data)),ylab='Differenced Log (Qty)')


# Step 5: Plot ACF and PACF to identify potential AR and MA model
par(mfrow = c(1,2))
acf(ts(diff(log10(data))),main='ACF Qty')
pacf(ts(diff(log10(data))),main='PACF Qty ')

# Step 6: Identification of best fit ARIMA model

require(forecast)
ARIMAfit = auto.arima(log10(data), approximation=FALSE,trace=FALSE)
summary(ARIMAfit)


# Step 6: Forecast sales using the best fit ARIMA model
par(mfrow = c(1,1))
pred = predict(ARIMAfit, n.ahead = 36)
pred
plot(data,type='l',xlim=c(2004,2018),ylim=c(1,1600),xlab = 'Year',ylab = ' Qty ')
lines(10^(pred$pred),col='blue')
lines(10^(pred$pred+2*pred$se),col='orange')
lines(10^(pred$pred-2*pred$se),col='orange')

# Step 7: Plot ACF and PACF for residuals of ARIMA model to ensure no more information is left for extraction
par(mfrow=c(1,2))
acf(ts(ARIMAfit$residuals),main='ACF Residual')

1 个答案:

答案 0 :(得分:0)

你让它变得比它需要的复杂一点。 auto.arima将确定自动使用的AR,MA和差异术语的数量。

Here is a link to read more on it.

最终,如果你只想要适合的代码,你可以做到这一点

library(forecast)
data = ts(data[,2],start = c(2013,1),frequency = 12)
model = auto.arima(data)

我们可以查看模型的摘要,以确定它适合的模型

> summary(model)
Series: dat 
ARIMA(0,1,1)                    

Coefficients:
          ma1
      -0.8501
s.e.   0.0591

sigma^2 estimated as 4166267:  log likelihood=-479.27
AIC=962.53   AICc=962.77   BIC=966.47

所以,我们有ARIMA(0,1,1)。模型中有一个差异和1个MA项自动选取。

如果我们预测模型,我们可以像这样绘制

plot(forecast(model,h=12),include=24)

enter image description here

我们之前没有看到像之前数据那样的峰值的原因是该模型不包括任何季节性参数。看一下情节,看起来峰值似乎不是在同一时间段内发生的。如果峰值与某些事件相关,则需要将其包含在模型中,这可以使用具有事件二进制指示符的xreg参数来完成。