I. Data Preparation & Forward Returns

# Libraries

library(tidyverse) # readr, dplyr, tidyr, tibble, ggplot2
library(slider)    # slide_dbl() for rolling earnings windows
library(dlm)       # dlmModPoly(), dlmFilter(), dlmMLE() for Kalman and one-sided HP filters
library(sandwich)  # NeweyWest() for HAC covariance matrices
library(lmtest)    # coeftest() for HAC t-statistics
library(grid)      # unit() for legend.key.width in ggplot2 themes

# Data Preparation & Forward Returns

fast_recursive_cf <- function(log_series, pl, pu, min_init = 120) {
  n <- length(log_series)
  trend_out <- rep(NA_real_, n)
  
  a  <- 2 * pi / pu
  b  <- 2 * pi / pl
  B0 <- (b - a) / pi
  j  <- seq_len(n)
  Bj_all <- (sin(b * j) - sin(a * j)) / (pi * j)
  cum_Bj <- cumsum(Bj_all)
  
  for (t in min_init:n) {
    sub <- log_series[1:t]
    drift_est <- (sub[t] - sub[1]) / (t - 1)
    x_tilde   <- sub - drift_est * (0:(t - 1))
    
    Bj  <- Bj_all[1:(t - 2)]
    w_1 <- -0.5 * B0 - cum_Bj[t - 2]
    w_t <-  0.5 * B0
    
    cycle_t <- w_1 * x_tilde[1] + sum(rev(Bj) * x_tilde[2:(t - 1)]) + w_t * x_tilde[t]
    trend_out[t] <- exp(sub[t] - cycle_t)
  }
  
  return(trend_out)
}

df_full <- 
  read_csv("shiller.csv") %>%
  mutate(
    date = seq(as.Date("1871-01-01"), length = length(p), by = "month"),
    p_real = p * (last(cpi) / cpi), # p = Shiller col. B; cpi = Shiller col E
    e_real = e * (last(cpi) / cpi), # e = Shiller col. D
    d_real = d * (last(cpi) / cpi), # d = Shiller col. C
    lag_e_real = lag(e_real, 1),
    smooth_e_10 = slide_dbl(lag_e_real, .f = mean, .before = 119, .complete = TRUE),
    smooth_e_7  = slide_dbl(lag_e_real, .f = mean, .before = 83,  .complete = TRUE),
    smooth_e_5  = slide_dbl(lag_e_real, .f = mean, .before = 59,  .complete = TRUE),
    smooth_e_3  = slide_dbl(lag_e_real, .f = mean, .before = 35,  .complete = TRUE),
    cape_10 = p_real / smooth_e_10,
    cape_7  = p_real / smooth_e_7,
    cape_5  = p_real / smooth_e_5,
    cape_3  = p_real / smooth_e_3,
    pe      = p_real / e_real,
    CF_short_e  = fast_recursive_cf(log(e_real), pl = 24, pu = 96,  min_init = 120),
    CF_short_pe = p_real / CF_short_e,
    CF_long_e   = fast_recursive_cf(log(e_real), pl = 36, pu = 180, min_init = 120),
    CF_long_pe  = p_real / CF_long_e
  ) %>%
  relocate(date)

df_base <- df_full %>%
  drop_na(cape_10) %>%
  mutate(
    five_yr_real_return = ((lead(real_tr_p, 60)  / real_tr_p)^(12 / 60))  - 1, # real_tr_p = Shiller col. J
    ten_yr_real_return  = ((lead(real_tr_p, 120) / real_tr_p)^(12 / 120)) - 1
  )

# Named lookup vector: raw column name = clean display label

base_metrics <- c(
  "cape_10" = "CAPE_10",
  "cape_7"  = "CAPE_7",
  "cape_5"  = "CAPE_5",
  "cape_3" = "CAPE_3",
  "pe"      = "PE"
)

II. Build log-linear dataframe

df_base_log <- 
  df_base %>%
  mutate(
    five_yr_real_return = (12 / 60)  * log(lead(real_tr_p, 60)  / real_tr_p),
    ten_yr_real_return  = (12 / 120) * log(lead(real_tr_p, 120) / real_tr_p),
    across(
      all_of(names(base_metrics)),
      ~ if_else(.x > 0, log(.x), NA_real_)
    )
  ) 

III. IS function

# Define a function to run in-sample OLS regressions with Newey-West standard errors
run_is_evaluation <- function(data, metric_map, horizon, last_n_months = NULL, sample_label = "Full Sample") {
  
  # 1. Choose the forward return column based on the forecast horizon (60 or 120 months)
  if (horizon == 60) {
    ret_col <- "five_yr_real_return"
  } else {
    ret_col <- "ten_yr_real_return"
  }
  
  # Extract the raw column names (e.g., "cape_10") from our named lookup vector
  raw_var_names <- names(metric_map)
  
  # 2. Prepare the modeling dataset
  # Keep only the date, our valuation metrics, and the forward return column.
  # Calling drop_na() here ensures every metric is tested on the exact same dates.
  df_model <- data %>%
    select(date, all_of(raw_var_names), all_of(ret_col)) %>%
    rename(future_return = all_of(ret_col)) %>%
    drop_na()
  
  # 3. Restrict to a trailing sub-sample if requested (e.g., last 360 realized months)
  # slice_tail() keeps the most recent rows at the bottom of the chronological dataframe.
  if (!is.null(last_n_months)) {
    df_model <- df_model %>%
      slice_tail(n = last_n_months)
  }
  
  # 4. Extract sample period boundaries and observation count for this estimation window
  # Note: period_end is the date of the final valuation observation; its forward return
  # realizes 'horizon' months later at the end of the full dataset.
  start_date <- min(df_model$date)
  end_date   <- max(df_model$date)
  num_obs    <- nrow(df_model)
  
  # Create an empty list to store the regression summary for each valuation metric
  results_list <- list()
  
  # 5. Loop through each valuation metric one by one
  for (i in seq_along(raw_var_names)) {
    
    # Get the raw column name (for the formula) and clean display label (for the table)
    v_name      <- raw_var_names[i]
    clean_label <- unname(metric_map[v_name])
    
    # Build the regression formula: future_return ~ v_name (both already in natural logs)
    reg_formula <- as.formula(paste("future_return ~", v_name))
    
    # Fit the standard Ordinary Least Squares (OLS) regression
    ols_fit <- lm(reg_formula, data = df_model)
    
    # Compute Newey-West standard errors to correct for overlapping return horizons.
    # Setting lag = horizon accounts for serial correlation up to the overlap length.
    nw_cov_matrix <- NeweyWest(ols_fit, lag = horizon, prewhite = FALSE)
    nw_summary    <- coeftest(ols_fit, vcov = nw_cov_matrix)
    
    # Extract the slope coefficient and its Newey-West t-statistic and p-value (row 2 is the predictor)
    slope_val <- coef(ols_fit)[2]
    t_stat    <- nw_summary[2, "t value"]
    p_val     <- nw_summary[2, "Pr(>|t|)"]
    
    # Extract the standard R-squared from the OLS summary (appropriate for single-predictor regressions)
    r2_val <- summary(ols_fit)$r.squared
    
    # Store this metric's results as a one-row tibble in our results list
    results_list[[i]] <- tibble(
      model          = clean_label,
      horizon_months = horizon,
      sample         = sample_label,
      period_start   = start_date,
      period_end     = end_date,
      n_obs          = num_obs,
      slope          = slope_val,
      t_statistic    = t_stat,
      p_value        = p_val,
      r_squared      = r2_val
    )
  }
  
  # Stack all individual metric rows into a single dataframe and return it
  final_results <- bind_rows(results_list)
  return(final_results)
}

III. OOS function

run_oos_evaluation <- function(data, metric_map, horizon, window_months = NULL,
                               min_train_obs = 480, window_label = "Expanding") {
  
  ret_col <- if (horizon == 60) "five_yr_real_return" else "ten_yr_real_return"
  raw_var_names <- names(metric_map)
  
  df_model <- data %>%
    select(date, all_of(raw_var_names), all_of(ret_col)) %>%
    rename(future_return = all_of(ret_col)) %>%
    arrange(date) %>%
    drop_na()
  
  total_rows    <- nrow(df_model)
  first_oos_idx <- min_train_obs + horizon
  oos_indices   <- first_oos_idx:total_rows
  num_oos_obs   <- length(oos_indices)
  oos_dates     <- df_model$date[oos_indices]
  
  # Precompute training window boundaries for all OOS steps at once
  end_idx   <- oos_indices - horizon
  start_idx <- if (is.null(window_months)) rep(1L, num_oos_obs) else pmax(1L, end_idx - window_months + 1L)
  n_tr      <- end_idx - start_idx + 1L
  
  eval_periods <- list("Full OOS Sample" = NULL)
  if (!is.null(window_months)) {
    eval_periods[[paste0("Last ", window_months / 12, " Years")]] <- window_months
  }
  
  y_all        <- df_model$future_return
  y_actual_vec <- y_all[oos_indices]
  cy           <- c(0, cumsum(y_all))
  sum_y        <- cy[end_idx + 1L] - cy[start_idx]
  y_mean       <- sum_y / n_tr
  y_pred_bench <- y_mean
  
  results_list <- list()
  row_counter  <- 1L
  
  for (i in seq_along(raw_var_names)) {
    v_name      <- raw_var_names[i]
    clean_label <- unname(metric_map[v_name])
    x_all       <- df_model[[v_name]]
    
    # Vectorized expanding/rolling OLS slopes and intercepts via cumulative sums
    cx  <- c(0, cumsum(x_all))
    cxx <- c(0, cumsum(x_all^2))
    cxy <- c(0, cumsum(x_all * y_all))
    
    sum_x  <- cx[end_idx + 1L]  - cx[start_idx]
    sum_xx <- cxx[end_idx + 1L] - cxx[start_idx]
    sum_xy <- cxy[end_idx + 1L] - cxy[start_idx]
    
    x_mean    <- sum_x / n_tr
    beta_hat  <- (sum_xy - n_tr * x_mean * y_mean) / (sum_xx - n_tr * x_mean^2)
    alpha_hat <- y_mean - beta_hat * x_mean
    
    y_pred_model <- alpha_hat + beta_hat * x_all[oos_indices]
    
    for (sample_name in names(eval_periods)) {
      sub_months <- eval_periods[[sample_name]]
      sub_idx <- if (is.null(sub_months)) 1:num_oos_obs else max(1L, num_oos_obs - sub_months + 1L):num_oos_obs
      
      dates_sub <- oos_dates[sub_idx]
      y_act_sub <- y_actual_vec[sub_idx]
      y_mod_sub <- y_pred_model[sub_idx]
      y_bch_sub <- y_pred_bench[sub_idx]
      
      err_model  <- y_act_sub - y_mod_sub
      err_bench  <- y_act_sub - y_bch_sub
      r2_oos_val <- 1 - (mean(err_model^2) / mean(err_bench^2))
      
      cw_f_series <- (err_bench^2) - ((err_model^2) - ((y_bch_sub - y_mod_sub)^2))
      cw_fit      <- lm(cw_f_series ~ 1)
      cw_nw_cov   <- NeweyWest(cw_fit, lag = horizon, prewhite = FALSE)
      cw_t        <- coeftest(cw_fit, vcov = cw_nw_cov)[1, "t value"]
      
      results_list[[row_counter]] <- tibble(
        window       = window_label,
        model        = clean_label,
        horizon      = horizon,
        sample       = sample_name,
        period_start = dates_sub[1],
        period_end   = dates_sub[length(dates_sub)],
        n_obs        = length(sub_idx),
        r2_oos       = r2_oos_val,
        cw_t_stat    = cw_t
      )
      row_counter <- row_counter + 1L
    }
  }
  
  bind_rows(results_list)
}

IV. EWMA and time series filter calcs

## 1. Exponentially Weighted Moving Averages (EWMA)
calc_ewma_series <- function(series, alpha) {
  n <- length(series)
  ewma_val <- numeric(n)
  ewma_val[1] <- series[1]
  for (t in 2:n) {
    ewma_val[t] <- alpha * series[t] + (1 - alpha) * ewma_val[t - 1]
  }
  return(ewma_val)
}

## 2. Causal Local-Linear-Trend Kalman Filters
kf_fixed_res <- dlmFilter(
  log(df_full$e_real),
  dlmModPoly(
    order = 2,
    dV    = 1.0,
    dW    = c(0.002, 0.00005),
    m0    = c(log(df_full$e_real[1]), 0),
    C0    = diag(c(1, 0.01))
  )
)

# 1. One-sided HP filters on log real earnings (exact state-space equivalence: dV / dW_2 = lambda)

lambda_hp    <- 14400
w_hp         <- 1 / lambda_hp
hp_kf_result <- dlmFilter(log(df_full$e_real), dlmModPoly(order = 2, dV = 1, dW = c(0, w_hp)))

lambda_120m    <- 129600
w_120m         <- 1 / lambda_120m
hp_120m_result <- dlmFilter(log(df_full$e_real), dlmModPoly(order = 2, dV = 1, dW = c(0, w_120m)))


run_recursive_kalman_mle <- function(log_series, min_init = 120, refit_every = 12) {
  n <- length(log_series)
  filtered_log_trend <- rep(NA_real_, n)

  build_fn <- function(theta) {
    dlmModPoly(
      order = 2,
      dV    = exp(theta[1]),
      dW    = c(exp(theta[2]), exp(theta[3])),
      m0    = c(log_series[1], 0),
      C0    = diag(c(1, 0.01))
    )
  }

  refit_points <- seq(from = min_init, to = n, by = refit_every)

  for (idx in seq_along(refit_points)) {
    t_start <- refit_points[idx]
    t_end   <- if (idx < length(refit_points)) refit_points[idx + 1] - 1L else n

    mle_fit <- dlmMLE(
      y     = log_series[1:t_start],
      parm  = log(c(0.05, 0.001, 0.00001)),
      build = build_fn
    )
    current_mod <- build_fn(mle_fit$par)

    kf_block <- dlmFilter(log_series[1:t_end], current_mod)
    filtered_log_trend[t_start:t_end] <- kf_block$m[(t_start + 1L):(t_end + 1L), 1]
  }

  return(exp(filtered_log_trend))
}

run_hamilton_recursive <- function(series, h = 24, p = 4, min_init = 120) {
  n <- length(series)
  trend <- rep(NA_real_, n)

  X_mat <- matrix(1, nrow = n, ncol = p + 1)
  for (i in 0:(p - 1)) {
    X_mat[, i + 2] <- dplyr::lag(series, h + i)
  }

  first_valid <- h + p
  start_idx   <- max(first_valid + 24L, min_init)

  for (t in start_idx:n) {
    fit <- lm.fit(x = X_mat[first_valid:t, , drop = FALSE], y = series[first_valid:t])
    trend[t] <- sum(X_mat[t, ] * fit$coefficients)
  }

  return(trend)
}


hamilton_24_log_trend <- run_hamilton_recursive(log(df_full$e_real), h = 24, p = 4, min_init = 120)

df_alts <- df_full %>%
  mutate(
    # EWMA
    ewma_3_e   = calc_ewma_series(e_real, 2 / (36 + 1)),
    ewma_3_pe  = p_real / ewma_3_e,
    ewma_5_e   = calc_ewma_series(e_real, 2 / (60 + 1)),
    ewma_5_pe  = p_real / ewma_5_e,
    ewma_7_e   = calc_ewma_series(e_real, 2 / (84 + 1)),
    ewma_7_pe  = p_real / ewma_7_e,
    ewma_10_e  = calc_ewma_series(e_real, 2 / (120 + 1)),
    ewma_10_pe = p_real / ewma_10_e,

    # Kalman
    kalman_fixed_e  = exp(drop(kf_fixed_res$m[-1, 1])),
    kalman_fixed_pe = p_real / kalman_fixed_e,
    kalman_mle_e    = run_recursive_kalman_mle(log(e_real), min_init = 120, refit_every = 12),
    kalman_mle_pe   = p_real / kalman_mle_e,

    # Hodrick-Prescott
    hp_onesided_e  = exp(drop(hp_kf_result$m[-1, 1])),
    hp_onesided_pe = p_real / hp_onesided_e,
    hp_120m_e      = exp(drop(hp_120m_result$m[-1, 1])),
    hp_120m_pe     = p_real / hp_120m_e,

    # Hamilton
    hamilton_24_e  = exp(hamilton_24_log_trend),
    hamilton_24_pe = p_real / hamilton_24_e,

    # Forward annualized real log returns
    five_yr_real_return = (12 / 60)  * log(lead(real_tr_p, 60)  / real_tr_p),
    ten_yr_real_return  = (12 / 120) * log(lead(real_tr_p, 120) / real_tr_p)
  ) %>%
  filter(date >= as.Date("1881-01-01"))

## 6. Log-transform all 17 valuation ratios into df_alts_log
all_metrics <- c(
  "cape_10"         = "CAPE_10",
  "cape_7"          = "CAPE_7",
  "cape_5"          = "CAPE_5",
  "cape_3"          = "CAPE_3",
  "pe"              = "PE",
  "ewma_3_pe"      = "EWMA_3",
  "ewma_5_pe"      = "EWMA_5",
  "ewma_7_pe"      = "EWMA_7",
  "ewma_10_pe"     = "EWMA_10",
  "CF_short_pe"     = "CF_24_96",
  "CF_long_pe"      = "CF_36_180",
  "kalman_fixed_pe" = "Kalman_Fixed",
  "kalman_mle_pe"   = "Kalman_MLE",
  "hp_onesided_pe"  = "HP_14400",
  "hp_120m_pe"      = "HP_129600",
  "hamilton_24_pe"  = "Hamilton_24"
)


df_alts_log <- df_alts %>%
  mutate(
    across(
      all_of(names(all_metrics)),
      ~ if_else(.x > 0, log(.x), NA_real_)
    )
  )

V. Regression tables (log~level): IS and OOS

# Run 5-year (60-month) IS evaluations for all 12 metrics
is_5yr_full <- run_is_evaluation(df_alts_log, all_metrics, horizon = 60, last_n_months = NULL, sample_label = "Full Sample")
is_5yr_30yr <- run_is_evaluation(df_alts_log, all_metrics, horizon = 60, last_n_months = 360,  sample_label = "Last 30 Years")

# (Optional) 10-year (120-month) IS evaluations for Appendix robustness
is_10yr_full <- run_is_evaluation(df_alts_log, all_metrics, horizon = 120, last_n_months = NULL, sample_label = "Full Sample")
is_10yr_30yr <- run_is_evaluation(df_alts_log, all_metrics, horizon = 120, last_n_months = 360,  sample_label = "Last 30 Years")

# Format IS table - 5 years
all_model_levels <- unname(all_metrics)

metrics_5yr_is <- bind_rows(is_5yr_full, is_5yr_30yr) %>%
  mutate(
    Model = factor(model, levels = all_model_levels),
    Beta  = round(slope, 3),
    t     = round(t_statistic, 2),
    R2    = round(r_squared, 3)
  ) %>%
  arrange(desc(n_obs), Model) %>%
  select(
    Model,
    `Period Start` = period_start,
    `Period End`   = period_end,
    N              = n_obs,
    Beta, t, R2
  )

# Format  IS table - 10 years

all_model_levels <- unname(all_metrics)

metrics_10yr_is <- bind_rows(is_10yr_full, is_10yr_30yr) %>%
  mutate(
    Model = factor(model, levels = all_model_levels),
    Beta  = round(slope, 3),
    t     = round(t_statistic, 2),
    R2    = round(r_squared, 3)
  ) %>%
  arrange(desc(n_obs), Model) %>%
  select(
    Model,
    `Period Start` = period_start,
    `Period End`   = period_end,
    N              = n_obs,
    Beta, t, R2
  )


### Chunk 2: OOS Evaluation & Combined Two-Panel Export for All Filters

## Combined IS and OOS table for all filters

# Run 5-year (60-month) OOS evaluations across all four window specifications
oos_5yr_exp  <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 60, window_months = NULL, min_train_obs = 480, window_label = "Expanding")
oos_5yr_40yr <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 60, window_months = 480,  min_train_obs = 480, window_label = "40-Yr Rolling")
oos_5yr_30yr <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 60, window_months = 360,  min_train_obs = 480, window_label = "30-Yr Rolling")
oos_5yr_20yr <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 60, window_months = 240,  min_train_obs = 480, window_label = "20-Yr Rolling")

# (Optional) 10-year (120-month) OOS evaluations for Appendix robustness
oos_10yr_exp  <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 120, window_months = NULL, min_train_obs = 480, window_label = "Expanding")
oos_10yr_40yr <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 120, window_months = 480,  min_train_obs = 480, window_label = "40-Yr Rolling")
oos_10yr_30yr <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 120, window_months = 360,  min_train_obs = 480, window_label = "30-Yr Rolling")
oos_10yr_20yr <- run_oos_evaluation(df_alts_log, all_metrics, horizon = 120, window_months = 240,  min_train_obs = 480, window_label = "20-Yr Rolling")

# Format OOS table - 5 year

metrics_5yr_oos <- bind_rows(
  oos_5yr_exp, oos_5yr_40yr, oos_5yr_30yr, oos_5yr_20yr
) %>%
  mutate(
    Model  = factor(model, levels = all_model_levels),
    prefix = case_when(
      window == "Expanding"     ~ "Exp",
      window == "40-Yr Rolling" ~ "40Y",
      window == "30-Yr Rolling" ~ "30Y",
      window == "20-Yr Rolling" ~ "20Y"
    ),
    R2     = round(r2_oos, 4),
    `CW t` = round(cw_t_stat, 2)
  ) %>%
  select(Model, `Period Start` = period_start, `Period End` = period_end, N = n_obs, prefix, R2, `CW t`) %>%
  pivot_wider(
    names_from  = prefix,
    values_from = c(R2, `CW t`),
    names_glue  = "{prefix} {.value}"
  ) %>%
  arrange(desc(N), Model) %>%
  select(
    Model, `Period Start`, `Period End`, N,
    `Exp R2`, `Exp CW t`,
    `40Y R2`, `40Y CW t`,
    `30Y R2`, `30Y CW t`,
    `20Y R2`, `20Y CW t`
  )


# Format OOS table - 10 year

metrics_10yr_oos <- bind_rows(
  oos_10yr_exp, oos_10yr_40yr, oos_10yr_30yr, oos_10yr_20yr
) %>%
  mutate(
    Model  = factor(model, levels = all_model_levels),
    prefix = case_when(
      window == "Expanding"     ~ "Exp",
      window == "40-Yr Rolling" ~ "40Y",
      window == "30-Yr Rolling" ~ "30Y",
      window == "20-Yr Rolling" ~ "20Y"
    ),
    R2     = round(r2_oos, 4),
    `CW t` = round(cw_t_stat, 2)
  ) %>%
  select(Model, `Period Start` = period_start, `Period End` = period_end, N = n_obs, prefix, R2, `CW t`) %>%
  pivot_wider(
    names_from  = prefix,
    values_from = c(R2, `CW t`),
    names_glue  = "{prefix} {.value}"
  ) %>%
  arrange(desc(N), Model) %>%
  select(
    Model, `Period Start`, `Period End`, N,
    `Exp R2`, `Exp CW t`,
    `40Y R2`, `40Y CW t`,
    `30Y R2`, `30Y CW t`,
    `20Y R2`, `20Y CW t`
  )
# Export  panels cleanly

write.csv(metrics_5yr_is,  "5yr_is.csv",  row.names = FALSE)
write.csv(metrics_5yr_oos, "5yr_oos.csv", row.names = FALSE)

write.csv(metrics_10yr_is, "10yr_is.csv", row.names = FALSE)
write.csv(metrics_10yr_oos, "10yr_oos.csv", row.names = FALSE)

VI. CAPE Horizon Stability Diagnostics (CAPE_10, CAPE_7, CAPE_5, CAPE_3)

cape_metrics <- c(
  "cape_10" = "CAPE_10",
  "cape_7"  = "CAPE_7",
  "cape_5"  = "CAPE_5",
  "cape_3"  = "CAPE_3"
)

# ------------------------------------------------------------------------------
# 1. Rolling Parameter Dispersion & Regime Consistency (20Y, 30Y, 40Y Windows)
# ------------------------------------------------------------------------------

run_cape_rolling_stability <- function(data, metric_map, horizon = 60,
                                       roll_windows = c("40-Yr Rolling" = 480L,
                                                        "30-Yr Rolling" = 360L,
                                                        "20-Yr Rolling" = 240L),
                                       min_exp_obs = 480L) {
  ret_col  <- if (horizon == 60) "five_yr_real_return" else "ten_yr_real_return"
  raw_vars <- names(metric_map)

  df_clean <- data %>%
    select(date, all_of(raw_vars), y = all_of(ret_col)) %>%
    arrange(date) %>%
    drop_na()

  n_tot <- nrow(df_clean)
  y_all <- df_clean$y

  # Helper: compute vectorized rolling/expanding OLS + exact Bartlett-kernel NW t-stat
  get_window_paths <- function(x_vec, y_vec, w_len = NULL, start_t = min_exp_obs) {
    t_idx     <- start_t:n_tot
    start_idx <- if (is.null(w_len)) rep(1L, length(t_idx)) else pmax(1L, t_idx - w_len + 1L)
    n_w       <- t_idx - start_idx + 1L

    cx  <- c(0, cumsum(x_vec))
    cy  <- c(0, cumsum(y_vec))
    cxx <- c(0, cumsum(x_vec^2))
    cyy <- c(0, cumsum(y_vec^2))
    cxy <- c(0, cumsum(x_vec * y_vec))

    sx  <- cx[t_idx + 1L]  - cx[start_idx]
    sy  <- cy[t_idx + 1L]  - cy[start_idx]
    sxx <- cxx[t_idx + 1L] - cxx[start_idx]
    syy <- cyy[t_idx + 1L] - cyy[start_idx]
    sxy <- cxy[t_idx + 1L] - cxy[start_idx]

    xm   <- sx / n_w
    ym   <- sy / n_w
    ss_x <- sxx - n_w * xm^2
    ss_y <- syy - n_w * ym^2
    sp   <- sxy - n_w * xm * ym

    beta  <- sp / ss_x
    alpha <- ym - beta * xm
    r2    <- (sp^2) / (ss_x * ss_y)

    # Exact Bartlett-kernel Newey-West t-stat (matching sandwich::NeweyWest, prewhite = FALSE)
    nw_t <- vapply(seq_along(t_idx), function(k) {
      idx_sub <- start_idx[k]:t_idx[k]
      nw_n    <- length(idx_sub)
      x_til   <- x_vec[idx_sub] - xm[k]
      u_hat   <- (y_vec[idx_sub] - ym[k]) - beta[k] * x_til
      z       <- x_til * u_hat

      omega <- sum(z^2)
      max_l <- min(horizon, nw_n - 1L)
      if (max_l >= 1L) {
        for (l in seq_len(max_l)) {
          wt    <- 1 - l / (horizon + 1)
          omega <- omega + 2 * wt * sum(z[(l + 1L):nw_n] * z[1:(nw_n - l)])
        }
      }
      omega   <- omega * (nw_n / (nw_n - 2))
      se_beta <- sqrt(omega) / ss_x[k]
      beta[k] / se_beta
    }, numeric(1))

    tibble(
      date  = df_clean$date[t_idx],
      alpha = alpha,
      beta  = beta,
      r2    = r2,
      nw_t  = nw_t
    )
  }

  all_paths <- lapply(raw_vars, function(v) {
    lbl   <- unname(metric_map[v])
    x_all <- df_clean[[v]]

    exp_df <- get_window_paths(x_all, y_all, w_len = NULL, start_t = min_exp_obs) %>%
      rename(alpha_exp = alpha, beta_exp = beta)

    bind_rows(lapply(names(roll_windows), function(w_lbl) {
      get_window_paths(x_all, y_all, w_len = roll_windows[[w_lbl]], start_t = min_exp_obs) %>%
        left_join(exp_df %>% select(date, alpha_exp, beta_exp), by = "date") %>%
        mutate(Model = lbl, Window = w_lbl)
    }))
  }) %>%
    bind_rows()

  summary_tbl <- all_paths %>%
    group_by(Window, Model) %>%
    summarise(
      `Period Start`          = min(date),
      `Period End`            = max(date),
      `Mean Beta`             = round(mean(beta), 3),
      `SD Beta`               = round(sd(beta), 3),
      `IQR Beta`              = round(IQR(beta), 3),
      `RMSE(Beta - Exp)`      = round(sqrt(mean((beta - beta_exp)^2)), 3),
      `SD Alpha`              = round(sd(alpha), 3),
      `Pct Beta < 0 (%)`      = round(100 * mean(beta < 0), 1),
      `Pct NW t < -1.96 (%)`  = round(100 * mean(nw_t < -1.96), 1),
      `Median R2 (%)`         = round(100 * median(r2), 1),
      `P10 R2 (%)`            = round(100 * quantile(r2, 0.10), 1),
      .groups = "drop"
    ) %>%
    mutate(
      Window = factor(Window, levels = names(roll_windows)),
      Model  = factor(Model, levels = unname(metric_map))
    ) %>%
    arrange(Window, Model)

  list(paths = all_paths, summary = summary_tbl)
}

cape_roll_5yr  <- run_cape_rolling_stability(df_base_log, cape_metrics, horizon = 60)
cape_roll_10yr <- run_cape_rolling_stability(df_base_log, cape_metrics, horizon = 120)

write.csv(cape_roll_5yr$summary,  "cape_rolling_stability_5yr.csv",  row.names = FALSE)
write.csv(cape_roll_10yr$summary, "cape_rolling_stability_10yr.csv", row.names = FALSE)


# ------------------------------------------------------------------------------
# 2. Partial HAC Sup-Wald Structural Break Tests (Slope vs. Intercept Stability)
#    Separates equilibrium multiple shifts (alpha) from return sensitivity (beta).
#    Andrews (1993) / Hansen (1997) 15% trimming asymptotic critical values:
#      df = 1 (pure slope or pure intercept): 10% = 7.12, 5% = 8.68, 1% = 12.16
#      df = 2 (joint break):                  10% = 10.01, 5% = 11.79, 1% = 15.51
# ------------------------------------------------------------------------------

run_partial_hac_supwald <- function(data, metric_map, horizon = 60, trim = 0.15, step = 3L) {
  ret_col  <- if (horizon == 60) "five_yr_real_return" else "ten_yr_real_return"
  raw_vars <- names(metric_map)

  df_clean <- data %>%
    select(date, all_of(raw_vars), y = all_of(ret_col)) %>%
    arrange(date) %>%
    drop_na()

  n_tot     <- nrow(df_clean)
  cand_taus <- seq(floor(trim * n_tot), ceiling((1 - trim) * n_tot), by = step)

  lapply(raw_vars, function(v) {
    df_m <- df_clean %>% select(date, x = all_of(v), y)

    scan_res <- lapply(cand_taus, function(tau) {
      d_vec <- as.numeric(seq_len(n_tot) > tau)

      # Unrestricted model: y = a1 + a2*D + b1*x + b2*(x*D) + e
      fit_full <- lm(y ~ d_vec * x, data = df_m)
      nw_full  <- NeweyWest(fit_full, lag = horizon, prewhite = FALSE)

      # Test 1: Pure slope break (b2 = 0, allowing unrestricted intercept shift a2)
      b_hat     <- coef(fit_full)
      w_slope   <- as.numeric((b_hat["d_vec:x"]^2) / nw_full["d_vec:x", "d_vec:x"])

      # Test 2: Joint break (a2 = 0 and b2 = 0)
      R_joint   <- rbind(c(0, 1, 0, 0), c(0, 0, 0, 1))
      Rb        <- R_joint %*% b_hat
      w_joint   <- as.numeric(t(Rb) %*% solve(R_joint %*% nw_full %*% t(R_joint)) %*% Rb)

      # Test 3: Pure intercept break holding slope constant: y = a1 + a2*D + b*x + e
      fit_int   <- lm(y ~ d_vec + x, data = df_m)
      nw_int    <- NeweyWest(fit_int, lag = horizon, prewhite = FALSE)
      w_int     <- as.numeric((coef(fit_int)["d_vec"]^2) / nw_int["d_vec", "d_vec"])

      tibble(
        tau     = tau,
        date    = df_m$date[tau],
        w_slope = w_slope,
        w_int   = w_int,
        w_joint = w_joint
      )
    }) %>%
      bind_rows()

    idx_s <- which.max(scan_res$w_slope)
    idx_i <- which.max(scan_res$w_int)
    idx_j <- which.max(scan_res$w_joint)

    tibble(
      Model                  = unname(metric_map[v]),
      Horizon                = paste0(horizon / 12, "-Year"),
      `Slope Sup-Wald`       = round(scan_res$w_slope[idx_s], 2),
      `Slope Break Date`     = scan_res$date[idx_s],
      `Intercept Sup-Wald`   = round(scan_res$w_int[idx_i], 2),
      `Intercept Break Date` = scan_res$date[idx_i],
      `Joint Sup-Wald`       = round(scan_res$w_joint[idx_j], 2),
      `Joint Break Date`     = scan_res$date[idx_j]
    )
  }) %>%
    bind_rows() %>%
    mutate(Model = factor(Model, levels = unname(metric_map))) %>%
    arrange(Model)
}

cape_partial_breaks <- bind_rows(
  run_partial_hac_supwald(df_base_log, cape_metrics, horizon = 60),
  run_partial_hac_supwald(df_base_log, cape_metrics, horizon = 120)
)

write.csv(cape_partial_breaks, "cape_partial_break_tests.csv", row.names = FALSE)


# ------------------------------------------------------------------------------
# 3. Expanding vs. Rolling OOS Forecast Invariance, DM & Encompassing vs CAPE_10
# ------------------------------------------------------------------------------

run_cape_oos_invariance <- function(data, metric_map, horizon = 60, min_train_obs = 480L) {
  ret_col  <- if (horizon == 60) "five_yr_real_return" else "ten_yr_real_return"
  raw_vars <- names(metric_map)

  df_model <- data %>%
    select(date, all_of(raw_vars), y = all_of(ret_col)) %>%
    arrange(date) %>%
    drop_na()

  oos_idx <- (min_train_obs + horizon):nrow(df_model)
  num_oos <- length(oos_idx)
  end_idx <- oos_idx - horizon
  y_all   <- df_model$y
  y_act   <- y_all[oos_idx]
  cy      <- c(0, cumsum(y_all))

  windows <- list(
    "Expanding"     = NULL,
    "40-Yr Rolling" = 480L,
    "30-Yr Rolling" = 360L,
    "20-Yr Rolling" = 240L
  )

  # Generate recursive OOS forecasts for every window and CAPE variant
  fc_all <- lapply(names(windows), function(w_lbl) {
    w_len     <- windows[[w_lbl]]
    start_idx <- if (is.null(w_len)) rep(1L, num_oos) else pmax(1L, end_idx - w_len + 1L)
    n_tr      <- end_idx - start_idx + 1L
    y_mean    <- (cy[end_idx + 1L] - cy[start_idx]) / n_tr

    lapply(raw_vars, function(v) {
      x_all <- df_model[[v]]
      cx    <- c(0, cumsum(x_all))
      cxx   <- c(0, cumsum(x_all^2))
      cxy   <- c(0, cumsum(x_all * y_all))

      xm   <- (cx[end_idx + 1L]  - cx[start_idx])  / n_tr
      sxx  <- cxx[end_idx + 1L] - cxx[start_idx]
      sxy  <- cxy[end_idx + 1L] - cxy[start_idx]
      beta <- (sxy - n_tr * xm * y_mean) / (sxx - n_tr * xm^2)
      alph <- y_mean - beta * xm

      tibble(
        Window  = w_lbl,
        Model   = unname(metric_map[v]),
        date    = df_model$date[oos_idx],
        y_act   = y_act,
        y_bench = y_mean,
        y_mod   = alph + beta * x_all[oos_idx]
      )
    }) %>%
      bind_rows()
  }) %>%
    bind_rows()

  # Compare each CAPE_k against CAPE_10 and against its own Expanding baseline
  res_tbl <- lapply(names(windows), function(w_lbl) {
    df_w   <- fc_all %>% filter(Window == w_lbl)
    ref_10 <- df_w %>% filter(Model == "CAPE_10") %>% arrange(date)
    e_10   <- ref_10$y_act - ref_10$y_mod

    lapply(unname(metric_map), function(m_lbl) {
      df_m  <- df_w %>% filter(Model == m_lbl) %>% arrange(date)
      e_mod <- df_m$y_act - df_m$y_mod
      e_bch <- df_m$y_act - df_m$y_bench

      r2_oos <- 1 - mean(e_mod^2) / mean(e_bch^2)

      # Clark-West t-stat vs prevailing mean
      cw_f   <- e_bch^2 - (e_mod^2 - (df_m$y_bench - df_m$y_mod)^2)
      cw_fit <- lm(cw_f ~ 1)
      cw_t   <- coeftest(cw_fit, vcov = NeweyWest(cw_fit, lag = horizon, prewhite = FALSE))[1, "t value"]

      if (m_lbl == "CAPE_10") {
        dm_t     <- NA_real_
        enc_lam  <- NA_real_
        enc_t    <- NA_real_
      } else {
        # Diebold-Mariano HAC t-stat: positive => CAPE_k has lower MSE than CAPE_10
        d_loss <- e_10^2 - e_mod^2
        dm_fit <- lm(d_loss ~ 1)
        dm_t   <- coeftest(dm_fit, vcov = NeweyWest(dm_fit, lag = horizon, prewhite = FALSE))[1, "t value"]

        # Harvey-Leybourne-Newbold (1998) forecast encompassing:
        # e_10 = lambda * (y_mod - y_10) + u  (lambda = 1 => CAPE_k encompasses CAPE_10)
        f_diff  <- df_m$y_mod - ref_10$y_mod
        enc_fit <- lm(e_10 ~ f_diff - 1)
        enc_ct  <- coeftest(enc_fit, vcov = NeweyWest(enc_fit, lag = horizon, prewhite = FALSE))
        enc_lam <- enc_ct[1, "Estimate"]
        enc_t   <- enc_ct[1, "t value"]
      }

      tibble(
        Window        = w_lbl,
        Model         = m_lbl,
        Horizon       = paste0(horizon / 12, "-Year"),
        `OOS R2 (%)`  = round(100 * r2_oos, 2),
        `CW t`        = round(cw_t, 2),
        `DM t vs C10` = round(dm_t, 2),
        `Encomp Lam`  = round(enc_lam, 2),
        `Encomp t`    = round(enc_t, 2)
      )
    }) %>%
      bind_rows()
  }) %>%
    bind_rows()

  # Attach Delta OOS R2 relative to Expanding window (forecast invariance metric)
  exp_ref <- res_tbl %>%
    filter(Window == "Expanding") %>%
    select(Model, exp_r2 = `OOS R2 (%)`)

  res_tbl %>%
    left_join(exp_ref, by = "Model") %>%
    mutate(
      `Delta R2 vs Exp (pp)` = round(`OOS R2 (%)` - exp_r2, 2),
      Window = factor(Window, levels = names(windows)),
      Model  = factor(Model, levels = unname(metric_map))
    ) %>%
    select(
      Horizon, Window, Model,
      `OOS R2 (%)`, `Delta R2 vs Exp (pp)`, `CW t`,
      `DM t vs C10`, `Encomp Lam`, `Encomp t`
    ) %>%
    arrange(Window, Model)
}

cape_oos_invariance <- bind_rows(
  run_cape_oos_invariance(df_base_log, cape_metrics, horizon = 60),
  run_cape_oos_invariance(df_base_log, cape_metrics, horizon = 120)
)

write.csv(cape_oos_invariance, "cape_oos_stability_comparison.csv", row.names = FALSE)


# ------------------------------------------------------------------------------
# 4. Rolling 30-Year Slope & R2 Trajectory Plot (5-Year Horizon, h = 60)
# ------------------------------------------------------------------------------

plot_df <- cape_roll_5yr$paths %>%
  filter(Window == "30-Yr Rolling") %>%
  mutate(
    Model = factor(Model, levels = c("CAPE_10", "CAPE_7", "CAPE_5", "CAPE_3")),
    r2_pct = 100 * r2
  ) %>%
  select(date, Model, `Rolling Slope (Beta)` = beta, `Rolling R2 (%)` = r2_pct) %>%
  pivot_longer(
    cols      = c(`Rolling Slope (Beta)`, `Rolling R2 (%)`),
    names_to  = "Metric",
    values_to = "Value"
  ) %>%
  mutate(Metric = factor(Metric, levels = c("Rolling Slope (Beta)", "Rolling R2 (%)")))

ref_lines <- tibble(
  Metric = factor(c("Rolling Slope (Beta)", "Rolling R2 (%)"),
                  levels = c("Rolling Slope (Beta)", "Rolling R2 (%)")),
  yintercept = c(-0.20, 0) # -1/h = -0.20 theoretical full mean reversion for h = 5
)

ggplot(plot_df, aes(x = date, y = Value, color = Model)) +
  geom_hline(data = ref_lines, aes(yintercept = yintercept),
             linetype = "dashed", color = "grey45", linewidth = 0.5) +
  geom_line(linewidth = 1.1) +
  facet_wrap(~ Metric, ncol = 1, scales = "free_y") +
  scale_color_manual(
    values = c(
      "CAPE_10" = "#666666",
      "CAPE_7"  = "#0072B2",
      "CAPE_5"  = "#009E73",
      "CAPE_3"  = "#D55E00"
    )
  ) +
  scale_x_date(date_breaks = "10 years", date_labels = "%Y") +
  labs(
    title    = "Rolling 30-Year Return Sensitivity and Explanatory Power Across CAPE Horizons",
    subtitle = "Five-year annualized real log returns (h = 60); dashed lines mark theoretical -1/h (-0.20) and zero R-squared",
    x        = NULL,
    y        = NULL,
    color    = "Valuation Measure"
  ) +
  theme_minimal(base_size = 11) +
  guides(color = guide_legend(override.aes = list(linewidth = 1.8))) +
  theme(
    legend.position  = "bottom",
    panel.grid.minor = element_blank(),
    plot.title       = element_text(face = "bold", size = 16),
    strip.text       = element_text(face = "bold", size = 13),
    legend.title     = element_text(size = 13),
    legend.text      = element_text(size = 13),
    legend.key.width = unit(1.5, "cm"),
    axis.text        = element_text(size = 11)
  )

VII. Stability tests as of 1990

## Out-of-Sample Forecast Invariance & Encompassing as of 1990

## (Strict real-time cutoff: only returns fully realized by as_of_date are used)

cape_metrics <- c(
  "cape_10" = "CAPE_10",
  "cape_7"  = "CAPE_7",
  "cape_5"  = "CAPE_5",
  "cape_3"  = "CAPE_3"
)

run_cape_oos_invariance <- function(data,
                                    metric_map,
                                    horizon       = 60L,
                                    min_train_obs = 480L,
                                    as_of_date    = as.Date("1990-12-01")) {
  ret_col  <- if (horizon == 60L) "five_yr_real_return" else "ten_yr_real_return"
  raw_vars <- names(metric_map)

  df_model <- data %>%
    arrange(date) %>%
    mutate(realize_date = lead(date, horizon)) %>%
    select(date, realize_date, all_of(raw_vars), y = all_of(ret_col)) %>%
    drop_na()

  if (!is.null(as_of_date)) {
    df_model <- df_model %>%
      filter(realize_date <= as.Date(as_of_date))
  }

  oos_idx <- (min_train_obs + horizon):nrow(df_model)
  num_oos <- length(oos_idx)
  end_idx <- oos_idx - horizon
  y_all   <- df_model$y
  y_act   <- y_all[oos_idx]
  cy      <- c(0, cumsum(y_all))

  windows <- list(
    "Expanding"     = NULL,
    "40-Yr Rolling" = 480L,
    "30-Yr Rolling" = 360L,
    "20-Yr Rolling" = 240L
  )

  # Generate recursive real-time OOS forecasts across all windows and CAPE variants
  fc_all <- lapply(names(windows), function(w_lbl) {
    w_len     <- windows[[w_lbl]]
    start_idx <- if (is.null(w_len)) rep(1L, num_oos) else pmax(1L, end_idx - w_len + 1L)
    n_tr      <- end_idx - start_idx + 1L
    y_mean    <- (cy[end_idx + 1L] - cy[start_idx]) / n_tr

    lapply(raw_vars, function(v) {
      x_all <- df_model[[v]]
      cx    <- c(0, cumsum(x_all))
      cxx   <- c(0, cumsum(x_all^2))
      cxy   <- c(0, cumsum(x_all * y_all))

      xm   <- (cx[end_idx + 1L]  - cx[start_idx])  / n_tr
      sxx  <- cxx[end_idx + 1L] - cxx[start_idx]
      sxy  <- cxy[end_idx + 1L] - cxy[start_idx]
      beta <- (sxy - n_tr * xm * y_mean) / (sxx - n_tr * xm^2)
      alph <- y_mean - beta * xm

      tibble(
        Window  = w_lbl,
        Model   = unname(metric_map[v]),
        date    = df_model$date[oos_idx],
        y_act   = y_act,
        y_bench = y_mean,
        y_mod   = alph + beta * x_all[oos_idx]
      )
    }) %>%
      bind_rows()
  }) %>%
    bind_rows()

  # Compute OOS R2, Clark-West, Diebold-Mariano vs CAPE_10, and Encompassing stats
  res_tbl <- lapply(names(windows), function(w_lbl) {
    df_w   <- fc_all %>% filter(Window == w_lbl)
    ref_10 <- df_w %>% filter(Model == "CAPE_10") %>% arrange(date)
    e_10   <- ref_10$y_act - ref_10$y_mod

    lapply(unname(metric_map), function(m_lbl) {
      df_m  <- df_w %>% filter(Model == m_lbl) %>% arrange(date)
      e_mod <- df_m$y_act - df_m$y_mod
      e_bch <- df_m$y_act - df_m$y_bench

      r2_oos <- 1 - mean(e_mod^2) / mean(e_bch^2)

      cw_f   <- e_bch^2 - (e_mod^2 - (df_m$y_bench - df_m$y_mod)^2)
      cw_fit <- lm(cw_f ~ 1)
      cw_t   <- coeftest(cw_fit, vcov = NeweyWest(cw_fit, lag = horizon, prewhite = FALSE))[1, "t value"]

      if (m_lbl == "CAPE_10") {
        dm_t    <- NA_real_
        enc_lam <- NA_real_
        enc_t   <- NA_real_
      } else {
        d_loss <- e_10^2 - e_mod^2
        dm_fit <- lm(d_loss ~ 1)
        dm_t   <- coeftest(dm_fit, vcov = NeweyWest(dm_fit, lag = horizon, prewhite = FALSE))[1, "t value"]

        f_diff  <- df_m$y_mod - ref_10$y_mod
        enc_fit <- lm(e_10 ~ f_diff - 1)
        enc_ct  <- coeftest(enc_fit, vcov = NeweyWest(enc_fit, lag = horizon, prewhite = FALSE))
        enc_lam <- enc_ct[1, "Estimate"]
        enc_t   <- enc_ct[1, "t value"]
      }

      tibble(
        Window        = w_lbl,
        Model         = m_lbl,
        Horizon       = paste0(horizon / 12L, "-Year"),
        `OOS R2 (%)`  = round(100 * r2_oos, 2),
        `CW t`        = round(cw_t, 2),
        `DM t vs C10` = round(dm_t, 2),
        `Encomp Lam`  = round(enc_lam, 2),
        `Encomp t`    = round(enc_t, 2)
      )
    }) %>%
      bind_rows()
  }) %>%
    bind_rows()

  exp_ref <- res_tbl %>%
    filter(Window == "Expanding") %>%
    select(Model, exp_r2 = `OOS R2 (%)`)

  res_tbl %>%
    left_join(exp_ref, by = "Model") %>%
    mutate(
      `Delta R2 vs Exp (pp)` = round(`OOS R2 (%)` - exp_r2, 2),
      Window = factor(Window, levels = names(windows)),
      Model  = factor(Model, levels = unname(metric_map))
    ) %>%
    select(
      Horizon, Window, Model,
      `OOS R2 (%)`, `Delta R2 vs Exp (pp)`, `CW t`,
      `DM t vs C10`, `Encomp Lam`, `Encomp t`
    ) %>%
    arrange(Window, Model)
}

# Run full 32-row OOS stability table as of December 1990
cape_oos_1990 <- bind_rows(
  run_cape_oos_invariance(df_base_log, cape_metrics, horizon = 60L,  as_of_date = as.Date("1990-12-01")),
  run_cape_oos_invariance(df_base_log, cape_metrics, horizon = 120L, as_of_date = as.Date("1990-12-01"))
) %>%
  mutate(
    Horizon = factor(Horizon, levels = c("5-Year", "10-Year")),
    Model   = factor(Model, levels = unname(cape_metrics))
  )

write.csv(cape_oos_1990, "cape_oos_stability_as_of_1990.csv", row.names = FALSE)

VIII. Directional accuracy and classification

# 1. Selected main valuation measures (> 3-year smoothing horizons) + secondary filters

dir_metrics <- c(
  # Main (> 3Y)
  "cape_10"         = "CAPE_10",
  "cape_7"          = "CAPE_7",
  "cape_5"          = "CAPE_5",
  "ewma_5_pe"      = "EWMA_5",
  "ewma_7_pe"      = "EWMA_7",
  "ewma_10_pe"     = "EWMA_10",
  "CF_short_pe"     = "CF_24_96",
  "CF_long_pe"      = "CF_36_180",
  # Secondary
  "kalman_fixed_pe" = "Kalman_Fixed",
  "kalman_mle_pe"   = "Kalman_MLE",
  "hp_onesided_pe"  = "HP_14400",
  "hp_120m_pe"      = "HP_129600",
  "hamilton_24_pe"  = "Hamilton_24"
)

# 2. Extract step-by-step OOS actuals and forecasts (exact match to run_oos_evaluation)
get_oos_forecasts <- function(data, metric_map, horizon = 60, window_months = 360,
                              min_train_obs = 480, window_label = "30-Yr Rolling") {
  ret_col  <- if (horizon == 60) "five_yr_real_return" else "ten_yr_real_return"
  raw_vars <- names(metric_map)

  df_model <- data %>%
    select(date, all_of(raw_vars), all_of(ret_col)) %>%
    rename(y = all_of(ret_col)) %>%
    arrange(date) %>%
    drop_na()

  oos_idx   <- (min_train_obs + horizon):nrow(df_model)
  num_oos   <- length(oos_idx)
  end_idx   <- oos_idx - horizon
  start_idx <- if (is.null(window_months)) rep(1L, num_oos) else pmax(1L, end_idx - window_months + 1L)
  n_tr      <- end_idx - start_idx + 1L

  y_all  <- df_model$y
  cy     <- c(0, cumsum(y_all))
  y_mean <- (cy[end_idx + 1L] - cy[start_idx]) / n_tr

  lapply(raw_vars, function(v) {
    x_all <- df_model[[v]]
    cx    <- c(0, cumsum(x_all))
    cxx   <- c(0, cumsum(x_all^2))
    cxy   <- c(0, cumsum(x_all * y_all))

    x_mean    <- (cx[end_idx + 1L]  - cx[start_idx])  / n_tr
    sum_xx    <- cxx[end_idx + 1L] - cxx[start_idx]
    sum_xy    <- cxy[end_idx + 1L] - cxy[start_idx]
    beta_hat  <- (sum_xy - n_tr * x_mean * y_mean) / (sum_xx - n_tr * x_mean^2)
    alpha_hat <- y_mean - beta_hat * x_mean

    tibble(
      window   = window_label,
      model    = unname(metric_map[v]),
      date     = df_model$date[oos_idx],
      y_act    = y_all[oos_idx],
      y_pred   = alpha_hat + beta_hat * x_all[oos_idx],
      act_neg  = y_all[oos_idx] < 0,
      pred_neg = (alpha_hat + beta_hat * x_all[oos_idx]) < 0
    )
  }) %>%
    bind_rows()
}

# 3. Score directional accuracy, false alarms, and missed negative returns
score_directional <- function(df_preds, model_levels, horizon = 60, sub_months = NULL,
                              sample_label = "Full OOS Sample") {
  if (!is.null(sub_months)) {
    df_preds <- df_preds %>%
      group_by(window, model) %>%
      slice_tail(n = sub_months) %>%
      ungroup()
  }

  bench_ref <- df_preds %>%
    filter(model == model_levels[1]) %>%
    mutate(
      model    = "Always_Positive",
      y_pred   = NA_real_,
      pred_neg = FALSE
    )

  combined <- bind_rows(bench_ref, df_preds) %>%
    mutate(model = factor(model, levels = c("Always_Positive", model_levels)))

  combined %>%
    group_by(window, model) %>%
    summarise(
      Sample                = sample_label,
      `Period Start`        = min(date),
      `Period End`          = max(date),
      N                     = n(),
      tp                    = sum(pred_neg & act_neg),
      fp                    = sum(pred_neg & !act_neg),
      fn                    = sum(!pred_neg & act_neg),
      tn                    = sum(!pred_neg & !act_neg),
      `Hit Rate (%)`        = round(100 * mean(pred_neg == act_neg), 1),
      #`Excess Hit (pp)`     = round(100 * (mean(pred_neg == act_neg) - mean(!act_neg)), 1),
      `HAC t`               = {
        diff_hit <- as.numeric(pred_neg == act_neg) - as.numeric(!act_neg)
        if (all(diff_hit == 0)) {
          NA_real_
        } else {
          fit <- lm(diff_hit ~ 1)
          nw  <- NeweyWest(fit, lag = horizon, prewhite = FALSE)
          round(coeftest(fit, vcov = nw)[1, "t value"], 2)
        }
      },
      #`Warnings (%)`        = round(100 * mean(pred_neg), 1),
      `FDR (%)` = ifelse((tp + fp) > 0, round(100 * fp / (tp + fp), 1), NA_real_),
      `FPR (%)` = round(100 * fp / (fp + tn), 1),
      `FNR (%)`  = round(100 * fn / (tp + fn), 1),
      .groups = "drop"
    ) %>%
    arrange(window, model) %>%
    select(
      Window = window, Model = model, Sample, `Period Start`, `Period End`, N,
      `Hit Rate (%)`, 
      #`Excess Hit (pp)`, 
      `HAC t`,
      #`Warnings (%)`, 
      `FDR (%)`, 
      `FPR (%)`, 
      `FNR (%)`
    )
}

# TABLE 1: Directional Accuracy Across 40-Yr, 30-Yr, and 20-Yr Rolling Windows
preds_40yr <- get_oos_forecasts(
  df_alts_log, dir_metrics, horizon = 60, window_months = 480, window_label = "40-Yr Rolling"
)
preds_30yr <- get_oos_forecasts(
  df_alts_log, dir_metrics, horizon = 60, window_months = 360, window_label = "30-Yr Rolling"
)
preds_20yr <- get_oos_forecasts(
  df_alts_log, dir_metrics, horizon = 60, window_months = 240, window_label = "20-Yr Rolling"
)

dir_table1_rolling <- bind_rows(
  score_directional(preds_40yr, unname(dir_metrics), horizon = 60, sub_months = NULL, sample_label = "Full OOS Sample"),
  score_directional(preds_40yr, unname(dir_metrics), horizon = 60, sub_months = 480,  sample_label = "Last 40 Years"),
  score_directional(preds_30yr, unname(dir_metrics), horizon = 60, sub_months = NULL, sample_label = "Full OOS Sample"),
  score_directional(preds_30yr, unname(dir_metrics), horizon = 60, sub_months = 360,  sample_label = "Last 30 Years"),
  score_directional(preds_20yr, unname(dir_metrics), horizon = 60, sub_months = NULL, sample_label = "Full OOS Sample"),
  score_directional(preds_20yr, unname(dir_metrics), horizon = 60, sub_months = 240,  sample_label = "Last 20 Years")
) %>%
  mutate(
    Window = factor(Window, levels = c("40-Yr Rolling", "30-Yr Rolling", "20-Yr Rolling")),
    Sample = factor(Sample, levels = c("Full OOS Sample", "Last 40 Years", "Last 30 Years", "Last 20 Years"))
  ) %>%
  arrange(Window, Sample, Model)

write.csv(dir_table1_rolling, "dir_acc_table1_rolling.csv", row.names = FALSE)

IX. Current valuations

all_val_metrics <- c(
  # CAPE family
  "cape_10"         = "CAPE_10",
  "cape_7"          = "CAPE_7",
  "cape_5"          = "CAPE_5",
  "cape_3"          = "CAPE_3",
  # EWMA family
  "ewma_3_pe"      = "EWMA_3",
  "ewma_5_pe"      = "EWMA_5",
  "ewma_7_pe"      = "EWMA_7",
  "ewma_10_pe"     = "EWMA_10",
  # Band-pass, state-space, and trend filters
  "CF_short_pe"     = "CF_24_96",
  "CF_long_pe"      = "CF_36_180",
  "kalman_fixed_pe" = "Kalman_Fixed",
  "kalman_mle_pe"   = "Kalman_MLE",
  "hp_onesided_pe"  = "HP_14400",
  "hp_120m_pe"      = "HP_129600",
  "hamilton_24_pe"  = "Hamilton_24"
)

build_valuation_table <- function(data, metric_map, as_of_date = as.Date("2026-06-30"),
                                  is_log = TRUE) {
  metric_map <- metric_map[names(metric_map) %in% names(data)]
  raw_vars   <- names(metric_map)

  df_sub <- data %>%
    filter(date <= as_of_date) %>%
    arrange(date)

  last_dt  <- max(df_sub$date[!is.na(df_sub[[raw_vars[1]]])])
  last_lbl <- paste0("Last Value (", format(last_dt, "%m/%Y"), ")")

  lapply(raw_vars, function(v) {
    s_df <- df_sub %>%
      select(date, val = all_of(v)) %>%
      drop_na()

    series   <- if (is_log) exp(s_df$val) else s_df$val
    last_val <- tail(series, 1)
    avg_20y  <- mean(tail(series, 240))
    avg_30y  <- mean(tail(series, 360))
    avg_40y  <- mean(tail(series, 480))

    tibble(
      Model             = unname(metric_map[v]),
      !!last_lbl       := round(last_val, 2),
      `20Y Avg`         = round(avg_20y, 2),
      `30Y Avg`         = round(avg_30y, 2),
      `40Y Avg`         = round(avg_40y, 2),
      `20Y Premium (%)` = round(100 * (last_val / avg_20y - 1), 1),
      `30Y Premium (%)` = round(100 * (last_val / avg_30y - 1), 1),
      `40Y Premium (%)` = round(100 * (last_val / avg_40y - 1), 1)
    )
  }) %>%
    bind_rows() %>%
    mutate(Model = factor(Model, levels = unname(metric_map))) %>%
    arrange(Model)
}

valuation_standing_table <- build_valuation_table(
  df_alts_log, all_val_metrics, as_of_date = as.Date("2026-06-30"), is_log = TRUE
)

write.csv(valuation_standing_table, "valuation_standing_june2026.csv", row.names = FALSE)

X. Forecasts using valuations

forecast_metrics <- c(
  # CAPE family
  "cape_10"         = "CAPE_10",
  "cape_7"          = "CAPE_7",
  "cape_5"          = "CAPE_5",
  "cape_3"          = "CAPE_3",
  # EWMA family
  "ewma_3_pe"      = "EWMA_3",
  "ewma_5_pe"      = "EWMA_5",
  "ewma_7_pe"      = "EWMA_7",
  "ewma_10_pe"     = "EWMA_10",
  # Band-pass, state-space, and trend filters
  "CF_short_pe"     = "CF_24_96",
  "CF_long_pe"      = "CF_36_180",
  "kalman_fixed_pe" = "Kalman_Fixed",
  "kalman_mle_pe"   = "Kalman_MLE",
  "hp_onesided_pe"  = "HP_14400",
  "hp_120m_pe"      = "HP_129600",
  "hamilton_24_pe"  = "Hamilton_24"
)

predict_current_returns <- function(data, metric_map, as_of_date = as.Date("2026-06-30")) {
  metric_map <- metric_map[names(metric_map) %in% names(data)]
  raw_vars   <- names(metric_map)

  df_base <- data %>%
    filter(date <= as_of_date) %>%
    arrange(date)

  windows <- list(
    "40-Yr Window" = 480L,
    "30-Yr Window" = 360L,
    "20-Yr Window" = 240L,
    "Full Sample"  = NULL
  )

  horizons <- list(
    "5-Year"  = list(col = "five_yr_real_return", lag = 60L),
    "10-Year" = list(col = "ten_yr_real_return",  lag = 120L)
  )

  results <- list()

  for (h_name in names(horizons)) {
    ret_col <- horizons[[h_name]]$col
    nw_lag  <- horizons[[h_name]]$lag
    if (!ret_col %in% names(df_base)) next

    for (w_name in names(windows)) {
      w_len <- windows[[w_name]]

      res_hw <- lapply(raw_vars, function(v) {
        # Latest valuation observation (06/2026)
        df_now <- df_base %>%
          select(date, x = all_of(v)) %>%
          drop_na() %>%
          slice_tail(n = 1)

        # Completed historical training sample
        df_tr <- df_base %>%
          select(date, x = all_of(v), y = all_of(ret_col)) %>%
          drop_na()

        if (!is.null(w_len)) {
          df_tr <- slice_tail(df_tr, n = w_len)
        }

        fit     <- lm(y ~ x, data = df_tr)
        pred    <- as.numeric(predict(fit, newdata = df_now))
        vcov_nw <- NeweyWest(fit, lag = nw_lag, prewhite = FALSE)
        x_vec   <- c(1, df_now$x)
        se_nw   <- sqrt(as.numeric(t(x_vec) %*% vcov_nw %*% x_vec))

        tibble(
          Horizon        = h_name,
          Window         = w_name,
          Model          = unname(metric_map[v]),
          `As Of`        = df_now$date,
          `Train Start`  = min(df_tr$date),
          `Train End`    = max(df_tr$date),
          N              = nrow(df_tr),
          `Forecast (%)` = round(100 * pred, 2),
          `HAC SE (%)`   = round(100 * se_nw, 2)
        )
      }) %>%
        bind_rows()

      results[[length(results) + 1L]] <- res_hw
    }
  }

  bind_rows(results) %>%
    mutate(
      Horizon = factor(Horizon, levels = c("5-Year", "10-Year")),
      Window  = factor(Window, levels = c("40-Yr Window", "30-Yr Window", "20-Yr Window", "Full Sample")),
      Model   = factor(Model, levels = unname(metric_map))
    ) %>%
    arrange(Horizon, Window, Model)
}

current_forecasts_long <- predict_current_returns(
  df_alts_log, forecast_metrics, as_of_date = as.Date("2026-06-30")
)

# Side-by-side summary table across training windows
current_forecasts_wide <- current_forecasts_long %>%
  select(Horizon, Model, Window, `Forecast (%)`) %>%
  pivot_wider(names_from = Window, values_from = `Forecast (%)`)

write.csv(current_forecasts_long, "current_forecasts_june2026_long.csv", row.names = FALSE)
write.csv(current_forecasts_wide, "current_forecasts_june2026_wide.csv", row.names = FALSE)

XI Exhibit 5. Cumulative squared error difference (5-year forecast) vs. historical mean full sample

plot_smoother_csse_vs_mean <- function(data,
                                       roll_months   = 360L,   # 360L = 30-Yr Rolling (NULL = Expanding, 480L = 40-Yr, 240L = 20-Yr)
                                       horizon       = 60L,    # 60L = 5-Year forecast horizon
                                       min_train_obs = 480L,
                                       start_plot    = NULL,   # NULL = earliest possible OOS origin date (1925-12-01)
                                       filter_by     = c("origin", "realization")) {
  filter_by <- match.arg(filter_by)
  ret_col   <- if (horizon == 60L) "five_yr_real_return" else "ten_yr_real_return"

  metric_map <- c(
    "cape_10"   = "CAPE_10",
    "cape_7"    = "CAPE_7",
    "cape_5"    = "CAPE_5",
    "ewma_7_pe" = "EWMA_7",
    "ewma_5_pe" = "EWMA_5"
  )
  raw_vars <- names(metric_map)

  df_model <- data %>%
    arrange(date) %>%
    mutate(realize_date = lead(date, horizon)) %>%
    select(date, realize_date, all_of(raw_vars), y = all_of(ret_col)) %>%
    drop_na()

  oos_idx   <- (min_train_obs + horizon):nrow(df_model)
  num_oos   <- length(oos_idx)
  end_idx   <- oos_idx - horizon
  start_idx <- if (is.null(roll_months)) {
    rep(1L, num_oos)
  } else {
    pmax(1L, end_idx - roll_months + 1L)
  }

  n_tr   <- end_idx - start_idx + 1L
  y_all  <- df_model$y
  y_act  <- y_all[oos_idx]
  cy     <- c(0, cumsum(y_all))
  y_mean <- (cy[end_idx + 1L] - cy[start_idx]) / n_tr

  # Generate recursive rolling OOS forecasts and forecast errors (e = actual - predicted)
  fc_models <- lapply(raw_vars, function(v) {
    x_all <- df_model[[v]]
    cx    <- c(0, cumsum(x_all))
    cxx   <- c(0, cumsum(x_all^2))
    cxy   <- c(0, cumsum(x_all * y_all))

    xm   <- (cx[end_idx + 1L]  - cx[start_idx])  / n_tr
    sxx  <- cxx[end_idx + 1L] - cxx[start_idx]
    sxy  <- cxy[end_idx + 1L] - cxy[start_idx]
    beta <- (sxy - n_tr * xm * y_mean) / (sxx - n_tr * xm^2)
    alph <- y_mean - beta * xm

    y_hat <- alph + beta * x_all[oos_idx]

    tibble(
      date         = df_model$date[oos_idx],
      realize_date = df_model$realize_date[oos_idx],
      Model        = unname(metric_map[v]),
      actual_pct   = 100 * y_act,
      pred_pct     = 100 * y_hat,
      error_pct    = 100 * (y_act - y_hat)
    )
  }) %>%
    bind_rows()

  # Recursive historical mean benchmark (sets the horizontal zero line)
  fc_bench <- tibble(
    date         = df_model$date[oos_idx],
    realize_date = df_model$realize_date[oos_idx],
    Model        = "Historical Mean",
    actual_pct   = 100 * y_act,
    pred_pct     = 100 * y_mean,
    error_pct    = 100 * (y_act - y_mean)
  )

  fc_df <- bind_rows(fc_models, fc_bench)

  # Set plot date axis and optional start filter
  if (filter_by == "origin") {
    fc_sub <- fc_df %>% mutate(plot_date = date)
    x_lbl  <- "Forecast Origin Date (t)"
  } else {
    fc_sub <- fc_df %>% mutate(plot_date = realize_date)
    x_lbl  <- paste0(horizon / 12L, "-Year Return Realization Date (t + ", horizon, ")")
  }

  if (!is.null(start_plot)) {
    fc_sub <- fc_sub %>% filter(plot_date >= as.Date(start_plot))
  }

  # Welch & Goyal (2008) Cumulative SSE Difference vs. Historical Mean
  err_bench_ref <- fc_sub %>%
    filter(Model == "Historical Mean") %>%
    select(plot_date, err_bench = error_pct)

  model_levels <- c("Historical Mean", "CAPE_10", "CAPE_7", "CAPE_5", "EWMA_7", "EWMA_5")

  plot_df <- fc_sub %>%
    left_join(err_bench_ref, by = "plot_date") %>%
    arrange(Model, plot_date) %>%
    group_by(Model) %>%
    mutate(
      csse_diff = cumsum(err_bench^2 - error_pct^2),
      Model     = factor(Model, levels = model_levels)
    ) %>%
    ungroup()

  x_breaks <- if (is.null(start_plot)) "10 years" else "5 years"

  p <- ggplot(plot_df, aes(x = plot_date, y = csse_diff, color = Model, linetype = Model)) +
    geom_line(linewidth = 1.6) +
    scale_color_manual(
      values = c(
        "Historical Mean" = "#4D4D4D",
        "CAPE_10"         = "#B22222",
        "CAPE_7"          = "#1F78B4",
        "CAPE_5"          = "#1B7837",
        "EWMA_7"          = "#6A3D9A",
        "EWMA_5"          = "#D95F02"
      )
    ) +
    scale_linetype_manual(
      values = c(
        "Historical Mean" = "solid",
        "CAPE_10"         = "solid",
        "CAPE_7"          = "solid",
        "CAPE_5"          = "solid",
        "EWMA_7"          = "dashed",
        "EWMA_5"          = "dashed"
      )
    ) +
    scale_x_date(date_breaks = x_breaks, date_labels = "%Y") +
    labs(
      x        = x_lbl,
      y        = "Cumulative Squared Error Difference",
      color    = NULL,
      linetype = NULL
    ) +
    theme_bw(base_size = 16) +
    guides(
      color    = guide_legend(nrow = 1),
      linetype = guide_legend(nrow = 1)
    ) +
    theme(
      axis.title       = element_text(size = 16, face = "bold"),
      axis.text        = element_text(size = 14),
      legend.position  = "top",
      legend.text      = element_text(size = 13),
      legend.key.width = unit(1.2, "cm"),
      panel.grid.minor = element_blank()
    )

  list(plot = p, data = plot_df)
}

# Generate and export full-history CSSE figure vs. Historical Mean (starts 1925-12-01)
res_smoother_csse_mean_full <- plot_smoother_csse_vs_mean(
  df_alts_log,
  roll_months = 360L,
  horizon     = 60L,
  start_plot  = NULL,
  filter_by   = "origin"
)

print(res_smoother_csse_mean_full$plot)

ggsave(
  "smoother_rolling_5yr_csse_vs_mean_full.png",
  res_smoother_csse_mean_full$plot,
  width  = 10,
  height = 6,
  dpi    = 300
)

XIa. Cumulative squared error difference (10-year forecast) vs. CAPE_10 full sample for comparison

# Cumulative Squared Error Difference (CSED) vs. CAPE_10 — 10-Year Horizon (1930–2016)
res_smoother_csed_10yr <- plot_smoother_csed_vs_cape10(
  df_alts_log,
  roll_months = 360L,   # 30-Yr Rolling (use NULL to compare Expanding window)
  horizon     = 120L,   # 10-Year forecast horizon
  start_plot  = NULL,   # Starts at earliest 10-yr OOS origin (1930-12-01)
  filter_by   = "origin"
)

print(res_smoother_csed_10yr$plot)

ggsave(
  "smoother_rolling_10yr_csed_vs_cape10_full.png",
  res_smoother_csed_10yr$plot,
  width  = 10,
  height = 6,
  dpi    = 300
)

# Inspect terminal CSED values and OOS span for direct comparison with the 5-year figure
res_smoother_csed_10yr$data %>%
  group_by(Model) %>%
  summarise(
    `Origin Start`  = min(plot_date),
    `Origin End`    = max(plot_date),
    N               = n(),
    `Terminal CSED` = round(last(csed), 1),
    .groups         = "drop"
  )

XII. Cumulative squared error difference vs. CAPE_10 since 1990 for conclusion

# Calcs

# df_full %>% 
#   filter(year(date) > 2015) %>% 
#   summarize(ret = ((last(e_real) / first(e_real))^(12/length(e_real))) -1) 

# CSEG

# Cumulative Squared Error Gain vs. CAPE_10 (CAPE_7, CAPE_5, EWMA_7, EWMA_5)

plot_smoother_cum_sse_gain_vs_cape10 <- function(data,
                                                 roll_months   = 360L,   # 360L = 30-Yr Rolling (NULL = Expanding, 480L = 40-Yr, 240L = 20-Yr)
                                                 horizon       = 60L,    # 60L = 5-Year forecast horizon
                                                 min_train_obs = 480L,
                                                 start_plot    = as.Date("1990-01-01"),
                                                 filter_by     = c("origin", "realization")) {
  filter_by <- match.arg(filter_by)
  ret_col   <- if (horizon == 60L) "five_yr_real_return" else "ten_yr_real_return"

  metric_map <- c(
    "cape_10"   = "CAPE_10",
    "cape_7"    = "CAPE_7",
    "cape_5"    = "CAPE_5",
    "ewma_7_pe" = "EWMA_7",
    "ewma_5_pe" = "EWMA_5"
  )
  raw_vars <- names(metric_map)

  df_model <- data %>%
    arrange(date) %>%
    mutate(realize_date = lead(date, horizon)) %>%
    select(date, realize_date, all_of(raw_vars), y = all_of(ret_col)) %>%
    drop_na()

  oos_idx   <- (min_train_obs + horizon):nrow(df_model)
  num_oos   <- length(oos_idx)
  end_idx   <- oos_idx - horizon
  start_idx <- if (is.null(roll_months)) {
    rep(1L, num_oos)
  } else {
    pmax(1L, end_idx - roll_months + 1L)
  }

  n_tr   <- end_idx - start_idx + 1L
  y_all  <- df_model$y
  y_act  <- y_all[oos_idx]
  cy     <- c(0, cumsum(y_all))
  y_mean <- (cy[end_idx + 1L] - cy[start_idx]) / n_tr

  # Generate recursive rolling OOS forecasts and forecast errors (e = actual - predicted)
  fc_df <- lapply(raw_vars, function(v) {
    x_all <- df_model[[v]]
    cx    <- c(0, cumsum(x_all))
    cxx   <- c(0, cumsum(x_all^2))
    cxy   <- c(0, cumsum(x_all * y_all))

    xm   <- (cx[end_idx + 1L]  - cx[start_idx])  / n_tr
    sxx  <- cxx[end_idx + 1L] - cxx[start_idx]
    sxy  <- cxy[end_idx + 1L] - cxy[start_idx]
    beta <- (sxy - n_tr * xm * y_mean) / (sxx - n_tr * xm^2)
    alph <- y_mean - beta * xm

    y_hat <- alph + beta * x_all[oos_idx]

    tibble(
      date         = df_model$date[oos_idx],
      realize_date = df_model$realize_date[oos_idx],
      Model        = unname(metric_map[v]),
      actual_pct   = 100 * y_act,
      pred_pct     = 100 * y_hat,
      error_pct    = 100 * (y_act - y_hat)
    )
  }) %>%
    bind_rows()

  # Filter to post-1990 sample (by forecast origin date or return realization date)
  if (filter_by == "origin") {
    fc_sub <- fc_df %>% filter(date >= start_plot) %>% mutate(plot_date = date)
    x_lbl  <- "Forecast Origin Date (t)"
  } else {
    fc_sub <- fc_df %>% filter(realize_date >= start_plot) %>% mutate(plot_date = realize_date)
    x_lbl  <- paste0(horizon / 12L, "-Year Return Realization Date (t + ", horizon, ")")
  }

  # Use CAPE_10 as the zero-line benchmark
  err_cape10_ref <- fc_sub %>%
    filter(Model == "CAPE_10") %>%
    select(plot_date, err_cape10 = error_pct)

  plot_df <- fc_sub %>%
    left_join(err_cape10_ref, by = "plot_date") %>%
    arrange(Model, plot_date) %>%
    group_by(Model) %>%
    mutate(
      cum_sse_gain = cumsum(err_cape10^2 - error_pct^2),
      Model = factor(Model, levels = c("CAPE_10", "CAPE_7", "CAPE_5", "EWMA_7", "EWMA_5"))
    ) %>%
    ungroup()

  p <- ggplot(plot_df, aes(x = plot_date, y = cum_sse_gain, color = Model, linetype = Model)) +
    geom_line(linewidth = 1.8) +
    scale_color_manual(
      values = c(
        "CAPE_10" = "#B22222",
        "CAPE_7"  = "#1F78B4",
        "CAPE_5"  = "#1B7837",
        "EWMA_7"  = "#6A3D9A",
        "EWMA_5"  = "#D95F02"
      )
    ) +
    scale_linetype_manual(
      values = c(
        "CAPE_10" = "solid",
        "CAPE_7"  = "solid",
        "CAPE_5"  = "solid",
        "EWMA_7"  = "dashed",
        "EWMA_5"  = "dashed"
      )
    ) +
    scale_x_date(date_breaks = "5 years", date_labels = "%Y") +
    labs(
      x        = x_lbl,
      y        = "Cumulative Squared Error Difference",
      color    = NULL,
      linetype = NULL
    ) +
    theme_bw(base_size = 16) +
    theme(
      axis.title       = element_text(size = 16, face = "bold"),
      axis.text        = element_text(size = 14),
      legend.position  = "top",
      legend.text      = element_text(size = 14),
      legend.key.width = unit(1.8, "cm"),
      panel.grid.minor = element_blank()
    )

  list(plot = p, data = plot_df)
}

# Generate and export figure (uses df_alts_log so EWMA columns are included)
res_smoother_cseg_vs_cape10 <- plot_smoother_cum_sse_gain_vs_cape10(
  df_alts_log,
  roll_months = 360L,
  horizon     = 60L,
  start_plot  = as.Date("1990-01-01"),
  filter_by   = "origin"
)

print(res_smoother_cseg_vs_cape10$plot)

ggsave(
  "smoother_rolling_5yr_cum_sse_gain_vs_cape10_1990.png",
  res_smoother_cseg_vs_cape10$plot,
  width  = 10,
  height = 6,
  dpi    = 300
)

XIV. Robustness Check: Regression tables (level): IS and OOS

# Level-Form Robustness Check: 5-Year and 10-Year IS & OOS Tests

df_alts_level <- df_alts %>%
  mutate(
    five_yr_real_return = ((lead(real_tr_p, 60)  / real_tr_p)^(12 / 60))  - 1,
    ten_yr_real_return  = ((lead(real_tr_p, 120) / real_tr_p)^(12 / 120)) - 1,
    across(
      all_of(names(all_metrics)),
      ~ if_else(.x > 0, .x, NA_real_)
    )
  )

all_model_levels <- unname(all_metrics)

# ------------------------------------------------------------------------------
# 1. In-Sample Regressions (5-Year and 10-Year Horizons, Level Form)
# ------------------------------------------------------------------------------

is_5yr_full_lvl  <- run_is_evaluation(df_alts_level, all_metrics, horizon = 60,  last_n_months = NULL, sample_label = "Full Sample")
is_5yr_30yr_lvl  <- run_is_evaluation(df_alts_level, all_metrics, horizon = 60,  last_n_months = 360,  sample_label = "Last 30 Years")
is_10yr_full_lvl <- run_is_evaluation(df_alts_level, all_metrics, horizon = 120, last_n_months = NULL, sample_label = "Full Sample")
is_10yr_30yr_lvl <- run_is_evaluation(df_alts_level, all_metrics, horizon = 120, last_n_months = 360,  sample_label = "Last 30 Years")

metrics_5yr_is_lvl <- bind_rows(is_5yr_full_lvl, is_5yr_30yr_lvl) %>%
  mutate(
    Model = factor(model, levels = all_model_levels),
    Beta  = round(slope, 4),
    t     = round(t_statistic, 2),
    R2    = round(r_squared, 3)
  ) %>%
  arrange(desc(n_obs), Model) %>%
  select(Model, `Period Start` = period_start, `Period End` = period_end, N = n_obs, Beta, t, R2)

metrics_10yr_is_lvl <- bind_rows(is_10yr_full_lvl, is_10yr_30yr_lvl) %>%
  mutate(
    Model = factor(model, levels = all_model_levels),
    Beta  = round(slope, 4),
    t     = round(t_statistic, 2),
    R2    = round(r_squared, 3)
  ) %>%
  arrange(desc(n_obs), Model) %>%
  select(Model, `Period Start` = period_start, `Period End` = period_end, N = n_obs, Beta, t, R2)

write.csv(metrics_5yr_is_lvl,  "5yr_is_level.csv",  row.names = FALSE)
write.csv(metrics_10yr_is_lvl, "10yr_is_level.csv", row.names = FALSE)

# ------------------------------------------------------------------------------
# 2. Out-of-Sample Regressions (5-Year and 10-Year Horizons, Level Form)
# ------------------------------------------------------------------------------

format_oos_table <- function(oos_df, model_lvls) {
  oos_df %>%
    mutate(
      Model  = factor(model, levels = model_lvls),
      prefix = case_when(
        window == "Expanding"     ~ "Exp",
        window == "40-Yr Rolling" ~ "40Y",
        window == "30-Yr Rolling" ~ "30Y",
        window == "20-Yr Rolling" ~ "20Y"
      ),
      R2     = round(r2_oos, 4),
      `CW t` = round(cw_t_stat, 2)
    ) %>%
    select(Model, `Period Start` = period_start, `Period End` = period_end, N = n_obs, prefix, R2, `CW t`) %>%
    pivot_wider(
      names_from  = prefix,
      values_from = c(R2, `CW t`),
      names_glue  = "{prefix} {.value}"
    ) %>%
    arrange(desc(N), Model) %>%
    select(
      Model, `Period Start`, `Period End`, N,
      `Exp R2`, `Exp CW t`,
      `40Y R2`, `40Y CW t`,
      `30Y R2`, `30Y CW t`,
      `20Y R2`, `20Y CW t`
    )
}

metrics_5yr_oos_lvl <- bind_rows(
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 60, window_months = NULL, min_train_obs = 480, window_label = "Expanding"),
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 60, window_months = 480,  min_train_obs = 480, window_label = "40-Yr Rolling"),
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 60, window_months = 360,  min_train_obs = 480, window_label = "30-Yr Rolling"),
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 60, window_months = 240,  min_train_obs = 480, window_label = "20-Yr Rolling")
) %>%
  format_oos_table(all_model_levels)

metrics_10yr_oos_lvl <- bind_rows(
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 120, window_months = NULL, min_train_obs = 480, window_label = "Expanding"),
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 120, window_months = 480,  min_train_obs = 480, window_label = "40-Yr Rolling"),
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 120, window_months = 360,  min_train_obs = 480, window_label = "30-Yr Rolling"),
  run_oos_evaluation(df_alts_level, all_metrics, horizon = 120, window_months = 240,  min_train_obs = 480, window_label = "20-Yr Rolling")
) %>%
  format_oos_table(all_model_levels)

write.csv(metrics_5yr_oos_lvl,  "5yr_oos_level.csv",  row.names = FALSE)
write.csv(metrics_10yr_oos_lvl, "10yr_oos_level.csv", row.names = FALSE)

XV. Additional SEs: Hodrick’s t

hodrick_metrics <- c(
  "cape_10"         = "CAPE_10",
  "cape_7"          = "CAPE_7",
  "cape_5"          = "CAPE_5",
  "cape_3"          = "CAPE_3",
  "pe"              = "PE",
  "ewma_3_pe"       = "EWMA_3",
  "ewma_5_pe"       = "EWMA_5",
  "ewma_7_pe"       = "EWMA_7",
  "ewma_10_pe"      = "EWMA_10",
  "CF_short_pe"     = "CF_24_96",
  "CF_long_pe"      = "CF_36_180",
  "kalman_fixed_pe" = "Kalman_Fixed",
  "kalman_mle_pe"   = "Kalman_MLE",
  "hp_onesided_pe"  = "HP_14400",
  "hp_120m_pe"      = "HP_129600",
  "hamilton_24_pe"  = "Hamilton_24"
)

# Automatically locate Shiller's real total return price column in `data`
detect_tr_price_col <- function(data) {
  df_chk <- data %>%
    filter(date >= as.Date("1881-01-01")) %>%
    arrange(date)

  num_cols <- names(df_chk)[vapply(df_chk, is.numeric, logical(1))]
  num_cols <- setdiff(num_cols, c("five_yr_real_return", "ten_yr_real_return"))

  # Match against five_yr_real_return (or ten_yr_real_return) via 1-month compounded log returns
  target_col <- intersect(c("five_yr_real_return", "ten_yr_real_return"), names(df_chk))[1L]
  h_chk      <- if (!is.na(target_col) && target_col == "ten_yr_real_return") 120L else 60L

  if (!is.na(target_col)) {
    y_target <- df_chk[[target_col]]
    valid    <- which(!is.na(y_target))
    for (col in num_cols) {
      p <- df_chk[[col]]
      if (all(p > 0, na.rm = TRUE) && sum(!is.na(p)) >= max(valid) + h_chk) {
        y_cand <- (12 / h_chk) * log(lead(p, h_chk) / p)
        if (max(abs(y_cand[valid] - y_target[valid]), na.rm = TRUE) < 1e-4) {
          message(sprintf("Matched real total return price column: `%s`", col))
          return(col)
        }
      }
    }
  }

  stop(
    "No real total return price column found in `df_alts`.\n",
    "Available columns: ", paste(names(data), collapse = ", "), "\n",
    "Join Shiller Column J by `date` from your raw Shiller data frame first."
  )
}

run_is_hodrick <- function(data, metric_map, horizon = 60,
                           start_date = as.Date("1881-01-01"),
                           sample_label = "Full Sample",
                           tr_price_col = NULL) {
  if (is.null(tr_price_col)) {
    tr_price_col <- detect_tr_price_col(data)
  }

  df_sub <- data %>%
    filter(date >= start_date) %>%
    arrange(date)

  p_tr  <- df_sub[[tr_price_col]]
  r_1m  <- log(lead(p_tr) / p_tr)
  T_tot <- nrow(df_sub)
  N     <- T_tot - horizon
  K_max <- N + horizon - 1L

  cr    <- c(0, cumsum(r_1m[1:K_max]))
  y_vec <- (12 / horizon) * (cr[(1:N) + horizon] - cr[1:N])
  e_1m  <- r_1m[1:K_max] - mean(r_1m[1:K_max])

  t_lo <- pmax(1L, (1:K_max) - horizon + 1L)
  t_hi <- pmin(N, 1:K_max)

  lapply(names(metric_map), function(v) {
    x_vec <- log(df_sub[[v]][1:N])

    fit  <- lm(y_vec ~ x_vec)
    beta <- coef(fit)[["x_vec"]]
    r2   <- summary(fit)$r.squared

    nw_vcov <- NeweyWest(fit, lag = horizon, prewhite = FALSE)
    t_nw    <- beta / sqrt(nw_vcov["x_vec", "x_vec"])

    Z     <- cbind(1, x_vec)
    ZtZ_i <- solve(crossprod(Z))
    cZ1   <- c(0, cumsum(Z[, 1]))
    cZ2   <- c(0, cumsum(Z[, 2]))

    W <- (12 / horizon) * cbind(
      cZ1[t_hi + 1L] - cZ1[t_lo],
      cZ2[t_hi + 1L] - cZ2[t_lo]
    )

    vcov_1b   <- ZtZ_i %*% crossprod(W * e_1m) %*% ZtZ_i
    t_hodrick <- beta / sqrt(vcov_1b[2, 2])

    tibble(
      Horizon        = paste0(horizon / 12, "-Year"),
      Sample         = sample_label,
      Model          = unname(metric_map[v]),
      `Period Start` = df_sub$date[1L],
      `Period End`   = df_sub$date[N],
      N              = N,
      Beta           = round(beta, 3),
      `NW t`         = round(t_nw, 2),
      `Hodrick t`    = round(t_hodrick, 2),
      R2             = round(r2, 3)
    )
  }) %>%
    bind_rows()
}

tr_col <- detect_tr_price_col(df_alts)

hodrick_results <- bind_rows(
  run_is_hodrick(df_alts, hodrick_metrics, horizon = 60,
                 start_date = as.Date("1881-01-01"), sample_label = "Full Sample", tr_price_col = tr_col),
  run_is_hodrick(df_alts, hodrick_metrics, horizon = 60,
                 start_date = as.Date("1991-07-01"), sample_label = "Last 30 Years", tr_price_col = tr_col),
  run_is_hodrick(df_alts, hodrick_metrics, horizon = 120,
                 start_date = as.Date("1881-01-01"), sample_label = "Full Sample", tr_price_col = tr_col),
  run_is_hodrick(df_alts, hodrick_metrics, horizon = 120,
                 start_date = as.Date("1986-07-01"), sample_label = "Last 30 Years", tr_price_col = tr_col)
)

print(hodrick_results, n = Inf)
## # A tibble: 64 × 10
##    Horizon Sample        Model   `Period Start` `Period End`     N   Beta `NW t`
##    <chr>   <chr>         <chr>   <date>         <date>       <dbl>  <dbl>  <dbl>
##  1 5-Year  Full Sample   CAPE_10 1881-01-01     2021-06-01    1686 -0.067  -2.87
##  2 5-Year  Full Sample   CAPE_7  1881-01-01     2021-06-01    1686 -0.07   -3.05
##  3 5-Year  Full Sample   CAPE_5  1881-01-01     2021-06-01    1686 -0.065  -2.94
##  4 5-Year  Full Sample   CAPE_3  1881-01-01     2021-06-01    1686 -0.057  -2.46
##  5 5-Year  Full Sample   PE      1881-01-01     2021-06-01    1686 -0.035  -1.37
##  6 5-Year  Full Sample   EWMA_3  1881-01-01     2021-06-01    1686 -0.061  -2.42
##  7 5-Year  Full Sample   EWMA_5  1881-01-01     2021-06-01    1686 -0.066  -2.66
##  8 5-Year  Full Sample   EWMA_7  1881-01-01     2021-06-01    1686 -0.068  -2.78
##  9 5-Year  Full Sample   EWMA_10 1881-01-01     2021-06-01    1686 -0.068  -2.9 
## 10 5-Year  Full Sample   CF_24_… 1881-01-01     2021-06-01    1686 -0.039  -1.53
## 11 5-Year  Full Sample   CF_36_… 1881-01-01     2021-06-01    1686 -0.053  -1.96
## 12 5-Year  Full Sample   Kalman… 1881-01-01     2021-06-01    1686 -0.033  -1.43
## 13 5-Year  Full Sample   Kalman… 1881-01-01     2021-06-01    1686 -0.035  -1.37
## 14 5-Year  Full Sample   HP_144… 1881-01-01     2021-06-01    1686 -0.032  -1.41
## 15 5-Year  Full Sample   HP_129… 1881-01-01     2021-06-01    1686 -0.037  -1.64
## 16 5-Year  Full Sample   Hamilt… 1881-01-01     2021-06-01    1686 -0.048  -2.21
## 17 5-Year  Last 30 Years CAPE_10 1991-07-01     2021-06-01     360 -0.225  -5.41
## 18 5-Year  Last 30 Years CAPE_7  1991-07-01     2021-06-01     360 -0.241  -5.88
## 19 5-Year  Last 30 Years CAPE_5  1991-07-01     2021-06-01     360 -0.24   -4.2 
## 20 5-Year  Last 30 Years CAPE_3  1991-07-01     2021-06-01     360 -0.2    -2.85
## 21 5-Year  Last 30 Years PE      1991-07-01     2021-06-01     360 -0.022  -0.39
## 22 5-Year  Last 30 Years EWMA_3  1991-07-01     2021-06-01     360 -0.224  -2.89
## 23 5-Year  Last 30 Years EWMA_5  1991-07-01     2021-06-01     360 -0.261  -3.99
## 24 5-Year  Last 30 Years EWMA_7  1991-07-01     2021-06-01     360 -0.26   -4.55
## 25 5-Year  Last 30 Years EWMA_10 1991-07-01     2021-06-01     360 -0.251  -4.95
## 26 5-Year  Last 30 Years CF_24_… 1991-07-01     2021-06-01     360 -0.049  -0.61
## 27 5-Year  Last 30 Years CF_36_… 1991-07-01     2021-06-01     360 -0.091  -1.03
## 28 5-Year  Last 30 Years Kalman… 1991-07-01     2021-06-01     360 -0.017  -0.35
## 29 5-Year  Last 30 Years Kalman… 1991-07-01     2021-06-01     360 -0.022  -0.39
## 30 5-Year  Last 30 Years HP_144… 1991-07-01     2021-06-01     360 -0.015  -0.33
## 31 5-Year  Last 30 Years HP_129… 1991-07-01     2021-06-01     360 -0.047  -0.7 
## 32 5-Year  Last 30 Years Hamilt… 1991-07-01     2021-06-01     360 -0.068  -1.48
## 33 10-Year Full Sample   CAPE_10 1881-01-01     2016-06-01    1626 -0.062  -4.91
## 34 10-Year Full Sample   CAPE_7  1881-01-01     2016-06-01    1626 -0.061  -4.64
## 35 10-Year Full Sample   CAPE_5  1881-01-01     2016-06-01    1626 -0.062  -4.58
## 36 10-Year Full Sample   CAPE_3  1881-01-01     2016-06-01    1626 -0.061  -4.14
## 37 10-Year Full Sample   PE      1881-01-01     2016-06-01    1626 -0.05   -2.54
## 38 10-Year Full Sample   EWMA_3  1881-01-01     2016-06-01    1626 -0.066  -4.37
## 39 10-Year Full Sample   EWMA_5  1881-01-01     2016-06-01    1626 -0.066  -4.61
## 40 10-Year Full Sample   EWMA_7  1881-01-01     2016-06-01    1626 -0.066  -4.76
## 41 10-Year Full Sample   EWMA_10 1881-01-01     2016-06-01    1626 -0.065  -4.87
## 42 10-Year Full Sample   CF_24_… 1881-01-01     2016-06-01    1626 -0.057  -2.98
## 43 10-Year Full Sample   CF_36_… 1881-01-01     2016-06-01    1626 -0.059  -2.81
## 44 10-Year Full Sample   Kalman… 1881-01-01     2016-06-01    1626 -0.048  -2.66
## 45 10-Year Full Sample   Kalman… 1881-01-01     2016-06-01    1626 -0.05   -2.54
## 46 10-Year Full Sample   HP_144… 1881-01-01     2016-06-01    1626 -0.047  -2.61
## 47 10-Year Full Sample   HP_129… 1881-01-01     2016-06-01    1626 -0.05   -2.88
## 48 10-Year Full Sample   Hamilt… 1881-01-01     2016-06-01    1626 -0.048  -2.6 
## 49 10-Year Last 30 Years CAPE_10 1986-07-01     2016-06-01     360 -0.149  -9.41
## 50 10-Year Last 30 Years CAPE_7  1986-07-01     2016-06-01     360 -0.157  -9.44
## 51 10-Year Last 30 Years CAPE_5  1986-07-01     2016-06-01     360 -0.168  -7.4 
## 52 10-Year Last 30 Years CAPE_3  1986-07-01     2016-06-01     360 -0.151  -4.04
## 53 10-Year Last 30 Years PE      1986-07-01     2016-06-01     360 -0.053  -1.23
## 54 10-Year Last 30 Years EWMA_3  1986-07-01     2016-06-01     360 -0.182  -7.21
## 55 10-Year Last 30 Years EWMA_5  1986-07-01     2016-06-01     360 -0.186  -9.94
## 56 10-Year Last 30 Years EWMA_7  1986-07-01     2016-06-01     360 -0.176 -10   
## 57 10-Year Last 30 Years EWMA_10 1986-07-01     2016-06-01     360 -0.162  -9.01
## 58 10-Year Last 30 Years CF_24_… 1986-07-01     2016-06-01     360 -0.089  -1.59
## 59 10-Year Last 30 Years CF_36_… 1986-07-01     2016-06-01     360 -0.09   -1.57
## 60 10-Year Last 30 Years Kalman… 1986-07-01     2016-06-01     360 -0.052  -1.22
## 61 10-Year Last 30 Years Kalman… 1986-07-01     2016-06-01     360 -0.053  -1.23
## 62 10-Year Last 30 Years HP_144… 1986-07-01     2016-06-01     360 -0.049  -1.2 
## 63 10-Year Last 30 Years HP_129… 1986-07-01     2016-06-01     360 -0.075  -1.38
## 64 10-Year Last 30 Years Hamilt… 1986-07-01     2016-06-01     360 -0.048  -1.19
## # ℹ 2 more variables: `Hodrick t` <dbl>, R2 <dbl>
write.csv(hodrick_results, "is_hodrick_robustness.csv", row.names = FALSE)