R/backtest_TSMOM_cop.R

#' backtest_TSMOM_cop
#'
#' @description Note that this function is changes manually in line 50, dependent on which coefficient shall be used
#' @param return log-excess return of the whole period
#' @param backtest_period backtest period
#' @param alpha alpha used for VaR
#' @param m number of simulations
#' @param par_cop parameter fitted copula
#' @param par_dp parameter time-varying parameter
#' @param sigma Calculated volatility used geometric average
#' @param par_coef parameter OLS estimation
#' @param lag used lag as predictor
#'
#' @return future, CI, VaR, time-varying parameter and simulation
#' @export
#'
backtest_TSMOM_cop <- function(return = X_all, backtest_period = 200,
                               alpha = 0.99, m = 200, par_cop, par_dp = cbind(NA, NA),
                               sigma = sig, par_coef = cbind(NA, NA),
                               lag = 3) {
  depen <- numeric(backtest_period)

  future <- matrix(ncol = 1, nrow = backtest_period)
  CI_out <- matrix(ncol = 2, nrow = backtest_period)
  VaR_out <- matrix(ncol = 1, nrow = backtest_period)

  sim_list = list()

  for (i in 0:(backtest_period - 1)) {

    TS <- as.matrix(return[(lag+2):(nrow(return)-backtest_period - i),])
    TS_lag <- as.matrix(return[2:(nrow(return)-backtest_period-lag - i),])
    sigma_1 <- as.matrix(sigma[(lag+1):(nrow(sigma)-backtest_period-1 - i),])
    sigma_lag <- as.matrix(sigma[1:(nrow(sigma)-backtest_period-lag - 1 - i),])

    res <- TS/sigma_1 - par_coef[1,] - par_coef[2,] * TS_lag/sigma_lag

    U_TS <- cbind(sn::pst(res[,1], dp = par_dp[,1]),
                  sn::pst(res[,2], dp = par_dp[,2]))
    colnames(U_TS) <- colnames(TS)

    depen[i+1] <- tail(LL_clayton_sim_cpp(par_cop, U_TS), 1)
    U. <- rCopula(m, copula = claytonCopula(param = depen[i+1], dim = 2))
    Z. <- sapply(1:2, function(j) {sn::qst(U.[,j], dp=par_dp[,j],
                                           tol = 1e-04)})

    ini_fore <- (as.matrix(return[(nrow(return)-backtest_period-lag - 1 - i),]) /
                   as.matrix(sigma[(nrow(sigma)-backtest_period-lag - i),]))

    sim <- Z. + as.numeric(ini_fore) * par_coef[2,]# + par_coef[1,]
    colnames(sim) <- colnames(return)
    Xs. <- rowSums(sim)

    Xs.mean <- mean(Xs.)
    Xs.CI <- quantile(Xs., probs = c(0.025, 0.975))
    alpha <- alpha
    VaR <- quantile(Xs., probs = alpha)

    future[i+1, 1] <- Xs.mean
    CI_out[i+1, ] <- Xs.CI
    VaR_out[i+1, 1] <- VaR

    sim_list[[i+1]] = sim

    print(i)
  }
  return(list(
    forecast = future,
    CI = CI_out,
    VaR = VaR_out,
    depen = depen,
    sim_list = sim_list
  ))
}
3schwartz/SpecialeScrAndFun documentation built on May 4, 2019, 6:29 a.m.