knitr::opts_chunk$set(echo = TRUE)

1 - Comb OLS

library(forecast)
library(ForecastComb)
custom_error <- function(actual, forecast_) {
  return(mean(abs(forecast_ - actual)))
}
h <- 29L

train_AirPassengers <- ts(AirPassengers[1:115], start = start(AirPassengers), frequency = frequency(AirPassengers))

arima_forecast <- forecast::forecast(forecast::auto.arima(train_AirPassengers), h=h)
ets_forecast <- forecast::forecast(forecast::ets(train_AirPassengers), h=h)
theta_forecast <- forecast::thetaf(train_AirPassengers, h=h)
ridge_forecast <- ahead::dynrmf(train_AirPassengers, h=h)
glmnet_forecast <- ahead::dynrmf(train_AirPassengers, h=h, 
fit_func = glmnet::cv.glmnet, predict_func = predict)
print(forecast::accuracy(arima_forecast, AirPassengers[116:144]))
print(forecast::accuracy(ets_forecast, AirPassengers[116:144]))
print(forecast::accuracy(theta_forecast, AirPassengers[116:144]))
print(forecast::accuracy(ridge_forecast, AirPassengers[116:144]))
print(forecast::accuracy(glmnet_forecast, AirPassengers[116:144]))
airpass <- cbind(arima_forecast$mean, 
ets_forecast$mean, theta_forecast$mean, 
ridge_forecast$mean, glmnet_forecast$mean,
ts(AirPassengers[116:144], 
start=start(arima_forecast$mean),
frequency=frequency(AirPassengers)))
colnames(airpass) <- c("ARIMA", "ETS", "Theta", "Ridge", "GLMNET", "Actual")
(forecasting_methods <- colnames(airpass)[1:5])

train_obs <- airpass[1:21, 6]
train_pred <- airpass[1:21, 1:5]
test_obs <- airpass[22:29, 6]
test_pred <- airpass[22:29, 1:5]

data <- ForecastComb::foreccomb(train_obs, train_pred, test_obs, test_pred)
start <- proc.time()[3]
obj <- ahead::comb_OLS(data, custom_error=custom_error)
print(proc.time()[3] - start)

print(obj$Accuracy_Test)

print(obj$Weights)

# check
print(mean(predict(obj, test_pred) - test_obs))

2 - Comb Ridge

start <- proc.time()[3]
obj <- ahead::comb_Ridge(data, custom_error=custom_error)
print(proc.time()[3] - start)
print(class(obj))

print(obj$Accuracy_Test)

# check 
print(mean(predict(obj, test_pred) - test_obs))
plot(obj)


Techtonique/ahead documentation built on Nov. 24, 2024, 10:33 a.m.