通过ARIMA模型进行时间序列预测

时间:2018-03-17 22:43:34

标签: r plot time-series forecasting arima

嗨,我是时间序列领域的新人。 我想对给定的时间序列进行预测

我使用下面的代码:

library(forecast)
library(TSPred)

dataSet <- 'data'
dataSetPath <- paste0("data/", dataSet, '.csv')

# load data
recDF <- read.csv(dataSetPath, skip=0)
rt = ts(recDF["s2"])

if(dataSet=="data"){
  nTrain <- 3000
  nSkip <- nTrain


nData <- length(rt)
testLength <- nData - nSkip

# testLength 

arima_output90 = vector(mode="numeric", length=testLength)
real = vector(mode="numeric", length=testLength)

pred2 <- arimapred(rt[seq(1, nTrain)], n.ahead=testLength)
forecast::auto.arima(rt[seq(1, nTrain)])


# Brute force ARIMA - recompute model every step
# while making predictions for the next N hours.

for(i in nSkip+1:testLength)
{
  # Compute ARIMA on the full dataset up to this point
  trainSet = window(rt, start=i-nTrain, end=i)
  fit_arima <- forecast::auto.arima(trainSet)

  #   fcast_arima <- predict(fit_arima, n.ahead = 5, se.fit = TRUE)
  #   mean <- fcast_arima$pred
  #   std <- fcast_arima$se

  fcast_arima <- forecast(fit_arima, h=50)
  pred <- fcast_arima$mean


  arima_output50[i] = pred[50]
  real[i] = rt[i]
  cat("step: ",i ,"true : ", rt[i], " prediction: ", pred[50], '\n')

}

我想在图表中绘制预测值和真实值,在同一图表中绘制相同时间步长的真实值和预测值的可视化。 怎么办呢?

在时间步长t的上述模型中,预测pred [50]是指值rt [i + 50](我想要提前50步预测),或参考 rt [i](根据模型蛮力训练,从以前的值估算)?

其中i是代码中的当前时间步长,而rt是时间步长i的实际值。

1 个答案:

答案 0 :(得分:0)

您可以使用:

ts.plot(fit_arima$x, fit_arima$fitted, pred, type='o', col=c('blue', 'green', 'red'), lty=c(1,2,3))
legend('topleft', c('train', 'fitted', 'forecast'), col=c('blue', 'green', 'red'), lty=c(1,2,3))

ts.plot自动从时间序列中提取时间戳,并在x轴上绘制它们。对于标准AirPassengers数据,您将获得以下输出。 enter image description here