2017-07-09 55 views
1

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

脚本:

#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') 
+0

做'plot(decomposed(data)'。有一个强大的季节性组件到你的数据中,考虑用这个做一些事情 – AkselA

+0

请阅读[在什么情况下我可以在我的问题中加入“urgent”或其他类似的短语,为了获得更快的答案?](// meta.stackoverflow.com/q/326569) - 总结是,这不是解决志愿者的理想方式,并且可能对获得答案起反作用。请不要将此添加到您的 – halfer

+0

对不起,但这是我第一次使用Stackoverflow,好的,谢谢您的建议 –

回答

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

,我们没有看到像尖刺我们在前面的数据做的原因是,该模型ISN”包括任何季节性参数。看看这个情节,似乎并不像在同一时间框架内出现峰值。如果峰值与某些需要包含在模型中的事件相关,则可以使用具有事件二进制指示符的xreg参数完成。

+0

请看看我的第二篇文章 –

+0

@TarhouniBilel这不是一个错误,它只是没有那么棒。 – Kristofersen

+0

感谢freind,我会尝试在模型中添加xreg –