---
title: "comb OLS AirPassengers"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{comb OLS AirPassengers}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# 1 - Comb OLS  

```{r}
library(forecast)
library(ForecastComb)
```

```{r}
custom_error <- function(actual, forecast_) {
  return(mean(abs(forecast_ - actual)))
}
```

```{r}
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)
```

```{r}
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]))
```

```{r}
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)))
```

```{r}
colnames(airpass) <- c("ARIMA", "ETS", "Theta", "Ridge", "GLMNET", "Actual")
```

```{r}
(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)
```

```{r fig.width=7.5}
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

```{r eval=TRUE}
start <- proc.time()[3]
obj <- ahead::comb_Ridge(data, custom_error=custom_error)
print(proc.time()[3] - start)
```

```{r eval=TRUE}
print(class(obj))

print(obj$Accuracy_Test)

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

```{r fig.width=7.5, eval=FALSE}
plot(obj)
```

