← Catálogo
· Capítulo 14
T14_mST_Script_VaR_ES.R
# ══════════════════════════════════════════════════
# T14 · Series Temporales — Value at Risk y Expected Shortfall
# Abre primero mSeriesTemporales.Rproj en RStudio
# ══════════════════════════════════════════════════
library(tidyverse)
library(rugarch)
pausa <- function(msg = "\n [Pulsa ENTER para continuar...]") {
if (interactive()) { cat(msg); invisible(readline()) }
}
set.seed(2026)
# ── 1. VaR HISTORICO Y NORMAL SOBRE UNA SERIE SIMULADA ─
n <- 6000
r <- rt(n, df = 4) * 0.01
alpha <- 0.01
VaR_hist <- -quantile(r, alpha)
VaR_norm <- -(mean(r) + qnorm(alpha) * sd(r))
cat(sprintf("VaR historico (1%%): %.3f%% | VaR normal (1%%): %.3f%%\n", VaR_hist * 100, VaR_norm * 100))
cat("Con datos t(4) simulados, el VaR historico deberia ser MAYOR que el normal (colas mas gruesas).\n")
pausa()
# ── 2. EXPECTED SHORTFALL ─────────────────────────
ES_hist <- -mean(r[r <= -VaR_hist])
ES_norm <- -(mean(r) - sd(r) * dnorm(qnorm(alpha)) / alpha)
cat(sprintf("ES historico: %.3f%% | ES normal: %.3f%%\n", ES_hist * 100, ES_norm * 100))
cat("El ES siempre debe ser mayor o igual que el VaR al mismo nivel.\n")
pausa()
# ── 3. FUNCIONES DE BACKTESTING: KUPIEC Y CHRISTOFFERSEN ─
kupiec_test <- function(viol, alpha) {
x <- sum(viol); Tt <- length(viol); pihat <- x / Tt
LR <- -2 * ((Tt - x) * log(1 - alpha) + x * log(alpha) -
(Tt - x) * log(1 - pihat) - x * log(pihat))
list(x = x, T = Tt, LR = LR, p = 1 - pchisq(LR, df = 1))
}
christoffersen_test <- function(viol) {
n00 <- n01 <- n10 <- n11 <- 0
for (t in 2:length(viol)) {
if (viol[t - 1] == 0 && viol[t] == 0) n00 <- n00 + 1
if (viol[t - 1] == 0 && viol[t] == 1) n01 <- n01 + 1
if (viol[t - 1] == 1 && viol[t] == 0) n10 <- n10 + 1
if (viol[t - 1] == 1 && viol[t] == 1) n11 <- n11 + 1
}
pi01 <- n01 / (n00 + n01); pi11 <- n11 / (n10 + n11); pi <- (n01 + n11) / (n00 + n01 + n10 + n11)
LL0 <- (n00 + n10) * log(1 - pi) + (n01 + n11) * log(pi)
LL1 <- n00 * log(1 - pi01) + n01 * log(pi01) + n10 * log(1 - pi11) + n11 * log(pi11)
LR_ind <- -2 * (LL0 - LL1)
list(LR = LR_ind, p = 1 - pchisq(LR_ind, df = 1))
}
viol_hist <- as.numeric(r < -VaR_hist)
ku <- kupiec_test(viol_hist, alpha)
ch <- christoffersen_test(viol_hist)
cat(sprintf("Kupiec: LR=%.2f p=%.4f | Christoffersen: LR=%.2f p=%.4f\n", ku$LR, ku$p, ch$LR, ch$p))
cat("Con datos t(4) i.i.d. (sin agrupamiento de volatilidad), ambos contrastes deberian aceptar H0.\n")
# === FIN Script T14 — Value at Risk y Expected Shortfall ===