Instruções Gerais:
1. Considere o modelo ARCH(1) dado por: \[r_t = \delta + \epsilon_t\] \[\epsilon_t = \sigma_t z_t, \ \ z_t ~ N(0,1)\] \[\sigma_{t}^{2} = \overline{w} + \alpha \epsilon_{t - 1}^{2}\]
onde \(\overline{w} > 0 \ \ e \ \ \alpha ≥ 0\). Seja o conjunto de informação \(I_{t−1} = \{ r1, r2, . . . , r_{t−1} \}\) .
(a) Explique em palavras por que os parâmetros $ $ e \(\alpha\) são restritos ser positivo e não negativo, respectivamente.
Modelo ARCH de ordem (1) pode ser expresso pela equação:
\[\sigma^2 = \overline{w} + \alpha \epsilon_{t - 1}^{2}\]
usa as variavéis dos resíduos ao quadrado \(\epsilon_{t - 1}^{2}\) como variáveis explicativas essa equação e deterministica, onde a variância tem que ser positiva \(\sigma^2 > 0\), então \(\overline{w} > 0\) e \(\alpha > 0\), para que eu tenha volatividade positiva. Onde \(\epsilon_{t - 1}^{2}\) está entre \([0,1]\)
(b) Explique em palavras como o modelo acima permite clusters de volatilidade, que é um fato empírico estilizado de séries financeiras.
Consegue capturar agrupamento de volatividade grandes choques seguidos por grandes choques na volatividade. Grandes choques tendem a ser seguidos por grandes choques. Capturando os cluster de volatividade.
(c) Cite dois fatos estilizados de séries temporais financeiras que não são capturados pelo modelo acima.
Distribuição normal não captura o fato estilizado de caudas pesadas. Pode precisar de um grande numero de regressores, assim perdendo o grau de liberdade.
(d) Explique em palavras a diferença entre variância condicional e incondicional.
Variância não-condicional ou variância incondicional é quando a variância é constante ao longo do tempo são mesmo dos modelos ARMA.
onde \(\sigma\) e o mesmo durante o tempo.
Variância condicional - é quando a variância é variante no tempo que nos chamamos de heterocedasticidade quando a variância dos erros não é a mesma em todas as observações feitas. É uma médida de risco é usada como input calculo de VaR (Value-at-Risk).
2. Descreva como as FAC e FACP são utilizadas no contexto de modelos da família ARCH. Em quais etapas do ajuste do modelo elas são úteis?
FAC e FACP são aplicadas aos resíduos ao quadrado da equação da média ou à série de retornos ao quadrado para verificar a presença de heterocedasticidade condicional. Os testes estatísticos como a estatística de Ljung-Box e o teste LM são utilizados para avaliar a significância dos lags das FAC e para determinar se há heterocedasticidade condicional na série temporal. Se a hipótese nula for rejeitada, isso sugere a presença de padrões significativos de autocorrelação nos resíduos ao quadrado, indicando a necessidade de considerar um modelo da família ARCH para capturar a volatilidade condicional.
As etapas em que as FAC e FACP são úteis no ajuste dos modelos ARCH incluem:
1.1 Identificação de Autocorrelação: Antes de ajustar um modelo ARCH, é importante examinar as FAC e FACP dos resíduos ao quadrado (ou da série de retornos ao quadrado) para identificar qualquer padrão de autocorrelação. Isso ajuda a determinar se a volatilidade condicional está presente na série.
1.2 Especificação de Termos AR e MA: As FAC e FACP podem sugerir a ordem dos termos autorregressivos (AR) e de média móvel (MA) a serem incluídos no modelo ARCH. Picos significativos nas FAC podem indicar a necessidade de termos AR, enquanto quedas lentas nas FACP podem sugerir a inclusão de termos MA.
2.1 Validação da Especificação do Modelo: Após escolher a ordem do modelo ARCH, as FAC e FACP podem ser usadas para validar se a especificação do modelo é adequada. Comparar as autocorrelações teóricas do modelo com as autocorrelações observadas nas FAC e FACP pode ajudar a identificar discrepâncias e refinar a especificação.
2.2 Ajuste dos Parâmetros: Durante a estimação dos parâmetros do modelo ARCH, as FAC e FACP podem ser usadas para guiar o processo de otimização. Elas podem ajudar a verificar se os parâmetros estimados estão capturando corretamente os padrões de autocorrelação na volatilidade condicional.
3.1 Validação dos Resíduos: Após ajustar o modelo ARCH, é importante analisar as FAC e FACP dos resíduos padronizados, ou seja, os resíduos divididos pelo desvio padrão estimado. Isso ajuda a verificar se os resíduos têm autocorrelações significativas, o que poderia indicar problemas na modelagem da volatilidade condicional.
3.2 Diagnóstico de Ajuste: Picos significativos nas FAC dos resíduos padronizados podem indicar que o modelo não está capturando completamente a autocorrelação presente nos dados. Quedas rápidas nas FACP podem indicar que os termos do modelo ARCH não estão capturando adequadamente os padrões de autocorrelação.
3. Ajuste os modelos da família ARCH vistos em aula, considerando a ordem (1,1) com as distribuições normal e t-Student para as seguintes séries, iniciando em 2019:
(a) log-retornos diários das ações da PETROBRAS
library(BatchGetSymbols) ### pegar dados yahoo finance (preços diárias ativos negociados em bolsa)
## Warning: package 'BatchGetSymbols' was built under R version 4.3.1
## Carregando pacotes exigidos: rvest
## Carregando pacotes exigidos: 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(rugarch)
## Warning: package 'rugarch' was built under R version 4.3.1
## Carregando pacotes exigidos: parallel
##
## Attaching package: 'rugarch'
## The following object is masked from 'package:stats':
##
## sigma
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.3.1
## Warning: package 'ggplot2' was built under R version 4.3.1
## Warning: package 'readr' was built under R version 4.3.1
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0 ✔ readr 2.1.4
## ✔ ggplot2 3.4.2 ✔ stringr 1.5.0
## ✔ lubridate 1.9.2 ✔ tibble 3.2.1
## ✔ purrr 1.0.1 ✔ tidyr 1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ readr::guess_encoding() masks rvest::guess_encoding()
## ✖ dplyr::lag() masks stats::lag()
## ✖ purrr::reduce() masks rugarch::reduce()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggthemes)
## Warning: package 'ggthemes' was built under R version 4.3.1
library(FinTS)
## Warning: package 'FinTS' was built under R version 4.3.1
## Carregando pacotes exigidos: zoo
##
## Attaching package: 'zoo'
##
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
library(WriteXLS)
library(xtable)
## Warning: package 'xtable' was built under R version 4.3.1
library(tbl2xts)
## Warning: package 'tbl2xts' was built under R version 4.3.1
library(forecast)
## Warning: package 'forecast' was built under R version 4.3.1
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
##
## Attaching package: 'forecast'
##
## The following object is masked from 'package:FinTS':
##
## Acf
library(tseries)
## Warning: package 'tseries' was built under R version 4.3.1
library(timeSeries)
## Warning: package 'timeSeries' was built under R version 4.3.1
## Carregando pacotes exigidos: timeDate
##
## Attaching package: 'timeDate'
##
## The following object is masked from 'package:xtable':
##
## align
##
##
## Attaching package: 'timeSeries'
##
## The following object is masked from 'package:zoo':
##
## time<-
library(lmtest)
## Warning: package 'lmtest' was built under R version 4.3.1
library(rugarch)
library(ggplot2)
library(cowplot)
## Warning: package 'cowplot' was built under R version 4.3.1
##
## Attaching package: 'cowplot'
##
## The following object is masked from 'package:ggthemes':
##
## theme_map
##
## The following object is masked from 'package:lubridate':
##
## stamp
library(dplyr)
library(moments)
##
## Attaching package: 'moments'
##
## The following objects are masked from 'package:timeDate':
##
## kurtosis, skewness
#limpar o diretório
rm(list=ls())
# para pegar vários, podemos usar o argumento abaixo:
tickers = c('PETR4.SA')
#### Sys.time() é a última data disponível
assets <- BatchGetSymbols(tickers,
first.date = '2019-03-03',
last.date = Sys.time(),
type.return = "log",
freq.data = "daily")
## Warning: `BatchGetSymbols()` was deprecated in BatchGetSymbols 2.6.4.
## ℹ Please use `yfR::yf_get()` instead.
## ℹ 2022-05-01: Package BatchGetSymbols will soon be replaced by yfR. More
## details about the change is available at github
## <<www.github.com/msperlin/yfR> You can install yfR by executing:
##
## remotes::install_github('msperlin/yfR')
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
##
## Running BatchGetSymbols for:
## tickers =PETR4.SA
## Downloading data for benchmark ticker
## ^GSPC | yahoo (1|1) | Not Cached | Saving cache
## PETR4.SA | yahoo (1|1) | Not Cached | Saving cache - Got 96% of valid prices | Got it!
petr4 <- assets[[2]]
# head(petr4)
# Eliminando os valores NA
petr4= na.omit(petr4)
head(petr4)
## price.open price.high price.low price.close volume price.adjusted
## 2 26.80 26.91 26.49 26.77 32835300 10.27945
## 3 26.49 26.75 26.22 26.67 49564400 10.24105
## 4 27.02 27.78 27.01 27.75 66742800 10.65576
## 5 27.79 27.96 27.25 27.50 64287300 10.55976
## 6 27.59 28.13 27.52 28.10 61057200 10.79015
## 7 28.15 28.20 27.91 28.19 42777800 10.82472
## ref.date ticker ret.adjusted.prices ret.closing.prices
## 2 2019-03-07 PETR4.SA 0.0003735814 0.0003736308
## 3 2019-03-08 PETR4.SA -0.0037423882 -0.0037425336
## 4 2019-03-11 PETR4.SA 0.0396963532 0.0396964991
## 5 2019-03-12 PETR4.SA -0.0090498339 -0.0090498355
## 6 2019-03-13 PETR4.SA 0.0215834441 0.0215835852
## 7 2019-03-14 PETR4.SA 0.0031979964 0.0031977342
daily_returns <- petr4 %>%
select(ref.date,ret.closing.prices)
date <- daily_returns %>%
select(ref.date) %>%
rename(date = ref.date) %>%
slice(-1)
daily_returns <- daily_returns %>%
select(ret.closing.prices) %>%
slice(-1)
## declarando como série temporal através do comando as.ts
daily_returns=as.ts(daily_returns)
Dados e análises descritivas.
# Fazer uma análise visual da série, verificando os fatos estilizados.
# Função para plotar os gráficos para qualquer ação que deseja analisar.
plot_graficos <- function(acao) {
# Gráfico 1: preços
p <- ggplot(acao, aes(ref.date, price.close)) +
geom_line(color='#006600') +
labs(x = "", y = 'Preço Fechamento',
title = paste("Cotação Diária da", acao$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
# Gráfico 2: retornos diários
daily_returns <- acao %>% select(ref.date, ticker, ret.closing.prices)
plot_returns <- ggplot(daily_returns) +
geom_line(aes(x = ref.date, y = ret.closing.prices), color='#006600') +
labs(x = "", y = 'Retornos',
title = paste("Retornos da", acao$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
# Gráfico 3: Retornos absolutos (abs)
plot_volatility <- ggplot(daily_returns) +
geom_line(aes(x = ref.date, y = abs(ret.closing.prices)), color='#006600') +
labs(x = "", y = 'Retornos absolutos',
title = paste("Retornos abs da", acao$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
# Gráfico 4: qqplot
qqplot <- ggplot(daily_returns, aes(sample = ret.closing.prices)) +
stat_qq() +
stat_qq_line() +
labs(x = "Teórico", y = 'Amostra',
title = "QQplot",
subtitle = paste("Retornos diários da", acao$ticker[1]),
caption = "Fonte: Elaborado a partir de dados da B3") +
theme_economist()
# Gráfico 5: Histograma
histogram <- ggplot(daily_returns) +
geom_histogram(aes(x = ret.closing.prices, y = after_stat(density)),
color = "white", fill = "Dark grey", linetype = "solid", alpha = 0.8, binwidth = 0.02) +
geom_density(aes(x = ret.closing.prices, y = after_stat(density)), color = "black") +
labs(x = "", y = 'Densidade',
title = "Histograma",
subtitle = paste("Retornos diários da", acao$ticker[1]),
caption = "Fonte: Elaborado a partir de dados da B3") +
theme_economist()
# Plotar os gráficos juntos
plot_grid(plot_returns, qqplot, plot_volatility, histogram, nrow = 2)
}
# Gráfico 1: preços
p <- ggplot(petr4, aes(ref.date, price.close)) +
geom_line(color='#006600') +
labs(x = "", y = 'Preço Fechamento',
title = paste("Cotação Diária da", petr4$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
p
plot_graficos(petr4)
# Calcular estatísticas descritivas para cada ação
estatisticas <- petr4 %>%
group_by(ticker) %>%
summarise(
media = mean(ret.closing.prices),
desvio_padrao = sd(ret.closing.prices),
variancia = var(ret.closing.prices),
curtose = kurtosis(ret.closing.prices),
assimetria = skewness(ret.closing.prices)
)
# Adicionar coluna indicando se a distribuição é normal ou de cauda pesada
estatisticas <- estatisticas %>%
mutate(distribuicao = ifelse(curtose > 3, "Cauda Pesada", "Normal"))
estatisticas
## # A tibble: 1 × 7
## ticker media desvio_padrao variancia curtose assimetria distribuicao
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
## 1 PETR4.SA 0.000129 0.0313 0.000978 26.0 -2.22 Cauda Pesada
# Função para calcular os graus de liberdade da distribuição t-Student
df_t_student <- function(data) {
n <- length(data)
df <- ifelse(n < 30, n - 1, 30)
return(df)
}
# Função para calcular estatísticas descritivas e plotar histograma
plot_estatisticas_histograma <- function(data, tickers) {
# Plotar histograma
grafico <- ggplot(data = data) +
geom_histogram(aes(x = ret.closing.prices, y = after_stat(density)),
color = "black", fill = "white") +
facet_wrap(~ticker, ncol = 2) +
geom_density(aes(x = ret.closing.prices),
color = "blue", fill = "lightblue", alpha = 0.5) +
stat_function(fun = dnorm,
args = list(mean = mean(data$ret.closing.prices), sd = sd(data$ret.closing.prices)),
color = "red", linetype = "dashed") +
stat_function(fun = dt,
args = list(df = df_t_student(data$ret.closing.prices)),
color = "green", linetype = "dotted") +
labs(x = "Retornos", y = "Densidade",
title = "Distribuição Normal e t-Student",
subtitle = "distribuicoes PETR4",
caption = "Fonte: Dados da Acao") +
theme_minimal()
print(grafico)
}
# Chamar a função para ações desejadas
plot_estatisticas_histograma(petr4, ticker)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# Calculando os retornos ao quadrado
returns_squared <- daily_returns^2
# Calculando a função de autocorrelação parcial (FACP) dos retornos ao quadrado
pacf_returns_squared <- pacf(returns_squared, lag.max = 50, plot = TRUE)
# Exibindo os resultados da FACP
pacf_returns_squared
##
## Partial autocorrelations of series 'returns_squared', by lag
##
## 1 2 3 4 5 6 7 8 9 10 11
## 0.253 0.101 0.273 0.159 0.043 -0.128 0.039 0.017 -0.023 -0.011 0.092
## 12 13 14 15 16 17 18 19 20 21 22
## -0.016 0.002 -0.010 -0.057 -0.017 0.012 0.026 0.007 0.008 -0.021 -0.016
## 23 24 25 26 27 28 29 30 31 32 33
## 0.002 -0.003 -0.004 0.010 0.009 0.014 -0.005 0.003 -0.013 0.009 -0.010
## 34 35 36 37 38 39 40 41 42 43 44
## 0.003 0.001 -0.004 -0.001 -0.003 0.000 -0.010 0.001 -0.008 -0.003 0.007
## 45 46 47 48 49 50
## -0.004 -0.012 0.031 -0.022 0.014 -0.026
Especificando os lags para o teste LM
lags = c(1,2,3,4,6,11)
# Testando efeito ARCH: Teste LM
for (lag in lags) {
arch_test <- ArchTest(daily_returns, lags = lag, demean = TRUE)
print(paste("Resultado do Teste LM (", lag, "lags):"))
print(arch_test)
}
## [1] "Resultado do Teste LM ( 1 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 70.477, df = 1, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 2 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 81.061, df = 2, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 3 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 156.98, df = 3, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 4 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 180.69, df = 4, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 6 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 197.12, df = 6, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 11 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 205.99, df = 11, p-value < 2.2e-16
# Testando efeito ARCH: Teste LM
for (lag in lags) {
arch_test <- ArchTest(daily_returns, lags = lag, demean = TRUE)
print(paste("Resultado do Teste LM (", lag, "lags):"))
print(arch_test)
}
## [1] "Resultado do Teste LM ( 1 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 70.477, df = 1, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 2 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 81.061, df = 2, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 3 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 156.98, df = 3, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 4 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 180.69, df = 4, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 6 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 197.12, df = 6, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 11 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 205.99, df = 11, p-value < 2.2e-16
Configurar as ordens padrão para os modelos
# Configurar as ordens padrão para os modelos
orders <- c(1, 1)
# Configurações padrão para GARCH, EGARCH e GJR-GARCH com distribuição norm
garch_spec_norm <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "norm")
egarch_spec_norm <- ugarchspec(variance.model = list(model = "eGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "norm")
gjr_spec_norm <- ugarchspec(variance.model = list(model = "gjrGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "norm")
# Configurações padrão para GARCH, EGARCH e GJR-GARCH com distribuição std
garch_spec_std <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "std")
egarch_spec_std <- ugarchspec(variance.model = list(model = "eGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "std")
gjr_spec_std <- ugarchspec(variance.model = list(model = "gjrGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "std")
Ajustando o modelo GARCH(1,1), EGARCH(1,1), GJR(1,1) para distribuição normal e t-student.
# Ajustando o modelo GARCH(1,1) com distribuição Normal e t-student aos retornos diários
garch_fit_norm <- ugarchfit(spec = garch_spec_norm, data = daily_returns[,1])
garch_fit_std <- ugarchfit(spec = garch_spec_std, data = daily_returns[,1])
# Ajustando o modelo EGARCH(1,1) com distribuição Normal e t-student aos retornos diários
egarch_fit_norm <- ugarchfit(spec = egarch_spec_norm, data = daily_returns[,1])
egarch_fit_std <- ugarchfit(spec = egarch_spec_std, data = daily_returns[,1])
# Ajustando o modelo GJR(1,1) com distribuição Normal e t-student aos retornos diários
gjr_fit_norm <- ugarchfit(spec = gjr_spec_norm, data = daily_returns[,1])
gjr_fit_std <- ugarchfit(spec = gjr_spec_std, data = daily_returns[,1])
Exibindo os resultados modelo GARCH(1,1), EGARCH(1,1), GJR(1,1) para distribuição normal e t-student.
# Exibindo os resultados GARCH(1,1) do ajuste com distribuição Normal e t-student
print("Resultado do ajuste GARCH(1,1) com distribuição Normal:")
## [1] "Resultado do ajuste GARCH(1,1) com distribuição Normal:"
garch_fit_norm
##
## *---------------------------------*
## * 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|)
## omega 0.000131 0.000053 2.4970 0.012526
## alpha1 0.212791 0.048275 4.4079 0.000010
## beta1 0.644104 0.099726 6.4587 0.000000
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000131 0.000173 0.75897 0.447871
## alpha1 0.212791 0.198942 1.06961 0.284793
## beta1 0.644104 0.361157 1.78344 0.074514
##
## LogLikelihood : 2432.014
##
## Information Criteria
## ------------------------------------
##
## Akaike -4.3964
## Bayes -4.3828
## Shibata -4.3964
## Hannan-Quinn -4.3913
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.1043 0.7467
## Lag[2*(p+q)+(p+q)-1][2] 0.2579 0.8196
## Lag[4*(p+q)+(p+q)-1][5] 1.6074 0.7135
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.2477 0.6187
## Lag[2*(p+q)+(p+q)-1][5] 1.1461 0.8258
## Lag[4*(p+q)+(p+q)-1][9] 2.4123 0.8505
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.4018 0.500 2.000 0.5262
## ARCH Lag[5] 0.4401 1.440 1.667 0.9012
## ARCH Lag[7] 0.5714 2.315 1.543 0.9715
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 2.1419
## Individual Statistics:
## omega 0.77216
## alpha1 0.05446
## beta1 0.37236
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 0.846 1.01 1.35
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 0.2314 0.81705
## Negative Sign Bias 1.8081 0.07086 *
## Positive Sign Bias 0.6531 0.51381
## Joint Effect 6.6708 0.08316 *
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 80.43 1.568e-09
## 2 30 90.36 3.207e-08
## 3 40 112.41 4.857e-09
## 4 50 117.94 1.295e-07
##
##
## Elapsed time : 0.1509631
# Exibindo os resultados do ajuste com distribuição t-Student
print("Resultado do ajuste GARCH(1,1) com distribuição t-Student:")
## [1] "Resultado do ajuste GARCH(1,1) com distribuição t-Student:"
garch_fit_std
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : sGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000042 0.000017 2.5314 0.011362
## alpha1 0.068768 0.022146 3.1052 0.001901
## beta1 0.875968 0.035873 24.4186 0.000000
## shape 4.104337 0.497345 8.2525 0.000000
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000042 0.000023 1.8020 0.071539
## alpha1 0.068768 0.039471 1.7422 0.081466
## beta1 0.875968 0.056418 15.5264 0.000000
## shape 4.104337 0.513194 7.9976 0.000000
##
## LogLikelihood : 2524.588
##
## Information Criteria
## ------------------------------------
##
## Akaike -4.5622
## Bayes -4.5440
## Shibata -4.5622
## Hannan-Quinn -4.5553
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.04772 0.8271
## Lag[2*(p+q)+(p+q)-1][2] 0.16219 0.8780
## Lag[4*(p+q)+(p+q)-1][5] 1.10302 0.8359
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 5.224 0.02228
## Lag[2*(p+q)+(p+q)-1][5] 5.453 0.12062
## Lag[4*(p+q)+(p+q)-1][9] 8.013 0.12815
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.3109 0.500 2.000 0.5771
## ARCH Lag[5] 0.3743 1.440 1.667 0.9199
## ARCH Lag[7] 0.5771 2.315 1.543 0.9709
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 1.9474
## Individual Statistics:
## omega 0.45619
## alpha1 0.09582
## beta1 0.22990
## shape 0.08835
##
## 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
## ------------------------------------
## t-value prob sig
## Sign Bias 0.03266 0.9739528
## Negative Sign Bias 3.86194 0.0001191 ***
## Positive Sign Bias 0.06886 0.9451175
## Joint Effect 18.67731 0.0003188 ***
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 22.62 0.2545
## 2 30 33.94 0.2414
## 3 40 40.01 0.4250
## 4 50 51.43 0.3790
##
##
## Elapsed time : 0.1875341
# Exibindo os resultados EGARCH(1,1) do ajuste com distribuição Normal e t-student
print("Resultado do ajuste EGARCH(1,1) com distribuição Normal:")
## [1] "Resultado do ajuste EGARCH(1,1) com distribuição Normal:"
egarch_fit_norm
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : eGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : norm
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega -0.626076 0.237079 -2.6408 0.008271
## alpha1 -0.063647 0.026978 -2.3592 0.018314
## beta1 0.910169 0.033028 27.5573 0.000000
## gamma1 0.303711 0.049066 6.1898 0.000000
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega -0.626076 0.706813 -0.88577 0.375740
## alpha1 -0.063647 0.073815 -0.86225 0.388550
## beta1 0.910169 0.100086 9.09390 0.000000
## gamma1 0.303711 0.172782 1.75777 0.078786
##
## LogLikelihood : 2436.2
##
## Information Criteria
## ------------------------------------
##
## Akaike -4.4022
## Bayes -4.3840
## Shibata -4.4022
## Hannan-Quinn -4.3953
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.06156 0.8041
## Lag[2*(p+q)+(p+q)-1][2] 0.31571 0.7870
## Lag[4*(p+q)+(p+q)-1][5] 1.54200 0.7296
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.803 0.3702
## Lag[2*(p+q)+(p+q)-1][5] 1.319 0.7842
## Lag[4*(p+q)+(p+q)-1][9] 2.617 0.8201
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.1473 0.500 2.000 0.7011
## ARCH Lag[5] 0.1796 1.440 1.667 0.9702
## ARCH Lag[7] 0.5250 2.315 1.543 0.9761
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 2.0644
## Individual Statistics:
## omega 0.4244
## alpha1 0.8648
## beta1 0.4916
## gamma1 0.7039
##
## 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
## ------------------------------------
## t-value prob sig
## Sign Bias 0.01233 0.99016
## Negative Sign Bias 2.14260 0.03236 **
## Positive Sign Bias 0.22298 0.82359
## Joint Effect 6.33572 0.09637 *
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 79.42 2.344e-09
## 2 30 91.77 1.940e-08
## 3 40 114.22 2.621e-09
## 4 50 124.46 1.708e-08
##
##
## Elapsed time : 0.1455359
# Exibindo os resultados EGARCH(1,1) do ajuste com distribuição t-Student
print("Resultado do ajuste EGARCH(1,1) com distribuição t-Student:")
## [1] "Resultado do ajuste EGARCH(1,1) com distribuição t-Student:"
egarch_fit_std
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : eGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega -0.259725 0.034761 -7.4718 0.000000
## alpha1 -0.050125 0.025800 -1.9428 0.052041
## beta1 0.964329 0.004684 205.8745 0.000000
## gamma1 0.143781 0.047721 3.0129 0.002587
## shape 4.136409 0.514395 8.0413 0.000000
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega -0.259725 0.052424 -4.9543 0.000001
## alpha1 -0.050125 0.028814 -1.7396 0.081926
## beta1 0.964329 0.006754 142.7769 0.000000
## gamma1 0.143781 0.096076 1.4965 0.134516
## shape 4.136409 0.575866 7.1829 0.000000
##
## LogLikelihood : 2524.574
##
## Information Criteria
## ------------------------------------
##
## Akaike -4.5603
## Bayes -4.5377
## Shibata -4.5604
## Hannan-Quinn -4.5517
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.01958 0.8887
## Lag[2*(p+q)+(p+q)-1][2] 0.22560 0.8387
## Lag[4*(p+q)+(p+q)-1][5] 1.16181 0.8221
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 5.360 0.02061
## Lag[2*(p+q)+(p+q)-1][5] 5.800 0.10018
## Lag[4*(p+q)+(p+q)-1][9] 8.189 0.11836
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.5708 0.500 2.000 0.4499
## ARCH Lag[5] 0.7663 1.440 1.667 0.8033
## ARCH Lag[7] 1.0580 2.315 1.543 0.9039
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 2.5557
## Individual Statistics:
## omega 0.1898
## alpha1 1.6764
## beta1 0.2155
## gamma1 1.0913
## shape 0.1798
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 1.28 1.47 1.88
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 0.1249 0.9005896
## Negative Sign Bias 3.8166 0.0001429 ***
## Positive Sign Bias 0.2959 0.7673768
## Joint Effect 17.3102 0.0006101 ***
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 27.40 0.09571
## 2 30 38.50 0.11157
## 3 40 41.32 0.36975
## 4 50 63.10 0.08492
##
##
## Elapsed time : 0.3061879
# Exibindo os resultados GJR(1,1) do ajuste com distribuição Normal e t-student
print("Resultado do ajuste GJR(1,1) com distribuição Normal:")
## [1] "Resultado do ajuste GJR(1,1) com distribuição Normal:"
gjr_fit_norm
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : gjrGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : norm
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000227 0.000065 3.5211 0.000430
## alpha1 0.117037 0.046135 2.5368 0.011186
## beta1 0.485895 0.115558 4.2048 0.000026
## gamma1 0.264311 0.091055 2.9028 0.003699
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000227 0.000217 1.04618 0.29548
## alpha1 0.117037 0.095995 1.21920 0.22277
## beta1 0.485895 0.408881 1.18835 0.23469
## gamma1 0.264311 0.305152 0.86616 0.38640
##
## LogLikelihood : 2438.431
##
## Information Criteria
## ------------------------------------
##
## Akaike -4.4062
## Bayes -4.3881
## Shibata -4.4062
## Hannan-Quinn -4.3994
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.08402 0.7719
## Lag[2*(p+q)+(p+q)-1][2] 0.23635 0.8322
## Lag[4*(p+q)+(p+q)-1][5] 1.75990 0.6761
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.001915 0.9651
## Lag[2*(p+q)+(p+q)-1][5] 0.950188 0.8708
## Lag[4*(p+q)+(p+q)-1][9] 1.770521 0.9306
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.4897 0.500 2.000 0.4841
## ARCH Lag[5] 0.6646 1.440 1.667 0.8342
## ARCH Lag[7] 0.9032 2.315 1.543 0.9288
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 2.6562
## Individual Statistics:
## omega 0.9723
## alpha1 0.0802
## beta1 0.4185
## gamma1 0.2452
##
## 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
## ------------------------------------
## t-value prob sig
## Sign Bias 0.1028 0.9182
## Negative Sign Bias 0.7168 0.4737
## Positive Sign Bias 0.1423 0.8869
## Joint Effect 0.9129 0.8223
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 76.77 6.647e-09
## 2 30 93.29 1.125e-08
## 3 40 117.19 9.445e-10
## 4 50 116.67 1.906e-07
##
##
## Elapsed time : 0.2364829
# Exibindo os resultados EGARCH(1,1) do ajuste com distribuição t-Student
print("Resultado do ajuste GJR(1,1) com distribuição t-Student:")
## [1] "Resultado do ajuste GJR(1,1) com distribuição t-Student:"
gjr_fit_std
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : gjrGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000042 0.000017 2.48038 0.013124
## alpha1 0.046262 0.030935 1.49542 0.134804
## beta1 0.882123 0.037245 23.68438 0.000000
## gamma1 0.028778 0.032035 0.89832 0.369014
## shape 4.113648 0.499588 8.23408 0.000000
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000042 0.000026 1.60214 0.10913
## alpha1 0.046262 0.038141 1.21291 0.22516
## beta1 0.882123 0.061580 14.32482 0.00000
## gamma1 0.028778 0.037121 0.77525 0.43819
## shape 4.113648 0.516094 7.97074 0.00000
##
## LogLikelihood : 2524.967
##
## Information Criteria
## ------------------------------------
##
## Akaike -4.5610
## Bayes -4.5384
## Shibata -4.5611
## Hannan-Quinn -4.5525
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.06183 0.8036
## Lag[2*(p+q)+(p+q)-1][2] 0.17734 0.8683
## Lag[4*(p+q)+(p+q)-1][5] 1.25989 0.7986
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 5.097 0.02397
## Lag[2*(p+q)+(p+q)-1][5] 5.264 0.13333
## Lag[4*(p+q)+(p+q)-1][9] 7.637 0.15141
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.2020 0.500 2.000 0.6531
## ARCH Lag[5] 0.2483 1.440 1.667 0.9537
## ARCH Lag[7] 0.4673 2.315 1.543 0.9813
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 2.6262
## Individual Statistics:
## omega 0.49699
## alpha1 0.09027
## beta1 0.23955
## gamma1 0.36572
## shape 0.09962
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 1.28 1.47 1.88
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 0.02971 0.9763052
## Negative Sign Bias 3.68199 0.0002427 ***
## Positive Sign Bias 0.19530 0.8451956
## Joint Effect 16.97049 0.0007167 ***
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 26.93 0.1064
## 2 30 33.02 0.2770
## 3 40 45.08 0.2326
## 4 50 51.33 0.3823
##
##
## Elapsed time : 0.5181241
Calculando os critérios de informação
# Calculando os critérios de informação
aics <- c(infocriteria(garch_fit_norm)[1], infocriteria(garch_fit_std)[1],
infocriteria(egarch_fit_norm)[1], infocriteria(egarch_fit_std)[1],
infocriteria(gjr_fit_norm)[1], infocriteria(gjr_fit_std)[1])
# Criando a tabela de resultados
results_table <- data.frame(Model = c("sGARCH Normal", "sGARCH t-Student",
"eGARCH Normal", "eGARCH t-Student",
"GJR-GARCH Normal", "GJR-GARCH t-Student"),
Aikake = aics)
# Ordenando a tabela pelo valor do AIC
results_table <- results_table[order(results_table$Aikake), ]
# Exibindo a tabela de resultados
print("Tabela de Resultados:")
## [1] "Tabela de Resultados:"
print(results_table)
## Model Aikake
## 2 sGARCH t-Student -4.562150
## 6 GJR-GARCH t-Student -4.561026
## 4 eGARCH t-Student -4.560314
## 5 GJR-GARCH Normal -4.406211
## 3 eGARCH Normal -4.402172
## 1 sGARCH Normal -4.396406
Seleção das configurações do modelos
| Seleção das configurações do modelos | PETR4 |
|---|---|
| Especificações | Amostra completa(Akaike) |
| sGARCH t-Student | -4.560799 |
| GJR-GARCH t-Student | -4.559693 |
| eGARCH t-Student | -4.558876 |
| GJR-GARCH Normal | -4.405005 |
| eGARCH Normal | -4.400731 |
| sGARCH Normal | -4.395106 |
Podemos analisar pelos critérios os melhores modelos são sGARCH t-Student, GJR-GARCH t-Student, sGARCH t-Student por se tratar de um modelo t-student observado anteriormente com fatos estilizados, escolheremos o modelo sGARCH(1,1)-std
Parametros dos modelo escolhido sGARCH(1,1)-std
# Exibindo a tabela de coeficientes em formato LaTeX
Table <- xtable(garch_fit_std@fit$matcoef)
print(Table, type = "latex", comment = FALSE)
## \begin{table}[ht]
## \centering
## \begin{tabular}{rrrrr}
## \hline
## & Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\
## \hline
## omega & 0.00 & 0.00 & 2.53 & 0.01 \\
## alpha1 & 0.07 & 0.02 & 3.11 & 0.00 \\
## beta1 & 0.88 & 0.04 & 24.42 & 0.00 \\
## shape & 4.10 & 0.50 & 8.25 & 0.00 \\
## \hline
## \end{tabular}
## \end{table}
Table
## % latex table generated in R 4.3.0 by xtable 1.8-4 package
## % Wed Aug 16 01:29:11 2023
## \begin{table}[ht]
## \centering
## \begin{tabular}{rrrrr}
## \hline
## & Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\
## \hline
## omega & 0.00 & 0.00 & 2.53 & 0.01 \\
## alpha1 & 0.07 & 0.02 & 3.11 & 0.00 \\
## beta1 & 0.88 & 0.04 & 24.42 & 0.00 \\
## shape & 4.10 & 0.50 & 8.25 & 0.00 \\
## \hline
## \end{tabular}
## \end{table}
Calculando e plotando a volatilidade condicional estimada
sigma <- sigma(garch_fit_std) %>% xts_tbl()
colnames(sigma) <- c("date", "sigma")
sigma <- sigma %>% mutate(date = as.Date(date))
# Plotando a volatilidade condicional estimada
ggplot(sigma) + geom_line(aes(x = date , y = sigma)) + theme_solarized()
Calculando o parâmetro de persistência escolhido da ação PETR4 para periodo completo, dos melhores modelos sGARCH(1,1)-std vs GJR-GARCH(1,1)-std
# Calculando o parâmetro de persistência escolhido para periodo completo
print("Parâmetro de Persistência EGARCH(1,1) t-student:")
## [1] "Parâmetro de Persistência EGARCH(1,1) t-student:"
print(persistence(garch_fit_std))
## [1] 0.9447355
print("Parâmetro de Persistência GJRGARCH(1,1) t-student:")
## [1] "Parâmetro de Persistência GJRGARCH(1,1) t-student:"
print(persistence(gjr_fit_std))
## [1] 0.9427739
# Calculando a persistência para cada modelo
persist_garch <- persistence(garch_fit_std)
persist_gjr <- persistence(gjr_fit_std)
# Calculando o half-life para cada modelo
half_life_garch <- -log(2) / log(persist_garch)
half_life_gjr <- -log(2) / log(persist_gjr)
# Criando a tabela com os resultados
results_table <- data.frame(Model = c("sGARCH(1,1) t-student", "GJRGARCH(1,1) t-student"),
Persistência = c(persist_garch, persist_gjr),
Half_Life = c(half_life_garch, half_life_gjr))
print("Tabela de Resultados Persistência e Half life:")
## [1] "Tabela de Resultados Persistência e Half life:"
print(results_table)
## Model Persistência Half_Life
## 1 sGARCH(1,1) t-student 0.9447355 12.19250
## 2 GJRGARCH(1,1) t-student 0.9427739 11.76245
Realizando previsões usando o modelo ajustado sGARCH(1,1) t-student
# Realizando previsões usando o modelo ajustado
n_ahead <- 10
egarch_std_forecast <- ugarchforecast(garch_fit_std, n.ahead = n_ahead)
print(paste("Previsão da Volatilidade para", n_ahead, "passos à frente:"))
## [1] "Previsão da Volatilidade para 10 passos à frente:"
print(egarch_std_forecast)
##
## *------------------------------------*
## * GARCH Model Forecast *
## *------------------------------------*
## Model: sGARCH
## Horizon: 10
## Roll Steps: 0
## Out of Sample: 0
##
## 0-roll forecast [T0=1105-01-01]:
## Series Sigma
## T+1 0 0.02175
## T+2 0 0.02211
## T+3 0 0.02245
## T+4 0 0.02276
## T+5 0 0.02306
## T+6 0 0.02333
## T+7 0 0.02358
## T+8 0 0.02382
## T+9 0 0.02405
## T+10 0 0.02426
(b) log-retornos diários do IBOVESPA.
library(BatchGetSymbols) ### pegar dados yahoo finance (preços diárias ativos negociados em bolsa)
library(tidyverse)
library(rugarch)
library(ggthemes)
library(FinTS)
library(WriteXLS)
library(xtable)
library(tbl2xts)
library(forecast)
library(tseries)
library(timeSeries)
library(lmtest)
library(rugarch)
library(ggplot2)
library(cowplot)
library(dplyr)
library(moments)
#limpar o diretório
rm(list=ls())
#ticker IBOVESPA
tickers<-c("^BVSP")
ibov<- BatchGetSymbols(tickers,
first.date = '2019-03-03',
last.date = Sys.time(),
type.return = "log",
freq.data = "daily")
##
## Running BatchGetSymbols for:
## tickers =^BVSP
## Downloading data for benchmark ticker
## ^GSPC | yahoo (1|1) | Found cache file
## ^BVSP | yahoo (1|1) | Not Cached | Saving cache - Got 96% of valid prices | Well done!
ibov <- ibov[[2]]
# Eliminando os valores NA
ibov= na.omit(ibov)
#glimpse(ibov)
daily_returns <- ibov %>%
select(ref.date,ret.closing.prices)
date <- daily_returns %>%
select(ref.date) %>%
rename(date = ref.date) %>%
slice(-1)
daily_returns <- daily_returns %>%
select(ret.closing.prices) %>%
slice(-1)
## declarando como série temporal através do comando as.ts
daily_returns=as.ts(daily_returns)
Dados e análises descritivas.
# Fazer uma análise visual da série, verificando os fatos estilizados.
# Função para plotar os gráficos para qualquer ação que deseja analisar.
plot_graficos <- function(acao) {
# Gráfico 1: preços
p <- ggplot(acao, aes(ref.date, price.close)) +
geom_line(color='#006600') +
labs(x = "", y = 'Preço Fechamento',
title = paste("Cotação Diária da", acao$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
# Gráfico 2: retornos diários
daily_returns <- acao %>% select(ref.date, ticker, ret.closing.prices)
plot_returns <- ggplot(daily_returns) +
geom_line(aes(x = ref.date, y = ret.closing.prices), color='#006600') +
labs(x = "", y = 'Retornos',
title = paste("Retornos da", acao$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
# Gráfico 3: Retornos absolutos (abs)
plot_volatility <- ggplot(daily_returns) +
geom_line(aes(x = ref.date, y = abs(ret.closing.prices)), color='#006600') +
labs(x = "", y = 'Retornos absolutos',
title = paste("Retornos abs da", acao$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
# Gráfico 4: qqplot
qqplot <- ggplot(daily_returns, aes(sample = ret.closing.prices)) +
stat_qq() +
stat_qq_line() +
labs(x = "Teórico", y = 'Amostra',
title = "QQplot",
subtitle = paste("Retornos diários da", acao$ticker[1]),
caption = "Fonte: Elaborado a partir de dados da B3") +
theme_economist()
# Gráfico 5: Histograma
histogram <- ggplot(daily_returns) +
geom_histogram(aes(x = ret.closing.prices, y = after_stat(density)),
color = "white", fill = "Dark grey", linetype = "solid", alpha = 0.8, binwidth = 0.02) +
geom_density(aes(x = ret.closing.prices, y = after_stat(density)), color = "black") +
labs(x = "", y = 'Densidade',
title = "Histograma",
subtitle = paste("Retornos diários da", acao$ticker[1]),
caption = "Fonte: Elaborado a partir de dados da B3") +
theme_economist()
# Plotar os gráficos juntos
plot_grid(plot_returns, qqplot, plot_volatility, histogram, nrow = 2)
}
# Gráfico 1: preços
p <- ggplot(ibov, aes(ref.date, price.close)) +
geom_line(color='#006600') +
labs(x = "", y = 'Preço Fechamento',
title = paste("Cotação Diária da", ibov$ticker[1]),
subtitle = "Período: de 03/03/2019 a 11/08/2023",
caption = "Fonte: B3") +
theme_economist()
p
plot_graficos(ibov)
Calcular estatísticas descritivas
# Calcular estatísticas descritivas para cada ação
estatisticas <- ibov %>%
group_by(ticker) %>%
summarise(
media = mean(ret.closing.prices),
desvio_padrao = sd(ret.closing.prices),
variancia = var(ret.closing.prices),
curtose = kurtosis(ret.closing.prices),
assimetria = skewness(ret.closing.prices)
)
# Adicionar coluna indicando se a distribuição é normal ou de cauda pesada
estatisticas <- estatisticas %>%
mutate(distribuicao = ifelse(curtose > 3, "Cauda Pesada", "Normal"))
estatisticas
## # A tibble: 1 × 7
## ticker media desvio_padrao variancia curtose assimetria distribuicao
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
## 1 ^BVSP 0.000189 0.0174 0.000304 22.1 -1.48 Cauda Pesada
# Função para calcular os graus de liberdade da distribuição t-Student
df_t_student <- function(data) {
n <- length(data)
df <- ifelse(n < 30, n - 1, 30)
return(df)
}
# Função para calcular estatísticas descritivas e plotar histograma
plot_estatisticas_histograma <- function(data, tickers) {
# Plotar histograma
grafico <- ggplot(data = data) +
geom_histogram(aes(x = ret.closing.prices, y = after_stat(density)),
color = "black", fill = "white") +
facet_wrap(~ticker, ncol = 2) +
geom_density(aes(x = ret.closing.prices),
color = "blue", fill = "lightblue", alpha = 0.5) +
stat_function(fun = dnorm,
args = list(mean = mean(data$ret.closing.prices), sd = sd(data$ret.closing.prices)),
color = "red", linetype = "dashed") +
stat_function(fun = dt,
args = list(df = df_t_student(data$ret.closing.prices)),
color = "green", linetype = "dotted") +
labs(x = "Retornos", y = "Densidade",
title = "Distribuição Normal e t-Student",
subtitle = "distribuicoes BVSP",
caption = "Fonte: Dados da Acao") +
theme_minimal()
print(grafico)
}
# Chamar a função para ações desejadas
plot_estatisticas_histograma(ibov, ticker)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# Calculando os retornos ao quadrado
returns_squared <- daily_returns^2
# Calculando a função de autocorrelação parcial (FACP) dos retornos ao quadrado
pacf_returns_squared <- pacf(returns_squared, lag.max = 50, plot = TRUE)
# Exibindo os resultados da FACP
pacf_returns_squared
##
## Partial autocorrelations of series 'returns_squared', by lag
##
## 1 2 3 4 5 6 7 8 9 10 11
## 0.580 0.386 0.038 0.007 -0.018 -0.121 0.207 0.059 -0.126 -0.061 0.152
## 12 13 14 15 16 17 18 19 20 21 22
## -0.038 0.002 -0.059 -0.016 0.017 0.106 -0.091 -0.028 0.060 0.004 -0.039
## 23 24 25 26 27 28 29 30 31 32 33
## -0.015 -0.059 0.081 0.050 0.030 -0.018 0.023 -0.034 0.014 0.001 -0.026
## 34 35 36 37 38 39 40 41 42 43 44
## -0.031 0.022 -0.008 -0.004 0.002 -0.015 0.011 0.034 0.004 -0.018 -0.013
## 45 46 47 48 49 50
## 0.002 -0.015 0.064 -0.024 -0.031 -0.005
Especificando os lags para o teste LM
# Especificando os lags para o teste LM
lags <- c(1, 2, 6, 7 )
# Testando efeito ARCH: Teste LM
for (lag in lags) {
arch_test <- ArchTest(daily_returns, lags = lag, demean = TRUE)
print(paste("Resultado do Teste LM (", lag, "lags):"))
print(arch_test)
}
## [1] "Resultado do Teste LM ( 1 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 369.21, df = 1, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 2 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 479.84, df = 2, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 6 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 488.5, df = 6, p-value < 2.2e-16
##
## [1] "Resultado do Teste LM ( 7 lags):"
##
## ARCH LM-test; Null hypothesis: no ARCH effects
##
## data: daily_returns
## Chi-squared = 513.86, df = 7, p-value < 2.2e-16
Configurar as ordens padrão para os modelos
# Configurar as ordens padrão para os modelos
orders <- c(1, 1)
# Configurações padrão para GARCH, EGARCH e GJR-GARCH com distribuição norm
garch_spec_norm <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "norm")
egarch_spec_norm <- ugarchspec(variance.model = list(model = "eGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "norm")
gjr_spec_norm <- ugarchspec(variance.model = list(model = "gjrGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "norm")
# Configurações padrão para GARCH, EGARCH e GJR-GARCH com distribuição std
garch_spec_std <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "std")
egarch_spec_std <- ugarchspec(variance.model = list(model = "eGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "std")
gjr_spec_std <- ugarchspec(variance.model = list(model = "gjrGARCH", garchOrder = orders),
mean.model = list(armaOrder = c(0, 0), include.mean = FALSE),
distribution.model = "std")
Ajustando o modelo GARCH(1,1), EGARCH(1,1), GJR(1,1) para distribuição normal e t-student.
# Ajustando o modelo GARCH(1,1) com distribuição Normal e t-student aos retornos diários
garch_fit_norm <- ugarchfit(spec = garch_spec_norm, data = daily_returns)
garch_fit_std <- ugarchfit(spec = garch_spec_std, data = daily_returns)
# Ajustando o modelo EGARCH(1,1) com distribuição Normal e t-student aos retornos diários
egarch_fit_norm <- ugarchfit(spec = egarch_spec_norm, data = daily_returns)
egarch_fit_std <- ugarchfit(spec = egarch_spec_std, data = daily_returns)
# Ajustando o modelo GJR(1,1) com distribuição Normal e t-student aos retornos diários
gjr_fit_norm <- ugarchfit(spec = gjr_spec_norm, data = daily_returns)
gjr_fit_std <- ugarchfit(spec = gjr_spec_std, data = daily_returns)
Exibindo os resultados modelo GARCH(1,1), EGARCH(1,1), GJR(1,1) para distribuição normal e t-student.
# Exibindo os resultados GARCH(1,1) do ajuste com distribuição Normal e t-student
print("Resultado do ajuste GARCH(1,1) com distribuição Normal:")
## [1] "Resultado do ajuste GARCH(1,1) com distribuição Normal:"
garch_fit_norm
##
## *---------------------------------*
## * 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|)
## omega 0.00001 0.000001 11.665 0
## alpha1 0.09892 0.009066 10.911 0
## beta1 0.85336 0.013638 62.572 0
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.00001 0.000002 4.942 1e-06
## alpha1 0.09892 0.009025 10.960 0e+00
## beta1 0.85336 0.019829 43.036 0e+00
##
## LogLikelihood : 3163.687
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7207
## Bayes -5.7071
## Shibata -5.7207
## Hannan-Quinn -5.7156
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 2.282 0.1308
## Lag[2*(p+q)+(p+q)-1][2] 2.360 0.2094
## Lag[4*(p+q)+(p+q)-1][5] 2.571 0.4910
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.02967 0.8632
## Lag[2*(p+q)+(p+q)-1][5] 1.92392 0.6365
## Lag[4*(p+q)+(p+q)-1][9] 6.86713 0.2105
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 2.507 0.500 2.000 0.1134
## ARCH Lag[5] 2.679 1.440 1.667 0.3398
## ARCH Lag[7] 3.171 2.315 1.543 0.4819
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 20.4028
## Individual Statistics:
## omega 2.80514
## alpha1 0.19880
## beta1 0.05978
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 0.846 1.01 1.35
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 1.5336 0.12540
## Negative Sign Bias 1.3992 0.16202
## Positive Sign Bias 0.6859 0.49290
## Joint Effect 8.0527 0.04493 **
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 39.92 0.003349
## 2 30 47.90 0.015067
## 3 40 64.77 0.005884
## 4 50 70.34 0.024461
##
##
## Elapsed time : 0.136158
# Exibindo os resultados do ajuste com distribuição t-Student
print("Resultado do ajuste GARCH(1,1) com distribuição t-Student:")
## [1] "Resultado do ajuste GARCH(1,1) com distribuição t-Student:"
garch_fit_std
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : sGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000009 0.000001 7.8317 0.0e+00
## alpha1 0.088993 0.008081 11.0123 0.0e+00
## beta1 0.865276 0.015416 56.1302 0.0e+00
## shape 10.146501 2.345792 4.3254 1.5e-05
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000009 0.000002 3.8630 0.000112
## alpha1 0.088993 0.007967 11.1695 0.000000
## beta1 0.865276 0.016149 53.5796 0.000000
## shape 10.146501 2.445037 4.1498 0.000033
##
## LogLikelihood : 3179.256
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7471
## Bayes -5.7289
## Shibata -5.7471
## Hannan-Quinn -5.7402
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 2.318 0.1279
## Lag[2*(p+q)+(p+q)-1][2] 2.403 0.2038
## Lag[4*(p+q)+(p+q)-1][5] 2.623 0.4802
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.005036 0.9434
## Lag[2*(p+q)+(p+q)-1][5] 2.665282 0.4716
## Lag[4*(p+q)+(p+q)-1][9] 8.377795 0.1086
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 3.444 0.500 2.000 0.06347
## ARCH Lag[5] 3.532 1.440 1.667 0.22136
## ARCH Lag[7] 4.123 2.315 1.543 0.32925
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 18.7711
## Individual Statistics:
## omega 2.44771
## alpha1 0.12319
## beta1 0.06767
## shape 0.13178
##
## 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
## ------------------------------------
## t-value prob sig
## Sign Bias 1.4681 0.14236
## Negative Sign Bias 1.6592 0.09736 *
## Positive Sign Bias 0.8111 0.41750
## Joint Effect 8.8778 0.03096 **
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 30.15 0.0499286
## 2 30 43.50 0.0409260
## 3 40 56.67 0.0334541
## 4 50 87.08 0.0006611
##
##
## Elapsed time : 0.1439171
# Exibindo os resultados EGARCH(1,1) do ajuste com distribuição Normal e t-student
print("Resultado do ajuste EGARCH(1,1) com distribuição Normal:")
## [1] "Resultado do ajuste EGARCH(1,1) com distribuição Normal:"
egarch_fit_norm
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : eGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : norm
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega -0.33432 0.076787 -4.3539 1.3e-05
## alpha1 -0.11426 0.004129 -27.6710 0.0e+00
## beta1 0.96067 0.008884 108.1291 0.0e+00
## gamma1 0.16251 0.020900 7.7759 0.0e+00
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega -0.33432 0.186040 -1.7971 0.072327
## alpha1 -0.11426 0.053914 -2.1194 0.034061
## beta1 0.96067 0.021801 44.0661 0.000000
## gamma1 0.16251 0.046889 3.4659 0.000529
##
## LogLikelihood : 3178.51
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7457
## Bayes -5.7276
## Shibata -5.7457
## Hannan-Quinn -5.7389
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 1.912 0.1668
## Lag[2*(p+q)+(p+q)-1][2] 2.007 0.2616
## Lag[4*(p+q)+(p+q)-1][5] 2.263 0.5577
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.2778 0.5981
## Lag[2*(p+q)+(p+q)-1][5] 1.6773 0.6963
## Lag[4*(p+q)+(p+q)-1][9] 3.3999 0.6915
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.8086 0.500 2.000 0.3685
## ARCH Lag[5] 0.9240 1.440 1.667 0.7556
## ARCH Lag[7] 1.5989 2.315 1.543 0.8013
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 1.0497
## Individual Statistics:
## omega 0.1299
## alpha1 0.5532
## beta1 0.1214
## gamma1 0.3904
##
## 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
## ------------------------------------
## t-value prob sig
## Sign Bias 1.093 0.2747
## Negative Sign Bias 1.081 0.2800
## Positive Sign Bias 1.336 0.1817
## Joint Effect 4.215 0.2392
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 33.26 0.022417
## 2 30 51.59 0.006057
## 3 40 68.61 0.002365
## 4 50 82.65 0.001876
##
##
## Elapsed time : 0.1869118
# Exibindo os resultados EGARCH(1,1) do ajuste com distribuição t-Student
print("Resultado do ajuste EGARCH(1,1) com distribuição t-Student:")
## [1] "Resultado do ajuste EGARCH(1,1) com distribuição t-Student:"
egarch_fit_std
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : eGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega -0.32646 0.046791 -6.9770 0.000000
## alpha1 -0.10813 0.016169 -6.6878 0.000000
## beta1 0.96204 0.005519 174.2996 0.000000
## gamma1 0.15687 0.052387 2.9944 0.002750
## shape 11.55783 3.093068 3.7367 0.000186
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega -0.32646 0.146993 -2.2209 0.026356
## alpha1 -0.10813 0.051358 -2.1055 0.035248
## beta1 0.96204 0.017497 54.9822 0.000000
## gamma1 0.15687 0.146551 1.0704 0.284451
## shape 11.55783 3.717904 3.1087 0.001879
##
## LogLikelihood : 3188.307
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7616
## Bayes -5.7390
## Shibata -5.7617
## Hannan-Quinn -5.7531
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 1.973 0.1601
## Lag[2*(p+q)+(p+q)-1][2] 2.071 0.2513
## Lag[4*(p+q)+(p+q)-1][5] 2.321 0.5447
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.1424 0.7059
## Lag[2*(p+q)+(p+q)-1][5] 1.9630 0.6272
## Lag[4*(p+q)+(p+q)-1][9] 4.0068 0.5877
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 1.169 0.500 2.000 0.2795
## ARCH Lag[5] 1.303 1.440 1.667 0.6457
## ARCH Lag[7] 2.044 2.315 1.543 0.7081
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 1.2541
## Individual Statistics:
## omega 0.11032
## alpha1 0.45348
## beta1 0.10167
## gamma1 0.67699
## shape 0.04881
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 1.28 1.47 1.88
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 1.103 0.2701
## Negative Sign Bias 1.267 0.2054
## Positive Sign Bias 1.421 0.1555
## Joint Effect 5.018 0.1705
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 37.10 0.0077106
## 2 30 57.34 0.0013062
## 3 40 72.45 0.0009042
## 4 50 85.09 0.0010634
##
##
## Elapsed time : 0.382
# Exibindo os resultados GJR(1,1) do ajuste com distribuição Normal e t-student
print("Resultado do ajuste GJR(1,1) com distribuição Normal:")
## [1] "Resultado do ajuste GJR(1,1) com distribuição Normal:"
gjr_fit_norm
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : gjrGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : norm
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000009 0.000000 64.81149 0.00000
## alpha1 0.002972 0.005434 0.54693 0.58442
## beta1 0.885883 0.009128 97.04709 0.00000
## gamma1 0.125355 0.022799 5.49832 0.00000
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000009 0.000000 50.10123 0.000000
## alpha1 0.002972 0.009177 0.32382 0.746072
## beta1 0.885883 0.012113 73.13570 0.000000
## gamma1 0.125355 0.044273 2.83141 0.004634
##
## LogLikelihood : 3175.282
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7399
## Bayes -5.7217
## Shibata -5.7399
## Hannan-Quinn -5.7330
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 1.629 0.2018
## Lag[2*(p+q)+(p+q)-1][2] 1.838 0.2911
## Lag[4*(p+q)+(p+q)-1][5] 2.116 0.5912
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.4393 0.5075
## Lag[2*(p+q)+(p+q)-1][5] 1.0277 0.8534
## Lag[4*(p+q)+(p+q)-1][9] 3.6999 0.6400
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.5434 0.500 2.000 0.4610
## ARCH Lag[5] 0.7552 1.440 1.667 0.8067
## ARCH Lag[7] 1.4381 2.315 1.543 0.8337
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 26.7801
## Individual Statistics:
## omega 7.33061
## alpha1 0.16547
## beta1 0.08629
## gamma1 0.22940
##
## 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
## ------------------------------------
## t-value prob sig
## Sign Bias 1.4058 0.1601
## Negative Sign Bias 0.5974 0.5504
## Positive Sign Bias 0.9656 0.3345
## Joint Effect 3.6738 0.2989
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 33.73 0.019755
## 2 30 52.19 0.005197
## 3 40 69.19 0.002052
## 4 50 67.90 0.038147
##
##
## Elapsed time : 0.339489
# Exibindo os resultados EGARCH(1,1) do ajuste com distribuição t-Student
print("Resultado do ajuste GJR(1,1) com distribuição t-Student:")
## [1] "Resultado do ajuste GJR(1,1) com distribuição t-Student:"
gjr_fit_std
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : gjrGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000009 0.000000 32.01126 0.000000
## alpha1 0.004512 0.007612 0.59271 0.553376
## beta1 0.890428 0.010801 82.43924 0.000000
## gamma1 0.116337 0.026005 4.47358 0.000008
## shape 10.914247 2.792874 3.90789 0.000093
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega 0.000009 0.000000 25.81086 0.000000
## alpha1 0.004512 0.011573 0.38987 0.696631
## beta1 0.890428 0.011068 80.45092 0.000000
## gamma1 0.116337 0.039931 2.91347 0.003574
## shape 10.914247 3.200048 3.41065 0.000648
##
## LogLikelihood : 3187.751
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7606
## Bayes -5.7380
## Shibata -5.7607
## Hannan-Quinn -5.7521
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 1.687 0.1940
## Lag[2*(p+q)+(p+q)-1][2] 1.889 0.2819
## Lag[4*(p+q)+(p+q)-1][5] 2.163 0.5804
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.3242 0.5691
## Lag[2*(p+q)+(p+q)-1][5] 1.0523 0.8477
## Lag[4*(p+q)+(p+q)-1][9] 3.9550 0.5965
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 0.7229 0.500 2.000 0.3952
## ARCH Lag[5] 0.9171 1.440 1.667 0.7577
## ARCH Lag[7] 1.6013 2.315 1.543 0.8008
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 28.726
## Individual Statistics:
## omega 6.44234
## alpha1 0.15254
## beta1 0.10010
## gamma1 0.17704
## shape 0.08306
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 1.28 1.47 1.88
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 1.3935 0.1637
## Negative Sign Bias 0.7262 0.4679
## Positive Sign Bias 0.9987 0.3181
## Joint Effect 4.0085 0.2605
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 38.91 0.0045376
## 2 30 62.18 0.0003286
## 3 40 66.95 0.0035350
## 4 50 74.68 0.0104917
##
##
## Elapsed time : 0.501442
Calculando os critérios de informação
# Calculando os critérios de informação
print("Critérios de Informação sGARCH(1,1) Normal:")
## [1] "Critérios de Informação sGARCH(1,1) Normal:"
print(infocriteria(garch_fit_norm))
##
## Akaike -5.720701
## Bayes -5.707106
## Shibata -5.720716
## Hannan-Quinn -5.715559
print("Critérios de Informação sGARCH(1,1) t-student :")
## [1] "Critérios de Informação sGARCH(1,1) t-student :"
print(infocriteria(garch_fit_std))
##
## Akaike -5.747069
## Bayes -5.728942
## Shibata -5.747095
## Hannan-Quinn -5.740213
print("Critérios de Informação eGARCH(1,1) Normal:")
## [1] "Critérios de Informação eGARCH(1,1) Normal:"
print(infocriteria(egarch_fit_norm))
##
## Akaike -5.745719
## Bayes -5.727592
## Shibata -5.745745
## Hannan-Quinn -5.738863
print("Critérios de Informação eGARCH(1,1) t-student:")
## [1] "Critérios de Informação eGARCH(1,1) t-student:"
print(infocriteria(egarch_fit_std))
##
## Akaike -5.761641
## Bayes -5.738982
## Shibata -5.761682
## Hannan-Quinn -5.753071
print("Critérios de Informação GJR(1,1)-Normal:")
## [1] "Critérios de Informação GJR(1,1)-Normal:"
print(infocriteria(gjr_fit_norm))
##
## Akaike -5.739876
## Bayes -5.721749
## Shibata -5.739902
## Hannan-Quinn -5.733020
print("Critérios de Informação GJR(1,1) t-student :")
## [1] "Critérios de Informação GJR(1,1) t-student :"
print(infocriteria(gjr_fit_std))
##
## Akaike -5.760635
## Bayes -5.737977
## Shibata -5.760676
## Hannan-Quinn -5.752065
Seleção das configurações de modelo
| Especificações | Amostra completa(Akaike) |
| sGARCH(1,1)-norm | -5.7206 |
| sGARCH(1,1)-std | -5.7472 |
| eGARCH(1,1)-norm | -5.7456 |
| eGARCH(1,1)-std | -5.7618 |
| gjrGARCH(1,1)-norm | -5.7397 |
| gjrGARCH(1,1)-std | -5.7607 |
De acordo com a tabela foram escolhidos os modelos eGARCH(1,1)-std, gjrGARCH(1,1)-std por se tratar de um modelo normal t-student observado anteriormente com fatos estilizados, escolheremos o modelo eGARCH(1,1)-std
Parametros dos modelo escolhido eGARCH(1,1)-std
# Exibindo a tabela de coeficientes em formato LaTeX
Table <- xtable(egarch_fit_std@fit$matcoef)
# print(Table, type = "latex", comment = FALSE)
Table
## % latex table generated in R 4.3.0 by xtable 1.8-4 package
## % Wed Aug 16 01:29:18 2023
## \begin{table}[ht]
## \centering
## \begin{tabular}{rrrrr}
## \hline
## & Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\
## \hline
## omega & -0.33 & 0.05 & -6.98 & 0.00 \\
## alpha1 & -0.11 & 0.02 & -6.69 & 0.00 \\
## beta1 & 0.96 & 0.01 & 174.30 & 0.00 \\
## gamma1 & 0.16 & 0.05 & 2.99 & 0.00 \\
## shape & 11.56 & 3.09 & 3.74 & 0.00 \\
## \hline
## \end{tabular}
## \end{table}
Calculando e plotando a volatilidade condicional estimada
sigma <- sigma(egarch_fit_std) %>% xts_tbl()
colnames(sigma) <- c("date", "sigma")
sigma <- sigma %>% mutate(date = as.Date(date))
# Plotando a volatilidade condicional estimada
ggplot(sigma) + geom_line(aes(x = date , y = sigma)) + theme_solarized()
Realizando previsões usando o modelo ajustado eGARCH(1,1)-std
# Realizando previsões usando o modelo ajustado
n_ahead <- 10
egarch_std_forecast <- ugarchforecast(egarch_fit_std, n.ahead = n_ahead)
print(paste("Previsão da Volatilidade para", n_ahead, "passos à frente:"))
## [1] "Previsão da Volatilidade para 10 passos à frente:"
print(egarch_std_forecast)
##
## *------------------------------------*
## * GARCH Model Forecast *
## *------------------------------------*
## Model: eGARCH
## Horizon: 10
## Roll Steps: 0
## Out of Sample: 0
##
## 0-roll forecast [T0=1105-01-01]:
## Series Sigma
## T+1 0 0.01137
## T+2 0 0.01145
## T+3 0 0.01153
## T+4 0 0.01160
## T+5 0 0.01167
## T+6 0 0.01173
## T+7 0 0.01180
## T+8 0 0.01186
## T+9 0 0.01192
## T+10 0 0.01198
# Plotando previsões da volatilidade
p1 <- plot(egarch_fit_std, which = 1)
p1
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : eGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega -0.32646 0.046791 -6.9770 0.000000
## alpha1 -0.10813 0.016169 -6.6878 0.000000
## beta1 0.96204 0.005519 174.2996 0.000000
## gamma1 0.15687 0.052387 2.9944 0.002750
## shape 11.55783 3.093068 3.7367 0.000186
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega -0.32646 0.146993 -2.2209 0.026356
## alpha1 -0.10813 0.051358 -2.1055 0.035248
## beta1 0.96204 0.017497 54.9822 0.000000
## gamma1 0.15687 0.146551 1.0704 0.284451
## shape 11.55783 3.717904 3.1087 0.001879
##
## LogLikelihood : 3188.307
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7616
## Bayes -5.7390
## Shibata -5.7617
## Hannan-Quinn -5.7531
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 1.973 0.1601
## Lag[2*(p+q)+(p+q)-1][2] 2.071 0.2513
## Lag[4*(p+q)+(p+q)-1][5] 2.321 0.5447
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.1424 0.7059
## Lag[2*(p+q)+(p+q)-1][5] 1.9630 0.6272
## Lag[4*(p+q)+(p+q)-1][9] 4.0068 0.5877
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 1.169 0.500 2.000 0.2795
## ARCH Lag[5] 1.303 1.440 1.667 0.6457
## ARCH Lag[7] 2.044 2.315 1.543 0.7081
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 1.2541
## Individual Statistics:
## omega 0.11032
## alpha1 0.45348
## beta1 0.10167
## gamma1 0.67699
## shape 0.04881
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 1.28 1.47 1.88
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 1.103 0.2701
## Negative Sign Bias 1.267 0.2054
## Positive Sign Bias 1.421 0.1555
## Joint Effect 5.018 0.1705
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 37.10 0.0077106
## 2 30 57.34 0.0013062
## 3 40 72.45 0.0009042
## 4 50 85.09 0.0010634
##
##
## Elapsed time : 0.382
p2 <- plot(egarch_fit_std, which = 3)
p2
##
## *---------------------------------*
## * GARCH Model Fit *
## *---------------------------------*
##
## Conditional Variance Dynamics
## -----------------------------------
## GARCH Model : eGARCH(1,1)
## Mean Model : ARFIMA(0,0,0)
## Distribution : std
##
## Optimal Parameters
## ------------------------------------
## Estimate Std. Error t value Pr(>|t|)
## omega -0.32646 0.046791 -6.9770 0.000000
## alpha1 -0.10813 0.016169 -6.6878 0.000000
## beta1 0.96204 0.005519 174.2996 0.000000
## gamma1 0.15687 0.052387 2.9944 0.002750
## shape 11.55783 3.093068 3.7367 0.000186
##
## Robust Standard Errors:
## Estimate Std. Error t value Pr(>|t|)
## omega -0.32646 0.146993 -2.2209 0.026356
## alpha1 -0.10813 0.051358 -2.1055 0.035248
## beta1 0.96204 0.017497 54.9822 0.000000
## gamma1 0.15687 0.146551 1.0704 0.284451
## shape 11.55783 3.717904 3.1087 0.001879
##
## LogLikelihood : 3188.307
##
## Information Criteria
## ------------------------------------
##
## Akaike -5.7616
## Bayes -5.7390
## Shibata -5.7617
## Hannan-Quinn -5.7531
##
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 1.973 0.1601
## Lag[2*(p+q)+(p+q)-1][2] 2.071 0.2513
## Lag[4*(p+q)+(p+q)-1][5] 2.321 0.5447
## d.o.f=0
## H0 : No serial correlation
##
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
## statistic p-value
## Lag[1] 0.1424 0.7059
## Lag[2*(p+q)+(p+q)-1][5] 1.9630 0.6272
## Lag[4*(p+q)+(p+q)-1][9] 4.0068 0.5877
## d.o.f=2
##
## Weighted ARCH LM Tests
## ------------------------------------
## Statistic Shape Scale P-Value
## ARCH Lag[3] 1.169 0.500 2.000 0.2795
## ARCH Lag[5] 1.303 1.440 1.667 0.6457
## ARCH Lag[7] 2.044 2.315 1.543 0.7081
##
## Nyblom stability test
## ------------------------------------
## Joint Statistic: 1.2541
## Individual Statistics:
## omega 0.11032
## alpha1 0.45348
## beta1 0.10167
## gamma1 0.67699
## shape 0.04881
##
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic: 1.28 1.47 1.88
## Individual Statistic: 0.35 0.47 0.75
##
## Sign Bias Test
## ------------------------------------
## t-value prob sig
## Sign Bias 1.103 0.2701
## Negative Sign Bias 1.267 0.2054
## Positive Sign Bias 1.421 0.1555
## Joint Effect 5.018 0.1705
##
##
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
## group statistic p-value(g-1)
## 1 20 37.10 0.0077106
## 2 30 57.34 0.0013062
## 3 40 72.45 0.0009042
## 4 50 85.09 0.0010634
##
##
## Elapsed time : 0.382
4. Para os modelos ajustados acima, calcule os coeficientes de persistência e half-life e interprete os resultados.
Calculando o parâmetro de persistência escolhido da ação IBOVESPA para periodo completo EGARCH(1,1)-std vs GJRGARCH(1,1)-std
# Calculando o parâmetro de persistência escolhido para periodo completo
print("Parâmetro de Persistência EGARCH(1,1) t-student:")
## [1] "Parâmetro de Persistência EGARCH(1,1) t-student:"
print(persistence(egarch_fit_std))
## [1] 0.9620381
print("Parâmetro de Persistência GJRGARCH(1,1) t-student:")
## [1] "Parâmetro de Persistência GJRGARCH(1,1) t-student:"
print(persistence(gjr_fit_std))
## [1] 0.953108
# Calculando a persistência para cada modelo
persist_egarch <- persistence(egarch_fit_std)
persist_gjr <- persistence(gjr_fit_std)
# Calculando o half-life para cada modelo
half_life_egarch <- -log(2) / log(persist_egarch)
half_life_gjr <- -log(2) / log(persist_gjr)
# Criando a tabela com os resultados
results_table <- data.frame(Model = c("EGARCH(1,1) t-student", "GJRGARCH(1,1) t-student"),
Persistência = c(persist_egarch, persist_gjr),
Half_Life = c(half_life_egarch, half_life_gjr))
print("Tabela de Resultados:")
## [1] "Tabela de Resultados:"
print(results_table)
## Model Persistência Half_Life
## 1 EGARCH(1,1) t-student 0.9620381 17.91022
## 2 GJRGARCH(1,1) t-student 0.9531080 14.43244
| PETR4 | ||
|---|---|---|
| Model | Persistência | Half_Life |
| sGARCH(1,1) t-student | 0.9446706 | 12.17 |
| GJRGARCH(1,1) t-student | 0.9426686 | 11.74 |
Comparando a tabela acima para modelo a um aumento de 0.942 para 0.944 na persistência dos choques os choques serão mais lentamente enfraquecidos ao longo do tempo. O cálculo da half-life mostra que no periodo inteiro conforme pedido no exercício da ação PETR4 modelo GJRGARCH-std 11,74 dias para dissipação de um choque e para o modelo sGARCH(1,1) t-student seria necessarios 12,17 dias para dissipação do choque de volatilidade.
| IBOV | ||
|---|---|---|
| Model | Persistência | Half_Life |
| EGARCH(1,1) t-student | 0.96 | 17.94 |
| GJRGARCH(1,1) t-student | 0.95 | 14.4 |
Comparando a tabela acima para modelo a um aumento de 0.95 para 0.96 na persistência dos choques os choques serão mais lentamente enfraquecidos ao longo do tempo. O cálculo da half-life mostra que no periodo inteiro conforme pedido no exercício IBOV modelo GJRGARCH 14,48 dias para dissipação de um choque e para o modelo EGARCH(1,1) t-student seria necessarios 17,9 dias para dissipação de um choque.