rdateindexingarimaforecast

Change index forecast object R to dates


The problem I have is that I have a time series which I need to forecast. I first use autoplot to show the data which runs flawlessly. Next, I use Arima() to make a model which I will then use to forecast. The indexes of my xts object are dates in UTC. I know the Arima model knows that because of the next information of str(), the code is below. The forecast() function does not know that these indexes are dates. It does not have an argument which I can specify. Does anyone know how to handle this?

rm(list=ls())
library(ggplot2)
library(tseries)
library(xts)
library(forecast)
set.seed(2023)

sample_ts = as.data.frame(rnorm(69))
sample_ts$dates = seq(from = as.Date("2017/1/1"), to = as.Date("2022/9/1"), by = "month")
sample_ts = xts(sample_ts$`rnorm(69)`, order.by = sample_ts$dates)
# autplot generates correct plot with dates on x-axis
autoplot(sample_ts)
# fit an Arima(3,0,1) as an example
ARIMA_sample = Arima(
  sample_ts,
  order = c(3, 0, 1),
  include.drift = T)
forecast = forecast(ARIMA_sample, h=24)
# autplot uses dummy indexes on x-axis
autoplot(forecast) +autolayer(forecast, showgap = F)
# what I believe the problem is
str(ARIMA_sample$x)
str(forecast$x)

Plots when you run the code:

Plot time series: enter image description here

Plot forecast: enter image description here


Solution

  • since this is monthly data add this immediately before the Arima statement

    sample_ts <- aggregate(sample_ts, as.yearmon, c)