R/HybridForecaster.R

Defines functions HybridForecaster

Documented in HybridForecaster

#' @importFrom forecast auto.arima forecast
#' @importFrom vars VAR
NULL


#' Forecast methods for covariate matrix
#'
#' @description Implements 3 types of forecasting methods for time series: single stands for auto.arima for each series
#' individually; multi stands for VAR (vector autoregression) with default lag order 2; true stands for forecasting using
#' the true X process specified.
#'
#'
#'
#' @param X.fitting a matrix. The original training X matrix for forecast, DAT$X.for.fcst (10 series)
#' @param horizon a number. Forecast horizon.
#' @param datatype a string. Choose from 'simple', 'block1', 'block2'. Should be consistent with the true datatype used for simulation.
#' @param parameters.of.X a list. The one that has been used for simulation.
#'
#' @return a list of components
#'
#' \item{single}{a matrix. Forecast values for each series produced by single method. Size should be horizon * nseries, 7 by 10}
#' \item{multi}{a matrix. Forecast values for each series produced by multi method. }
#' \item{true}{a matrix. Forecast values for each series produced by true method. }
#'
#'
#' @export
#'
#' @examples
#'#' ##
#'


HybridForecaster <- function(X.fitting,   # it is DAT$X.for.fcst
                             horizon,
                             datatype,
                             parameters.of.X){


  n.series <- ncol(X.fitting)

  res.forecast.single <- matrix(rep(0, horizon*n.series), horizon, n.series) # each column is one series
  res.forecast.multi <- res.forecast.true <- res.forecast.single

  # ----------- 1. multi VAR
  VARX <- VAR(X.fitting, 2, type = 'both')
  fcst.VARX <- predict(VARX, n.ahead = horizon, ci = 0.95)

  for (k in 1:n.series){

    # ----------- 2. single arima
    fit.auto <- auto.arima(X.fitting[, k] )
    res.forecast.single[, k] <- forecast(fit.auto, h = horizon)$mean

    # ----------- multi, but need to separate each series from its own list
    res.forecast.multi[, k] <- fcst.VARX$fcst[[k]][, 1]
  }


  # ----------- 3. true process

  FcstTrue <- XFcstTrue(datatype = datatype,
                        horizon = horizon,
                        parameters.of.X = parameters.of.X,
                        Xinput = X.fitting)
  res.forecast.true <- FcstTrue$xtrue.fcst


  results <- list('single' = res.forecast.single,
                  'multi' = res.forecast.multi,
                  'true' = res.forecast.true)
  return(results)
}
yymmhaha/PackPaper1 documentation built on May 24, 2019, 8:55 a.m.