#Seleccionar los Paquetes a Utilizar
library(rugarch)
## 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
library(readxl)
library(tseries)
## Warning: package 'tseries' was built under R version 4.3.3
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(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
library(quantmod)
## Warning: package 'quantmod' was built under R version 4.3.3
## Loading required package: xts
## Warning: package 'xts' 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: 'xts'
## The following objects are masked from 'package:dplyr':
##
## first, last
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 4.3.3
library(PerformanceAnalytics)
## Warning: package 'PerformanceAnalytics' was built under R version 4.3.3
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
El Russell 2000 se utiliza como un indicador del desempeño del mercado de pequeñas empresas en Estados Unidos. Es mas relevante porque estas empresas, aunque más riesgosas, tienen un gran potencial de crecimiento y son más sensibles a los cambios en la economía. Es calculado y gestionado por FTSE Russell , una división de la Bolsa de Londres.
getSymbols("RUT", from= "2010-01-01")
## Warning: RUT contains missing values. Some functions will not work if objects
## contain missing values in the middle of the series. Consider using na.omit(),
## na.approx(), na.fill(), etc to remove or replace them.
## [1] "RUT"
Russell_2000 <-get("RUT")
Graficos de los Retornos:
Russell_2000 <-na.omit(Russell_2000)
plot(Russell_2000$RUT.Adjusted)
La presencia de valores faltantes (Datos NA) y los problemas de discontinuidad en las fechas hacen que procesar los datos del Russell 2000 sea más dificil y propenso a errores, por lo que me pasare a analizar le indicador Sp500.
El índice S&P 500 (GSPC) es un indicador del mercado bursátil en Estados Unidos. Representa el desempeño de las 500 empresas más grandes y sólidas según su capitalización de mercado, a sectores clave como tecnología, salud, finanzas y consumo.
getSymbols("GSP", from= "2010-01-01")
## Warning: GSP contains missing values. Some functions will not work if objects
## contain missing values in the middle of the series. Consider using na.omit(),
## na.approx(), na.fill(), etc to remove or replace them.
## [1] "GSP"
SP500 <- get("GSP")
plot(SP500$GSP.Adjusted)
#SPY
getSymbols("SPY", from= "2010-01-01")
## [1] "SPY"
SP5002 <- get("SPY")
plot(SP5002$SPY.Adjusted)
Elegí trabajar con SPY ya que el mismo representa el ETF del S&P 500, un activo negociable que refleja el comportamiento real del mercado, incluyendo dividendos y ajustes por splits. Esto permite obtener datos más completos y realistas para calcular rendimientos (el GSP, tiene muchos valores NA), volatilidad y modelos como GARCH.
Por otro lado, esta grafica del S&P 500 muestra una tendenca alcista a lo largo del tiempo, para los años entre 2018 y 2020 muestra una gran volatilidad en el mercado donde se pbserva una caida pronunciada posiblemente por la Pandemia de Covid-19, en el año 2020.
Calculos de los rendiemientos.
SP5002_Ret <- CalculateReturns(SP5002$SPY.Adjusted , method = "log")
#CALCULO DE LA VOLATILIDAD DIRARIA
sd(SP5002_Ret, na.rm = T)
## [1] 0.01076922
sd(SP5002_Ret["2024"], na.rm = T)
## [1] 0.007693391
La volatilidad diaria promedio para los rendimientos en el año 2024 es aproximadamente 0.76%.
#CALCULO DE LA VOLATILIDAD ANUALIZADA
sqrt(252)*sd(SP5002_Ret, na.rm = T)
## [1] 0.170956
La volatilidad anualizada es 17.1%.
#CALCULO DE LA VOLATILIDAD DE LA VENTANA MOVIL
chart.RollingPerformance(R=SP5002_Ret, width = 22, FUN = "sd.annualized", scale= 252, main = "VOLATILIDAD ROLLING ANUALIZADA")
Se muestra una gran volatilidad lo que indica una mayor incertidumbre y movimientos en los precios; Para el año 2020 es donde se muestra el pico más alto, en ese año pasaron los eventos de la crisis del COVID-19, más adelante los periodos se van estabilizando.
library(forecast)
## Warning: package 'forecast' was built under R version 4.3.3
auto.arima(SP5002_Ret)
## Series: SP5002_Ret
## ARIMA(4,0,4) with non-zero mean
##
## Coefficients:
## ar1 ar2 ar3 ar4 ma1 ma2 ma3 ma4 mean
## -0.2147 0.7846 -0.2883 -0.7931 0.1422 -0.7416 0.3212 0.6837 5e-04
## s.e. 0.0444 0.0615 0.0569 0.0403 0.0517 0.0696 0.0626 0.0453 2e-04
##
## sigma^2 = 0.0001121: log likelihood = 11776.47
## AIC=-23532.95 AICc=-23532.89 BIC=-23470.62
# ELIMINAR VALORES NA DE LOS RETORNOS
anyNA(SP5002_Ret)
## [1] TRUE
SP5002_Ret <- na.omit(SP5002_Ret)
# ESPECIFICACIÓN DEL MODELO
ModeloG_sp500 <- ugarchspec(mean.model = list(armaOrder = c(1, 4)),
variance.model = list(model = "sGARCH"),
distribution.model = "norm")
Model_Gfit_sp500 <- ugarchfit(data = SP5002_Ret, spec = ModeloG_sp500)
# PREDECIR LA VOLATILIDAD DE LOS RETORNOS FUTUROS
ModeloGForecast_Sp <- ugarchforecast(fitORspec = Model_Gfit_sp500, n.ahead = 5)
# COEFICIENTES DEL MODELO
ModelGcoef_Sp <- coef(Model_Gfit_sp500)
print(ModelGcoef_Sp)
## mu ar1 ma1 ma2 ma3
## 8.191501e-04 9.628155e-01 -1.011400e+00 3.293723e-02 -2.151339e-02
## ma4 omega alpha1 beta1
## 1.764865e-02 3.527538e-06 1.701907e-01 7.999372e-01
# CALCULAR LA VARIANZA INCONDICIONAL
ModelG_uncva_Sp <- uncvariance(Model_Gfit_sp500)
print(ModelG_uncva_Sp)
## [1] 0.0001180878
# OBTENER LA MEDIA PREDICHA
ModelG_Mean_sp <- fitted(Model_Gfit_sp500)
print(ModelG_Mean_sp)
## m.c.seq.row..seq.n...seq.col..drop...FALSE.
## 2010-01-05 0.0008191501
## 2010-01-06 0.0007305238
## 2010-01-07 0.0007951981
## 2010-01-08 0.0005899306
## 2010-01-11 0.0006110469
## 2010-01-12 0.0005966721
## 2010-01-13 0.0011165230
## 2010-01-14 0.0004541757
## 2010-01-15 0.0008270811
## 2010-01-19 0.0011565707
## ...
## 2024-12-02 0.0001469935
## 2024-12-03 0.0004336551
## 2024-12-04 0.0003218582
## 2024-12-05 0.0001200490
## 2024-12-06 0.0004535527
## 2024-12-09 0.0002132473
## 2024-12-10 0.0006860041
## 2024-12-11 0.0006363241
## 2024-12-12 0.0003158124
## 2024-12-13 0.0008204121
# OBTENER LA VOLATILIDAD PREDICHA
ModelG_vol_Sp <- sigma(Model_Gfit_sp500)
print(ModelG_vol_Sp)
## m.c.seq.row..seq.n...seq.col..drop...FALSE.
## 2010-01-05 0.010742199
## 2010-01-06 0.010742199
## 2010-01-07 0.010742199
## 2010-01-08 0.010742199
## 2010-01-11 0.009854263
## 2010-01-12 0.009017280
## 2010-01-13 0.009245316
## 2010-01-14 0.008997623
## 2010-01-15 0.008315488
## 2010-01-19 0.009155297
## ...
## 2024-12-02 0.006325886
## 2024-12-03 0.005999864
## 2024-12-04 0.005685431
## 2024-12-05 0.005936835
## 2024-12-06 0.005679221
## 2024-12-09 0.005448065
## 2024-12-10 0.005673615
## 2024-12-11 0.005633375
## 2024-12-12 0.006116162
## 2024-12-13 0.006210095
#VARIANZA A LARGO PLAZO
(Model_Gfit_sp500@fit[["coef"]][["omega"]]/1-Model_Gfit_sp500@fit[["coef"]][["alpha1"]]-Model_Gfit_sp500@fit[["coef"]][["beta1"]])
## [1] -0.9701243
sqrt(ModelG_uncva_Sp)
## [1] 0.01086682
# grafico volatilidad estimada
plot(ModelG_vol_Sp)
Como se muestra en el grafico aun se muestra mucha volatilidad en e modelo, principalmente para el 2020.
sigma(ModeloGForecast_Sp)
## 2024-12-13
## T+1 0.005878270
## T+2 0.006086821
## T+3 0.006282530
## T+4 0.006466735
## T+5 0.006640556
fitted(ModeloGForecast_Sp)
## 2024-12-13
## T+1 0.0004702718
## T+2 0.0006922934
## T+3 0.0006221871
## T+4 0.0006115272
## T+5 0.0006192476