En el presente trabajo presentare la elaboración de un modelo Garchs simétricos
y asimetricos, el sotfware eleigido es R y su editor es Rstudio el scrip sera
presentado al final o se podra descargar directo en desde la pagina de Rpub.
library(quantmod)
Loading required package: xts
Loading required package: zoo
Attaching package: 㤼㸱zoo㤼㸲
The following objects are masked from 㤼㸱package:base㤼㸲:
as.Date, as.Date.numeric
Loading required package: TTR
Registered S3 method overwritten by 'quantmod':
method from
as.zoo.data.frame zoo
Version 0.4-0 included new data defaults. See ?getSymbols.
library(PerformanceAnalytics)
Attaching package: 㤼㸱PerformanceAnalytics㤼㸲
The following object is masked from 㤼㸱package:graphics㤼㸲:
legend
library(tseries)
㤼㸱tseries㤼㸲 version: 0.10-47
㤼㸱tseries㤼㸲 is a package for time series analysis and computational finance.
See 㤼㸱library(help="tseries")㤼㸲 for details.
library(MLmetrics)
Attaching package: 㤼㸱MLmetrics㤼㸲
The following object is masked from 㤼㸱package:base㤼㸲:
Recall
library(normtest)
library(forecast)
library(tidyverse)
Registered S3 methods overwritten by 'dbplyr':
method from
print.tbl_lazy
print.tbl_sql
-- Attaching packages --------------------------------------- tidyverse 1.3.0 --
v ggplot2 3.3.0 v purrr 0.3.4
v tibble 3.0.3 v dplyr 1.0.0
v tidyr 1.1.0 v stringr 1.4.0
v readr 1.3.1 v forcats 0.5.0
-- Conflicts ------------------------------------------ tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::first() masks xts::first()
x dplyr::lag() masks stats::lag()
x dplyr::last() masks xts::last()
library(readxl)
fechas<-seq(fecha,by="daily",length=length(data))
Error in seq.Date(fecha, by = "daily", length = length(data)) :
invalid string for 'by'
chartSeries(TC, type = "candlesticks", theme = "white", TA = 'addBBands(); addBBands(draw = "p"); addVo(); addMACD(); addRSI(); addSMA()',
subset = "last 60 weeks",name = "Tipo de cambio USD/PEN")
requested length is greater than original
retornos<-Return.calculate(TC,method = "log")[-1]
chartSeries(retornos,name="Retorno del tipo de cambio",subset = "last 50 week",theme = "white")
requested length is greater than original
adf.test(retornos)
p-value smaller than printed p-value
Augmented Dickey-Fuller Test
data: retornos
Dickey-Fuller = -6.0177, Lag order = 6, p-value = 0.01
alternative hypothesis: stationary
Por cuestión de tiempo solo utiliare la función ´´´auto.arima()´´´ del paquete
´´´forecast´´´
par(mfrow=c(1,2))
acf(retornos)
pacf(retornos)
layout(1)
modelo<-auto.arima(retornos)
summary(modelo)
Series: retornos
ARIMA(1,0,1) with zero mean
Coefficients:
ar1 ma1
-0.1502 0.4920
s.e. 0.1698 0.1495
sigma^2 estimated as 0.0001242: log likelihood=791.94
AIC=-1577.88 AICc=-1577.79 BIC=-1567.23
Training set error measures:
ME RMSE MAE MPE MAPE MASE ACF1
Training set 0.0001930351 0.0111012 0.00803595 96.56709 126.0553 0.8591846 -0.01743586
El mejor modelo es un ARMA(1,1) para los retornos.
p<-seq(0,2)
q<-seq(0,2)
datos<-NULL
indice<- NULL
for(i in p){
for(a in q){
ata<- summary(arma(retornos,order = c(i,a)))$aic
datos<- c(datos,ata)
atita<- paste(i,a)
indice<- c(indice,atita)
table<- data.frame("ARMA"=indice,"AIC"=datos)
print(table)
}
}
one-dimensional optimization by Nelder-Mead is unreliable:
use "Brent" or optimize() directly
Siendo el mejor modelo escogido por el menor AIC es el modelo ARMA(1,1) para los retornos
Por motivo de tiempo solo se procedera hacer los modelos la teoría de tras de ello
no se tocara a fondo.
residuos<-na.omit(modelo$residuals)^2
par(mfrow=c(1,2))
acf(residuos)
pacf(residuos)
layout(1)
Por teoria el GARCH(1,1) es el mejor asi que solo hare:
library(rugarch)
Loading required package: parallel
Attaching package: 㤼㸱rugarch㤼㸲
The following object is masked from 㤼㸱package:purrr㤼㸲:
reduce
The following object is masked from 㤼㸱package:stats㤼㸲:
sigma
ata=ugarchfit(data = residuos,spec = ugarchspec())
ata
*---------------------------------*
* GARCH Model Fit *
*---------------------------------*
Conditional Variance Dynamics
-----------------------------------
GARCH Model : sGARCH(1,1)
Mean Model : ARFIMA(1,0,1)
Distribution : norm
Optimal Parameters
------------------------------------
Estimate Std. Error t value Pr(>|t|)
mu 0.000113 0.000019 6.018828 0.000000
ar1 0.308770 0.222481 1.387848 0.165183
ma1 0.008990 0.217228 0.041387 0.966988
omega 0.000000 0.000000 0.005223 0.995833
alpha1 0.056306 0.012983 4.336888 0.000014
beta1 0.901117 0.021822 41.293699 0.000000
Robust Standard Errors:
Estimate Std. Error t value Pr(>|t|)
mu 0.000113 0.003430 0.032801 0.97383
ar1 0.308770 882.720544 0.000350 0.99972
ma1 0.008990 945.645293 0.000010 0.99999
omega 0.000000 0.002016 0.000001 1.00000
alpha1 0.056306 351.463825 0.000160 0.99987
beta1 0.901117 310.203534 0.002905 0.99768
LogLikelihood : 1794.972
Information Criteria
------------------------------------
Akaike -13.922
Bayes -13.839
Shibata -13.923
Hannan-Quinn -13.889
Weighted Ljung-Box Test on Standardized Residuals
------------------------------------
statistic p-value
Lag[1] 0.07418 0.7853
Lag[2*(p+q)+(p+q)-1][5] 1.52283 0.9976
Lag[4*(p+q)+(p+q)-1][9] 3.37917 0.8252
d.o.f=2
H0 : No serial correlation
Weighted Ljung-Box Test on Standardized Squared Residuals
------------------------------------
statistic p-value
Lag[1] 0.006731 0.9346
Lag[2*(p+q)+(p+q)-1][5] 0.213784 0.9915
Lag[4*(p+q)+(p+q)-1][9] 0.399407 0.9993
d.o.f=2
Weighted ARCH LM Tests
------------------------------------
Statistic Shape Scale P-Value
ARCH Lag[3] 0.1677 0.500 2.000 0.6821
ARCH Lag[5] 0.2393 1.440 1.667 0.9560
ARCH Lag[7] 0.2955 2.315 1.543 0.9930
Nyblom stability test
------------------------------------
Joint Statistic: 74.1615
Individual Statistics:
mu 0.07828
ar1 0.02974
ma1 0.05880
omega 7.69870
alpha1 0.23736
beta1 0.09644
Asymptotic Critical Values (10% 5% 1%)
Joint Statistic: 1.49 1.68 2.12
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 327.7 4.134e-58
2 30 367.9 2.300e-60
3 40 380.7 1.294e-57
4 50 398.1 3.477e-56
Elapsed time : 0.1089871
specificacion= ugarchspec(
variance.model=list(model="fGARCH", submodel="TGARCH",garchOrder=c(1,1)),
mean.model=list(armaOrder=c(2,1))
)
ata2=ugarchfit(data = residuos,spec = specificacion)
curva2=newsimpact(ata2)
plot(curva2$zx,curva2$zy,type="l",main="Curva de impacto")
pre %>% plot()
Make a plot selection (or 0 to exit):
1: Time Series Prediction (unconditional)
2: Time Series Prediction (rolling)
3: Sigma Prediction (unconditional)
4: Sigma Prediction (rolling)
1
Make a plot selection (or 0 to exit):
1: Time Series Prediction (unconditional)
2: Time Series Prediction (rolling)
3: Sigma Prediction (unconditional)
4: Sigma Prediction (rolling)
3
Make a plot selection (or 0 to exit):
1: Time Series Prediction (unconditional)
2: Time Series Prediction (rolling)
3: Sigma Prediction (unconditional)
4: Sigma Prediction (rolling)
0
m=mean(retornos)
s=sd(retornos)
par.2<-VaR(retornos,p=0.99,method = "gaussian")
ggplot(retornos,aes(TC))+geom_histogram(aes(
y=..density..
),binwidth = 0.01,fill="blue",color="black",alpha=0.4)+geom_vline(xintercept = par.2,lty=2)+
stat_function(fun = dnorm,args =
list(mean=m,sd=s),col="red")+labs(title="VaR de los retornos")
par(mfrow=c(1,1))
plot(density(retornos), main = "Retorno de Distribución Empírica"); curve(dnorm(x, mean = m, sd = s), from = -0.1, to = 0.1, add = TRUE, col = 'blue')