# “GESTIÓN DEL RIESGO DE LIQUIDEZ EN EL SISTEMA BANCARIO DE GUATEMALA EN 
#  CONTEXTOS DE INESTABILIDAD MACROECONÓMICA: APLICACIÓN DE MODELOS LAR Y GARCH"
#  TESIS DE GRADO
#  R studio
#  Luis David Wug Escobar 1297721
# 1. Instalación y carga de librerías
#Cargar las librerías necesarias
library(readxl)
## Warning: package 'readxl' was built under R version 4.4.3
library(xts)
## Warning: package 'xts' was built under R version 4.4.2
## Cargando paquete requerido: zoo
## 
## Adjuntando el paquete: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(tseries)
## Warning: package 'tseries' was built under R version 4.4.2
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(rugarch)
## Warning: package 'rugarch' was built under R version 4.4.3
## Cargando paquete requerido: parallel
## 
## Adjuntando el paquete: 'rugarch'
## The following object is masked from 'package:stats':
## 
##     sigma
library(moments)
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
library(gridExtra)
## Warning: package 'gridExtra' was built under R version 4.4.3
library(extrafont)
## Registering fonts with R
library(scales)
## Warning: package 'scales' was built under R version 4.4.3
library(lubridate)
## 
## Adjuntando el paquete: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.3
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Adjuntando el paquete: 'dplyr'
## The following object is masked from 'package:gridExtra':
## 
##     combine
## The following objects are masked from 'package:xts':
## 
##     first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(zoo)
library(tidyr) 
library(FinTS)  
## Warning: package 'FinTS' was built under R version 4.4.2
library(tibble)
library(xts)
library(readr)
## 
## Adjuntando el paquete: 'readr'
## The following object is masked from 'package:scales':
## 
##     col_factor
library(knitr)
library(kableExtra)
## Warning: package 'kableExtra' was built under R version 4.4.3
## 
## Adjuntando el paquete: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
#Cargar fuentes adicionales
loadfonts(device = "win")
# 2. Ruta del archivo y lectura de datos
ruta_archivo <- "C:\\\\Users\\\\ldesc\\\\Desktop\\\\Universidad\\\\Clases 2025\\\\TESIS 2\\\\BD_TDG_LDWE.xlsx"
#Leer datos desde Excel
datos <- read_excel(ruta_archivo)
#Tabla completa
kable(
head(datos, 193),
format = "html",
caption = "Base de datos de los depósitos Monetarios, de Ahorro y a Plazo del Balance General Condensado Consolidado del Sistema Bancario de Guatemala, del 31 de enero del 2008 al 31 de diciembre del 2023, Cifras en miles de Quetzales"
) |>
kable_styling(
full_width = TRUE,
bootstrap_options = c("striped", "hover", "condensed"),
font_size = 11,
html_font = "Times New Roman"
)
Base de datos de los depósitos Monetarios, de Ahorro y a Plazo del Balance General Condensado Consolidado del Sistema Bancario de Guatemala, del 31 de enero del 2008 al 31 de diciembre del 2023, Cifras en miles de Quetzales
Fecha Depositos_Monetarios Depositos_Ahorro Depositos_Plazo
2008-01-31 32857653 18532054 23737035
2008-02-29 31531649 18698666 23922434
2008-03-31 32384692 18573769 24262472
2008-04-30 31170412 18504258 24564694
2008-05-31 31042161 18362880 25288461
2008-06-30 31667736 18398144 25748910
2008-07-31 31540208 18338776 26618152
2008-08-31 31113962 18349755 27231248
2008-09-30 31509715 18442440 27677024
2008-10-31 32869787 18413061 28064904
2008-11-30 33959954 18457321 28181486
2008-12-31 35870548 18851128 28321640
2009-01-31 37098708 18886376 28661392
2009-02-28 35364736 19104878 29300174
2009-03-31 35845270 19359652 30290574
2009-04-30 35035056 19408953 30950635
2009-05-31 35043398 19424146 31531569
2009-06-30 34992934 19600403 32541373
2009-07-31 35324237 19664312 32836890
2009-08-31 34028043 19793832 32925719
2009-09-30 34227445 19607729 33343771
2009-10-31 35090010 19663955 33366512
2009-11-30 36128788 19666499 33515229
2009-12-31 36157506 20244988 33565834
2010-01-31 37850177 20208305 33678640
2010-02-28 36006666 20079676 34084475
2010-03-31 35382735 20185133 34621384
2010-04-30 35736261 20350058 34919729
2010-05-31 36024394 20806460 35190901
2010-06-30 36306773 21055219 35555436
2010-07-31 36388260 21695905 35452894
2010-08-31 36633490 21989194 35919744
2010-09-30 36373009 21999671 36321473
2010-10-31 37010941 21949342 36430761
2010-11-30 37768694 21999257 36492977
2010-12-31 38811718 22919750 36903993
2011-01-31 39388204 22852380 37404036
2011-02-28 38585481 23059855 37514933
2011-03-31 39621663 23294315 37840201
2011-04-30 40685604 23565993 38143370
2011-05-31 39422960 23722944 38637169
2011-06-30 40494434 24085135 39355470
2011-07-31 40848182 24327740 39590834
2011-08-31 39847123 24496360 40274185
2011-09-30 39696754 24504676 40957250
2011-10-31 40606143 24591691 40598394
2011-11-30 40910709 24745940 40966614
2011-12-31 43552717 25162901 40698432
2012-01-31 43510691 25213558 40694894
2012-02-29 42702156 25634028 41293618
2012-03-31 43390352 25755929 42275908
2012-04-30 42729799 25840153 42526156
2012-05-31 41506152 25790942 43509044
2012-06-30 43099199 25816512 44966686
2012-07-31 42037019 26164166 45453448
2012-08-31 42564433 26791820 46207832
2012-09-30 42307469 26677012 47308358
2012-10-31 43106843 26543922 47619516
2012-11-30 45169442 26129558 47997192
2012-12-31 47540062 26700710 47994217
2013-01-31 46440686 26586960 49024952
2013-02-28 45879917 26869784 49828778
2013-03-31 46303594 27015057 50518787
2013-04-30 47277415 27227063 51513196
2013-05-31 46575986 27855200 52120182
2013-06-30 47896976 27622560 52785607
2013-07-31 46894233 28022476 53510516
2013-08-31 47316455 27936452 53920407
2013-09-30 46813983 28072352 55358094
2013-10-31 46599165 28738893 55428719
2013-11-30 47080904 28216868 55592741
2013-12-31 48686939 28741151 55771154
2014-01-31 48960625 28599961 56350997
2014-02-28 48410884 28893749 56835587
2014-03-31 48944745 29008096 57734654
2014-04-30 50415282 29199386 57880284
2014-05-31 48600146 29090247 58754860
2014-06-30 50067810 30231236 59445279
2014-07-31 49828816 30283023 59706924
2014-08-31 49043333 30456074 60397197
2014-09-30 47768958 30291780 61305687
2014-10-31 48493281 29941647 61310195
2014-11-30 49016152 29893634 61714666
2014-12-31 51001601 30613593 62075577
2015-01-31 52565742 30935555 62502672
2015-02-28 52671952 31952370 63220173
2015-03-31 52995951 32101502 63847486
2015-04-30 54684589 32212241 64397095
2015-05-31 54183683 31713446 66223500
2015-06-30 55400636 32088694 66474026
2015-07-31 54625481 32667713 67817018
2015-08-31 52607122 32717924 68621049
2015-09-30 51910554 32837932 69670222
2015-10-31 52473946 33004471 70871861
2015-11-30 52253289 32994356 70936513
2015-12-31 53979729 33597716 71470341
2016-01-31 54606790 33630187 72377136
2016-02-29 54716969 33912403 73040018
2016-03-31 55421207 34456298 73556059
2016-04-30 56164049 34775789 73826277
2016-05-31 54771884 34817737 74979521
2016-06-30 56058432 35278240 75584201
2016-07-31 56211153 35509206 76419204
2016-08-31 54422310 35644956 77626194
2016-09-30 54830132 35810053 78191703
2016-10-31 55905941 35625714 78558597
2016-11-30 56383482 35924638 78230605
2016-12-31 57885159 36503152 78191200
2017-01-31 58059513 36761195 79214576
2017-02-28 55760267 37114420 79856212
2017-03-31 56440184 37607811 80614720
2017-04-30 58688528 37785165 81127816
2017-05-31 57314644 38134032 81135684
2017-06-30 57829473 38601704 82086488
2017-07-31 58128150 39209329 82222196
2017-08-31 56996672 39406085 82803245
2017-09-30 57470720 39559242 83647947
2017-10-31 58773922 39671454 84738961
2017-11-30 58969607 39805174 84264258
2017-12-31 63078634 40500128 83559297
2018-01-31 61546903 40582596 83909181
2018-02-28 60872351 40997075 84235418
2018-03-31 60584006 41355192 84622087
2018-04-30 61583117 41689834 85578793
2018-05-31 60771342 41978866 85878667
2018-06-30 61608090 42314586 86394272
2018-07-31 62156481 43306959 86772476
2018-08-31 61655422 43497809 87470840
2018-09-30 61148461 43968742 87685645
2018-10-31 62148407 44129177 87899459
2018-11-30 62884689 44302499 87967408
2018-12-31 67442964 45016392 88190085
2019-01-31 66464399 44966905 89468647
2019-02-28 65724645 45341139 89725448
2019-03-31 67197809 46037127 90485712
2019-04-30 69449614 46231089 91331111
2019-05-31 67662337 46749637 92178574
2019-06-30 68745799 47454710 92543649
2019-07-31 68556169 48559005 92843268
2019-08-31 68160823 49158085 93256421
2019-09-30 67804649 49642966 94019192
2019-10-31 68752489 50375569 94528954
2019-11-30 69252719 50371093 94565336
2019-12-31 72397171 51357565 94516572
2020-01-31 72213551 51844241 95181199
2020-02-29 72042038 52317514 95173092
2020-03-31 72520318 52287031 96319456
2020-04-30 73963677 52818355 96122990
2020-05-31 74394624 53931349 96782506
2020-06-30 79480818 55111128 97629382
2020-07-31 79732197 56976005 98190976
2020-08-31 81205563 58274432 98936364
2020-09-30 83482702 59313669 99085173
2020-10-31 86094068 59724436 99875583
2020-11-30 85391983 60682308 100609255
2020-12-31 88425563 61805927 101897773
2021-01-31 89179567 62068517 102107307
2021-02-28 89081992 62437064 102483040
2021-03-31 88131622 62728149 103548678
2021-04-30 90488098 63370966 104107125
2021-05-31 89808390 64353820 104623938
2021-06-30 91451883 65786596 103990562
2021-07-31 92783415 67101807 104514220
2021-08-31 90329293 67760400 105805549
2021-09-30 90475809 68218963 106974058
2021-10-31 92041454 68584886 107370478
2021-11-30 92786892 68937034 107760627
2021-12-31 96619328 70775818 109425749
2022-01-31 96211131 74188354 109624696
2022-02-28 96767242 75072702 109326155
2022-03-31 97947950 76009774 109670289
2022-04-30 99737589 76452078 110295692
2022-05-31 96994787 76858718 111012268
2022-06-30 98495042 77982546 110469754
2022-07-31 99599421 79365518 111586196
2022-08-31 98177456 80449210 111593997
2022-09-30 99210347 80753659 111871926
2022-10-31 101348597 80980520 113604313
2022-11-30 102595042 81306252 114309472
2022-12-31 107526237 83116043 114641057
2023-01-31 106171339 85463194 114449906
2023-02-28 106490370 86131173 115231895
2023-03-31 108909421 86391051 116395157
2023-04-30 110765523 87371953 117088823
2023-05-31 108946480 88236655 118120161
2023-06-30 111460469 89073609 119136246
2023-07-31 111206475 90612627 119548112
2023-08-31 107675092 90546965 120193399
2023-09-30 107949123 90540159 122572072
2023-10-31 108830654 89952986 124262152
2023-11-30 108054075 90524206 125513396
2023-12-31 114148447 91387679 128052457
# 3. Series temporales y métricas descriptivas
DM <- xts(datos$Depositos_Monetarios, order.by = datos$Fecha)
DA <- xts(datos$Depositos_Ahorro, order.by = datos$Fecha)
DP <- xts(datos$Depositos_Plazo, order.by = datos$Fecha)
# 3.1 Índice de liquidez
rtl <- read_excel(ruta_archivo, sheet = "RTL")
anio <- rtl$anio
ratio_raw <- rtl$`Ratio de liquidez`
ratio_pct <- suppressWarnings(parse_number(as.character(ratio_raw)))
ratio_pct <- ifelse(ratio_pct <= 1, ratio_pct * 100, ratio_pct)
par(family = "serif", cex.main = 1.1, cex.lab = 1.1, cex.axis = 1.1, mar = c(4, 4, 4, 2))
plot(anio, ratio_pct, type = "l", lwd = 3, col = "black",
     ylim = c(17, 23),  
     main = "Ratio de liquidez de las instituciones bancarias de Guatemala del año 2008 al 2023",
     xlab = "", ylab = "", xaxt = "n")
axis(1, at = anio, labels = anio)
text(anio, ratio_pct, labels = paste0(round(ratio_pct, 2), "%"), pos = 3, cex = 0.8)
modelo <- lm(ratio_pct ~ anio)
abline(modelo, col = "gray40", lwd = 2)

# 3.2 Volatilidad de los depósitos (12M rodante)
mensual <- datos %>%
  mutate(YearMonth = zoo::as.yearmon(as.Date(Fecha))) %>%
  group_by(YearMonth) %>%
  summarise(DM = last(Depositos_Monetarios),
            DA = last(Depositos_Ahorro),
            DP = last(Depositos_Plazo), .groups = "drop") %>%
  arrange(YearMonth)

vol <- mensual %>%
  mutate(Vol_DM = zoo::rollapply(DM, 12, sd, align="right", fill=NA, na.rm=TRUE),
         Vol_DA = zoo::rollapply(DA, 12, sd, align="right", fill=NA, na.rm=TRUE),
         Vol_DP = zoo::rollapply(DP, 12, sd, align="right", fill=NA, na.rm=TRUE))

idx <- rowSums(is.finite(as.matrix(vol[,c("Vol_DM","Vol_DA","Vol_DP")]))) > 0
x     <- as.Date(vol$YearMonth[idx])
Yk <- as.matrix(vol[idx, c("Vol_DM","Vol_DA","Vol_DP")])         # ya está en miles de Q
yt    <- pretty(c(0, max(Yk, na.rm=TRUE)*1.1), n=6)
ticks <- seq(min(x), max(x), by="1 month")
labs  <- format(ticks, "%b-%Y")

par(family="serif", cex.main=1.1, cex.lab=1.0, cex.axis=0.8, mar=c(7,4,4,2))
matplot(x, Yk, type="l", lwd=2, lty=1, pch=16, col=c("black","gray50","gray"),
        main="Volatilidad mensual de los depósitos monetarios, de ahorro y a plazo del sistema bancario del año 2009 al 2023",
        ylab="Volatilidad (Miles de Quetzales)",
        xaxt="n", yaxt="n", ylim=range(yt))
axis(1, at=ticks, labels=labs, las=2)
axis(2, at=yt, labels=format(yt, big.mark=",", scientific=FALSE))
legend("bottom", inset=c(0,-0.30), xpd=TRUE, horiz=TRUE,
       legend=c("Monetarios","Ahorro","Plazo"),
       col=c("black","gray50","gray"), lty=1, pch=16, cex=0.9, bty="n")

# 4. Verificación de estacionariedad (ADF)
#Función para realizar la Prueba ADF
adf_test <- function(serie) {
  resultado <- adf.test(serie, alternative = "stationary")
  cat("Prueba ADF: p-valor =", resultado$p.value, "\n")
  if (resultado$p.value < 0.05) {
    cat("La serie es estacionaria.\n")
  } else {
    cat("La serie no es estacionaria.\n")
  }
}
#Prueba ADF para cada serie
cat("Resultados para Depósitos Monetarios:\n")
## Resultados para Depósitos Monetarios:
adf_test(DM)
## Warning in adf.test(serie, alternative = "stationary"): p-value greater than printed p-value
## Prueba ADF: p-valor = 0.99 
## La serie no es estacionaria.
cat("Resultados para Depósitos de Ahorro:\n")
## Resultados para Depósitos de Ahorro:
adf_test(DA)
## Warning in adf.test(serie, alternative = "stationary"): p-value greater than printed p-value
## Prueba ADF: p-valor = 0.99 
## La serie no es estacionaria.
cat("Resultados para Depósitos a Plazo:\n")
## Resultados para Depósitos a Plazo:
adf_test(DP)
## Prueba ADF: p-valor = 0.9386744 
## La serie no es estacionaria.
# 5. Transformación a series estacionarias (log-diff)
#Aplicar logaritmo y diferenciación (variaciones logarítmicas)
DM_diff <- diff(log(DM))[-1]
DA_diff <- diff(log(DA))[-1]
DP_diff <- diff(log(DP))[-1]
#Prueba ADF después de la transformación
cat("Resultados para Depósitos Monetarios (transformados):\n")
## Resultados para Depósitos Monetarios (transformados):
adf_test(DM_diff)
## Warning in adf.test(serie, alternative = "stationary"): p-value smaller than printed p-value
## Prueba ADF: p-valor = 0.01 
## La serie es estacionaria.
cat("Resultados para Depósitos de Ahorro (transformados):\n")
## Resultados para Depósitos de Ahorro (transformados):
adf_test(DA_diff)
## Warning in adf.test(serie, alternative = "stationary"): p-value smaller than printed p-value
## Prueba ADF: p-valor = 0.01 
## La serie es estacionaria.
cat("Resultados para Depósitos a Plazo (transformados):\n")
## Resultados para Depósitos a Plazo (transformados):
adf_test(DP_diff)
## Warning in adf.test(serie, alternative = "stationary"): p-value smaller than printed p-value
## Prueba ADF: p-valor = 0.01 
## La serie es estacionaria.
#Función para aplicar prueba ARCH
arch_test <- function(serie, nombre_serie) {
  cat("\nPrueba ARCH-LM para", nombre_serie, ":\n")
  resultado <- ArchTest(serie, lags = 12)
  print(resultado)
  if (resultado$p.value < 0.05) {
    cat("→ Existe heterocedasticidad condicional. Se puede aplicar GARCH.\n")
  } else {
    cat("→ No se detecta heterocedasticidad. GARCH no es necesario.\n")
  }
}
#Aplicar prueba para cada serie transformada
arch_test(DM_diff, "Depósitos Monetarios")
## 
## Prueba ARCH-LM para Depósitos Monetarios :
## 
##  ARCH LM-test; Null hypothesis: no ARCH effects
## 
## data:  serie
## Chi-squared = 40.846, df = 12, p-value = 5.199e-05
## 
## → Existe heterocedasticidad condicional. Se puede aplicar GARCH.
arch_test(DA_diff, "Depósitos de Ahorro")
## 
## Prueba ARCH-LM para Depósitos de Ahorro :
## 
##  ARCH LM-test; Null hypothesis: no ARCH effects
## 
## data:  serie
## Chi-squared = 21.056, df = 12, p-value = 0.04956
## 
## → Existe heterocedasticidad condicional. Se puede aplicar GARCH.
arch_test(DP_diff, "Depósitos a Plazo")
## 
## Prueba ARCH-LM para Depósitos a Plazo :
## 
##  ARCH LM-test; Null hypothesis: no ARCH effects
## 
## data:  serie
## Chi-squared = 57.496, df = 12, p-value = 6.432e-08
## 
## → Existe heterocedasticidad condicional. Se puede aplicar GARCH.
#Graficos
par(family = "serif", cex.main = 1.1, cex.lab = 1.1, cex.axis = 1.1)
plot(DM_diff)

plot(DA_diff)

plot(DP_diff)

# 6. Supuestos del modelo GARCH
# 6.1 Nula observabilidad directa de la volatilidad
# Debido a que la volatilidad no se observa directamente, sino que se infiere 
# a partir de los datos, lo cual es una premisa fundamental del modelo, este 
# supuesto se cumple con el desarrollo de este. 
# 6.2 Aglomeración de la volatilidad (variaciones)
# Calcular variaciones logarítmicas
DM_variaciones <- diff(log(DM))
DA_variaciones <- diff(log(DA))
DP_variaciones <- diff(log(DP))
#Eliminar NA
DM_variaciones <- na.omit(DM_variaciones)
DA_variaciones <- na.omit(DA_variaciones)
DP_variaciones <- na.omit(DP_variaciones)
#Crear data.frame completo para cada serie
df_DM <- data.frame(Fecha = index(DM_variaciones),
                    Variacion = as.numeric(DM_variaciones),
                    Serie = "Depósitos Monetarios")
df_DA <- data.frame(Fecha = index(DA_variaciones),
                    Variacion = as.numeric(DA_variaciones),
                    Serie = "Depósitos de Ahorro")
df_DP <- data.frame(Fecha = index(DP_variaciones),
                    Variacion = as.numeric(DP_variaciones),
                    Serie = "Depósitos a Plazo")
#Filtrar desde 2009 hasta 2023
df_DM <- df_DM %>% filter(year(Fecha) >= 2009 & year(Fecha) <= 2023)
df_DA <- df_DA %>% filter(year(Fecha) >= 2009 & year(Fecha) <= 2023)
df_DP <- df_DP %>% filter(year(Fecha) >= 2009 & year(Fecha) <= 2023)
#Gráfico de variaciones
ggplot(df_DM, aes(x = Fecha, y = Variacion)) +
  geom_line(color = "black") +
  labs(title = "Variaciones logarítmicas mensuales - Depósitos Monetarios (2009–2023)",
       x = "Fecha", y = "Variaciones logarítmicas") +
  theme_minimal(base_family = "serif", base_size = 11) +
  theme(plot.title = element_text(face = "bold", hjust = 0.5))

ggplot(df_DA, aes(x = Fecha, y = Variacion)) +
  geom_line(color = "black") +
  labs(title = "Variaciones logarítmicas mensuales - Depósitos de Ahorro (2009–2023)",
       x = "Fecha", y = "Variaciones logarítmicas") +
  theme_minimal(base_family = "serif", base_size = 11) +
  theme(plot.title = element_text(face = "bold", hjust = 0.5))

ggplot(df_DP, aes(x = Fecha, y = Variacion)) +
  geom_line(color = "black") +
  labs(title = "Variaciones logarítmicas mensuales - Depósitos a Plazo (2009–2023)",
       x = "Fecha", y = "Variaciones logarítmicas") +
  theme_minimal(base_family = "serif", base_size = 11) +
  theme(plot.title = element_text(face = "bold", hjust = 0.5))

# 6.3 Reversión a la media (ACF de la varianza condicional)
# Para validar el supuesto de reversión a la media se realizan las pruebas ACF
# con el fin de determinar la autocorrelación de la varianza condicional de las
# variaciones para cada tipo de depósito. 
#Verificación de estructura de las series
print(str(DM_diff))  
## An xts object on 2008-02-29 / 2023-12-31 containing: 
##   Data:    double [191, 1]
##   Index:   POSIXct,POSIXt [191] (TZ: "UTC")
## NULL
print(head(DM_diff))
## Warning: object timezone ('UTC') is different from system timezone ('')
##   NOTE: set 'options(xts_check_TZ = FALSE)' to disable this warning
##     This note is displayed once per session
##                    [,1]
## 2008-02-29 -0.041192914
## 2008-03-31  0.026694070
## 2008-04-30 -0.038216530
## 2008-05-31 -0.004122999
## 2008-06-30  0.019952058
## 2008-07-31 -0.004035194
#Conversión de las series a formato 'ts'
if (.Platform$OS.type == "windows") {
  if ("extrafont" %in% rownames(installed.packages())) {
    extrafont::loadfonts(device = "win", quiet = TRUE)
  }
  suppressWarnings(
    windowsFonts("Times New Roman" = windowsFont("Times New Roman"))
  )
}
.op <- par(
  family   = "Times New Roman",
  cex.main = 1.1,  # títulos ~11 pt
  cex.lab  = 1.1,  # ejes ~11 pt
  cex.axis = 1.1   # marcas de eje ~11 pt
)
print(str(DM_diff)); print(head(DM_diff))
## An xts object on 2008-02-29 / 2023-12-31 containing: 
##   Data:    double [191, 1]
##   Index:   POSIXct,POSIXt [191] (TZ: "UTC")
## NULL
## Warning: object timezone ('UTC') is different from system timezone ('')
##                    [,1]
## 2008-02-29 -0.041192914
## 2008-03-31  0.026694070
## 2008-04-30 -0.038216530
## 2008-05-31 -0.004122999
## 2008-06-30  0.019952058
## 2008-07-31 -0.004035194
DM_diff_ts <- ts(as.numeric(DM_diff), start = c(2008, 2), frequency = 12)
DA_diff_ts <- ts(as.numeric(DA_diff), start = c(2008, 2), frequency = 12)
DP_diff_ts <- ts(as.numeric(DP_diff), start = c(2008, 2), frequency = 12)
#Prueba de autocorrelación con estructura correcta
par(mfrow=c(1,1))
acf(DM_diff_ts^2, main="Autocorrelación de la Varianza Condicional (Depósitos Monetarios)")

acf(DA_diff_ts^2, main="Autocorrelación de la Varianza Condicional (Depósitos de Ahorro)")

acf(DP_diff_ts^2, main="Autocorrelación de la Varianza Condicional (Depósitos a Plazo)")

# 6.4 Persistencia (Ljung–Box en residuos al cuadrado)
# El supuesto de persistencia de la volatilidad en el modelo GARCH establece que
# los choques en la volatilidad tienen efectos prolongados en el tiempo, por 
# lo tanto, la volatilidad en un período determinado influye en la volatilidad 
# futura. Para evaluar este supuesto, se ha realizado la Prueba de Ljung-Box 
# sobre los residuos al cuadrado. La prueba cuenta las siguientes hipótesis, 
# para verificar su validez.

# Prueba de Ljung-Box sobre los residuos al cuadrado
Box_test <- Box.test(DM_diff^2, lag = 10, type = "Ljung-Box")
cat("Prueba de Ljung-Box: p-valor =", Box_test$p.value, "\n")
## Prueba de Ljung-Box: p-valor = 0.09451936
Box_test <- Box.test(DA_diff^2, lag = 10, type = "Ljung-Box")
cat("Prueba de Ljung-Box: p-valor =", Box_test$p.value, "\n")
## Prueba de Ljung-Box: p-valor = 0.04883461
Box_test <- Box.test(DP_diff^2, lag = 10, type = "Ljung-Box")
cat("Prueba de Ljung-Box: p-valor =", Box_test$p.value, "\n")
## Prueba de Ljung-Box: p-valor = 6.328271e-15
# 6.5 Estructura de la varianza condicional (α y β)
# Para validar este supuesto para los 3 tipos de depósitos se analizaron las 
# variables Alpha y Beta para evaluar su impacto en los choques recientes
# y la persistencia de la volatilidad. 
DM_diff <- diff(log(DM))[-1]
DA_diff <- diff(log(DA))[-1]
DP_diff <- diff(log(DP))[-1]
spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1,1)), mean.model = list(armaOrder = c(0,0)))
fit <- ugarchfit(spec, data = DM_diff)
show(fit)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error    t value Pr(>|t|)
## mu      0.006607    0.001637 4.0369e+00 0.000054
## omega   0.000000    0.000002 2.6021e-02 0.979241
## alpha1  0.000000    0.000053 1.9800e-04 0.999842
## beta1   0.999000    0.000067 1.4978e+04 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error    t value Pr(>|t|)
## mu      0.006607    0.001370 4.8216e+00 0.000001
## omega   0.000000    0.000005 8.6290e-03 0.993115
## alpha1  0.000000    0.000064 1.6600e-04 0.999868
## beta1   0.999000    0.000033 3.0542e+04 0.000000
## 
## LogLikelihood : 452.2469 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -4.6937
## Bayes        -4.6256
## Shibata      -4.6945
## Hannan-Quinn -4.6661
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      3.312 0.06878
## Lag[2*(p+q)+(p+q)-1][2]     3.758 0.08762
## Lag[4*(p+q)+(p+q)-1][5]     7.661 0.03575
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.5834  0.4450
## Lag[2*(p+q)+(p+q)-1][5]    3.1385  0.3823
## Lag[4*(p+q)+(p+q)-1][9]    4.9458  0.4374
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]     3.180 0.500 2.000 0.07454
## ARCH Lag[5]     4.354 1.440 1.667 0.14459
## ARCH Lag[7]     4.913 2.315 1.543 0.23348
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  24.9244
## Individual Statistics:              
## mu     0.11513
## omega  4.59218
## alpha1 0.03023
## beta1  0.03093
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value    prob sig
## Sign Bias           0.7171 0.47421    
## Negative Sign Bias  2.2385 0.02637  **
## Positive Sign Bias  0.5882 0.55708    
## Joint Effect        7.8841 0.04847  **
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     16.64       0.6140
## 2    30     17.12       0.9604
## 3    40     30.78       0.8234
## 4    50     43.29       0.7028
## 
## 
## Elapsed time : 0.09919786
spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1,1)), mean.model = list(armaOrder = c(0,0)))
fit <- ugarchfit(spec, data = DA_diff)
show(fit)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error   t value Pr(>|t|)
## mu      0.008571    0.000442 19.393320 0.000000
## omega   0.000071    0.000063  1.135393 0.256211
## alpha1  0.348910    0.159489  2.187670 0.028694
## beta1   0.000001    0.590440  0.000001 0.999999
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.008571    0.001629   5.2625  0.00000
## omega   0.000071    0.000180   0.3943  0.69336
## alpha1  0.348910    0.221753   1.5734  0.11562
## beta1   0.000001    1.652445   0.0000  1.00000
## 
## LogLikelihood : 612.4126 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.3708
## Bayes        -6.3027
## Shibata      -6.3717
## Hannan-Quinn -6.3432
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.7635  0.3822
## Lag[2*(p+q)+(p+q)-1][2]    1.0413  0.4850
## Lag[4*(p+q)+(p+q)-1][5]    5.4496  0.1209
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      0.176  0.6748
## Lag[2*(p+q)+(p+q)-1][5]     2.259  0.5586
## Lag[4*(p+q)+(p+q)-1][9]     5.835  0.3176
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.5524 0.500 2.000 0.45736
## ARCH Lag[5]    4.9538 1.440 1.667 0.10532
## ARCH Lag[7]    6.8151 2.315 1.543 0.09515
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  2.1438
## Individual Statistics:              
## mu     0.40782
## omega  0.57109
## alpha1 0.05027
## beta1  0.58634
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           0.6656 0.5065    
## Negative Sign Bias  0.5081 0.6120    
## Positive Sign Bias  0.1034 0.9178    
## Joint Effect        0.5242 0.9135    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     26.91      0.10687
## 2    30     43.50      0.04088
## 3    40     58.84      0.02156
## 4    50     71.57      0.01940
## 
## 
## Elapsed time : 0.177444
spec <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1,1)), mean.model = list(armaOrder = c(0,0)))
fit <- ugarchfit(spec, data = DP_diff)
show(fit)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.007621    0.000568  13.4207 0.000000
## omega   0.000007    0.000001  13.4014 0.000000
## alpha1  0.128700    0.036177   3.5575 0.000374
## beta1   0.740772    0.047050  15.7443 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.007621    0.000853   8.9315 0.000000
## omega   0.000007    0.000001  12.4552 0.000000
## alpha1  0.128700    0.036243   3.5510 0.000384
## beta1   0.740772    0.059186  12.5160 0.000000
## 
## LogLikelihood : 666.3505 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.9356
## Bayes        -6.8675
## Shibata      -6.9365
## Hannan-Quinn -6.9080
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic   p-value
## Lag[1]                      8.546 0.0034626
## Lag[2*(p+q)+(p+q)-1][2]    11.624 0.0007120
## Lag[4*(p+q)+(p+q)-1][5]    19.605 0.0000249
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                   0.007455  0.9312
## Lag[2*(p+q)+(p+q)-1][5]  1.187864  0.8159
## Lag[4*(p+q)+(p+q)-1][9]  2.248538  0.8733
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]   0.05126 0.500 2.000  0.8209
## ARCH Lag[5]   1.13270 1.440 1.667  0.6940
## ARCH Lag[7]   1.36991 2.315 1.543  0.8471
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  6.9435
## Individual Statistics:             
## mu     1.9838
## omega  1.1161
## alpha1 0.5105
## beta1  0.3264
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           0.9183 0.3597    
## Negative Sign Bias  0.3812 0.7035    
## Positive Sign Bias  0.2336 0.8156    
## Joint Effect        4.1968 0.2410    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     14.34       0.7635
## 2    30     26.54       0.5965
## 3    40     39.99       0.4258
## 4    50     39.63       0.8280
## 
## 
## Elapsed time : 0.1492898
# 6.6 Innovaciones con media cero y varianza condicional
# Según este supuesto, los residuos deben de tener una media cercana a cero, 
# para indicar que no hay sesgo en la serie de innovaciones, para validarlo, 
# se realizaron los histogramas con los residuos resultantes del modelo GARCH 
# (1,1) de los tres tipos de depósitos: 
# Función para ajustar un modelo GARCH(1,1) y extraer los residuos
ajustar_garch <- function(data, nombre, tipo_letra = "serif", tamano_fuente = 11) {
  #Ajustar el modelo GARCH(1,1)
  spec <- ugarchspec(
    variance.model = list(model = "sGARCH", garchOrder = c(1,1)),
    mean.model = list(armaOrder = c(0,0)),
    distribution.model = "norm"
  )
  fit <- ugarchfit(spec, data = data)
  print(fit)
  #Extraer residuos estandarizados como vector numérico
  residuos_xts <- residuals(fit, standardize = TRUE)
  residuos <- as.numeric(na.omit(residuos_xts))
  #Configurar fuente y tamaño de letra para la ventana gráfica
  par(family = tipo_letra, cex.main = 1.1, cex.lab = 1.1, cex.axis = 1.1, cex = tamano_fuente / 10)
  #Graficar histograma
  hist(residuos, breaks = 30, probability = TRUE,
       main = paste("Histograma de residuos -", nombre),
       col = "gray", border = "black", xlab = "Residuos estandarizados",
       cex.main = 1.2, cex.lab = 1, cex.axis = 1)
  lines(density(residuos), col = "red", lwd = 2)
  #Pruebas estadísticas
  cat("\nResultados para", nombre, "\n")
  print(shapiro.test(residuos))
  print(Box.test(residuos, lag = 10, type = "Ljung-Box"))
  print(Box.test(residuos^2, lag = 10, type = "Ljung-Box"))
}
#Aplicar a cada tipo de depósito
ajustar_garch(DM_diff, "Depósitos Monetarios")
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error    t value Pr(>|t|)
## mu      0.006607    0.001637 4.0369e+00 0.000054
## omega   0.000000    0.000002 2.6021e-02 0.979241
## alpha1  0.000000    0.000053 1.9800e-04 0.999842
## beta1   0.999000    0.000067 1.4978e+04 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error    t value Pr(>|t|)
## mu      0.006607    0.001370 4.8216e+00 0.000001
## omega   0.000000    0.000005 8.6290e-03 0.993115
## alpha1  0.000000    0.000064 1.6600e-04 0.999868
## beta1   0.999000    0.000033 3.0542e+04 0.000000
## 
## LogLikelihood : 452.2469 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -4.6937
## Bayes        -4.6256
## Shibata      -4.6945
## Hannan-Quinn -4.6661
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      3.312 0.06878
## Lag[2*(p+q)+(p+q)-1][2]     3.758 0.08762
## Lag[4*(p+q)+(p+q)-1][5]     7.661 0.03575
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.5834  0.4450
## Lag[2*(p+q)+(p+q)-1][5]    3.1385  0.3823
## Lag[4*(p+q)+(p+q)-1][9]    4.9458  0.4374
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]     3.180 0.500 2.000 0.07454
## ARCH Lag[5]     4.354 1.440 1.667 0.14459
## ARCH Lag[7]     4.913 2.315 1.543 0.23348
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  24.9244
## Individual Statistics:              
## mu     0.11513
## omega  4.59218
## alpha1 0.03023
## beta1  0.03093
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value    prob sig
## Sign Bias           0.7171 0.47421    
## Negative Sign Bias  2.2385 0.02637  **
## Positive Sign Bias  0.5882 0.55708    
## Joint Effect        7.8841 0.04847  **
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     16.64       0.6140
## 2    30     17.12       0.9604
## 3    40     30.78       0.8234
## 4    50     43.29       0.7028
## 
## 
## Elapsed time : 0.080302

## 
## Resultados para Depósitos Monetarios 
## 
##  Shapiro-Wilk normality test
## 
## data:  residuos
## W = 0.99218, p-value = 0.3966
## 
## 
##  Box-Ljung test
## 
## data:  residuos
## X-squared = 50.42, df = 10, p-value = 2.234e-07
## 
## 
##  Box-Ljung test
## 
## data:  residuos^2
## X-squared = 8.8402, df = 10, p-value = 0.5473
ajustar_garch(DA_diff, "Depósitos de Ahorro")
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error   t value Pr(>|t|)
## mu      0.008571    0.000442 19.393320 0.000000
## omega   0.000071    0.000063  1.135393 0.256211
## alpha1  0.348910    0.159489  2.187670 0.028694
## beta1   0.000001    0.590440  0.000001 0.999999
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.008571    0.001629   5.2625  0.00000
## omega   0.000071    0.000180   0.3943  0.69336
## alpha1  0.348910    0.221753   1.5734  0.11562
## beta1   0.000001    1.652445   0.0000  1.00000
## 
## LogLikelihood : 612.4126 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.3708
## Bayes        -6.3027
## Shibata      -6.3717
## Hannan-Quinn -6.3432
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.7635  0.3822
## Lag[2*(p+q)+(p+q)-1][2]    1.0413  0.4850
## Lag[4*(p+q)+(p+q)-1][5]    5.4496  0.1209
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      0.176  0.6748
## Lag[2*(p+q)+(p+q)-1][5]     2.259  0.5586
## Lag[4*(p+q)+(p+q)-1][9]     5.835  0.3176
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.5524 0.500 2.000 0.45736
## ARCH Lag[5]    4.9538 1.440 1.667 0.10532
## ARCH Lag[7]    6.8151 2.315 1.543 0.09515
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  2.1438
## Individual Statistics:              
## mu     0.40782
## omega  0.57109
## alpha1 0.05027
## beta1  0.58634
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           0.6656 0.5065    
## Negative Sign Bias  0.5081 0.6120    
## Positive Sign Bias  0.1034 0.9178    
## Joint Effect        0.5242 0.9135    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     26.91      0.10687
## 2    30     43.50      0.04088
## 3    40     58.84      0.02156
## 4    50     71.57      0.01940
## 
## 
## Elapsed time : 0.1346462

## 
## Resultados para Depósitos de Ahorro 
## 
##  Shapiro-Wilk normality test
## 
## data:  residuos
## W = 0.9748, p-value = 0.001601
## 
## 
##  Box-Ljung test
## 
## data:  residuos
## X-squared = 21.615, df = 10, p-value = 0.01719
## 
## 
##  Box-Ljung test
## 
## data:  residuos^2
## X-squared = 11.79, df = 10, p-value = 0.2994
ajustar_garch(DP_diff, "Depósitos a Plazo")
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.007621    0.000568  13.4207 0.000000
## omega   0.000007    0.000001  13.4014 0.000000
## alpha1  0.128700    0.036177   3.5575 0.000374
## beta1   0.740772    0.047050  15.7443 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.007621    0.000853   8.9315 0.000000
## omega   0.000007    0.000001  12.4552 0.000000
## alpha1  0.128700    0.036243   3.5510 0.000384
## beta1   0.740772    0.059186  12.5160 0.000000
## 
## LogLikelihood : 666.3505 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.9356
## Bayes        -6.8675
## Shibata      -6.9365
## Hannan-Quinn -6.9080
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic   p-value
## Lag[1]                      8.546 0.0034626
## Lag[2*(p+q)+(p+q)-1][2]    11.624 0.0007120
## Lag[4*(p+q)+(p+q)-1][5]    19.605 0.0000249
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                   0.007455  0.9312
## Lag[2*(p+q)+(p+q)-1][5]  1.187864  0.8159
## Lag[4*(p+q)+(p+q)-1][9]  2.248538  0.8733
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]   0.05126 0.500 2.000  0.8209
## ARCH Lag[5]   1.13270 1.440 1.667  0.6940
## ARCH Lag[7]   1.36991 2.315 1.543  0.8471
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  6.9435
## Individual Statistics:             
## mu     1.9838
## omega  1.1161
## alpha1 0.5105
## beta1  0.3264
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           0.9183 0.3597    
## Negative Sign Bias  0.3812 0.7035    
## Positive Sign Bias  0.2336 0.8156    
## Joint Effect        4.1968 0.2410    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     14.34       0.7635
## 2    30     26.54       0.5965
## 3    40     39.99       0.4258
## 4    50     39.63       0.8280
## 
## 
## Elapsed time : 0.385993

## 
## Resultados para Depósitos a Plazo 
## 
##  Shapiro-Wilk normality test
## 
## data:  residuos
## W = 0.9839, p-value = 0.02743
## 
## 
##  Box-Ljung test
## 
## data:  residuos
## X-squared = 43.034, df = 10, p-value = 4.904e-06
## 
## 
##  Box-Ljung test
## 
## data:  residuos^2
## X-squared = 4.7668, df = 10, p-value = 0.9062
# 6.7 Colas pesadas (kurtosis y Jarque–Bera)
#Curtosis y Prueba de Jarque-Bera
curtosis_val <- kurtosis(DM_diff, na.rm = TRUE)
jarque_bera_test <- jarque.bera.test(DA_diff)
cat("Curtosis de la serie: ", curtosis_val, "\n")
## Curtosis de la serie:  3.138453
cat("Prueba de Jarque-Bera: p-valor =", jarque_bera_test$p.value, "\n")
## Prueba de Jarque-Bera: p-valor = 6.532677e-07
curtosis_val <- kurtosis(DA_diff, na.rm = TRUE)
jarque_bera_test <- jarque.bera.test(DA_diff)
cat("Curtosis de la serie: ", curtosis_val, "\n")
## Curtosis de la serie:  4.429045
cat("Prueba de Jarque-Bera: p-valor =", jarque_bera_test$p.value, "\n")
## Prueba de Jarque-Bera: p-valor = 6.532677e-07
curtosis_val <- kurtosis(DP_diff, na.rm = TRUE)
jarque_bera_test <- jarque.bera.test(DA_diff)
cat("Curtosis de la serie: ", curtosis_val, "\n")
## Curtosis de la serie:  4.052304
cat("Prueba de Jarque-Bera: p-valor =", jarque_bera_test$p.value, "\n")
## Prueba de Jarque-Bera: p-valor = 6.532677e-07
# 7. Modelos GARCH
# 7.1 Ajuste GARCH(1,1) por serie
#Especificación del modelo GARCH(1,1)
especificacion_garch <- ugarchspec(
  variance.model = list(model = "sGARCH", garchOrder = c(1,1)),
  mean.model     = list(armaOrder = c(0,0), include.mean = TRUE),
  distribution.model = "norm" 
)
#Función para ajustar GARCH y mostrar resumen
ajustar_garch <- function(serie, nombre_serie) {
  cat("\n---------------------------------------\n")
  cat("Ajuste GARCH(1,1) para", nombre_serie, "\n")
  cat("---------------------------------------\n")
  
  modelo <- ugarchfit(spec = especificacion_garch, data = serie)
  show(modelo)
  
  return(modelo)
}
#Ajustar modelos para cada serie
fit_DM <- ajustar_garch(DM_diff, "Depósitos Monetarios")
## 
## ---------------------------------------
## Ajuste GARCH(1,1) para Depósitos Monetarios 
## ---------------------------------------
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error    t value Pr(>|t|)
## mu      0.006607    0.001637 4.0369e+00 0.000054
## omega   0.000000    0.000002 2.6021e-02 0.979241
## alpha1  0.000000    0.000053 1.9800e-04 0.999842
## beta1   0.999000    0.000067 1.4978e+04 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error    t value Pr(>|t|)
## mu      0.006607    0.001370 4.8216e+00 0.000001
## omega   0.000000    0.000005 8.6290e-03 0.993115
## alpha1  0.000000    0.000064 1.6600e-04 0.999868
## beta1   0.999000    0.000033 3.0542e+04 0.000000
## 
## LogLikelihood : 452.2469 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -4.6937
## Bayes        -4.6256
## Shibata      -4.6945
## Hannan-Quinn -4.6661
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      3.312 0.06878
## Lag[2*(p+q)+(p+q)-1][2]     3.758 0.08762
## Lag[4*(p+q)+(p+q)-1][5]     7.661 0.03575
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.5834  0.4450
## Lag[2*(p+q)+(p+q)-1][5]    3.1385  0.3823
## Lag[4*(p+q)+(p+q)-1][9]    4.9458  0.4374
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]     3.180 0.500 2.000 0.07454
## ARCH Lag[5]     4.354 1.440 1.667 0.14459
## ARCH Lag[7]     4.913 2.315 1.543 0.23348
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  24.9244
## Individual Statistics:              
## mu     0.11513
## omega  4.59218
## alpha1 0.03023
## beta1  0.03093
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value    prob sig
## Sign Bias           0.7171 0.47421    
## Negative Sign Bias  2.2385 0.02637  **
## Positive Sign Bias  0.5882 0.55708    
## Joint Effect        7.8841 0.04847  **
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     16.64       0.6140
## 2    30     17.12       0.9604
## 3    40     30.78       0.8234
## 4    50     43.29       0.7028
## 
## 
## Elapsed time : 0.08955789
fit_DA <- ajustar_garch(DA_diff, "Depósitos de Ahorro")
## 
## ---------------------------------------
## Ajuste GARCH(1,1) para Depósitos de Ahorro 
## ---------------------------------------
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error   t value Pr(>|t|)
## mu      0.008571    0.000442 19.393320 0.000000
## omega   0.000071    0.000063  1.135393 0.256211
## alpha1  0.348910    0.159489  2.187670 0.028694
## beta1   0.000001    0.590440  0.000001 0.999999
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.008571    0.001629   5.2625  0.00000
## omega   0.000071    0.000180   0.3943  0.69336
## alpha1  0.348910    0.221753   1.5734  0.11562
## beta1   0.000001    1.652445   0.0000  1.00000
## 
## LogLikelihood : 612.4126 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.3708
## Bayes        -6.3027
## Shibata      -6.3717
## Hannan-Quinn -6.3432
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.7635  0.3822
## Lag[2*(p+q)+(p+q)-1][2]    1.0413  0.4850
## Lag[4*(p+q)+(p+q)-1][5]    5.4496  0.1209
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      0.176  0.6748
## Lag[2*(p+q)+(p+q)-1][5]     2.259  0.5586
## Lag[4*(p+q)+(p+q)-1][9]     5.835  0.3176
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.5524 0.500 2.000 0.45736
## ARCH Lag[5]    4.9538 1.440 1.667 0.10532
## ARCH Lag[7]    6.8151 2.315 1.543 0.09515
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  2.1438
## Individual Statistics:              
## mu     0.40782
## omega  0.57109
## alpha1 0.05027
## beta1  0.58634
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           0.6656 0.5065    
## Negative Sign Bias  0.5081 0.6120    
## Positive Sign Bias  0.1034 0.9178    
## Joint Effect        0.5242 0.9135    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     26.91      0.10687
## 2    30     43.50      0.04088
## 3    40     58.84      0.02156
## 4    50     71.57      0.01940
## 
## 
## Elapsed time : 0.1371191
fit_DP <- ajustar_garch(DP_diff, "Depósitos a Plazo")
## 
## ---------------------------------------
## Ajuste GARCH(1,1) para Depósitos a Plazo 
## ---------------------------------------
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.007621    0.000568  13.4207 0.000000
## omega   0.000007    0.000001  13.4014 0.000000
## alpha1  0.128700    0.036177   3.5575 0.000374
## beta1   0.740772    0.047050  15.7443 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.007621    0.000853   8.9315 0.000000
## omega   0.000007    0.000001  12.4552 0.000000
## alpha1  0.128700    0.036243   3.5510 0.000384
## beta1   0.740772    0.059186  12.5160 0.000000
## 
## LogLikelihood : 666.3505 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.9356
## Bayes        -6.8675
## Shibata      -6.9365
## Hannan-Quinn -6.9080
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic   p-value
## Lag[1]                      8.546 0.0034626
## Lag[2*(p+q)+(p+q)-1][2]    11.624 0.0007120
## Lag[4*(p+q)+(p+q)-1][5]    19.605 0.0000249
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                   0.007455  0.9312
## Lag[2*(p+q)+(p+q)-1][5]  1.187864  0.8159
## Lag[4*(p+q)+(p+q)-1][9]  2.248538  0.8733
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]   0.05126 0.500 2.000  0.8209
## ARCH Lag[5]   1.13270 1.440 1.667  0.6940
## ARCH Lag[7]   1.36991 2.315 1.543  0.8471
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  6.9435
## Individual Statistics:             
## mu     1.9838
## omega  1.1161
## alpha1 0.5105
## beta1  0.3264
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           0.9183 0.3597    
## Negative Sign Bias  0.3812 0.7035    
## Positive Sign Bias  0.2336 0.8156    
## Joint Effect        4.1968 0.2410    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     14.34       0.7635
## 2    30     26.54       0.5965
## 3    40     39.99       0.4258
## 4    50     39.63       0.8280
## 
## 
## Elapsed time : 0.1274989
# 7.2 Gráfico de volatilidad (σ) por serie
#Configurar fuente Times New Roman y tamaño 11
par(family = "serif", cex.main = 1.1, cex.lab = 1.1, cex.axis = 1.1)
plot(sigma(fit_DM), type="l", col="black", main="Volatilidad - Depósitos Monetarios", 
     ylab="Volatilidad", xlab="Tiempo")

plot(sigma(fit_DA), type="l", col="black", main="Volatilidad - Depósitos de Ahorro", 
     ylab="Volatilidad", xlab="Tiempo")

plot(sigma(fit_DP), type="l", col="black", main="Volatilidad - Depósitos a Plazo", 
     ylab="Volatilidad", xlab="Tiempo")

# 8. Simulación de estrés
# 8.1 Función para simular una serie de variaciones GARCH con shock puntual 
sim_garch <- function(fit, shocks) {
  sim_spec <- getspec(fit)
  #Extraer parámetros del modelo ajustado
  params <- as.list(coef(fit))
  #Asignar los parámetros al modelo de simulación
  setfixed(sim_spec) <- params
  #Simular variaciones (12 meses útiles + 50 burn-in)
  sim_series <- ugarchpath(spec = sim_spec, n.sim = 12, n.start = 50)
  sim_vars <- as.numeric(fitted(sim_series))  # variaciones simuladas (media condicional)
  #Aplicar shock en el primer mes
  sim_vars_stress <- sim_vars
  sim_vars_stress[1] <- sim_vars[1] + shocks  # shock positivo
  return(sim_vars_stress)
}
# 8.2 Función para ajustar y mostrar resumen del modelo GARCH
ajustar_garch <- function(serie_xts, nombre) {
  spec <- ugarchspec(
    variance.model = list(model = "sGARCH", garchOrder = c(1, 1)),
    mean.model = list(armaOrder = c(0, 0)),
    distribution.model = "norm"
  )
  fit <- ugarchfit(spec, data = serie_xts, solver = "hybrid")  # más robusto
  cat("\n*---------------------------------*\n")
  cat(paste("* GARCH Model Fit for", nombre, "*\n"))
  cat("*---------------------------------*\n\n")
  show(fit)
}
#Semilla para reproducibilidad
set.seed(123)
shock_recesion <- 0.05  # Shock inicial
# 8.3 Simulaciones de variaciones con shock para 1 año (12 meses)
sim_DM <- sim_garch(fit_DM, shock_recesion)
sim_DA <- sim_garch(fit_DA, shock_recesion)
sim_DP <- sim_garch(fit_DP, shock_recesion)
#Crear fechas futuras para 12 meses
fechas_futuras <- seq(from = as.Date("2024-01-01"), by = "months", length.out = 12)
#Convertir simulaciones en xts
sim_DM_xts <- xts(sim_DM, order.by = fechas_futuras)
sim_DA_xts <- xts(sim_DA, order.by = fechas_futuras)
sim_DP_xts <- xts(sim_DP, order.by = fechas_futuras)
#Ajustar modelos GARCH simulados
ajustar_garch(sim_DM_xts, "Depósitos Monetarios")
## Warning in .sgarchfit(spec = spec, data = data, out.sample = out.sample, : 
## ugarchfit-->waring: using less than 100 data
##  points for estimation
## 
## *---------------------------------*
## * GARCH Model Fit for Depósitos Monetarios *
## *---------------------------------*
## 
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.006903    0.001249 5.529043 0.000000
## omega   0.000001    0.000008 0.087147 0.930555
## alpha1  0.000000    0.112419 0.000000 1.000000
## beta1   0.698003    0.224242 3.112730 0.001854
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.006903    0.000977 7.062430 0.000000
## omega   0.000001    0.000015 0.047975 0.961736
## alpha1  0.000000    0.182143 0.000000 1.000000
## beta1   0.698003    0.369329 1.889922 0.058768
## 
## LogLikelihood : 39.77281 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -5.9621
## Bayes        -5.8005
## Shibata      -6.1180
## Hannan-Quinn -6.0220
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      1.717  0.1901
## Lag[2*(p+q)+(p+q)-1][2]     1.782  0.3017
## Lag[4*(p+q)+(p+q)-1][5]     2.830  0.4390
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                    0.04217  0.8373
## Lag[2*(p+q)+(p+q)-1][5]   0.67950  0.9268
## Lag[4*(p+q)+(p+q)-1][9]   1.91102  0.9154
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]   0.06949 0.500 2.000  0.7921
## ARCH Lag[5]   0.41001 1.440 1.667  0.9098
## ARCH Lag[7]   0.85934 2.315 1.543  0.9353
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  3.5696
## Individual Statistics:              
## mu     0.07847
## omega  0.31453
## alpha1 0.16259
## beta1  0.08421
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias          0.03428 0.9736    
## Negative Sign Bias 0.15303 0.8827    
## Positive Sign Bias 0.45185 0.6650    
## Joint Effect       0.22903 0.9728    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     14.67       0.7435
## 2    30     28.00       0.5179
## 3    40     34.67       0.6678
## 4    50     46.33       0.5819
## 
## 
## Elapsed time : 0.08731198
ajustar_garch(sim_DA_xts, "Depósitos de Ahorro")
## Warning in .sgarchfit(spec = spec, data = data, out.sample = out.sample, : 
## ugarchfit-->waring: using less than 100 data
##  points for estimation
## 
## *---------------------------------*
## * GARCH Model Fit for Depósitos de Ahorro *
## *---------------------------------*
## 
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu       0.00465    0.001158 4.015844 0.000059
## omega    0.00000    0.000005 0.000000 1.000000
## alpha1   0.00011    0.253818 0.000435 0.999653
## beta1    0.73151    0.495067 1.477594 0.139517
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu       0.00465    0.000612 7.597771  0.00000
## omega    0.00000    0.000008 0.000000  1.00000
## alpha1   0.00011    0.427910 0.000258  0.99979
## beta1    0.73151    0.850257 0.860337  0.38960
## 
## LogLikelihood : 42.12359 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.3539
## Bayes        -6.1923
## Shibata      -6.5098
## Hannan-Quinn -6.4138
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                   0.001896  0.9653
## Lag[2*(p+q)+(p+q)-1][2]  0.160879  0.8788
## Lag[4*(p+q)+(p+q)-1][5]  0.638872  0.9343
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.0664  0.7966
## Lag[2*(p+q)+(p+q)-1][5]    0.2556  0.9880
## Lag[4*(p+q)+(p+q)-1][9]    0.5842  0.9975
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]   0.06664 0.500 2.000  0.7963
## ARCH Lag[5]   0.20066 1.440 1.667  0.9653
## ARCH Lag[7]   0.27927 2.315 1.543  0.9938
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  3.4542
## Individual Statistics:              
## mu     0.08154
## omega  0.50985
## alpha1 0.22877
## beta1  0.11486
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           0.8814 0.4074    
## Negative Sign Bias  1.4506 0.1902    
## Positive Sign Bias  0.8804 0.4079    
## Joint Effect        3.6301 0.3043    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     21.33       0.3187
## 2    30     38.00       0.1223
## 3    40     48.00       0.1529
## 4    50     46.33       0.5819
## 
## 
## Elapsed time : 0.07490492
ajustar_garch(sim_DP_xts, "Depósitos a Plazo")
## Warning in .sgarchfit(spec = spec, data = data, out.sample = out.sample, : 
## ugarchfit-->waring: using less than 100 data
##  points for estimation
## 
## *---------------------------------*
## * GARCH Model Fit for Depósitos a Plazo *
## *---------------------------------*
## 
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.006098    0.001129 5.402773 0.000000
## omega   0.000000    0.000007 0.000000 1.000000
## alpha1  0.000166    0.092376 0.001793 0.998570
## beta1   0.706952    0.151246 4.674195 0.000003
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.006098    0.000710 8.588721 0.000000
## omega   0.000000    0.000013 0.000000 1.000000
## alpha1  0.000166    0.112982 0.001466 0.998831
## beta1   0.706952    0.227281 3.110472 0.001868
## 
## LogLikelihood : 41.45473 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -6.2425
## Bayes        -6.0808
## Shibata      -6.3983
## Hannan-Quinn -6.3023
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.7157  0.3975
## Lag[2*(p+q)+(p+q)-1][2]    1.1539  0.4509
## Lag[4*(p+q)+(p+q)-1][5]    1.8159  0.6625
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                    0.09672  0.7558
## Lag[2*(p+q)+(p+q)-1][5]   0.60493  0.9404
## Lag[4*(p+q)+(p+q)-1][9]   2.35778  0.8583
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.1736 0.500 2.000  0.6769
## ARCH Lag[5]    0.4972 1.440 1.667  0.8845
## ARCH Lag[7]    1.1530 2.315 1.543  0.8875
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  4.2372
## Individual Statistics:              
## mu     0.07279
## omega  0.15174
## alpha1 0.12044
## beta1  0.08821
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value   prob sig
## Sign Bias          0.49658 0.6347    
## Negative Sign Bias 0.53823 0.6071    
## Positive Sign Bias 0.05035 0.9612    
## Joint Effect       1.60242 0.6588    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     18.00       0.5224
## 2    30     28.00       0.5179
## 3    40     48.00       0.1529
## 4    50     54.67       0.2681
## 
## 
## Elapsed time : 0.1002541
# 8.4 Gráficos: 2023 real + 2024 simulado
#Tomar las últimas 12 variaciones reales del año 2023
real_DM_2023 <- tail(DM_diff, 12)
real_DA_2023 <- tail(DA_diff, 12)
real_DP_2023 <- tail(DP_diff, 12)
#Fechas reales del año 2023
fechas_2023 <- seq(from = as.Date("2023-01-01"), by = "months", length.out = 12)
real_DM_xts <- xts(real_DM_2023, order.by = fechas_2023)
real_DA_xts <- xts(real_DA_2023, order.by = fechas_2023)
real_DP_xts <- xts(real_DP_2023, order.by = fechas_2023)
#Crear fechas futuras simuladas para 2024
fechas_2024 <- seq(from = as.Date("2024-01-01"), by = "months", length.out = 12)
sim_DM_xts <- xts(sim_DM, order.by = fechas_2024)
sim_DA_xts <- xts(sim_DA, order.by = fechas_2024)
sim_DP_xts <- xts(sim_DP, order.by = fechas_2024)
# Combinar 2023 + 2024 para una serie continua
completo_DM_xts <- c(real_DM_xts, sim_DM_xts)
completo_DA_xts <- c(real_DA_xts, sim_DA_xts)
completo_DP_xts <- c(real_DP_xts, sim_DP_xts)
par(family = "serif", cex.main = 1.1, cex.lab = 1.1, cex.axis = 1.1)
etiquetas_completas <- format(index(completo_DM_xts), "%b-%Y")
#Gráfico Depósitos Monetarios
plot(index(completo_DM_xts), coredata(completo_DM_xts), type = "l", col = "black",
     main = "Volatilidad Simulada durante 2024 - Depósitos Monetarios (Años 2023 y 2024)",
     xlab = "", ylab = "Volatilidad", xaxt = "n", ylim = c(min(coredata(completo_DM_xts)), 0.06))
axis(1, at = index(completo_DM_xts), labels = etiquetas_completas, las = 2, cex.axis = 0.8)

#Gráfico Depósitos de Ahorro
plot(index(completo_DA_xts), coredata(completo_DA_xts), type = "l", col = "black",
     main = "Volatilidad Simulada durante 2024 - Depósitos de Ahorro (Años 2023 y 2024)",
     xlab = "", ylab = "Volatilidad", xaxt = "n", ylim = c(min(coredata(completo_DA_xts)), 0.06))
axis(1, at = index(completo_DA_xts), labels = etiquetas_completas, las = 2, cex.axis = 0.8)

#Gráfico Depósitos a Plazo
plot(index(completo_DP_xts), coredata(completo_DP_xts), type = "l", col = "black",
     main = "Volatilidad Simulada durante 2024 - Depósitos a Plazo (Años 2023 y 2024)",
     xlab = "", ylab = "Volatilidad", xaxt = "n", ylim = c(min(coredata(completo_DP_xts)), 0.06))
axis(1, at = index(completo_DP_xts), labels = etiquetas_completas, las = 2, cex.axis = 0.8)

# 9. LaR/VaR normal (95%)
#Función para calcular el VaR normal al 95% (con signo negativo)
calcular_VaR <- function(fit, nivel_confianza = 0.95) {
  sigma <- sigma(fit)
  ult_sigma <- tail(sigma, 1)
  VaR <- -qnorm(nivel_confianza, mean = 0, sd = ult_sigma)
  return(VaR)
}
# 9.1 Cálculo del VaR normal al 95%
VaR_DM_normal <- calcular_VaR(fit_DM)
VaR_DA_normal <- calcular_VaR(fit_DA)
VaR_DP_normal <- calcular_VaR(fit_DP)
#Mostrar resultados
cat("=== VaR Normal al 95% ===\n")
## === VaR Normal al 95% ===
cat("Depósitos Monetarios:", VaR_DM_normal, "\n")
## Depósitos Monetarios: -0.03428054
cat("Depósitos de Ahorro:", VaR_DA_normal, "\n")
## Depósitos de Ahorro: -0.01404021
cat("Depósitos a Plazo:", VaR_DP_normal, "\n")
## Depósitos a Plazo: -0.01104264
# 9.2 Backtesting del VaR al 95%
validar_var <- function(modelo_garch, serie_diff, nombre_serie) {
  sigma <- sigma(modelo_garch)
  mu <- fitted(modelo_garch)
  VaR_95 <- mu - sigma * qnorm(0.95)  # signo negativo para pérdidas
  
  serie_var <- as.numeric(serie_diff)
  excedencias <- serie_var < VaR_95
  
  cat("\n--- Backtesting VaR al 95% -", nombre_serie, "---\n")
  cat("Número de excepciones:", sum(excedencias), "\n")
  cat("Porcentaje de excepciones:", mean(excedencias) * 100, "%\n")
  
  fecha <- index(serie_diff)
  df <- data.frame(Fecha = fecha, Variaciones = serie_var,
                   VaR_95 = VaR_95, Excedencia = excedencias)
  
  ggplot(df, aes(x = Fecha)) +
    geom_line(aes(y = Variaciones, color = "Variaciones observadas"), size = 0.7) +
    geom_line(aes(y = VaR_95, color = "LaR al 95%"), size = 0.7) +
    geom_point(data = df[df$Excedencia, ],
               aes(y = Variaciones, color = "Excepciones (Variaciones < LaR)"),
               size = 2) +
    scale_color_manual(name = "Leyenda",
                       values = c("Variaciones observadas" = "black",
                                  "LaR al 95%" = "red",
                                  "Excepciones (Variaciones < LaR)" = "blue1")) +
    labs(title = paste("Backtesting del LaR al 95% -", nombre_serie),
         x = "Fecha", y = "Variaciones") +
    theme_minimal(base_family = "serif", base_size = 11) +
    theme(plot.title = element_text(face = "bold", hjust = 0.5),
          legend.position = "bottom",
          legend.title = element_text(face = "bold"))
}
# Llamadas
validar_var(fit_DM, DM_diff, "Depósitos Monetarios")
## 
## --- Backtesting VaR al 95% - Depósitos Monetarios ---
## Número de excepciones: 11 
## Porcentaje de excepciones: 5.759162 %
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.

validar_var(fit_DA, DA_diff, "Depósitos de Ahorro")
## 
## --- Backtesting VaR al 95% - Depósitos de Ahorro ---
## Número de excepciones: 6 
## Porcentaje de excepciones: 3.141361 %

validar_var(fit_DP, DP_diff, "Depósitos a Plazo")
## 
## --- Backtesting VaR al 95% - Depósitos a Plazo ---
## Número de excepciones: 8 
## Porcentaje de excepciones: 4.188482 %

# 10. LaR/VaR en estrés (99% y +5% σ)
# 10.1 Función para calcular el VaR con aumento del 5% de volatilidad 
calcular_VaR_crisis <- function(fit, z_alpha = 2.33, aumento_vol = 0.05) {
  sigma <- sigma(fit)
  sigma_ult <- tail(sigma, 1)
  sigma_crisis <- sigma_ult * (1 + aumento_vol)
  VaR_crisis <- -z_alpha * sigma_crisis  # signo negativo para pérdida
  return(VaR_crisis)
}
# 10.2 Cálculo del VaR en crisis
VaR_DM_crisis <- calcular_VaR_crisis(fit_DM)
VaR_DA_crisis <- calcular_VaR_crisis(fit_DA)
VaR_DP_crisis <- calcular_VaR_crisis(fit_DP)
cat("\n=== VaR bajo estrés (99%, +5% Volatilidad) ===\n")
## 
## === VaR bajo estrés (99%, +5% Volatilidad) ===
cat("Depósitos Monetarios:", VaR_DM_crisis, "\n")
## Depósitos Monetarios: -0.05098772
cat("Depósitos de Ahorro:", VaR_DA_crisis, "\n")
## Depósitos de Ahorro: -0.02088293
cat("Depósitos a Plazo:", VaR_DP_crisis, "\n")
## Depósitos a Plazo: -0.01642445
# 10.3 Backtesting del VaR al 99% (crisis)
validar_var_crisis <- function(modelo_garch, serie_diff, nombre_serie, aumento_vol = 0.05) {
  sigma <- sigma(modelo_garch)
  mu <- fitted(modelo_garch)
  sigma_crisis <- sigma * (1 + aumento_vol)
  VaR_99_Crisis <- mu - sigma_crisis * qnorm(0.99)  
  
  serie_var <- as.numeric(serie_diff)
  excedencias <- serie_var < VaR_99_Crisis
  
  cat("\n--- Backtesting VaR al 99% (Crisis) -", nombre_serie, "---\n")
  cat("Número de excepciones:", sum(excedencias), "\n")
  cat("Porcentaje de excepciones:", mean(excedencias) * 100, "%\n")
  
  fecha <- index(serie_diff)
  df <- data.frame(Fecha = fecha, Variaciones = serie_var,
                   VaR_99_Crisis = VaR_99_Crisis, Excedencia = excedencias)
  
  ggplot(df, aes(x = Fecha)) +
    geom_line(aes(y = Variaciones, color = "Variaciones observadas"), size = 0.7) +
    geom_line(aes(y = VaR_99_Crisis, color = "LaR al 99% (Crisis)"), size = 0.7) +
    geom_point(data = df[df$Excedencia, ],
               aes(y = Variaciones, color = "Excepciones (Variaciones < LaR)"),
               size = 2) +
    scale_color_manual(name = "Leyenda",
                       values = c("Variaciones observadas" = "black",
                                  "LaR al 99% (Crisis)" = "red",
                                  "Excepciones (Variaciones < LaR)" = "blue1")) +
    labs(title = paste("Backtesting del LaR al 99% (Crisis Financiera) -", nombre_serie),
         x = "Fecha", y = "Variaciones") +
    theme_minimal(base_family = "serif", base_size = 11) +
    theme(plot.title = element_text(face = "bold", hjust = 0.5),
          legend.position = "bottom",
          legend.title = element_text(face = "bold"))
}
validar_var_crisis(fit_DM, DM_diff, "Depósitos Monetarios")
## 
## --- Backtesting VaR al 99% (Crisis) - Depósitos Monetarios ---
## Número de excepciones: 1 
## Porcentaje de excepciones: 0.5235602 %

validar_var_crisis(fit_DA, DA_diff, "Depósitos de Ahorro")
## 
## --- Backtesting VaR al 99% (Crisis) - Depósitos de Ahorro ---
## Número de excepciones: 1 
## Porcentaje de excepciones: 0.5235602 %

validar_var_crisis(fit_DP, DP_diff, "Depósitos a Plazo")
## 
## --- Backtesting VaR al 99% (Crisis) - Depósitos a Plazo ---
## Número de excepciones: 0 
## Porcentaje de excepciones: 0 %

# 11. Comparación normal vs. estrés y Expected Shortfall
# Configurar la fuente Times New Roman
par(family = "serif", cex.main = 1.1, cex.lab = 1.1, cex.axis = 1.1)
# 11.1 Última volatilidad (σ) estimada
vol_DM <- tail(sigma(fit_DM), 1)
vol_DA <- tail(sigma(fit_DA), 1)
vol_DP <- tail(sigma(fit_DP), 1)
# 11.2 σ en crisis (+5%)
vol_DM_crisis <- vol_DM * 1.05
vol_DA_crisis <- vol_DA * 1.05
vol_DP_crisis <- vol_DP * 1.05
# 11.3 Expected Shortfall (95% y 99%)
ES_normal <- function(sigma, alpha = 0.95) {
  -sigma * dnorm(qnorm(alpha)) / (1 - alpha)
}

ES_crisis <- function(sigma, alpha = 0.99) {
  -sigma * dnorm(qnorm(alpha)) / (1 - alpha)
}
# 11.4 Tabla comparativa (σ, LaR/VaR y ES)
tabla_comparativa <- tibble::tibble(
  Fecha = rep(as.Date("2023-12-31"), 6),
  Serie = rep(c("Depósitos Monetarios", "Depósitos de Ahorro", "Depósitos a Plazo"), each = 2),
  Escenario = rep(c("Normal (95%)", "Crisis (99%)"), times = 3),
  Volatilidad = c(as.numeric(vol_DM), as.numeric(vol_DM_crisis),
                  as.numeric(vol_DA), as.numeric(vol_DA_crisis),
                  as.numeric(vol_DP), as.numeric(vol_DP_crisis)),
  VaR = c(as.numeric(VaR_DM_normal), as.numeric(VaR_DM_crisis),
          as.numeric(VaR_DA_normal), as.numeric(VaR_DA_crisis),
          as.numeric(VaR_DP_normal), as.numeric(VaR_DP_crisis)),
  ES = c(ES_normal(vol_DM), ES_crisis(vol_DM_crisis),
         ES_normal(vol_DA), ES_crisis(vol_DA_crisis),
         ES_normal(vol_DP), ES_crisis(vol_DP_crisis))
)

print(tabla_comparativa)
## # A tibble: 6 × 6
##   Fecha      Serie                Escenario    Volatilidad     VaR ES[,1]     
##   <date>     <chr>                <chr>              <dbl>   <dbl> <xts[,1]>  
## 1 2023-12-31 Depósitos Monetarios Normal (95%)     0.0208  -0.0343 -0.04298918
## 2 2023-12-31 Depósitos Monetarios Crisis (99%)     0.0219  -0.0510 -0.05832326
## 3 2023-12-31 Depósitos de Ahorro  Normal (95%)     0.00854 -0.0140 -0.01760699
## 4 2023-12-31 Depósitos de Ahorro  Crisis (99%)     0.00896 -0.0209 -0.02388734
## 5 2023-12-31 Depósitos a Plazo    Normal (95%)     0.00671 -0.0110 -0.01384792
## 6 2023-12-31 Depósitos a Plazo    Crisis (99%)     0.00705 -0.0164 -0.01878742
comparacion_VaR <- tabla_comparativa %>%
  select(Serie, Escenario, VaR) %>%
  pivot_wider(names_from = Escenario, values_from = VaR) %>%
  rename(VaR_Normal_95 = `Normal (95%)`, VaR_Crisis_99 = `Crisis (99%)`)

comparacion_larga <- comparacion_VaR %>%
  pivot_longer(cols = starts_with("VaR"), names_to = "Tipo_VaR", values_to = "Valor_VaR") %>%
  mutate(Tipo_VaR = factor(Tipo_VaR,
                           levels = c("VaR_Normal_95", "VaR_Crisis_99"),
                           labels = c("LaR al 95% (Normal)", "LaR al 99% (Crisis)")))
# 11.5 Gráfico comparativo (LaR/Q)
#Obtener saldos al 31 de diciembre de 2023
saldo_DM <- as.numeric(DM["2023-12-31"])
saldo_DA <- as.numeric(DA["2023-12-31"])
saldo_DP <- as.numeric(DP["2023-12-31"])
# Calcular LaR monetario 
VaR_abs_DM_normal <- abs(saldo_DM * VaR_DM_normal)
VaR_abs_DA_normal <- abs(saldo_DA * VaR_DA_normal)
VaR_abs_DP_normal <- abs(saldo_DP * VaR_DP_normal)
VaR_abs_DM_crisis <- abs(saldo_DM * VaR_DM_crisis)
VaR_abs_DA_crisis <- abs(saldo_DA * VaR_DA_crisis)
VaR_abs_DP_crisis <- abs(saldo_DP * VaR_DP_crisis)
# Crear tabla comparativa de VaR monetario
tabla_VaR_monetaria <- tibble(
  Serie = rep(c("Depósitos Monetarios", "Depósitos de Ahorro", "Depósitos a Plazo"), each = 2),
  Escenario = rep(c("Normal (95%)", "Crisis (99%)"), times = 3),
  VaR_monetario = c(VaR_abs_DM_normal, VaR_abs_DM_crisis,
                    VaR_abs_DA_normal, VaR_abs_DA_crisis,
                    VaR_abs_DP_normal, VaR_abs_DP_crisis)
)
#Crear tabla comparativa de niveles de saldo 
tabla_saldos <- tibble(
  Serie = c("Depósitos Monetarios", "Depósitos de Ahorro", "Depósitos a Plazo"),
  Saldo_Normal = c(saldo_DM - VaR_abs_DM_normal,
                   saldo_DA - VaR_abs_DA_normal,
                   saldo_DP - VaR_abs_DP_normal),
  `Saldo_Estres (VaR 99%)` = c(saldo_DM - VaR_abs_DM_crisis,
                               saldo_DA - VaR_abs_DA_crisis,
                               saldo_DP - VaR_abs_DP_crisis)
)
# Mostrar tabla de saldos
print(tabla_saldos)
## # A tibble: 3 × 3
##   Serie                Saldo_Normal `Saldo_Estres (VaR 99%)`[,1]
##   <chr>                       <dbl> <xts[,1]>                   
## 1 Depósitos Monetarios   110235377. 108328278                   
## 2 Depósitos de Ahorro     90104577.  89479236                   
## 3 Depósitos a Plazo      126638420. 125949265
# Gráfico de comparación del LaR monetario
tabla_VaR_monetaria <- tabla_VaR_monetaria %>%
  mutate(Escenario = factor(Escenario, levels = c("Normal (95%)", "Crisis (99%)")))

ggplot(tabla_VaR_monetaria, aes(x = Serie, y = VaR_monetario, fill = Escenario)) +
  geom_bar(stat = "identity", position = position_dodge(), color = "black") +
  scale_fill_manual(values = c("gray40", "gray70")) +
  scale_y_continuous(labels = comma) +
  labs(title = "Comparación del LaR Monetario: Normal vs Crisis (Dic 2023)",
       x = "Tipo de Depósito", y = "LaR Monetario (Q)",
       fill = "Escenario") +
  theme_minimal(base_family = "serif", base_size = 11) +
  theme(plot.title = element_text(face = "bold", hjust = 0.5),
        legend.position = "bottom",
        legend.title = element_text(face = "bold"))