BTCSP <- read.csv("C:/Users/Personal/Desktop/BTCSP.csv", sep=";")
apple<-BTCSP
Revisión de valores de inicio y finales de la base de datos.
head(apple)
##         Date BTC.Close SP.Close
## 1 01.01.2014     740.3  1842.95
## 2 02.01.2014     775.0  1826.50
## 3 03.01.2014     812.1  1825.50
## 4 06.01.2014     934.5  1820.75
## 5 07.01.2014     791.0  1830.75
## 6 08.01.2014     828.5  1832.50
tail(apple)
##            Date BTC.Close SP.Close
## 1599 24.01.2020    8447.1  3293.50
## 1600 26.01.2020    8621.6  3259.12
## 1601 27.01.2020    8912.0  3239.50
## 1602 28.01.2020    9393.7  3278.25
## 1603 29.01.2020    9304.2  3272.50
## 1604 30.01.2020    9512.7  3289.38
library(zoo)
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
Construcción de objeto zoo y gráfico de series de tiempo.
apple.zoo=zoo(apple[,-1], order.by=as.Date(strptime(as.character(apple[,1]), "%d.%m.%Y")))
plot(apple.zoo, main="Precios de Cierre BTC y S&P 500 (2014-2020)")

###### Análisis y suavización de datos medias móviles.

library(chron)
plot(rollapply(apple.zoo, width=120, mean, na.rm=T), main="Mean of Rolling  120 Obs.")

plot(rollapply(apple.zoo, width=120, mean, by=120, na.rm=T),main="Mean of Each 120 Obs.")

Análisis de retornos

library(PerformanceAnalytics)
## Loading required package: xts
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
tmp <- merge(apple.zoo[,"BTC.Close"], apple.zoo[,"SP.Close"])
tmp.ret <- CalculateReturns(tmp)
colnames(tmp) <- colnames(tmp.ret) <- c("BTC.Close","SP.Close")
plot(tmp, main="Precios de Cierre BTC y S&P 500 (2014-2020)", xlab="Date")

plot(tmp.ret, main="Retornos Precios Cierre BTC y S&P 500 (2014-2020)", xlab="Date")

###### Función coredate

plot(coredata(na.omit(tmp.ret)), pch=".", main="Retornos Precios Cierre BTC y S&P 500 (2014-2020)")

Coeficientes de regresión precios de cierre BTC a través de S&P 500

rr <- rollapply(na.approx(na.trim(tmp, side="both")), width = 120,
                FUN = function(z) coef(lm(BTC.Close ~ SP.Close, data = as.data.frame(z))),
                by.column = FALSE, align = "right")
rr.var <- rollapply(na.approx(na.trim(tmp, side="both")), width = 120,
                    FUN = function(z) sd(residuals(lm(BTC.Close ~ SP.Close, data = as.data.frame(z)))),
                    by.column = FALSE, align = "right")
res <- merge(rr,rr.var)
colnames(res)[3] <- "Desv  Estandar Res." 
plot(res, main="Coeficiente de Regresion.", xlab="Date")

Resumen y distribución de datos del modelo.
summary(res)
##      Index             (Intercept)           SP.Close       
##  Min.   :2014-06-18   Min.   :-120844.4   Min.   :-10.3194  
##  1st Qu.:2015-11-13   1st Qu.: -14978.2   1st Qu.: -0.1529  
##  Median :2017-04-11   Median :   -903.8   Median :  0.8113  
##  Mean   :2017-04-11   Mean   : -10054.0   Mean   :  5.2066  
##  3rd Qu.:2018-09-06   3rd Qu.:    702.8   3rd Qu.:  7.5255  
##  Max.   :2020-01-30   Max.   :  40337.8   Max.   : 50.1830  
##  Desv  Estandar Res.
##  Min.   :  17.97    
##  1st Qu.:  65.97    
##  Median : 108.01    
##  Mean   : 673.01    
##  3rd Qu.: 997.44    
##  Max.   :3048.28
hist(res[,"SP.Close"], breaks=100, main="Histograma de los coeficientes estimados", xlab="Value")

Coeficiente de regresion con los retornos de la Serie.

rr <- rollapply(na.approx(na.trim(tmp.ret, side="both")), width = 120,
                FUN = function(z) coef(lm(BTC.Close~ SP.Close, data = as.data.frame(z))),
                by.column = FALSE, align = "right")
rr.var <- rollapply(na.approx(na.trim(tmp.ret, side="both")), width = 120,
                    FUN = function(z) sd(residuals(lm (BTC.Close~ SP.Close, data = as.data.frame(z)))),
                    by.column = FALSE, align = "right")
res.ret <- merge(rr,rr.var)
colnames(res.ret)[3] <- "St. Dev. Resid." 
plot(res.ret, main="Coeficiente de regression de los retornos de las series.", xlab="Date")

Resumen y distribución de errores.
summary(res.ret)
##      Index             (Intercept)           SP.Close        St. Dev. Resid.  
##  Min.   :2014-06-19   Min.   :-0.008115   Min.   :-1.90007   Min.   :0.01588  
##  1st Qu.:2015-11-15   1st Qu.:-0.001573   1st Qu.:-0.50235   1st Qu.:0.03541  
##  Median :2017-04-11   Median : 0.002882   Median :-0.05253   Median :0.04189  
##  Mean   :2017-04-11   Mean   : 0.002795   Mean   : 0.08352   Mean   :0.04359  
##  3rd Qu.:2018-09-06   3rd Qu.: 0.006041   3rd Qu.: 0.39382   3rd Qu.:0.04975  
##  Max.   :2020-01-30   Max.   : 0.017093   Max.   : 3.41480   Max.   :0.06856
hist(res.ret[,"SP.Close"], breaks=100, main="Histograma coeficientes estimados de los retornos", xlab="Value")

Análisis de la desviación estándar.

library(xts)
tail(to.yearly(apple.zoo))
##            apple.zoo.Open apple.zoo.High apple.zoo.Low apple.zoo.Close
## 2015-12-31          313.9          466.5         183.0           429.0
## 2016-12-30          432.9          981.7         358.9           959.3
## 2017-12-29         1019.3        18934.0         778.6         14317.0
## 2018-12-31        13354.0        16917.0        3282.8          3830.5
## 2019-12-31         3963.0        12876.0        3436.1          7208.3
## 2020-01-30         7212.7         9512.7        6989.4          9512.7
start(apple.zoo)
## [1] "2014-01-01"
end(apple.zoo)
## [1] "2020-01-30"
plot(apply.monthly(window(apple.zoo [,"BTC.Close"], start="2014-01-01") ,function(x) sd(x, na.rm=TRUE)), main="D.E Mensual de los Precios de Cierre de BTC 2014-20", ylab="Desviacion Estandar", xlab="Año")

plot(apply.yearly(window(apple.zoo[,"BTC.Close"], start="2014-01-01",end="2019-12-30") ,function(x) sd(x, na.rm=TRUE)), main="D.E Anual de los Precios de Cierre de BTC 2014-19", ylab="Desviacion Estandar", xlab="Año")

plot(apply.monthly(window(apple.zoo [,"SP.Close"], start="2014-01-01") ,function(x) sd(x, na.rm=TRUE)), main="D.E Mensual de los Precios de Cierre del S&P500 2014-20", ylab="Desviacion Estandar", xlab="Año")

plot(apply.yearly(window(apple.zoo[,"SP.Close"], start="2014-01-01",end="2019-12-30") ,function(x) sd(x, na.rm=TRUE)), main="D.E Anual de los Precios de Cierre del S&P500 2014-19", ylab="Desviacion Estandar", xlab="Año")

Modelización ARIMA

library(vars)
## Loading required package: MASS
## Loading required package: strucchange
## Loading required package: sandwich
## Loading required package: urca
## Loading required package: lmtest
library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Registered S3 methods overwritten by 'forecast':
##   method             from    
##   fitted.fracdiff    fracdiff
##   residuals.fracdiff fracdiff
library(TSA)
## Registered S3 methods overwritten by 'TSA':
##   method       from    
##   fitted.Arima forecast
##   plot.Arima   forecast
## 
## Attaching package: 'TSA'
## The following objects are masked from 'package:PerformanceAnalytics':
## 
##     kurtosis, skewness
## The following objects are masked from 'package:stats':
## 
##     acf, arima
## The following object is masked from 'package:utils':
## 
##     tar
library(ggplot2)
library(tseries)
## 
## Attaching package: 'tseries'
## The following object is masked from 'package:chron':
## 
##     is.weekend
Gráficas y aplicación de logaritmos y diferencias.
apple.mod <- na.approx(na.trim(apple.zoo[,"BTC.Close"], side="both"))
head(to.daily(apple.mod))
##            apple.mod.Open apple.mod.High apple.mod.Low apple.mod.Close
## 2014-01-01          740.3          740.3         740.3           740.3
## 2014-01-02          775.0          775.0         775.0           775.0
## 2014-01-03          812.1          812.1         812.1           812.1
## 2014-01-06          934.5          934.5         934.5           934.5
## 2014-01-07          791.0          791.0         791.0           791.0
## 2014-01-08          828.5          828.5         828.5           828.5
apple.mod1 <- to.daily(apple.mod)[,"apple.mod.Close"]
start(apple.mod1)
## [1] "2014-01-01"
apple.ts <- ts(apple.mod1, start=c(2014,01,01), freq=270)
autoplot(log(apple.ts), main="Log de Los Precios de Cierre de BTC 2014-20")

ggtsdisplay(diff(log(apple.ts)))

adf.test(diff(log(apple.ts)))
## Warning in adf.test(diff(log(apple.ts))): p-value smaller than printed p-value
## 
##  Augmented Dickey-Fuller Test
## 
## data:  diff(log(apple.ts))
## Dickey-Fuller = -10.811, Lag order = 11, p-value = 0.01
## alternative hypothesis: stationary
pp.test(diff(log(apple.ts), alternative="stationary"))
## Warning in pp.test(diff(log(apple.ts), alternative = "stationary")): p-value
## smaller than printed p-value
## 
##  Phillips-Perron Unit Root Test
## 
## data:  diff(log(apple.ts), alternative = "stationary")
## Dickey-Fuller Z(alpha) = -1696.1, Truncation lag parameter = 8, p-value
## = 0.01
## alternative hypothesis: stationary
plot(decompose(diff(log(apple.ts))))

arima(log(apple.ts), order = c(0,1,0))
## 
## Call:
## arima(x = log(apple.ts), order = c(0, 1, 0))
## 
## 
## sigma^2 estimated as 0.002075:  log likelihood = 2677.01,  aic = -5354.03
arima(log(apple.ts), order = c(1,1,1))
## 
## Call:
## arima(x = log(apple.ts), order = c(1, 1, 1))
## 
## Coefficients:
##          ar1      ma1
##       0.1991  -0.2177
## s.e.  0.8046   0.7909
## 
## sigma^2 estimated as 0.002074:  log likelihood = 2677.31,  aic = -5350.62
Test de validación
tsdiag(arima(log(apple.ts), order = c(0,1,0)))

tsdiag(arima(log(apple.ts), order = c(1,1,1)))

checkresiduals(arima(log(apple.ts), order = c(0,1,0)))

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(0,1,0)
## Q* = 350.21, df = 321, p-value = 0.126
## 
## Model df: 0.   Total lags used: 321

Modelización Garch (Completo)

library(rmgarch)
## Loading required package: rugarch
## Loading required package: parallel
## 
## Attaching package: 'rugarch'
## The following object is masked from 'package:stats':
## 
##     sigma
## 
## Attaching package: 'rmgarch'
## The following objects are masked from 'package:xts':
## 
##     first, last
library(PerformanceAnalytics)
model<- window(apple.zoo [,"BTC.Close"],  start="2014-01-01")
model<- na.approx(na.trim(CalculateReturns(model), side="both"))
spec = ugarchspec()
print(spec)
## 
## *---------------------------------*
## *       GARCH Model Spec          *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## ------------------------------------
## GARCH Model      : sGARCH(1,1)
## Variance Targeting   : FALSE 
## 
## Conditional Mean Dynamics
## ------------------------------------
## Mean Model       : ARFIMA(1,0,1)
## Include Mean     : TRUE 
## GARCH-in-Mean        : FALSE 
## 
## Conditional Distribution
## ------------------------------------
## Distribution :  norm 
## Includes Skew    :  FALSE 
## Includes Shape   :  FALSE 
## Includes Lambda  :  FALSE
def.fit = ugarchfit(spec = spec, data = model)
print(def.fit)
## 
## *---------------------------------*
## *          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.002540    0.001101   2.3077 0.021014
## ar1     0.814833    0.382341   2.1312 0.033075
## ma1    -0.791863    0.402468  -1.9675 0.049124
## omega   0.000125    0.000026   4.7669 0.000002
## alpha1  0.122571    0.020129   6.0893 0.000000
## beta1   0.825323    0.024812  33.2629 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.002540    0.001164   2.1824 0.029081
## ar1     0.814833    0.541378   1.5051 0.132296
## ma1    -0.791863    0.565336  -1.4007 0.161305
## omega   0.000125    0.000074   1.6862 0.091765
## alpha1  0.122571    0.033899   3.6158 0.000299
## beta1   0.825323    0.052460  15.7325 0.000000
## 
## LogLikelihood : 2788.191 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -3.4712
## Bayes        -3.4511
## Shibata      -3.4713
## Hannan-Quinn -3.4638
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.1034  0.7478
## Lag[2*(p+q)+(p+q)-1][5]    1.3352  0.9995
## Lag[4*(p+q)+(p+q)-1][9]    4.7756  0.5055
## d.o.f=2
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.3453  0.5568
## Lag[2*(p+q)+(p+q)-1][5]    1.0215  0.8548
## Lag[4*(p+q)+(p+q)-1][9]    1.3170  0.9692
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.2712 0.500 2.000  0.6025
## ARCH Lag[5]    0.3865 1.440 1.667  0.9165
## ARCH Lag[7]    0.4865 2.315 1.543  0.9796
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  1.3331
## Individual Statistics:              
## mu     0.32344
## ar1    0.03306
## ma1    0.03301
## omega  0.10592
## alpha1 0.07153
## beta1  0.10984
## 
## 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
## ------------------------------------
##                    t-value   prob sig
## Sign Bias           1.0648 0.2871    
## Negative Sign Bias  1.1088 0.2677    
## Positive Sign Bias  0.7929 0.4279    
## Joint Effect        1.9171 0.5898    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     286.9    9.624e-50
## 2    30     299.4    1.056e-46
## 3    40     316.5    3.768e-45
## 4    50     329.7    3.034e-43
## 
## 
## Elapsed time : 1.699994
Modelo eGarch (2,1) Distribución de errores T-Student
garch112e2.2.2.spec = ugarchspec(mean.model = list(armaOrder = c(0,0)), 
                               variance.model = list(garchOrder = c(2,1),
                                                     model = "eGARCH"), distribution.model = "std")
garch.fit112e2.2.2= ugarchfit(garch112e2.2.2.spec, data = model, fit.control=list(scale=TRUE))
print(garch.fit112e2.2.2)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : eGARCH(2,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : std 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.001261    0.000528   2.3895 0.016871
## omega  -0.098617    0.052158  -1.8908 0.058657
## alpha1 -0.091854    0.062178  -1.4773 0.139602
## alpha2  0.112060    0.062577   1.7908 0.073330
## beta1   0.983072    0.008942 109.9359 0.000000
## gamma1  0.451433    0.099049   4.5577 0.000005
## gamma2 -0.137387    0.080693  -1.7026 0.088644
## shape   2.550534    0.186797  13.6540 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.001261    0.000509   2.4788 0.013183
## omega  -0.098617    0.070233  -1.4041 0.160275
## alpha1 -0.091854    0.065685  -1.3984 0.161993
## alpha2  0.112060    0.064881   1.7272 0.084139
## beta1   0.983072    0.012533  78.4368 0.000000
## gamma1  0.451433    0.107693   4.1918 0.000028
## gamma2 -0.137387    0.085209  -1.6124 0.106885
## shape   2.550534    0.197290  12.9278 0.000000
## 
## LogLikelihood : 3036.887 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -3.7790
## Bayes        -3.7522
## Shibata      -3.7791
## Hannan-Quinn -3.7691
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      3.322 0.06836
## Lag[2*(p+q)+(p+q)-1][2]     4.493 0.05561
## Lag[4*(p+q)+(p+q)-1][5]     7.590 0.03721
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                          statistic p-value
## Lag[1]                      0.1405  0.7078
## Lag[2*(p+q)+(p+q)-1][8]     0.7473  0.9883
## Lag[4*(p+q)+(p+q)-1][14]    1.9573  0.9920
## d.o.f=3
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[4]   0.01235 0.500 2.000  0.9115
## ARCH Lag[6]   0.38116 1.461 1.711  0.9244
## ARCH Lag[8]   0.58042 2.368 1.583  0.9750
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  2.4443
## Individual Statistics:              
## mu     0.51929
## omega  0.17655
## alpha1 0.40823
## alpha2 0.42594
## beta1  0.14497
## gamma1 0.09465
## gamma2 0.09181
## shape  0.13315
## 
## 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.0846 0.2783    
## Negative Sign Bias  0.4547 0.6494    
## Positive Sign Bias  1.4585 0.1449    
## Joint Effect        3.0063 0.3907    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     38.41     0.005261
## 2    30     38.43     0.113098
## 3    40     53.32     0.062957
## 4    50     50.24     0.423920
## 
## 
## Elapsed time : 2.322001
garch.fit = ugarchfit(garch112e2.2.2.spec, data = model, fit.control=list(scale=TRUE))
print(garch.fit)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : eGARCH(2,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : std 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.001261    0.000528   2.3895 0.016871
## omega  -0.098617    0.052158  -1.8908 0.058657
## alpha1 -0.091854    0.062178  -1.4773 0.139602
## alpha2  0.112060    0.062577   1.7908 0.073330
## beta1   0.983072    0.008942 109.9359 0.000000
## gamma1  0.451433    0.099049   4.5577 0.000005
## gamma2 -0.137387    0.080693  -1.7026 0.088644
## shape   2.550534    0.186797  13.6540 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.001261    0.000509   2.4788 0.013183
## omega  -0.098617    0.070233  -1.4041 0.160275
## alpha1 -0.091854    0.065685  -1.3984 0.161993
## alpha2  0.112060    0.064881   1.7272 0.084139
## beta1   0.983072    0.012533  78.4368 0.000000
## gamma1  0.451433    0.107693   4.1918 0.000028
## gamma2 -0.137387    0.085209  -1.6124 0.106885
## shape   2.550534    0.197290  12.9278 0.000000
## 
## LogLikelihood : 3036.887 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -3.7790
## Bayes        -3.7522
## Shibata      -3.7791
## Hannan-Quinn -3.7691
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      3.322 0.06836
## Lag[2*(p+q)+(p+q)-1][2]     4.493 0.05561
## Lag[4*(p+q)+(p+q)-1][5]     7.590 0.03721
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                          statistic p-value
## Lag[1]                      0.1405  0.7078
## Lag[2*(p+q)+(p+q)-1][8]     0.7473  0.9883
## Lag[4*(p+q)+(p+q)-1][14]    1.9573  0.9920
## d.o.f=3
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[4]   0.01235 0.500 2.000  0.9115
## ARCH Lag[6]   0.38116 1.461 1.711  0.9244
## ARCH Lag[8]   0.58042 2.368 1.583  0.9750
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  2.4443
## Individual Statistics:              
## mu     0.51929
## omega  0.17655
## alpha1 0.40823
## alpha2 0.42594
## beta1  0.14497
## gamma1 0.09465
## gamma2 0.09181
## shape  0.13315
## 
## 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.0846 0.2783    
## Negative Sign Bias  0.4547 0.6494    
## Positive Sign Bias  1.4585 0.1449    
## Joint Effect        3.0063 0.3907    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     38.41     0.005261
## 2    30     38.43     0.113098
## 3    40     53.32     0.062957
## 4    50     50.24     0.423920
## 
## 
## Elapsed time : 2.003004
plot(garch.fit, which=3)

###### Gráfica de Valor en Riesgo VaR

plot(garch.fit, which=2)
## 
## please wait...calculating quantiles...

###### Valor en riesgo y reportes.

garchroll <- ugarchroll(garch112e2.2.2.spec, data = model, n.start =500,
                        refit.window = "moving"
                        , refit.every = 100)
garchVaR <- quantile(garchroll, probs=0.01)
actual <- xts(as.data.frame(garchroll)$Realized, time(garchVaR))

mean(actual < garchVaR)
## [1] 0.008159565
VaRplot(alpha = 0.01, actual = actual, VaR = garchVaR)

report(garchroll, type = "VaR", VaR.alpha = 0.01, conf.level = 0.99)
## VaR Backtest Report
## ===========================================
## Model:               eGARCH-std
## Backtest Length: 1103
## Data:                
## 
## ==========================================
## alpha:               1%
## Expected Exceed: 11
## Actual VaR Exceed:   9
## Actual %:            0.8%
## 
## Unconditional Coverage (Kupiec)
## Null-Hypothesis: Correct Exceedances
## LR.uc Statistic: 0.403
## LR.uc Critical:      6.635
## LR.uc p-value:       0.526
## Reject Null:     NO
## 
## Conditional Coverage (Christoffersen)
## Null-Hypothesis: Correct Exceedances and
##                  Independence of Failures
## LR.cc Statistic: 0.551
## LR.cc Critical:      9.21
## LR.cc p-value:       0.759
## Reject Null:     NO
Gráficos de residuos del modelo.
plot(garch.fit, which=1)

plot(garch.fit, which=8)

plot(garch.fit, which=9)

plot(garch.fit, which=12)

plot(garch.fit, which = "all")
## 
## please wait...calculating quantiles...

###### Interpretación y pronósticos.

forecast1<-ugarchforecast(garch.fit,n.ahead = 3) 
forecast1
## 
## *------------------------------------*
## *       GARCH Model Forecast         *
## *------------------------------------*
## Model: eGARCH
## Horizon: 3
## Roll Steps: 0
## Out of Sample: 0
## 
## 0-roll forecast [T0=2020-01-30]:
##       Series   Sigma
## T+1 0.001261 0.04461
## T+2 0.001261 0.04622
## T+3 0.001261 0.04635
plot(forecast1,which=1)

plot(forecast1,which=3)

###### Método Forecast Rolling.

modelfit=ugarchfit(garch112e2.2.2.spec,data=model, solver="hybrid", out.sample=5)
modelforecast<-ugarchforecast(modelfit, data = NULL, n.ahead = 10, n.roll = 5, external.forecasts = list(mregfor = NULL, vregfor = NULL))
modelforecast
## 
## *------------------------------------*
## *       GARCH Model Forecast         *
## *------------------------------------*
## Model: eGARCH
## Horizon: 10
## Roll Steps: 5
## Out of Sample: 5
## 
## 0-roll forecast [T0=2020-01-24]:
##        Series   Sigma
## T+1  0.001192 0.03927
## T+2  0.001192 0.04096
## T+3  0.001192 0.04116
## T+4  0.001192 0.04136
## T+5  0.001192 0.04155
## T+6  0.001192 0.04174
## T+7  0.001192 0.04193
## T+8  0.001192 0.04212
## T+9  0.001192 0.04230
## T+10 0.001192 0.04249
Pronósticos a 10 días.
plot(modelforecast,which=2)

plot(modelforecast,which=4)

Modelo Garch de correlacion dinamica condicional-DCC Garch

garch1 <- merge(apple.zoo[,"BTC.Close"], apple.zoo[,"SP.Close"])
colnames(garch1)<-c("BTC","SP")
tst <- na.approx(na.trim(CalculateReturns(garch1), side="both"))
garch112e2.2.2.spec= ugarchspec(mean.model = list(armaOrder = c(0,0)), 
variance.model = list(garchOrder = c(2,1), 
model = "eGARCH"), distribution.model = "std")
dcc.garch12.1.spec = dccspec(uspec = multispec( replicate(2, garch112e2.2.2.spec )), dccOrder = c(1,1),model = "aDCC",distribution ="mvt")
dcc.fit.1 = dccfit(dcc.garch12.1.spec, data = tst, fit.control=list(scale=TRUE))
print(dcc.fit.1)
## 
## *---------------------------------*
## *          DCC GARCH Fit          *
## *---------------------------------*
## 
## Distribution         :  mvt
## Model                :  aDCC(1,1)
## No. Parameters       :  21
## [VAR GARCH DCC UncQ] : [0+16+4+1]
## No. Series           :  2
## No. Obs.             :  1603
## Log-Likelihood       :  8717.84
## Av.Log-Likelihood    :  5.44 
## 
## Optimal Parameters
## -----------------------------------
##                Estimate  Std. Error   t value Pr(>|t|)
## [BTC].mu       0.001261    0.000443  2.845261 0.004437
## [BTC].omega   -0.098617    0.067614 -1.458534 0.144694
## [BTC].alpha1  -0.091854    0.059079 -1.554772 0.120000
## [BTC].alpha2   0.112060    0.059290  1.890041 0.058753
## [BTC].beta1    0.983072    0.012050 81.580138 0.000000
## [BTC].gamma1   0.451433    0.105853  4.264710 0.000020
## [BTC].gamma2  -0.137387    0.080808 -1.700162 0.089100
## [BTC].shape    2.550534    0.075947 33.583264 0.000000
## [SP].mu        0.000503    0.000472  1.065980 0.286433
## [SP].omega    -0.588570    0.317145 -1.855837 0.063477
## [SP].alpha1   -0.213872    0.117771 -1.816000 0.069370
## [SP].alpha2   -0.042003    0.050273 -0.835489 0.403442
## [SP].beta1     0.941702    0.032926 28.600350 0.000000
## [SP].gamma1    0.220626    0.133934  1.647270 0.099503
## [SP].gamma2   -0.025682    0.122223 -0.210124 0.833571
## [SP].shape     4.896249    1.087639  4.501721 0.000007
## [Joint]dcca1   0.012674    0.008973  1.412385 0.157837
## [Joint]dccb1   0.947733    0.038296 24.747789 0.000000
## [Joint]dccg1   0.000410    0.010705  0.038321 0.969431
## [Joint]mshape  4.000001    0.329756 12.130200 0.000000
## 
## Information Criteria
## ---------------------
##                     
## Akaike       -10.851
## Bayes        -10.780
## Shibata      -10.851
## Hannan-Quinn -10.825
## 
## 
## Elapsed time : 22.07168
Retornos de las series.
garch.fit = ugarchfit(garch112e2.2.2.spec, data = tst[,1], fit.control=list(scale=TRUE))

print(garch.fit)
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : eGARCH(2,1)
## Mean Model   : ARFIMA(0,0,0)
## Distribution : std 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.001261    0.000528   2.3895 0.016871
## omega  -0.098617    0.052158  -1.8908 0.058657
## alpha1 -0.091854    0.062178  -1.4773 0.139602
## alpha2  0.112060    0.062577   1.7908 0.073330
## beta1   0.983072    0.008942 109.9359 0.000000
## gamma1  0.451433    0.099049   4.5577 0.000005
## gamma2 -0.137387    0.080693  -1.7026 0.088644
## shape   2.550534    0.186797  13.6540 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.001261    0.000509   2.4788 0.013183
## omega  -0.098617    0.070233  -1.4041 0.160275
## alpha1 -0.091854    0.065685  -1.3984 0.161993
## alpha2  0.112060    0.064881   1.7272 0.084139
## beta1   0.983072    0.012533  78.4368 0.000000
## gamma1  0.451433    0.107693   4.1918 0.000028
## gamma2 -0.137387    0.085209  -1.6124 0.106885
## shape   2.550534    0.197290  12.9278 0.000000
## 
## LogLikelihood : 3036.887 
## 
## Information Criteria
## ------------------------------------
##                     
## Akaike       -3.7790
## Bayes        -3.7522
## Shibata      -3.7791
## Hannan-Quinn -3.7691
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                      3.322 0.06836
## Lag[2*(p+q)+(p+q)-1][2]     4.493 0.05561
## Lag[4*(p+q)+(p+q)-1][5]     7.590 0.03721
## d.o.f=0
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                          statistic p-value
## Lag[1]                      0.1405  0.7078
## Lag[2*(p+q)+(p+q)-1][8]     0.7473  0.9883
## Lag[4*(p+q)+(p+q)-1][14]    1.9573  0.9920
## d.o.f=3
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[4]   0.01235 0.500 2.000  0.9115
## ARCH Lag[6]   0.38116 1.461 1.711  0.9244
## ARCH Lag[8]   0.58042 2.368 1.583  0.9750
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  2.4443
## Individual Statistics:              
## mu     0.51929
## omega  0.17655
## alpha1 0.40823
## alpha2 0.42594
## beta1  0.14497
## gamma1 0.09465
## gamma2 0.09181
## shape  0.13315
## 
## 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.0846 0.2783    
## Negative Sign Bias  0.4547 0.6494    
## Positive Sign Bias  1.4585 0.1449    
## Joint Effect        3.0063 0.3907    
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     38.41     0.005261
## 2    30     38.43     0.113098
## 3    40     53.32     0.062957
## 4    50     50.24     0.423920
## 
## 
## Elapsed time : 3.765648
plot(garch.fit, which=3)

plot(tst, main="Retornos de Precios de BTC y S&P500", xlab="Date")

###### Media condicional.

plot(dcc.fit.1, which=1)
## Warning in plot.window(...): relative range of values ( 50 * EPS) is small (axis
## 2)
## Warning in plot.window(...): relative range of values ( 27 * EPS) is small (axis
## 2)

###### Sigma Vs Returns.

plot(dcc.fit.1, which=2)

###### Covarianza y correlación condicional.

plot(dcc.fit.1, which=3)

plot(dcc.fit.1, which=4)

Portafolio y VaR al 1%.
plot(dcc.fit.1, which=5)

###### Forecast.

fit01 = dccfit(dcc.garch12.1.spec, data = tst, out.sample = 15, fit.control = list(eval.se=FALSE))
forc2 = dccforecast(fit01, n.ahead = 1, n.roll = 10)
plot(forc2, which=1)

plot(forc2, which=2)

plot(forc2, which=3)

plot(forc2, which=5)

forc2
## 
## *---------------------------------*
## *       DCC GARCH Forecast        *
## *---------------------------------*
## 
## Distribution         :  mvt
## Model                :  aDCC(1,1)
## Horizon              :  1
## Roll Steps           :  10
## -----------------------------------
## 
## 0-roll forecast: 
## , , 1
## 
##          [,1]     [,2]
## [1,]  1.00000 -0.07547
## [2,] -0.07547  1.00000
Otros gráficos del modelo.
r1=rcor(dcc.fit.1, type="R")
r1.z=zoo(r1[1,2,], order.by=time(tst))
plot(r1.z, main=paste(colnames(garch1)[1],"-", colnames(garch1)[2], "Correlacion Condicional", sep=" "), 
     ylab="Correlacion Condicional",
     xlab="Date")
abline(h=mean(r1.z), lty=2, lwd=1, col="blue")
abline(h=(mean(r1.z)+sd(r1.z)), lty=2, lwd=1, col="blue")
abline(h=(mean(r1.z)-sd(r1.z)), lty=2, lwd=1, col="blue")

###### Predicciones.

mr1z <- mean(window(r1.z, start="2020-01-01"))
sr1z <- sd(window(r1.z, start="2020-01-01"))

plot(window(r1.z, start="2020-01-01"), main=paste(colnames(garch1)[1],"-", colnames(garch1)[2], "Correlacion Condicional", sep=" "), 
     ylab="Correlacion Condicional", sub=paste("mean:", round(mr1z,3),"sd:", round(sr1z,3)),
     xlab="Date")

abline(h=mr1z, lty=2, lwd=1, col="blue")

abline(h=(mr1z+sr1z), lty=2, lwd=1, col="red")
abline(h=(mr1z-sr1z), lty=2, lwd=1, col="red")