如何提取并输出使用forecast函数的预测值,ARIMA model in R

Example code with given Fourier series order K

<R>
#for daily time series forecasting and plot the forecasting result, ref : http://robjhyndman.com/hyndsight/longseasonality/

n <- 2000
m <- 200

y <- ts(rnorm(n) + (1:n)%%100/30, f=m)
fourier <- function(t,terms,period)
{
  n <- length(t)
  X <- matrix(,nrow=n,ncol=2*terms)
  for(i in 1:terms)
  {
    X[,2*i-1] <- sin(2*pi*i*t/period)
    X[,2*i] <- cos(2*pi*i*t/period)
  }
  colnames(X) <- paste(c("S","C"),rep(1:terms,rep(2,terms)),sep="")
  return(X)
}

library(forecast)

fit <- Arima(y, order=c(2,0,1), xreg=fourier(1:n,4,m))


print(fit$aicc)

pred = forecast(final_fit, h=2*m, xreg=fourier(n+1:(2*m),final_k,m))
plot(pred)

# finish plotting the forecasting result.

print(pred$mean)# this is the forecasting values in the forecasting interval.

# The code below is for writing the forecasting values in the file. ref:http://robjhyndman.com/hyndsight/batch-forecasting/
fcast <- matrix(NA, nrow=2*m, ncol=1)
fcast[,1] <- pred$mean
write(t(fcast), file="result.csv", sep=",", ncol=ncol(fcast))

</R>

Note

for the code above, we can see that the ‘pred’ is a list. According to the reference for the forecasting function (https://cran.r-project.org/web/packages/forecast/forecast.pdf), it has values list including ‘model’ to ‘fitted’. My trial tells me that pred[[4]] corresponds to pred$mean, i.e. the forecasting values.

Example code with Inferring Fourier series order K

Traversing all the possible K values. Choose the optimal K with the minimal AICc metric.

<R>
min_aicc <- 10000000000
final_k <- -1
final_fit <- NULL 
for(k in seq(1, 15, by = 1))
{
fit <- auto.arima(y, seasonal=FALSE, xreg=fourier(1:n,k,m))
print(k)
print(fit$aicc)
    if(fit$aicc < min_aicc)
    {
        min_aicc <- fit$aicc
        final_k <- k
        final_fit <- fit
    }
}


print(final_k)

print(final_fit$aicc)
</R>

你可能感兴趣的:(如何提取并输出使用forecast函数的预测值,ARIMA model in R)