2017-07-09 54 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 –