-
Notifications
You must be signed in to change notification settings - Fork 1
/
var_vecm.R
1060 lines (913 loc) · 32 KB
/
var_vecm.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library(tidyverse)
library(plotly)
library(ggpubr)
# tidyverts core
library(tsibble)
library(fable)
library(feasts)
# tidyverts improvements tools
library(tsibbletalk)
library(fable.prophet)
library(fabletools)
# Multivariáveis
library(vars)
library(tsDyn)
load("workspace.RData")
graphics.off() # clear all graphs
rm(list = ls()) # remove all files from your workspace
# DIÁRIO: ___ 00 de aaa ________________________________________________________
# ______________________________________________________________________________
# 1) Tratamento da Base =============================================
dds <- read_csv("dds.csv")
dds |> glimpse()
dds <- dds |> filter(!is.na(petro))
dds$cambio <- dds$cambio |>
str_replace(pattern = ",", replacement = ".") |>
as.numeric()
dds$dt <- seq(from = lubridate::ym('1990 Jan'),
to = lubridate::ym('2022 Jul'), # alternativa: length=
by = "month")
dds <- dds |> mutate("ptr_br_log" = log(cambio) + log(petro),
"ipca_log" = log(ipca),
"petro_log" = log(petro),
"cambio_log" = log(cambio),
"petro_brent_log" = log(petro_brent),
"petro_dubai_log" = log(petro_dubai),
"petro_texas_log" = log(petro_texas))
dds |> glimpse()
dds |> View()
dds <- dds |> filter(dt >= lubridate::ym("1994 Jul"))
dd <- dds |>
dplyr::select(dt, ptr_br_log, ipca_log, cambio_log, petro_log) |>
dplyr::mutate(dt = tsibble::yearmonth(as.character(dt))) |>
as_tsibble(index = dt)
dd |> interval()
# 2) Visualizações ==================================================
ggplotly(dd |>
ggplot() +
geom_line(aes(x=dt, y=ipca_log),
color='seagreen4') +
geom_line(aes(x=dt, y=ptr_br_log),
color='deepskyblue3') +
ylab('Logaritmo') +
xlab('Tempo')+
ggtitle("Logaritmo do Índice do IPCA e do Preço Internacional do Petróleo em Reais."))
plt_cambio <- plot_ly(dds,type = 'scatter', mode = 'lines') |>
add_trace(x = ~dt, y = ~cambio,
name = "Câmbio",
line = list(color = "#30d5c8", width = 2)) |>
layout(showlegend = F,
title='Taxa de Câmbio - R$/US$ - Comercial - Compra - Média - R$ ',
xaxis = list(rangeslider = list(visible = T),
title = "Data",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "R$/US$",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
plt_cambio
plt_ipca <- plot_ly(dds,type = 'scatter', mode = 'lines') |>
add_trace(x = ~dt, y = ~ipca,
name = "IPCA",
line = list(color = "#551a8b", width = 2)) |>
layout(showlegend = F,
title='índice de Preços ao Consumidor Amplo - IPCA, Brasil, de Jan/90 a Jul/2022.',
xaxis = list(rangeslider = list(visible = T),
title = "Data",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Índice",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
plt_ipca
plt_petro <- plot_ly(dds,type = 'scatter', mode = 'lines') |>
add_trace(x = ~dt, y = ~petro,
name = "Petroleum",
line = list(color = "#2E8B57", width = 2)) |>
layout(showlegend = F,
title='Média do Preço Internacional do Petróleo',
xaxis = list(rangeslider = list(visible = T),
title = "Data",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Preço em Dólar",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
plt_petro
plt_petro_n <- plot_ly(dds,type = 'scatter', mode = 'lines') |>
add_trace(x = ~dt, y = ~petro*cambio,
name = "Petroleum (R$)",
line = list(color = "#073320", width = 2)) |>
layout(showlegend = F,
title='Média do Preço Internacional do Petróleo, em Reais',
xaxis = list(rangeslider = list(visible = T),
title = "Data",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Preço em Reais",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
plt_petro_n
plt2 <- plot_ly(dd,type = 'scatter', mode = 'lines') |>
add_trace(x = ~dt, y = ~ipca_log,
name = "Log(IPCA)",
line = list(color = "#2E8B57", width = 2)) |>
add_trace(x = ~dt, y = ~ptr_br_log,
name = "Log(Petro)",
line = list(color = "#009acd", width = 2)) |>
layout(showlegend = T,
title='IPCA e do Preço Internacional do Petróleo em Reais.',
xaxis = list(rangeslider = list(visible = T),
title = "Data",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Índices Log",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
plt2
# 3) Tendências e Raíz Unitária =====================================
dd |> gg_subseries(ptr_br_log) |> plotly_build()
dd |>
dplyr::select(ptr_br_log, dt) |>
model(classical_decomposition(
ptr_br_log,
type = "multiplicative")) |>
components() |>
autoplot() |>
plotly_build() |>
layout(title = htmltools::HTML("Decomposição Multiplicativa Clássica:\npetro_br_log = trend * seasonal * randon"))
dd |> feasts::ACF(ptr_br_log, lag_max = 36) |> autoplot()
dd |> feasts::ACF(ipca_log, lag_max = 36) |> autoplot()
# KPSS unit root test H0: is trend-stationary (is stationary around a deterministic trend) or series has no unit root, I(0).
# "in the KPSS test, the absence of a unit root is not a proof of stationarity but, by design, of trend-stationarity. This is an important distinction since it is possible for a time series to be non-stationary, have no unit root yet be trend-stationary"
# types specify as deterministic component either a constant "mu" or a constant with linear trend "tau".
# PP test H0: ϕ=1 or I(1). H1: ϕ < 1
dd |> features( ptr_br_log, c(unitroot_kpss, unitroot_pp))
# KPSS: há raíz unitária. PP: estacionário
dd |> features( ipca_log, c(unitroot_kpss, unitroot_pp))
# KPSS: há raíz unitária. PP: raíz unitária
dd |> features( petro_log, c(unitroot_kpss, unitroot_pp))
# KPSS: há raíz unitária. PP: estacionário
dd |> features( cambio_log, c(unitroot_kpss, unitroot_pp))
# KPSS: há raíz unitária. PP: estacionário
dd <- dd |>
dplyr::mutate(
ptr_br_log_dif = difference(ptr_br_log, lag = 1),
ipca_log_dif = difference(ipca_log, lag = 1),
petro_log_dif = difference(petro_log, lag = 1),
cambio_log_dif = difference(cambio_log, lag = 1),
ptr_br_log_dif12 = difference(ptr_br_log, lag = 12),
ipca_log_dif12 = difference(ipca_log, lag = 12),
petro_log_dif12 = difference(petro_log, lag = 12),
cambio_log_dif12 = difference(cambio_log, lag = 12)) |>
dplyr::filter(!is.na(petro_log_dif12))
dd |> features(ptr_br_log_dif, c(unitroot_kpss, unitroot_pp))
dd |> features(ipca_log_dif, c(unitroot_kpss, unitroot_pp))
dd |> features(petro_log_dif, c(unitroot_kpss, unitroot_pp))
dd |> features(cambio_log_dif, c(unitroot_kpss, unitroot_pp))
dd |> features(ptr_br_log_dif12, c(unitroot_kpss, unitroot_pp))
dd |> features(ipca_log_dif12, c(unitroot_kpss, unitroot_pp))
dd |> features(petro_log_dif12, c(unitroot_kpss, unitroot_pp))
dd |> features(cambio_log_dif12, c(unitroot_kpss, unitroot_pp))
# Novamente, exceto em petro_log_dif, os testes estão "contradizendo-se",
# uma possível explicação é que:
# "Reject unit root, reject stationarity: both hypotheses are component hypotheses – heteroskedasticity in a series may make a bigs difference; if there is structural break it will affect inference." (https://stats.stackexchange.com/questions/30569/what-is-the-difference-between-a-stationary-test-and-a-unit-root-test)
# Portanto, vamos ver os gráficos:
attach(dd)
for (i in c("ptr_br_log_dif","ipca_log_dif","petro_log_dif","cambio_log_dif")) {
plot.default( x=as.Date(dt), y=get(i),ylab=i, type="l")
}
# Vamos retirar de julho de 99 pra baixo, quando o Brasil adotou o regime flutuante para o câmbio:
dd <- dd |> filter(dt >= lubridate::my("Jul 1999"))
attach(dd)
# Realizando novamente os testes KPSS e PP acima, temos que aceitar e rejeitar H0, respectivamente. Ou seja, ambos apontam estacionariedade.
ggarrange(
dd |> feasts::ACF(ptr_br_log_dif, lag_max = 36) |> ggplot2::autoplot(),
dd |> feasts::PACF(ptr_br_log_dif, lag_max = 36) |> ggplot2::autoplot()
#,labels = "F.A.'s de Dif( Log( Preço do Petro em Reais ))"
)
ggarrange(
dd |> feasts::ACF(ipca_log_dif, lag_max = 36) |> autoplot(),
dd |> feasts::PACF(ipca_log_dif, lag_max = 36) |> autoplot()
#,labels = "F.A.'s de Dif( Log( IPCA ))"
) # Maior influnência do passado na contemporânea
ggarrange(
dd |> feasts::ACF(petro_log_dif, lag_max = 36) |> autoplot(),
dd |> feasts::PACF(petro_log_dif, lag_max = 36) |> autoplot()
#,labels = "F.A.'s de Dif( Log( Preço do Petro ))"
)
ggarrange(
dd |> feasts::ACF(cambio_log_dif, lag_max = 36) |> autoplot(),
dd |> feasts::PACF(cambio_log_dif, lag_max = 36) |> autoplot()
#,labels = "F.A.'s de Dif( Log( R$/US$ ))"
)
# Os FAC e FACP de dif_12 mostram alta persistência dos erros e significância de vários lags múltiplos de 6. É horrível diferenciar em 12.
# 4) VAR p selection and Model ======================================
var1_p_select <- VARselect(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, petro_log_dif, cambio_log_dif),
lag.max = 12,
season = 12,
type = "both")
var1_p_select$selection
var2_p_select <- VARselect(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, ptr_br_log_dif),
lag.max = 12,
season = 12,
type = "both")
var2_p_select$selection
var1 <- VAR(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, cambio_log_dif, petro_log_dif),
p = 1,
type = "both",
season = NULL,
exog = NULL)
var11 <- VAR(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, cambio_log_dif, petro_log_dif),
p = 4,
type = "both",
season = NULL,
exog = NULL)
var111 <- VAR(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, cambio_log_dif, petro_log_dif),
p = 1,
type = "both",
season = 12L,
exog = NULL)
var2 <- VAR(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, ptr_br_log_dif),
p = 1,
type = "both",
season = NULL,
exog = NULL)
var22 <- VAR(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, ptr_br_log_dif),
p = 4,
type = "both",
season = NULL,
exog = NULL)
summary(var1)
summary(var11)
summary(var111)
summary(var2)
summary(var22)
# Há diferenças significativas entre var1 e var2, com "season = 12L". Principalmente para a eq do IPCA, da dummie 4 a 8.
# p=4 parece não ser parcimonioso pelas significâncias dos coefs, mas produz um R^2 ajust melhor (maior) que em p=1.
# Foi testado tbm com p=2, nenhum lag 2 é significativo.
# De const e trend, somente const de ipca foi significativo
# Vamos refazer var1 com const e var2 com o par ipca e ptr_br:
var1 <- vars::VAR(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, cambio_log_dif, petro_log_dif),
p = 1,
type = "const",
season = NULL,
exog = NULL)
var2 <- vars::VAR(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log_dif, ptr_br_log_dif),
p = 1,
type = "const",
season = NULL,
exog = NULL)
realz_fit <- dplyr::tibble(
dd |> dplyr::as_tibble() |> dplyr::select(dt),
var1[["y"]] |> as.data.frame(),
var2$y |> as.data.frame() |> dplyr::select(ptr_br_log_dif),
"v1_fitted_ipca" = c(NA, var1$varresult$ipca_log_dif$fitted.values),
"v1_fitted_cambio" = c(NA, var1$varresult$cambio_log_dif$fitted.values),
"v1_fitted_petro" = c(NA, var1$varresult$petro_log_dif$fitted.values),
"v2_fitted_ipca"= c(NA,var2$varresult$ipca_log_dif$fitted.values),
"v2_fitted_ptr"= c(NA,var2$varresult$ptr_br_log_dif$fitted.values) ) |>
dplyr::filter(!is.na(v2_fitted_ptr))
cor(realz_fit$ipca_log_dif, realz_fit$v1_fitted_ipca)
cor(realz_fit$ipca_log_dif, realz_fit$v2_fitted_ipca)
resids <- dplyr::tibble(
dd |> dplyr::as_tibble() |> dplyr::select(dt) |> tail(-1),
"v1_ipca" = var1[["varresult"]][["ipca_log_dif"]][["residuals"]],
"v1_cambio" = var1[["varresult"]][["cambio_log_dif"]][["residuals"]],
"v1_petro" = var1[["varresult"]][["petro_log_dif"]][["residuals"]],
"v2_ipca" = var2[["varresult"]][["ipca_log_dif"]][["residuals"]],
"v2_ptr" = var2[["varresult"]][["ptr_br_log_dif"]][["residuals"]]
)
dplyr::tibble(realz_fit$ipca_log_dif - realz_fit$v1_fitted_ipca,
c(NA,resids$v1_ipca))
# portanto, as datas e os NA's colocados em fitted estão certos!
summary(var1)
summary(var1, equation="ipca_log_dif")
Acoef(var1)
summary(var2)
summary(var2, equation="ipca_log_dif")
# 5) Diagnóstico dos Resíduos do VAR ===============================
# 5.1.1) Autocorrelação: Breusch-Godfrey?
# H0: os coeficientes do lag do erro sao insignificantes.
test_autocorr_var1 <- serial.test(
var1,
lags.pt = 12, type = "BG")
test_autocorr_var1
# p-valor: 0.04735, i.e., há autocorrelação dos erros.
test_autocorr_var2 <- serial.test(
var2,
lags.pt = 12, type = "BG")
test_autocorr_var2
# p-valor: 0.1228, i.e., os coeficientes do lag do erro sao insignificantes.
# 5.1.2) Autocorrelação: Ljung-Box
# LB: null hypothesis of independence in a given time series.
resids$v1_ipca |> ljung_box(lag = 12)
resids$v1_cambio |> ljung_box(lag = 12)
resids$v1_petro |> ljung_box(lag = 12)
resids$v2_ipca |> ljung_box(lag = 12)
resids$v2_ptr |> ljung_box(lag = 12)
# 5.1.3) Autocorrelação: FAC e FACP nos Resíduos
ggarrange(
ACF(resids |>
dplyr::select(dt, v1_ipca) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
,PACF(resids |>
dplyr::select(dt, v1_ipca) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
)
ggarrange(
ACF(resids |>
dplyr::select(dt, v1_cambio) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
,PACF(resids |>
dplyr::select(dt, v1_cambio) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
)
ggarrange(
ACF(resids |>
dplyr::select(dt, v1_petro) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
,PACF(resids |>
dplyr::select(dt, v1_petro) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
)
ggarrange(
ACF(resids |>
dplyr::select(dt, v2_ipca) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
,PACF(resids |>
dplyr::select(dt, v2_ipca) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
)
ggarrange(
ACF(resids |>
dplyr::select(dt, v2_ptr) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
,PACF(resids |>
dplyr::select(dt, v2_ptr) |>
as_tsibble(),
lag_max = 36) |>
autoplot()
)
# 5.2) Heterocedasticidade: ARCH Multiplicador de Lagrange
# H0: coeficients of the past vech() dont explain the actual vech()
test_var1_arch <- arch.test(var1,
lags.multi = 12,
multivariate.only = TRUE)
test_var1_arch
# p-value = 1.368e-08: Não há heterocedasticidade nos resíduos.
test_var2_arch <-
arch.test(var2, lags.multi = 12, multivariate.only = TRUE)
test_var2_arch
# p-value = 0.001181: Não há heterocedasticidade nos resíduos.
# 5.3) Normalidade: Teste de JB
# H0: aproxima-se de uma normal em assimetria e curtose
test_var1_norm <-
normality.test(var1,multivariate.only = TRUE)
test_var1_norm
# rejeita H0 de normalidade
test_var2_norm <-
normality.test(var2,multivariate.only = TRUE)
test_var2_norm
# rejeita H0 de normalidade
# 5.4) Quebra Estrutural: Teste CUSUM
test_var1_cusum <- stability(var1, type = "OLS-CUSUM")
test_var1_cusum |> plot()
test_var2_cusum <- stability(var2, type = "OLS-CUSUM")
test_var2_cusum |> plot()
ggplot(resids) +
stat_qq(aes(sample=v1_ipca), color="steelblue")
ggplot(resids) +
stat_qq(aes(sample=v1_cambio), color="seagreen")
ggplot(resids) +
stat_qq(aes(sample=v1_petro), color="tomato")
# 6) VAR Estrutural =================================================
# 6.1) Análise Impulso-Resposta
# 6.2) Decomposição da Variância
# 6.3) Causalidade de Granger
# 7) Teste de Cointegração de Johansen ==============================
johansen_var1_trc <- ca.jo(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log, cambio_log, petro_log),
type = "trace",
ecdet = "const",
K = 2,
spec = "transitory",
season = 12,
dumvar = NULL
)
johansen_var1_max <- ca.jo(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log, cambio_log, petro_log),
type = "eigen",
ecdet = "const",
K = 2,
spec = "transitory",
season = 12,
dumvar = NULL
)
johansen_var1_trc |> summary()
johansen_var1_max |> summary()
# por ambos os testes, a estatística 6.86 indica que H0: r <= 1 pode ser aceita,
# mas a estatística de H0: r = 0 não pode ser aceita.
# Ou seja, há pelo menos 1 vetor de cointegração independente.
johansen_var2_trc <- ca.jo(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log, ptr_br_log),
type = "trace",
ecdet = "none",
K = 2,
spec = "transitory",
season = 12,
dumvar = NULL
)
johansen_var2_max <- ca.jo(
dd |> dplyr::as_tibble() |>
dplyr::select(ipca_log, ptr_br_log),
type = "eigen",
ecdet = "none",
K = 2,
spec = "transitory",
season = 12,
dumvar = NULL
)
johansen_var2_trc |> summary()
johansen_var2_max |> summary()
# Johansen test model 2 with trend, const and none.
# const: not cointegrated
# trend: r=0
# none: r=1
# 8) VECM ===========================================================
vecm1 <- tsDyn::VECM(
dd |> dplyr::as_tibble() |> dplyr::select(ipca_log, cambio_log,petro_log),
lag = 1,
r=1,
include = "const",
estim = "2OLS",
LRinclude = "none"
)
vecm2 <- tsDyn::VECM(
dd |> dplyr::as_tibble() |> dplyr::select(ipca_log, cambio_log,petro_log),
lag = 1,
r=1,
include = "const",
estim = "ML",
LRinclude = "none"
)
vecm3 <- tsDyn::VECM(
dd |> dplyr::as_tibble() |> dplyr::select(ipca_log, cambio_log,petro_log),
lag = 1,
r=1,
include = "none",
estim = "2OLS",
LRinclude = "none"
)
vecm3 |> tsDyn::plot_ECT()
#vecm3 |> toLatex()
vecm3 |> residuals()
vecm3 |> vcov()
vecm4 <- tsDyn::VECM(
dd |> dplyr::as_tibble() |> dplyr::select(ipca_log, cambio_log,petro_log),
lag = 1,
r=1,
include = "both",
estim = "2OLS",
LRinclude = "none"
)
vecm5 <- tsDyn::VECM(
dd |> dplyr::as_tibble() |> dplyr::select(ipca_log, cambio_log,petro_log),
lag = 1,
r=1,
include = "none",
estim = "2OLS",
LRinclude = "both"
)
vecm1 |> summary()
vecm2 |> summary()
vecm3 |> summary()
vecm3 |> summary(equation="ipca_log")
vecm4 |> summary()
vecm5 |> summary()
# Error Correction Term
ect_vecm3 <- dplyr::tibble(
dd |> dplyr::as_tibble() |> dplyr::select(dt),
"ect" = vecm3[["model"]][["ECT"]]
)
plt_ECT_vecm3 <- plot_ly(ect_vecm3,
type = 'scatter', mode = 'lines') |>
add_trace(x = ~as.Date(dt), y = ~ect,
name = "Error Correction Term",
line = list(color = "#551a8b", width = 2)) |>
layout(showlegend = T,
title='Termo de Ajuste do Curto-prazo em VECM3',
xaxis = list(rangeslider = list(visible = T),
title = "Data",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Dif Log",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
plt_ECT_vecm3
ect_vecm3 |> as_tsibble() |>
model(classical_decomposition(
ect,
type = "multiplicative")) |>
components() |>
autoplot() |>
plotly_build() |>
layout(title = htmltools::HTML("Decomposição Multiplicativa Clássica:\nECT = trend * seasonal * randon"))
# Comparing IPCA
realz_fit_vecm3 <- dplyr::tibble(
dd |> dplyr::as_tibble() |> dplyr::select(dt),
"realiz_ipca" = vecm3[["model"]] |>
dplyr::as_tibble() |> pull(`ipca_log -1`),
"fit_ipca" = c(0,0,0,vecm3[["fitted.values"]] |>
dplyr::as_tibble() |> pull(ipca_log))
)
plt_ipca_vecm3 <- plot_ly(realz_fit_vecm3,
type = 'scatter', mode = 'lines') |>
add_trace(x = ~as.Date(dt), y = ~realiz_ipca,
name = "IPCA",
line = list(color = "#551a8b", width = 2)) |>
add_trace(x = ~as.Date(dt), y = ~fit_ipca,
name = "Fitted",
line = list(color = "#0e0417", width = 2, dash = 'dot')) |>
layout(showlegend = T,
title='Dif(Log(IPCA)) Realizado e Estimado em VECM3',
xaxis = list(rangeslider = list(visible = T),
title = "Data",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Dif Log IPCA",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
plt_ipca_vecm3
# 9) Formas Estruturais =================================================
# Matriz de coeficientes estimados. para modelos -A ou -AB do VAR
A_var <- matrix(NA, nrow=2, ncol=2)
A_var[2,1] <- 0
A_var
# Matriz de impacto de longo prazo estimada do VECM.
LR_vecm <- matrix(NA, nrow=3, ncol=3)
LR_vecm[3,1:2] <- 0
LR_vecm[2,1] <- 0
LR_vecm
# Matriz de impacto contemporâneo estimado do VECM.
SR_vecm <- matrix(NA, nrow=3, ncol=3)
SR_vecm
svar <- SVAR(var2, Amat=A_var, estmethod="direct", lrtest=F)
svec <- SVEC(johansen_var1_max,
LR = LR_vecm, SR = SR_vecm, r = 1,
lrtest=F, boot=TRUE,runs=1000)
svar |> summary()
svec |> summary()
# 10) Função Impulso-resposta ===========================================
ir_svar <- irf(svar, response = "ipca_log_dif", n.ahead = 12, boot = TRUE)
ir_svar |> plot()
ir_dd_svar <- tibble(
"ir_ipca_u_log_dif" = ir_svar[["Upper"]][["ipca_log_dif"]][,1],
"ir_ipca_log_dif" = ir_svar[["irf"]][["ipca_log_dif"]][,1],
"ir_ipca_l_log_dif" = ir_svar[["Lower"]][["ipca_log_dif"]][,1],
"ir_ptr_u_log_dif" = ir_svar[["Upper"]][["ptr_br_log_dif"]][,1],
"ir_ptr_log_dif" = ir_svar[["irf"]][["ptr_br_log_dif"]][,1],
"ir_ptr_l_log_dif" = ir_svar[["Lower"]][["ptr_br_log_dif"]][,1]
)
ir_svar_plt1 <- plot_ly(ir_dd_svar, type = 'scatter', mode = 'lines') |>
add_trace(x = ~1:13, y = ~ir_ipca_u_log_dif,
name = "IC Sup",
showlegend = FALSE,
line = list(color = 'transparent')) |>
add_trace(x = ~1:13, y = ~ir_ipca_l_log_dif,
name = "IC Inf",
showlegend = FALSE,
fill = 'tonexty', fillcolor='rgba(0,100,80,0.2)',
line = list(color = 'transparent')) |>
add_trace(x = ~1:13, y = ~ir_ipca_log_dif,
name = "IR-IPCA",
showlegend = FALSE,
line = list(color='rgb(0,100,80)')) |>
layout(title='SVAR Impulso-resposta de IPCA no IPCA',
xaxis = list(#rangeslider = list(visible = T),
title = "Meses",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Impacto em Dif(Log(IPCA))",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
ir_svar_plt1
ir_svar_plt2 <- plot_ly(ir_dd_svar, type = 'scatter', mode = 'lines') |>
add_trace(x = ~1:13, y = ~ir_ptr_u_log_dif,
name = "IC Sup",
showlegend = FALSE,
line = list(color = 'transparent')) |>
add_trace(x = ~1:13, y = ~ir_ptr_l_log_dif,
name = "IC Inf",
showlegend = FALSE,
fill = 'tonexty', fillcolor='rgba(0,100,80,0.2)',
line = list(color = 'transparent')) |>
add_trace(x = ~1:13, y = ~ir_ptr_log_dif,
name = "IR-IPCA",
showlegend = FALSE,
line = list(color='rgb(0,100,80)')) |>
layout(title='SVAR Impulso-resposta de R$ Preto no IPCA',
xaxis = list(#rangeslider = list(visible = T),
title = "Meses",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Impacto em Dif(Log(IPCA))",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
ir_svar_plt2
ir_svec <- irf(svec, response = "ipca_log", n.ahead = 36, boot = TRUE)
ir_svec |> plot()
ir_dd_svec <- tibble(
"ir_ipca_u_log" = ir_svec[["Upper"]][["ipca_log"]][,1],
"ir_ipca_log" = ir_svec[["irf"]][["ipca_log"]][,1],
"ir_ipca_l_log" = ir_svec[["Lower"]][["ipca_log"]][,1],
"ir_petro_u_log" = ir_svec[["Upper"]][["petro_log"]][,1],
"ir_petro_log" = ir_svec[["irf"]][["petro_log"]][,1],
"ir_petro_l_log" = ir_svec[["Lower"]][["petro_log"]][,1],
"ir_cambio_u_log" = ir_svec[["Upper"]][["cambio_log"]][,1],
"ir_cambio_log" = ir_svec[["irf"]][["cambio_log"]][,1],
"ir_cambio_l_log" = ir_svec[["Lower"]][["cambio_log"]][,1]
)
ir_svec_plt1 <- plot_ly(ir_dd_svec, type = 'scatter', mode = 'lines') |>
add_trace(x = ~1:37, y = ~ir_ipca_u_log,
name = "IC Sup",
showlegend = FALSE,
line = list(color = 'transparent')) |>
add_trace(x = ~1:37, y = ~ir_ipca_l_log,
name = "IC Inf",
showlegend = FALSE,
fill = 'tonexty', fillcolor='rgba(0, 104, 201,0.2)',
line = list(color = 'transparent')) |>
add_trace(x = ~1:37, y = ~ir_ipca_log,
name = "IR-IPCA",
showlegend = FALSE,
line = list(color='rgb(0, 104, 201)')) |>
layout(title='SVEC Impulso-resposta de IPCA no IPCA',
xaxis = list(#rangeslider = list(visible = T),
title = "Meses",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Impacto em Dif(Log(IPCA))",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
ir_svec_plt1
ir_svec_plt2 <- plot_ly(ir_dd_svec, type = 'scatter', mode = 'lines') |>
add_trace(x = ~1:37, y = ~ir_cambio_u_log,
name = "IC Sup",
showlegend = FALSE,
line = list(color = 'transparent')) |>
add_trace(x = ~1:37, y = ~ir_cambio_l_log,
name = "IC Inf",
showlegend = FALSE,
fill = 'tonexty', fillcolor='rgba(0, 104, 201,0.2)',
line = list(color = 'transparent')) |>
add_trace(x = ~1:37, y = ~ir_cambio_log,
name = "IR-Câmbio",
showlegend = FALSE,
line = list(color='rgb(0, 104, 201)')) |>
layout(title='SVEC Impulso-resposta de Câmbio no IPCA',
xaxis = list(#rangeslider = list(visible = T),
title = "Meses",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Impacto em Dif(Log(IPCA))",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
ir_svec_plt2
ir_svec_plt3 <- plot_ly(ir_dd_svec, type = 'scatter', mode = 'lines') |>
add_trace(x = ~1:37, y = ~ir_petro_u_log,
name = "IC Sup",
showlegend = FALSE,
line = list(color = 'transparent')) |>
add_trace(x = ~1:37, y = ~ir_petro_l_log,
name = "IC Inf",
showlegend = FALSE,
fill = 'tonexty', fillcolor='rgba(0, 104, 201,0.2)',
line = list(color = 'transparent')) |>
add_trace(x = ~1:37, y = ~ir_petro_log,
name = "IR-Câmbio",
showlegend = FALSE,
line = list(color='rgb(0, 104, 201)')) |>
layout(title='SVEC Impulso-resposta de US$ Petro no IPCA',
xaxis = list(#rangeslider = list(visible = T),
title = "Meses",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(title = "Impacto em Dif(Log(IPCA))",
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
plot_bgcolor='#e5ecf6')
ir_svec_plt3
# 11) Decomposição da Variância =========================================
fevd_svar_ipca <- fevd(svar, n.ahead = 24)$ipca_log_dif
fevd_svar_ipca <- fevd_svar_ipca |>
dplyr::as_tibble() |> add_column("m" = 1:24)
fevd_svar_plt <- plot_ly(fevd_svar_ipca, type = "bar") |>
add_trace(x = ~m, y = ~ipca_log_dif, name="IPCA",
marker = list(color = '#009779')) |>
add_trace(x = ~m, y = ~ptr_br_log_dif, name="Petro",
marker = list(color = '#ca0028')) |>
layout(title = "Decomposição da Variância SVAR no IPCA",
barmode = 'stack',
xaxis = list(title = "Meses"),
yaxis = list(title = "Dif(Log( IPCA ))"))
fevd_svar_plt
fevd_svec_ipca <- fevd(svec, n.ahead = 24)$ipca_log
fevd_svec_ipca <- fevd_svec_ipca |>
dplyr::as_tibble() |> add_column("m" = 1:24)
fevd_svec_plt <- plot_ly(fevd_svec_ipca, type = "bar") |>
add_trace(x = ~m, y = ~ipca_log, name="IPCA",
marker = list(color = '#009ac9')) |>
add_trace(x = ~m, y = ~cambio_log, name="Câmbio",
marker = list(color = '#00c950')) |>
add_trace(x = ~m, y = ~petro_log, name="Petro",
marker = list(color = '#ff922c')) |>
layout(title = "Decomposição da Variância SVEC no IPCA",
barmode = 'stack',
xaxis = list(title = "Meses"),
yaxis = list(title = "Dif(Log( IPCA ))"))
fevd_svec_plt
# 12) Decomposição Histórica ============================================
# carregar a função de Daniel Ryback (https://stackoverflow.com/questions/36950491/historical-decomposition-in-r)
VARmakexy <- function(DATA,lags,c_case){
nobs <- nrow(DATA)
#Y matrix
Y <- DATA[(lags+1):nrow(DATA),]
Y <- DATA[-c(1:lags),]
#X-matrix
if (c_case==0){
X <- NA
for (jj in 0:(lags-1)){
X <- rbind(DATA[(jj+1):(nobs-lags+jj),])
}
} else if(c_case==1){ #constant
X <- NA
for (jj in 0:(lags-1)){
X <- rbind(DATA[(jj+1):(nobs-lags+jj),])
}
X <- cbind(matrix(1,(nobs-lags),1), X)
} else if(c_case==2){ # time trend and constant
X <- NA
for (jj in 0:(lags-1)){
X <- rbind(DATA[(jj+1):(nobs-lags+jj),])
}
trend <- c(1:nrow(X))
X <-cbind(matrix(1,(nobs-lags),1), t(trend))
}
A <- (t(X) %*% as.matrix(X))
B <- (as.matrix(t(X)) %*% as.matrix(Y))
Ft <- ginv(A) %*% B
retu <- list(X=X,Y=Y, Ft=Ft)
return(retu)
}
companionmatrix <- function (x)
{
if (!(class(x) == "varest")) {
stop("\nPlease provide an object of class 'varest', generated by 'VAR()'.\n")
}
K <- x$K
p <- x$p
A <- unlist(Acoef(x))
companion <- matrix(0, nrow = K * p, ncol = K * p)
companion[1:K, 1:(K * p)] <- A
if (p > 1) {
j <- 0
for (i in (K + 1):(K * p)) {
j <- j + 1
companion[i, j] <- 1
}
}
return(companion)
}
VARhd <- function(Estimation){
## make X and Y
nlag <- Estimation$p # number of lags
DATA <- Estimation$y # data
QQ <- VARmakexy(DATA,nlag,1)
## Retrieve and initialize variables
invA <- t(chol(as.matrix(summary(Estimation)$covres))) # inverse of the A matrix
Fcomp <- companionmatrix(Estimation) # Companion matrix
#det <- c_case # constant and/or trends
F1 <- t(QQ$Ft) # make comparable to notes
eps <- ginv(invA) %*% t(residuals(Estimation)) # structural errors
nvar <- Estimation$K # number of endogenous variables