options(scipen = 9999)
options(max.print = 100000)Modelo Café Arábica - Mínimos Quadrados Ordinários
UNIVERSIDADE FEDERAL DA PARAÍBA
PROFESSOR: Sinézio Fernandes Maia
Atividade em Mínimos Quadrados Ordinários (MQO)
A atividade abaixo se refere a busca de um modelo robusto e não tendencioso em MQO, para encontrar a quantidade ótima de contratos de hedge para o mercado futuro de café arábica.
Configurações iniciais
Para evitar notações científicas:
Pacotes útilizados:
library(urca)
library(readxl)
library(tidyverse)
library(deflateBR)
library(dynlm)
library(ggplot2)
library(fBasics)
library(lmtest)
library(whitestrap)
library(FinTS)Base de dados
dados <- read_excel("/Users/josue/Documents/R/Derivativos/modelo mqo/ICFFUT_(Mensal).xlsx")Plotagem dos dados
ggplot(dados, aes(x = Data)) +
geom_line(aes(y = Abertura, color = "Spot")) +
geom_line(aes(y = Fechamento, color = "Futuro")) +
labs(title = "CAFÉ ARÁBICA",
x = "Data",
y = "Preço",
color = "Variáveis") +
scale_color_manual(values = c("Spot" = "blue", "Futuro" = "red")) +
theme_minimal()Transformando em Séries Temporais e Deflacionando pelo pacote ‘deflateBR’
# Transformando em séries temporais
spot <- ts(dados$Abertura, start= c(2003,01), end=c(2024,03), frequency = 12)
futuro <- ts(dados$Fechamento, start= c(2003,01), end=c(2024,03), frequency = 12)
# Definindo o tempo
times <- seq(as.Date("2003/1/2"), by = "month", length.out = 255)
# Deflacionando
spotR <- deflate(spot, nominal_dates = times, real_date = "02/2024", index = "ipca")
futuroR <- deflate(futuro, nominal_dates = times, real_date = "02/2024", index = "ipca")Plotando os Gráficos de Preço Spot e Futuro
par(mfrow = c(1,2))
plot(spotR, main = "CAFÉ ARÁBICA - Spot"); plot(futuroR, main = "CAFÉ ARÁBICA - Futuro")Tranformando dem logaritmo
O objetivo é corrigir a heterocedásticidade
lspot <- log(spotR)
lfuturo <- log(futuroR)
plot(lspot, main = "CAFÉ ARÁBICA - log SPOT"); plot(lfuturo, main = "CAFÉ ARÁBICA - log FUTURO")Fazendo a regressão em diferença
Para corrigir os problemas causados pela autocorrelação nós fazemos a regressão em diferença
lag <- stats::lag
Regressao <- dynlm(diff(lspot)~diff(lag(lfuturo,11)))
summary(Regressao)
Time series regression with "ts" data:
Start = 2003(2), End = 2023(4)
Call:
dynlm(formula = diff(lspot) ~ diff(lag(lfuturo, 11)))
Residuals:
Min 1Q Median 3Q Max
-0.21827 -0.05323 -0.00249 0.05326 0.32666
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.009883 0.005375 -1.839 0.0672 .
diff(lag(lfuturo, 11)) -0.135043 0.063875 -2.114 0.0355 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.08345 on 241 degrees of freedom
Multiple R-squared: 0.01821, Adjusted R-squared: 0.01413
F-statistic: 4.47 on 1 and 241 DF, p-value: 0.03553
Regressao
Time series regression with "ts" data:
Start = 2003(2), End = 2023(4)
Call:
dynlm(formula = diff(lspot) ~ diff(lag(lfuturo, 11)))
Coefficients:
(Intercept) diff(lag(lfuturo, 11))
-0.009883 -0.135043
Testes para resíduos
par(mfrow = c(1,1))
residuos <- residuals(Regressao); head(residuos) fev 2003 mar 2003 abr 2003 mai 2003 jun 2003 jul 2003
0.087184851 -0.213692794 -0.013379014 0.112945752 -0.090207365 -0.004864075
plot(residuos, type="l", col="red")
abline(h=0, col="blue", lw=3)par(mfrow=c(1,2))
hist(residuos, main="", col="cadetblue", prob=T, xlab = names(residuos)[1], breaks = 30)
curve(expr=dnorm(x,mean=mean(residuos),sd=sd(residuos)),col="red",add= TRUE, lwd=2)
qqnorm(residuos, col="blue")
qqline(residuos, col="red")Teste para a presença de normalidade
Teste de Jarque Bera:
jarqueberaTest(residuos)
Title:
Jarque - Bera Normalality Test
Test Results:
STATISTIC:
X-squared: 4.5414
P VALUE:
Asymptotic p Value: 0.1032
Teste de Shapiro Wilk:
shapiro.test(residuos)
Shapiro-Wilk normality test
data: residuos
W = 0.99039, p-value = 0.1087
Testes para presença de heteroscedasticidade
Teste de Goldfeld-Quandt:
length(residuos); length(residuos)*0.15[1] 243
[1] 36.45
gqtest(Regressao, fraction = 38.1, alternative = "greater")
Goldfeld-Quandt test
data: Regressao
GQ = 0.87604, df1 = 101, df2 = 100, p-value = 0.746
alternative hypothesis: variance increases from segment 1 to 2
Teste de Breusch-Pagan-Godfrey:
bptest(Regressao)
studentized Breusch-Pagan test
data: Regressao
BP = 2.4905, df = 1, p-value = 0.1145
Teste de White:
library(whitestrap)
white_test(Regressao)White's test results
Null hypothesis: Homoskedasticity of the residuals
Alternative hypothesis: Heteroskedasticity of the residuals
Test Statistic: 2.93
P-value: 0.231571
Testes de autocorrelação
Teste de Durbin Watson:
dwtest(Regressao)
Durbin-Watson test
data: Regressao
DW = 2.0771, p-value = 0.7271
alternative hypothesis: true autocorrelation is greater than 0
Teste de Breusch-Godfrey (1978):
bgtest(Regressao, order = 4)
Breusch-Godfrey test for serial correlation of order up to 4
data: Regressao
LM test = 3.8461, df = 4, p-value = 0.4272
Teste de Arch:
ArchTest(residuos, lags = 4)
ARCH LM-test; Null hypothesis: no ARCH effects
data: residuos
Chi-squared = 0.20293, df = 4, p-value = 0.9952
Teste de Dickey-Fuller
dfuller <- ur.df(residuos, lags = 0, type="drift")
summary(dfuller)
###############################################
# Augmented Dickey-Fuller Test Unit Root Test #
###############################################
Test regression drift
Call:
lm(formula = z.diff ~ z.lag.1 + 1)
Residuals:
Min 1Q Median 3Q Max
-0.21476 -0.05322 -0.00270 0.05033 0.32902
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.0003468 0.0053585 -0.065 0.948
z.lag.1 -1.0426757 0.0644559 -16.177 <0.0000000000000002 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.08336 on 240 degrees of freedom
Multiple R-squared: 0.5216, Adjusted R-squared: 0.5196
F-statistic: 261.7 on 1 and 240 DF, p-value: < 0.00000000000000022
Value of test-statistic is: -16.1766 130.8488
Critical values for test statistics:
1pct 5pct 10pct
tau2 -3.46 -2.88 -2.57
phi1 6.52 4.63 3.81
Conclusão
Corrigindo todos os problemas de heterocedásticidade, autocorrelação e mantendo uma distribuição normal, podemos concluir que para cada unidade de futuro, há uma perda de 13,50% no preço spot e aumenta o risco em 0,98%.