Search code examples
vectortime-seriesmoving-averageforecast

Error using 'residuals' on moving average for ts


I have been working on forecasting using ts object. In order to test the accuracy of a moving average, I used the code below:

fixt_ma <- ma(fixtures_training, 3)
residuals(fixt_ma)
acc_fixt_ma <- accuracy(fixt_ma, fixtures_test)

dput for fixtures_training

structure(c(161L, 338L, 393L, 405L, 439L, 386L, 442L, 406L, 413L, 
421L), .Tsp = c(2019.48076923077, 2019.65384615385, 52), class = "ts")

When I use the residuals(fixt_ma) function, or alternatively when I write the code like residuals$fixt_ma, I get the error below:

Error: $ operator is invalid for atomic vectors

Does anyone know how I can fix this?


Solution

  • forecast::ma does moving average smoothing. It is not a model and so it has no residuals.

    Perhaps you wanted an MA(3) model, in which case you could use

    fixt_ma <- Arima(fixtures_training, order=c(0,0,3))
    

    Then residuals() will work:

    residuals(fixt_ma)
    #> Time Series:
    #> Start = c(2019, 26) 
    #> End = c(2019, 35) 
    #> Frequency = 52 
    #>  [1] -79.553356  99.757891 -16.836345  -8.949918  42.906861   4.752855
    #>  [7]  39.762007 -29.453682  47.281713  11.804971
    

    However accuracy() will give an error using the code in your question. If you want forecast accuracy measures on the test set, you first have to produce forecasts:

    fc_ma <- forecast(fixt_ma, h=length(fixtures_test))
    acc_fixt_ma <- accuracy(fc_ma, fixtures_test)