Search code examples
rforecastingtrend

Modelling (deterministic) trend with nnetar


how do you handle trends with nnetar? What would be the best way to forecast for this example:

 library(timeDate)
 library(forecast)
 library(lattice)
 library(ggplot2)
 library(caret)

 set.seed(1234)

 T <- seq(0,100,length=100)
 Y <- 10 + 2*T + rnorm(100)

 fit <- nnetar(Y)

 plot(forecast(fit,h=30))
 points(1:length(Y),fitted(fit),type="l",col='red')

Thx&kind regards


Solution

  • You have two options.

    1. You can tell nnetar to use more orders (if you print fit you'll see it only used one lag in your example).

      fit <- nnetar(Y, p=5)
      plot(forecast(fit,h=30))
      
    2. You can add the trend directly to the model as an external regressor with the xreg argument. Note that you also need to provide that argument for the forecast (the values I gave are not exactly right for your example, but work well enough for illustrative purposes).

      fit <- nnetar(Y, xreg=T)
      plot(forecast(fit,xreg=101:130, h=30))
      

    For your example problem, either works. Although more generally, if you know what the trend is, the second option is probably best.

    By the way, keep in mind that R uses capital "T" as shorthand for TRUE (and similarly "F" for FALSE), so overriding this can cause some confusion or induce bugs. For example, it made me do a double take after writing xreg=T.