Está en la página 1de 9

Tarea-modelos-VAR.

R
jimena

2022-05-16
#### Tarea 1 Modelos VAR ####
# Realizar un análisis VAR con los retornos de los precios al cierre
# de AAPL, GOOG.
# 1. Seleccionar el más parsimonioso y estimarlo
# 2. Diagnóstico
# a. Si el modelo satisface el diagnóstico, usarlo para el pronóstico;
# análisis de impulso-reGOOGuesta.
# b. Si el modelo no satisface el diagnóstico, estimar VAR(p)
# con orden más grande.
# Usar el siguiente código para bajar los datos
# (frecuencia diaria: 252 observaciones por año)

rm(list = ls())
library(tseries)

## Registered S3 method overwritten by 'quantmod':


## method from
## as.zoo.data.frame zoo

library(vars)

## Loading required package: MASS

## Loading required package: strucchange

## Loading required package: zoo

##
## Attaching package: 'zoo'

## The following objects are masked from 'package:base':


##
## as.Date, as.Date.numeric

## Loading required package: sandwich

## Loading required package: urca

## Loading required package: lmtest

library(quantmod)

## Loading required package: xts


## Loading required package: TTR

getSymbols("AAPL", from = "2010-01-01", to = "2019-12-31")

## [1] "AAPL"

getSymbols("GOOG", from = "2010-01-01", to = "2019-12-31")

## [1] "GOOG"

## Definir la serie de los precios al cierre


AAPL.ts <- ts(AAPL$AAPL.Close, frequency = 252)
GOOG.ts <- ts(GOOG$GOOG.Close, frequency = 252)
## Definir las series de los retornos
AAPL.rtn <- diff(log(AAPL.ts))
GOOG.rtn <- diff(log(GOOG.ts))
## Verificar si las series de retornos son estacionarias
## Estacionariedad de los retornos
adf.test(AAPL.rtn)

## Warning in adf.test(AAPL.rtn): p-value smaller than printed p-value

##
## Augmented Dickey-Fuller Test
##
## data: AAPL.rtn
## Dickey-Fuller = -12.893, Lag order = 13, p-value = 0.01
## alternative hypothesis: stationary

pp.test(AAPL.rtn)

## Warning in pp.test(AAPL.rtn): p-value smaller than printed p-value

##
## Phillips-Perron Unit Root Test
##
## data: AAPL.rtn
## Dickey-Fuller Z(alpha) = -2402.9, Truncation lag parameter = 8, p-value
## = 0.01
## alternative hypothesis: stationary

kpss.test(AAPL.rtn)

## Warning in kpss.test(AAPL.rtn): p-value greater than printed p-value

##
## KPSS Test for Level Stationarity
##
## data: AAPL.rtn
## KPSS Level = 0.068559, Truncation lag parameter = 8, p-value = 0.1
## es estacionaria
# en todos los casos se concluye que es estacionaria
adf.test(GOOG.rtn)

## Warning in adf.test(GOOG.rtn): p-value smaller than printed p-value

##
## Augmented Dickey-Fuller Test
##
## data: GOOG.rtn
## Dickey-Fuller = -14.541, Lag order = 13, p-value = 0.01
## alternative hypothesis: stationary

pp.test(GOOG.rtn)

## Warning in pp.test(GOOG.rtn): p-value smaller than printed p-value

##
## Phillips-Perron Unit Root Test
##
## data: GOOG.rtn
## Dickey-Fuller Z(alpha) = -2371.5, Truncation lag parameter = 8, p-value
## = 0.01
## alternative hypothesis: stationary

kpss.test(GOOG.rtn)

## Warning in kpss.test(GOOG.rtn): p-value greater than printed p-value

##
## KPSS Test for Level Stationarity
##
## data: GOOG.rtn
## KPSS Level = 0.070865, Truncation lag parameter = 8, p-value = 0.1

## Conclusión: Ambas series de retornos son estacionarias


## podemos usar un modelo VAR(p)
## La librería "vars" necesita los datos en forma de data frame
AAPLGOOG <- data.frame(AAPL.rtn, GOOG.rtn)
## El nombre de las variables son: "AAPL.Close",
## "GOOG.Close", respectivamente:
names(AAPLGOOG)

## [1] "AAPL.Close" "GOOG.Close"

## Los retornos no tienen tendencia:


plot.ts(cbind(AAPL.rtn, GOOG.rtn))
## No tienen tendencia => seleccionar el orden p
## con el parámetro "type = const"
## orden máximo = 12 (p=12: 50 coeficientes a estimar)

VARselect(AAPLGOOG, lag.max = 12, type = "const")

## $selection
## AIC(n) HQ(n) SC(n) FPE(n)
## 1 1 1 1
##
## $criteria
## 1 2 3 4
5
## AIC(n) -1.683881e+01 -1.683638e+01 -1.683454e+01 -1.683407e+01 -
1.683290e+01
## HQ(n) -1.683374e+01 -1.682793e+01 -1.682270e+01 -1.681885e+01 -
1.681430e+01
## SC(n) -1.682484e+01 -1.681310e+01 -1.680194e+01 -1.679216e+01 -
1.678168e+01
## FPE(n) 4.864053e-08 4.875860e-08 4.884874e-08 4.887179e-08 4.892892e-
08
## 6 7 8 9
10
## AIC(n) -1.683439e+01 -1.683267e+01 -1.683383e+01 -1.683100e+01 -
1.682914e+01
## HQ(n) -1.681242e+01 -1.680732e+01 -1.680510e+01 -1.679888e+01 -
1.679364e+01
## SC(n) -1.677386e+01 -1.676283e+01 -1.675468e+01 -1.674253e+01 -
1.673136e+01
## FPE(n) 4.885589e-08 4.893995e-08 4.888328e-08 4.902197e-08 4.911305e-
08
## 11 12
## AIC(n) -1.682879e+01 -1.682594e+01
## HQ(n) -1.678991e+01 -1.678368e+01
## SC(n) -1.672170e+01 -1.670953e+01
## FPE(n) 4.913026e-08 4.927074e-08

## Explicación de los criterios de información (IC)


## SC (Schwarz IC): más parsimonioso
## AIC (Akaike IC): menos parsimonioso
## FPE (Forecast prediction error): +/- AIC
## HQ (Hannah-Quinn IC): entre AIC, FPE y SC
## Se quiere minimizar el IC elegido

#### Estrategia de selección del modelo VAR(p) ####


## 1. Seleccionar el más parsimonioso y estimarlo
## 2. Diagnóstico
## a. Si el modelo satisface el diagnóstico, usarlo para el pronóstico;
## análisis de impulso-reGOOGuesta.
## b. Si el modelo no satisface el diagnóstico, estimar VAR(p)
## con orden más grande.
##
## En este ejemplo, la función "VARSelect()" indica p=1.
## Estimar el modelo y realizar el diagnóstico.

#### Estimación del modelo VAR(1) ####


AAPLGOOG.fit1 <- VAR(AAPLGOOG, p = 1, type = "const")
summary(AAPLGOOG.fit1)

##
## VAR Estimation Results:
## =========================
## Endogenous variables: AAPL.Close, GOOG.Close
## Deterministic variables: const
## Sample size: 2513
## Log Likelihood: 14032.222
## Roots of the characteristic polynomial:
## 0.04503 0.00454
## Call:
## VAR(y = AAPLGOOG, p = 1, type = "const")
##
##
## Estimation results for equation AAPL.Close:
## ===========================================
## AAPL.Close = AAPL.Close.l1 + GOOG.Close.l1 + const
##
## Estimate Std. Error t value Pr(>|t|)
## AAPL.Close.l1 0.0275045 0.0225596 1.219 0.22288
## GOOG.Close.l1 -0.0232303 0.0239468 -0.970 0.33210
## const 0.0008856 0.0003249 2.726 0.00646 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
##
## Residual standard error: 0.01626 on 2510 degrees of freedom
## Multiple R-Squared: 0.0006737, Adjusted R-squared: -0.0001225
## F-statistic: 0.8461 on 2 and 2510 DF, p-value: 0.4292
##
##
## Estimation results for equation GOOG.Close:
## ===========================================
## GOOG.Close = AAPL.Close.l1 + GOOG.Close.l1 + const
##
## Estimate Std. Error t value Pr(>|t|)
## AAPL.Close.l1 -0.0173224 0.0212570 -0.815 0.415
## GOOG.Close.l1 0.0220631 0.0225641 0.978 0.328
## const 0.0005829 0.0003061 1.904 0.057 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
##
## Residual standard error: 0.01532 on 2510 degrees of freedom
## Multiple R-Squared: 0.0004462, Adjusted R-squared: -0.0003502
## F-statistic: 0.5603 on 2 and 2510 DF, p-value: 0.5711
##
##
##
## Covariance matrix of residuals:
## AAPL.Close GOOG.Close
## AAPL.Close 0.0002644 0.0001164
## GOOG.Close 0.0001164 0.0002348
##
## Correlation matrix of residuals:
## AAPL.Close GOOG.Close
## AAPL.Close 1.0000 0.4672
## GOOG.Close 0.4672 1.0000

#### Diagnóstico gráfico usando ACF, PACF con los residuos ####
dev.off()

## null device
## 1
# Usar el nombre de las variables; cf., línea 41 arriba
plot(AAPLGOOG.fit1, names = "AAPL.Close") # parece OK
plot(AAPLGOOG.fit1, names = "GOOG.Close") # parece OK

#### Diagnóstico: residuos ####


## 1. Ruido blanco
## a. Prueba Portmanteau (PT)
## b. Prueba LM Breusch-Godfrey
## 2. Efecto ARCH residuo
## 3. Normalidad
## Observación: En la literatura, las pruebas de Ljung-Box, Box-Pierce se
## conocen como pruebas Portmanteau
##
## lag = 12: probar si existe correlación a lo largo de un año
## Prueba portmanteau (PT) (Default)
## La variante "PT. Adjusted" en caso de corrección por tamaño muestral
## pequeño.
## La versión Breusch-Godfrey usa una prueba con una regresión auxiliar
## semejante a la prueba de correlación serial de un modelo de regresión.
## Usaremos PT. Se presentan también las otras solo para
# propósitos demostrativos.
serial.test(AAPLGOOG.fit1, lags.pt = 12)

##
## Portmanteau Test (asymptotic)
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 52.584, df = 44, p-value = 0.1758

#p= 0.1758 = los residuos se comporta con ruido blanco


## Variante Breusch-Godfrey
serial.test(AAPLGOOG.fit1, lags.bg = 12, type = "BG")

##
## Breusch-Godfrey LM test
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 60.376, df = 48, p-value = 0.1084

#misma conclusion
## PT, ajustando a muestras pequeñas
serial.test(AAPLGOOG.fit1, lags.pt = 12, type = "PT.adjusted")

##
## Portmanteau Test (adjusted)
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 52.725, df = 44, p-value = 0.1723

#mismo resultado
## Conclusión: no existe evidencia de correlación serial residua
##
## Normalidad: Prueba JB (Prueba Jarque-Bera)
## El orden de las variables cuando se define el data frame
# (cf., línea 38 arriba) puede dar resultados diferentes
normality.test(AAPLGOOG.fit1)

## $JB
##
## JB-Test (multivariate)
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 26099, df = 4, p-value < 2.2e-16
##
##
## $Skewness
##
## Skewness only (multivariate)
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 388.08, df = 2, p-value < 2.2e-16
##
##
## $Kurtosis
##
## Kurtosis only (multivariate)
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 25711, df = 2, p-value < 2.2e-16

## Existe evidencia que los errores no tienen distribución normal.


##
## Efecto ARCH residuo
## En conjunto
arch.test(AAPLGOOG.fit1)

##
## ARCH (multivariate)
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 177.31, df = 45, p-value < 2.2e-16

## En conjunto e individualmente
arch.test(AAPLGOOG.fit1, multivariate.only = F)

## $AAPL.Close
##
## ARCH test (univariate)
##
## data: Residual of AAPL.Close equation
## Chi-squared = 63.449, df = 16, p-value = 1.359e-07
##
##
## $GOOG.Close
##
## ARCH test (univariate)
##
## data: Residual of GOOG.Close equation
## Chi-squared = 11.716, df = 16, p-value = 0.7633
##
##
##
## ARCH (multivariate)
##
## data: Residuals of VAR object AAPLGOOG.fit1
## Chi-squared = 177.31, df = 45, p-value < 2.2e-16

## Conclusión general VAR(1): no se detecta correlación serial

También podría gustarte