library(readxl)
library(xts)
library(quantmod)
library(forecast)
library(tseries)
library(FinTS)
library(dynlm)
library(ggplot2)
library(rugarch)
bacolombia1 <- read_excel("C:/Users/luisa/OneDrive/Escritorio/universidad/series_de_tiempo/ultimotallercor3/Bancolombia.xlsx")
bacolombia1_xts = xts(bacolombia1$Último, order.by = bacolombia1$Fecha)
class(bacolombia1_xts)
[1] "xts" "zoo"
summary(bacolombia1)
Fecha Último
Min. :2014-01-02 00:00:00 Min. :17700
1st Qu.:2016-09-29 06:00:00 1st Qu.:26300
Median :2019-07-03 12:00:00 Median :30940
Mean :2019-07-02 00:26:53 Mean :31234
3rd Qu.:2022-03-29 18:00:00 3rd Qu.:35058
Max. :2024-12-30 00:00:00 Max. :45500
plot(bacolombia1_xts, main = "Precio último")
obtenemos el rendimiento diario de la acción
rendimiento1 = dailyReturn(bacolombia1_xts)
plot(rendimiento1, main= "Rendimiento del precio último")
Los rendimientos oscilan alrededor de cero, con algunos picos de volatilidad.
No se observa una tendencia clara, pero hay posibles agrupamientos de volatilidad.
modelo 1
modelo1 = auto.arima(rendimiento1)
summary(modelo1)
Series: rendimiento1
ARIMA(0,0,0) with zero mean
sigma^2 = 0.0004295: log likelihood = 6581.26
AIC=-13160.53 AICc=-13160.53 BIC=-13154.64
Training set error measures:
ME RMSE MAE MPE MAPE MASE ACF1
Training set 0.0003873942 0.02072389 0.01397926 100 100 1 0.0119337
autoplot(modelo1)
El modelo no tiene componentes autorregresivos (AR) y sin de medias móviles (MA)
Corresponde a un modelo ARIMA(0,0,0) (ruido blanco)
checkresiduals(modelo1)
Ljung-Box test
data: Residuals from ARIMA(0,0,0) with zero mean
Q* = 18.789, df = 10, p-value = 0.04303
Model df: 0. Total lags used: 10
ndiffs(rendimiento1)
[1] 0
adf.test(rendimiento1)
Aviso: p-value smaller than printed p-value
Augmented Dickey-Fuller Test
data: rendimiento1
Dickey-Fuller = -14.576, Lag order = 13, p-value = 0.01
alternative hypothesis: stationary
H0 = No es ESTACIONARIA si el p-value es mayor que 0.05
H1 = Si es ESTACIONARIA si el p-value es menor que 0.05
es estacionaria p-value = 0.0
El mejor modelo según auto.arima() es ARIMA(0,0,0)
La prueba ADF confirma que la serie es estacionaria (p-value = 0.01 < 0.05).
Generamos el modelo ARCH a un rezago
modeloarch1 = ArchTest(rendimiento1, lags = 1, demean = T) # lags son los rezagos
modeloarch1
ARCH LM-test; Null hypothesis: no ARCH effects
data: rendimiento1
Chi-squared = 230.2, df = 1, p-value < 2.2e-16
H0 = No hay efectos ARCH si el p-value es mayor que 0.05
H1 = Si hay efectos ARCH si el p-value es menor que 0.05
calcular los resuduales al cuadrado de nuestro modelo ARMA(0,0,0)
esto para conocer si hay heterocedastica
Errores_cuadrado = resid(modelo1)^2
plot(Errores_cuadrado, main = "Errores_cuadrado")
Box.test(Errores_cuadrado, lag = 5, type = "Ljung-Box")
Box-Ljung test
data: Errores_cuadrado
X-squared = 533.13, df = 5, p-value < 2.2e-16
Se hace una regresión con los residuales al cuadrado rezagados esto para observar si nos enfrentamos a un modelo ARCH o no
Regresion1 = dynlm(Errores_cuadrado ~ L(Errores_cuadrado,1))
summary(Regresion1)
Time series regression with "ts" data:
Start = 86401(1), End = 231292801(1)
Call:
dynlm(formula = Errores_cuadrado ~ L(Errores_cuadrado, 1))
Residuals:
Min 1Q Median 3Q Max
-0.009058 -0.000317 -0.000262 -0.000018 0.057875
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.034e-04 3.233e-05 9.384 <2e-16 ***
L(Errores_cuadrado, 1) 2.939e-01 1.848e-02 15.906 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.001621 on 2675 degrees of freedom
Multiple R-squared: 0.0864, Adjusted R-squared: 0.08606
F-statistic: 253 on 1 and 2675 DF, p-value: < 2.2e-16
H0 = No hay efectos ARCH si el p-value es mayor que 0.05
H1 = Si hay efectos ARCH si el p-value es menor que 0.05
Se revisa la autocorrelación y autocorrelación parcial
autoplot(acf(Errores_cuadrado, lag.max = 2434, ylim = c(-0.5,1))) +
labs(title = "Autocorrelación parcial de los errores al cuadrado") +
xlab("Rezagos") +
ylab("Autocorrelación parcial")
# Para identificar el orden de los efectos ARCH:
acf(Errores_cuadrado, lag.max=20)
pacf(Errores_cuadrado, lag.max=20)
ugarch1 = ugarchspec(mean.model = list(armaOrder = c(0,0)))
#resumen
ugarch1
*---------------------------------*
* GARCH Model Spec *
*---------------------------------*
Conditional Variance Dynamics
------------------------------------
GARCH Model : sGARCH(1,1)
Variance Targeting : FALSE
Conditional Mean Dynamics
------------------------------------
Mean Model : ARFIMA(0,0,0)
Include Mean : TRUE
GARCH-in-Mean : FALSE
Conditional Distribution
------------------------------------
Distribution : norm
Includes Skew : FALSE
Includes Shape : FALSE
Includes Lambda : FALSE
ugfit1 = ugarchfit(spec = ugarch1, data = rendimiento1)
ugfit1
*---------------------------------*
* 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.000639 0.000313 2.0400 0.041348
omega 0.000007 0.000002 3.0185 0.002540
alpha1 0.078693 0.008107 9.7062 0.000000
beta1 0.904183 0.005724 157.9627 0.000000
Robust Standard Errors:
Estimate Std. Error t value Pr(>|t|)
mu 0.000639 0.000290 2.2063 0.027366
omega 0.000007 0.000007 1.0516 0.292990
alpha1 0.078693 0.013101 6.0066 0.000000
beta1 0.904183 0.026879 33.6391 0.000000
LogLikelihood : 6940.956
Information Criteria
------------------------------------
Akaike -5.1807
Bayes -5.1719
Shibata -5.1807
Hannan-Quinn -5.1775
Weighted Ljung-Box Test on Standardized Residuals
------------------------------------
statistic p-value
Lag[1] 1.766 0.1839
Lag[2*(p+q)+(p+q)-1][2] 2.168 0.2363
Lag[4*(p+q)+(p+q)-1][5] 2.521 0.5014
d.o.f=0
H0 : No serial correlation
Weighted Ljung-Box Test on Standardized Squared Residuals
------------------------------------
statistic p-value
Lag[1] 1.534 0.2156
Lag[2*(p+q)+(p+q)-1][5] 3.961 0.2590
Lag[4*(p+q)+(p+q)-1][9] 6.574 0.2375
d.o.f=2
Weighted ARCH LM Tests
------------------------------------
Statistic Shape Scale P-Value
ARCH Lag[3] 0.04115 0.500 2.000 0.8392
ARCH Lag[5] 4.93650 1.440 1.667 0.1063
ARCH Lag[7] 5.62359 2.315 1.543 0.1686
Nyblom stability test
------------------------------------
Joint Statistic: 6.1846
Individual Statistics:
mu 0.02789
omega 0.49470
alpha1 0.50593
beta1 0.50523
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
------------------------------------
Adjusted Pearson Goodness-of-Fit Test:
------------------------------------
group statistic p-value(g-1)
1 20 163.9 4.392e-25
2 30 190.3 1.198e-25
3 40 238.5 1.770e-30
4 50 248.1 2.065e-28
Elapsed time : 1.144861
# ver coeficientes
ugfit1@fit$coef
mu omega alpha1 beta1
6.388982e-04 7.322562e-06 7.869304e-02 9.041831e-01
El modelo GARCH estimado tiene β₁ ≈ 1, indicando alta persistencia en la volatilidad.
Sin embargo, α₁ ≈ 0, lo que sugiere que los shocks recientes no afectan significativamente la varianza condicional.
#imprimir varianza
ug_var1 = ugfit1@fit$var
autoplot(ts(ug_var1))
# residuales
ug_resid1 = (ugfit1@fit$residuals)^2
autoplot(ts(ug_resid1))
# pronostico
ug_forecast1 = ugarchforecast(ugfit1, n.ahead = 30)
ug_forecast1
*------------------------------------*
* GARCH Model Forecast *
*------------------------------------*
Model: sGARCH
Horizon: 30
Roll Steps: 0
Out of Sample: 0
0-roll forecast [T0=2024-12-30]:
Series Sigma
T+1 0.0006389 0.01290
T+2 0.0006389 0.01307
T+3 0.0006389 0.01324
T+4 0.0006389 0.01340
T+5 0.0006389 0.01356
T+6 0.0006389 0.01371
T+7 0.0006389 0.01386
T+8 0.0006389 0.01400
T+9 0.0006389 0.01414
T+10 0.0006389 0.01428
T+11 0.0006389 0.01442
T+12 0.0006389 0.01455
T+13 0.0006389 0.01467
T+14 0.0006389 0.01480
T+15 0.0006389 0.01492
T+16 0.0006389 0.01503
T+17 0.0006389 0.01515
T+18 0.0006389 0.01526
T+19 0.0006389 0.01537
T+20 0.0006389 0.01547
T+21 0.0006389 0.01558
T+22 0.0006389 0.01568
T+23 0.0006389 0.01578
T+24 0.0006389 0.01587
T+25 0.0006389 0.01597
T+26 0.0006389 0.01606
T+27 0.0006389 0.01615
T+28 0.0006389 0.01624
T+29 0.0006389 0.01633
T+30 0.0006389 0.01641
# Último precio observado (ejemplo, debes reemplazar con el valor real)
P_t <- bacolombia1$Último[nrow(bacolombia1)]
# Pronósticos de rendimiento
R_forecasts <- c(0.0006389)
# Precios pronosticados
P_t1 <- P_t * (1 + R_forecasts[1])
P_t2 <- P_t1 * (1 + R_forecasts[1])
P_t3 <- P_t2 * (1 + R_forecasts[1])
P_t4 <- P_t3 * (1 + R_forecasts[1])
P_t5 <- P_t4 * (1 + R_forecasts[1])
P_t6 <- P_t5 * (1 + R_forecasts[1])
P_t7 <- P_t6 * (1 + R_forecasts[1])
P_t8 <- P_t7 * (1 + R_forecasts[1])
P_t9 <- P_t8 * (1 + R_forecasts[1])
P_t10 <- P_t9 * (1 + R_forecasts[1])
P_t11 <- P_t10 * (1 + R_forecasts[1])
P_t12 <- P_t11 * (1 + R_forecasts[1])
P_t13 <- P_t12 * (1 + R_forecasts[1])
P_t14 <- P_t13 * (1 + R_forecasts[1])
P_t15 <- P_t14 * (1 + R_forecasts[1])
P_t16 <- P_t15 * (1 + R_forecasts[1])
P_t17 <- P_t16 * (1 + R_forecasts[1])
P_t18 <- P_t17 * (1 + R_forecasts[1])
P_t19 <- P_t18 * (1 + R_forecasts[1])
P_t20 <- P_t19 * (1 + R_forecasts[1])
P_t21 <- P_t20 * (1 + R_forecasts[1])
P_t22 <- P_t21 * (1 + R_forecasts[1])
P_t23 <- P_t22 * (1 + R_forecasts[1])
P_t24 <- P_t23 * (1 + R_forecasts[1])
P_t25 <- P_t24 * (1 + R_forecasts[1])
P_t26 <- P_t25 * (1 + R_forecasts[1])
P_t27 <- P_t26 * (1 + R_forecasts[1])
P_t28 <- P_t27 * (1 + R_forecasts[1])
P_t29 <- P_t28 * (1 + R_forecasts[1])
P_t30 <- P_t29 * (1 + R_forecasts[1])
P_t1
[1] 23655.1
P_t5
[1] 23715.61
P_t10
[1] 23791.47
P_t20
[1] 23943.91
P_t30
[1] 24097.33
Comportamiento: Los rendimientos muestran una media cercana a cero (0.000639) con volatilidad variable
Estacionariedad: Confirmada por la prueba ADF (p-value=0.01)
Autocorrelación: El modelo ARIMA(0,0,0) sugiere que no hay estructura lineal en los rendimientos
El modelo GARCH estimado mostró alta persistencia (β₁ ≈ 1), pero con un impacto casi nulo de shocks recientes (α₁ ≈ 0).
Presencia de heterocedasticidad:
Prueba ARCH altamente significativa (p-value < 2.2e-16)
Autocorrelación en errores al cuadrado (Ljung-Box p-value < 2.2e-16)
Regresión de errores cuadrados muestra dependencia significativa (β=0.294, p<2e-16)
σ²ₜ = 7.32e-06 + 0.0787ε²ₜ₋₁ + 0.904σ²ₜ₋₁
Alta persistencia en volatilidad (β₁=0.904)
Los shocks recientes tienen impacto moderado (α₁=0.0787)
La suma α₁+β₁ ≈ 0.983 (<1) indica proceso estacionario pero con alta memoria
Rendimientos: Constantes en ~0.0006389 (0.06389% diario)
Precios proyectados:
T+1: 23,655.1
T+5: 23,715.61 (+0.26% en 5 días)
T+30: 24,097.33 (+1.87% en 30 días)
Clustering de volatilidad: Los períodos de alta volatilidad tienden a agruparse temporalmente
Persistencia: La volatilidad muestra memoria de largo plazo (β₁ cercano a 1)