Cargar los Paquetes Necesarios:

## Installing package into 'C:/Users/DELL/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'PerformanceAnalytics' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\downloaded_packages
## Installing package into 'C:/Users/DELL/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'PerformanceAnalytics' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\downloaded_packages
## Installing package into 'C:/Users/DELL/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'quantmod' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\downloaded_packages
## Installing package into 'C:/Users/DELL/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'zoo' successfully unpacked and MD5 sums checked
## Warning: cannot remove prior installation of package 'zoo'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): problema al copiar
## C:\Users\DELL\AppData\Local\R\win-library\4.3\00LOCK\zoo\libs\x64\zoo.dll a
## C:\Users\DELL\AppData\Local\R\win-library\4.3\zoo\libs\x64\zoo.dll: Permission
## denied
## Warning: restored 'zoo'
## 
## The downloaded binary packages are in
##  C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\downloaded_packages
## Installing package into 'C:/Users/DELL/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'rugarch' successfully unpacked and MD5 sums checked
## Warning: cannot remove prior installation of package 'rugarch'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): problema al copiar
## C:\Users\DELL\AppData\Local\R\win-library\4.3\00LOCK\rugarch\libs\x64\rugarch.dll
## a C:\Users\DELL\AppData\Local\R\win-library\4.3\rugarch\libs\x64\rugarch.dll:
## Permission denied
## Warning: restored 'rugarch'
## 
## The downloaded binary packages are in
##  C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\downloaded_packages
## Installing package into 'C:/Users/DELL/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'latexpdf' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\downloaded_packages
## If reinstallation fails, try install_tinytex() again. Then install the following packages:
## 
## tinytex::tlmgr_install(c("amscls", "amsfonts", "amsmath", "atbegshi", "atveryend", "auxhook", "babel", "bibtex", "bigintcalc", "bitset", "bookmark", "booktabs", "cm", "ctablestack", "dehyph", "dvipdfmx", "dvips", "ec", "epstopdf", "epstopdf-pkg", "etex", "etexcmds", "etoolbox", "euenc", "fancyvrb", "filehook", "firstaid", "float", "fontspec", "framed", "geometry", "gettitlestring", "glyphlist", "graphics", "graphics-cfg", "graphics-def", "helvetic", "hycolor", "hyperref", "hyph-utf8", "hyphen-base", "iftex", "inconsolata", "infwarerr", "intcalc", "knuth-lib", "kpathsea", "kvdefinekeys", "kvoptions", "kvsetkeys", "l3backend", "l3kernel", "l3packages", "latex", "latex-amsmath-dev", "latex-bin", "latex-fonts", "latex-tools-dev", "latexconfig", "latexmk", "letltxmacro", "lm", "lm-math", "ltxcmds", "lua-alt-getopt", "lua-uni-algos", "luahbtex", "lualatex-math", "lualibs", "luaotfload", "luatex", "luatexbase", "mdwtools", "metafont", "mfware", "modes", "natbib", "pdfescape", "pdftex", "pdftexcmds", "plain", "psnfss", "refcount", "rerunfilecheck", "scheme-infraonly", "selnolig", "stringenc", "symbol", "tex", "tex-ini-files", "texlive-scripts", "texlive-scripts-extra", "texlive.infra", "times", "tipa", "tlgpg", "tlgs", "tlperl", "tools", "unicode-data", "unicode-math", "uniquecounter", "url", "xcolor", "xetex", "xetexconfig", "xkeyval", "xunicode", "zapfding"))
## The directory C:\Users\DELL\AppData\Roaming\TinyTeX/texmf-local is not empty. It will be backed up to C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\file34ac3979604 and restored later.
## tlmgr install tlgpg
## tlmgr update --self
## tlmgr install tlgpg
## tlmgr --repository http://www.preining.info/tlgpg/ install tlgpg
## tlmgr option repository "https://ctan.math.illinois.edu/systems/texlive/tlnet"
## tlmgr update --list
## Installing package into 'C:/Users/DELL/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'tinytex' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\DELL\AppData\Local\Temp\RtmpySTDIO\downloaded_packages
## Warning: package 'PerformanceAnalytics' was built under R version 4.3.3
## Loading required package: xts
## Warning: package 'xts' was built under R version 4.3.3
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 4.3.3
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
## Warning: package 'quantmod' was built under R version 4.3.3
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 4.3.3
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Warning: package 'rugarch' was built under R version 4.3.3
## Loading required package: parallel
## 
## Attaching package: 'rugarch'
## The following object is masked from 'package:stats':
## 
##     sigma
## Warning: package 'tseries' was built under R version 4.3.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.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'dplyr'
## 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

Descargar Datos del Tipo de Cambio DOP/USD:

getSymbols("USDDOP=X", from="2015-01-01")
## [1] "USDDOP=X"
USD_DOP <-get("USDDOP=X")
help("quantmod")
## starting httpd help server ... done
View(USD_DOP)

Graficar los Datos del Tipo de Cambio:

plot(USD_DOP$`USDDOP=X.Adjusted`)

Calculo de Retornos Logarítmicos

USD_DOP_Return <- CalculateReturns(USD_DOP$`USDDOP=X.Adjusted`, method = "log")

Calculo de la Volatilidad Anualizada

sqrt(252)*sd(USD_DOP_Return, na.rm = T)
## [1] 0.147544

El resultado de 0.1475717 significa que, la tasa de cambio podría variar hasta un 14.76% hacia arriba o hacia abajo durante un año. Es una forma de medir de cmo seran las fluctuaciones o cambio que pueden haber en el valor del dólar en comparación con el peso dominicano a lo largo de un año.

Calculo las Ventanas de Volatilidad

chart.RollingPerformance(R=USD_DOP_Return, width = 22, FUN = "sd.annualized", scale=252, main = "Volitilidad Rolling Anualizada del USD/DOP")

Este grafico muestra como es la volatilidad del Dolar/Peso, mostrando aquellos cambios mas relevante entre el 2018 y 2019, donde se muestran icos altos por ambios muy grandes, esto pudo ser por eventos economicos o politicos, ya sea locales, en la Republica Dominicana o por eventos externos. Despues del 2020 se observa una disminucion en los niveles de volatilidad, lo que significa se fue estabilizando el tipo de cambio en esos periodos.

Modelo GARCH()

anyNA(USD_DOP_Return)
## [1] TRUE
USD_DOP_Return <-na.omit(USD_DOP_Return)

library(forcats)
library(forecast)
## Warning: package 'forecast' was built under R version 4.3.3
library(rugarch)
library(stargazer)
## 
## Please cite as:
##  Hlavac, Marek (2022). stargazer: Well-Formatted Regression and Summary Statistics Tables.
##  R package version 5.2.3. https://CRAN.R-project.org/package=stargazer
auto.arima(USD_DOP_Return)
## Series: USD_DOP_Return 
## ARIMA(1,0,1) with non-zero mean 
## 
## Coefficients:
##           ar1      ma1   mean
##       -0.0005  -0.7153  1e-04
## s.e.   0.0265   0.0178  0e+00
## 
## sigma^2 = 5.716e-05:  log likelihood = 8929.34
## AIC=-17850.67   AICc=-17850.66   BIC=-17827.26
garchspec<-ugarchspec(mean.model = list(arma0rder=c(1,1)),
variance.model = list(model="sGARCH"),
distribution.model = "sstd")
## Warning: unidentified option(s) in mean.model:
##  arma0rder
garchfit<- ugarchfit(data = USD_DOP_Return,spec = garchspec)

garchforecast <- ugarchforecast(fitORspec = garchfit, n.ahead = 5)

#Coeficientes: 
garchcoef<-coef(garchfit)
print(garchcoef)
##            mu           ar1           ma1         omega        alpha1 
## -3.627148e-05 -2.954752e-02 -6.101151e-01  3.405560e-06  4.347448e-01 
##         beta1          skew         shape 
##  5.642551e-01  7.411115e-01  3.245674e+00
#Varianza:

garchuncvar<-uncvariance(garchfit)
garchuncvar
## [1] 0.003405116

Ajustar el Modelo GARCH

Especificar y Ajustar un Modelo GJR-GARCH

#Paquete a Utilizar:
library(rugarch)
install.packages("rugarch")
## Warning: package 'rugarch' is in use and will not be installed
library(rugarch)

#media predicha:
garchmean<-fitted(garchfit)

#volatilidad: 
garchvol<-sigma(garchfit)


#Ajuste del MOdelo: 

gjr_garch_spec <- ugarchspec(
  mean.model = list(armaOrder = c(1, 1)),
  variance.model = list(model = "gjrGARCH", garchOrder = c(1, 1)),
  distribution.model = "sstd"
)

# Ajustar el modelo GJR-GARCH a los datos de retorno:
gjr_garch_fit <- ugarchfit(spec = gjr_garch_spec, data = USD_DOP_Return)

# la media predicha:
garchmean <- fitted(gjr_garch_fit)

# volatilidad estimada:
gjrgarchvol <- sigma(gjr_garch_fit)

# coeficientes del modelo ajustado:
gjrgarchcoef <- coef(gjr_garch_fit)

# Mostrar los coeficientes:
print(gjrgarchcoef)
##            mu           ar1           ma1         omega        alpha1 
## -5.239831e-05 -2.155114e-02 -5.942694e-01  3.725494e-06  3.941301e-01 
##         beta1        gamma1          skew         shape 
##  5.454575e-01  1.397228e-01  7.411897e-01  3.177558e+00

Comparacion de los Modelos Garch y GJR-Garch.

print(garchfit)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(1,0,1)
## Distribution : sstd 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu     -0.000036    0.000030  -1.1909 0.233679
## ar1    -0.029548    0.023065  -1.2811 0.200174
## ma1    -0.610115    0.019637 -31.0694 0.000000
## omega   0.000003    0.000001   2.7168 0.006591
## alpha1  0.434745    0.033990  12.7904 0.000000
## beta1   0.564255    0.030287  18.6302 0.000000
## skew    0.741112    0.016228  45.6685 0.000000
## shape   3.245674    0.112764  28.7830 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error   t value Pr(>|t|)
## mu     -0.000036    0.000041  -0.88226 0.377636
## ar1    -0.029548    0.025657  -1.15164 0.249470
## ma1    -0.610115    0.033547 -18.18678 0.000000
## omega   0.000003    0.000006   0.52850 0.597156
## alpha1  0.434745    0.082411   5.27532 0.000000
## beta1   0.564255    0.216961   2.60072 0.009303
## skew    0.741112    0.033123  22.37453 0.000000
## shape   3.245674    0.169834  19.11081 0.000000
## 
## LogLikelihood : 9756.336 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -7.5686
## Bayes        -7.5504
## Shibata      -7.5686
## Hannan-Quinn -7.5620
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic   p-value
## Lag[1]                      4.669 3.072e-02
## Lag[2*(p+q)+(p+q)-1][5]    12.294 0.000e+00
## Lag[4*(p+q)+(p+q)-1][9]    15.964 1.196e-05
## d.o.f=2
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      1.598  0.2062
## Lag[2*(p+q)+(p+q)-1][5]     3.380  0.3420
## Lag[4*(p+q)+(p+q)-1][9]     5.553  0.3528
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.8811 0.500 2.000  0.3479
## ARCH Lag[5]    1.2766 1.440 1.667  0.6530
## ARCH Lag[7]    2.7236 2.315 1.543  0.5672
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  62.2203
## Individual Statistics:             
## mu     0.6056
## ar1    0.3235
## ma1    1.2601
## omega  0.3232
## alpha1 7.1218
## beta1  1.4279
## skew   5.8062
## shape  2.9252
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.89 2.11 2.59
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value      prob sig
## Sign Bias            1.493 0.1356455    
## Negative Sign Bias   1.557 0.1196349    
## Positive Sign Bias   3.572 0.0003602 ***
## Joint Effect        16.294 0.0009868 ***
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     72.62    3.359e-08
## 2    30     94.72    6.716e-09
## 3    40    116.86    1.060e-09
## 4    50    127.14    7.277e-09
## 
## 
## Elapsed time : 2.230694
print(gjr_garch_fit)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : gjrGARCH(1,1)
## Mean Model   : ARFIMA(1,0,1)
## Distribution : sstd 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error   t value Pr(>|t|)
## mu     -0.000052    0.000033  -1.59481 0.110755
## ar1    -0.021551    0.024355  -0.88488 0.376223
## ma1    -0.594269    0.021613 -27.49599 0.000000
## omega   0.000004    0.000001   4.05432 0.000050
## alpha1  0.394130    0.041195   9.56751 0.000000
## beta1   0.545457    0.020534  26.56395 0.000000
## gamma1  0.139723    0.061201   2.28302 0.022429
## skew    0.741190    0.016343  45.35195 0.000000
## shape   3.177558    0.110690  28.70686 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error   t value Pr(>|t|)
## mu     -0.000052    0.000045  -1.16769 0.242931
## ar1    -0.021551    0.027638  -0.77976 0.435533
## ma1    -0.594269    0.042874 -13.86077 0.000000
## omega   0.000004    0.000003   1.18752 0.235024
## alpha1  0.394130    0.039479   9.98323 0.000000
## beta1   0.545457    0.125582   4.34343 0.000014
## gamma1  0.139723    0.182068   0.76742 0.442831
## skew    0.741190    0.028899  25.64747 0.000000
## shape   3.177558    0.143154  22.19684 0.000000
## 
## LogLikelihood : 9758.21 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -7.5693
## Bayes        -7.5488
## Shibata      -7.5693
## Hannan-Quinn -7.5618
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic   p-value
## Lag[1]                      6.424 1.126e-02
## Lag[2*(p+q)+(p+q)-1][5]    14.743 0.000e+00
## Lag[4*(p+q)+(p+q)-1][9]    18.596 4.515e-07
## d.o.f=2
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      1.807  0.1789
## Lag[2*(p+q)+(p+q)-1][5]     3.745  0.2876
## Lag[4*(p+q)+(p+q)-1][9]     6.190  0.2769
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.9716 0.500 2.000  0.3243
## ARCH Lag[5]    1.4013 1.440 1.667  0.6186
## ARCH Lag[7]    3.1555 2.315 1.543  0.4847
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  68.6569
## Individual Statistics:             
## mu     0.6713
## ar1    0.3514
## ma1    1.2490
## omega  0.3165
## alpha1 7.3795
## beta1  1.3465
## gamma1 5.3106
## skew   6.0345
## shape  2.7759
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          2.1 2.32 2.82
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value      prob sig
## Sign Bias            1.530 0.1262178    
## Negative Sign Bias   1.703 0.0887750   *
## Positive Sign Bias   3.539 0.0004093 ***
## Joint Effect        16.955 0.0007221 ***
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     84.53    3.045e-10
## 2    30     98.82    1.509e-09
## 3    40    111.92    5.740e-09
## 4    50    143.14    3.736e-11
## 
## 
## Elapsed time : 4.024892

Diagnóstico de los Residuos:

RESIDUOS_Garch <-residuals(garchfit)

plot(RESIDUOS_Garch, main= "Residuos Garch Estandarizados", col= "royalblue" )

RESIDUOS_GJRGARCH<- residuals(gjr_garch_fit)

plot(RESIDUOS_GJRGARCH, main= "Residuos Estandarizados GJR-Garch", col= "peru")

Analizar la Volatilidad Condicional

library(quantmod)
VOLATILIDAD_USD_DOP <- plot(abs(gjrgarchvol), col = "darkblue", main = "Volatilidad Condicional: GARCH vs GJR-GARCH", 
                ylab = "Volatilidad Condicional", xlab = "Tiempo")
VOLATILIDAD_USD_DOP <- addSeries(garchvol, col = "lightblue", on = 1)


#Muestra del Grafico Final
show(VOLATILIDAD_USD_DOP)

Evaluar la Volatilidad y su Impacto en el Ahorro

Segun los Datos obtenidos, se puede observar que la volatilidad del Dolar/Peso es bastante alta, lo que significa que el valor del peso, frente al dólar puede fluctuar mucho mas. Esto significa que, si se ahorra en pesos, los ahorros podrían perder valor rápidamente debido a la volatilidad en el tipo de cambio. Por otro lado, el dólar tiende a ser más estable y, por lo tanto, ahorrar en dólares podría ser una opción más segura para mantener el valor de los ahorros a largo plazo.

Consideraciones Económicas Adicionales

La inflación es un facto importante, ya que si el país experimenta una alta inflación, el valor de los ahorros en pesos se depresia rápidamente, lo que hace que ahorrar en dólares la mejor opcion, debido a la menor inflación de esta moneda. Además, las tasas de interés en pesos pueden influir positivamente en el rendimiento de los ahorros, especialmente si son altas. Ademas, este beneficio puede verse compensado si la inflación también es elevada o si la volatilidad del peso afecta negativamente el valor real de los ahorros, haciendo que el riesgo de fluctuaciones en el tipo de cambio sea un factor determinante.

Conclusión Final

Dado que la volatilidad en el peso es alta, lo más seguro sería ahorrar en dólares, ya que esta moneda es más estable y puede ayudar a proteger mejor el valor de los ahorros frente a las fluctuaciones del tipo de cambio.