I hope I’m in the right place and someone can help me with my problem as I’m feeling a bit lost at the moment. I would like to reproduce an algorithm from a conference paper using generalized exponential smoothing to forecast l-ahead steps, but I can’t get it run properly. The algorithm is given by
GDES forecasting algorithm
gdes_forecast <- function(Pt, k, alpha_range) {
model <- lm(Pt[1:k] ~ seq_len(k))
beta0 <- coef(model)[1]
beta1 <- coef(model)[2]
alpha <- seq(alpha_range[1], alpha_range[2], by = 0.01)
S1_0 <- beta0 - ((1 - alpha) / alpha) * beta1
S2_0 <- beta0 - ((2 * (1 - alpha)) / alpha) * beta1
for (t in seq_along(Pt)) {
S1_t <- alpha * Pt[t] + (1 - alpha) * ifelse(t == 1, S1_0, S1_t_prev)
S2_t <- alpha * S1_t + (1 - alpha) * ifelse(t == 1, S2_0, S2_t_prev)
l <- 1
Pt_l <- (2 + (alpha * l) / (1 - alpha)) * S1_t - (1 + (alpha * l) / (1 - alpha)) * S2_t
S1_t_prev <- S1_t
S2_t_prev <- S2_t
}
alpha_opt <- NULL
for (a in alpha) {
errors <- NULL
for (t in (k + 1):(length(Pt)-l)) {
errors[t] <- (Pt[t + l] - Pt[t])^2
}
alpha_opt[a] <- sum(errors)
}
alpha_opt <- which.min(alpha_opt)
for (t in seq_along(Pt)) {
S1_t <- alpha_opt * Pt[t] + (1 - alpha_opt) * ifelse(t == 1, S1_0, S1_t_prev)
S2_t <- alpha_opt * S1_t + (1 - alpha_opt) * ifelse(t == 1, S2_0, S2_t_prev)
l <- 1
Pt_l <- 2 + (alpha_opt * l / (1 - alpha_opt)) * S1_t - (1 + (alpha_opt * l / (1 - alpha_opt))) * S2_t
S1_t_prev <- S1_t
S2_t_prev <- S2_t
}
P_n_opt_l <- 2 + (alpha_opt * l / (1 - alpha_opt)) * S1_t - (1 + (alpha_opt * l / (1 - alpha_opt))) * S2_t
return(list(alpha_opt = alpha_opt, P_n_opt_l = P_n_opt_l))
}
If I run it with some test data, e.g. S&P 500 return data from 2023-01-01 to 2024-02-29, it always identifies an optimal alpha of 1 and I’m a bit lost how to implement the optionality for l-steps ahead so that I could calculate out-of-sample forecasts.
library(tidyverse)
library(tidyquant)
sp500 <- tq_get("^GSPC", from = "2023-01-01", to = "2024-06-30") %>%
column_to_rownames("date") %>%
mutate(return = (adjusted - lag(adjusted)) / lag(adjusted)) %>%
select(return)
gdes_forecast(sp500$return, k = 30, alpha_range = c(0,1))
Does anyone have any idea what the problem might be and how I could implement the out-of-sample forecast functionality? Every hint helps me! Thank you very much!
user20880144 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.