forked from englianhu/binary.com-interview-question
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-Q1Multi-GARCH.Rmd
3819 lines (3110 loc) · 151 KB
/
binary-Q1Multi-GARCH.Rmd
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
---
title: "<img src='www/binary-logo-resize.jpg' width='240'>"
subtitle: "[binary.com](https://github.com/englianhu/binary.com-interview-question) Interview Question I - Multivariate GARCH Models"
author: "[®γσ, Lian Hu](https://englianhu.github.io/) <img src='www/RYO.jpg' width='24'> <img src='www/RYU.jpg' width='24'> <img src='www/ENG.jpg' width='24'>®"
date: "`r lubridate::today('Asia/Tokyo')`"
output:
html_document:
number_sections: yes
toc: yes
toc_depth: 4
toc_float:
collapsed: yes
smooth_scroll: yes
code_folding: hide
---
```{r setup}
suppressPackageStartupMessages(library('BBmisc'))
#'@ suppressPackageStartupMessages(library('rmsfuns'))
pkgs <- c('knitr', 'kableExtra', 'devtools', 'lubridate', 'data.table', 'quantmod', 'qrmtools', 'tidyquant', 'plyr', 'stringr', 'magrittr', 'dplyr', 'tidyverse', 'memoise', 'highcharter', 'formattable', 'DT', 'rugarch', 'ccgarch', 'mgarchBEKK', 'rmgarch')
suppressAll(lib(pkgs))
#'@ load_pkg(pkgs)
funs <- c('calc_fx.R', 'opt_arma.R', 'filterFX.R', 'filter_spec.R', 'mv_fx.R', 'read_umodels.R')
l_ply(funs, function(x) source(paste0('./function/', x)))
options(warn=-1)#, 'scipen'=100, 'digits'=4)
rm(pkgs)
```
# Introduction
From previous papers, I tried to apply few models for FOREX price forecasting and eventually got to know <span style='color:red'>Fractional Intergrated GJR-GARCH</span> is the best fit model as we can refer to <span style='color:goldenrod'>*GARCH模型中的ARIMA(p,d,q)参数最优化*</span>. **The standalone ARFIMAX model and methods** in the [A short introduction to the rugarch package](http://www.unstarched.net/r-examples/rugarch/a-short-introduction-to-the-rugarch-package/) describe the `autoarfima()` function where we can easily get the optimal MA and AR figure.
Today I am zooming into the multivariate GARCH models.
# Data
## Read Data
Similar with <span style='color:goldenrod'>*GARCH模型中的ARIMA(p,d,q)参数最优化*</span>, I use the dataset from [Binary-Q1 (Extention)](http://rpubs.com/englianhu/binary-Q1E).
```{r read-data, warning=FALSE}
cr_code <- c('AUDUSD=X', 'EURUSD=X', 'GBPUSD=X', 'CHF=X', 'CAD=X',
'CNY=X', 'JPY=X')
#'@ names(cr_code) <- c('AUDUSD', 'EURUSD', 'GBPUSD', 'USDCHF', 'USDCAD',
#'@ 'USDCNY', 'USDJPY')
names(cr_code) <- c('USDAUD', 'USDEUR', 'USDGBP', 'USDCHF', 'USDCAD', 'USDCNY', 'USDJPY')
## Read presaved Yahoo data.
mbase <- sapply(names(cr_code), function(x) readRDS(paste0('./data/', x, '.rds')) %>% na.omit)
.price_types <- c('OHLC', 'HLC', 'HL', 'C')
## all currencies trading day.
timeID <- llply(mbase, function(x) as.character(index(x))) %>%
unlist
timeID %<>% plyr::count()
#timeID %>% dplyr::count(freq)
## A tibble: 4 x 2
# freq n
# <int> <int>
#1 1 1
#2 3 1
#3 6 3
#4 7 1472
timeID %<>% dplyr::filter(freq == 7) %>% .$x %>% unique %>% as.Date %>% sort
timeID <- c(timeID, xts::last(timeID) + days(1)) #the last date + 1 in order to predict the next day of last date to make whole dataset completed.
timeID0 <- ymd('2013-01-01')
timeID %<>% .[. >= timeID0]
.cl = TRUE
```
# Modelling
## Introduce Multivariate Garch Models
Multivariate GARCH models including DCC, GO-GARCH and Copula-GARCH, CCC and BEKK. Paper <span style='color:goldenrod'>*Comparison of Multivariate GARCH Models with Application to Zero-Coupon Bond Volatility*</span> compares DCC and BEKK model on bond market with maturities of 6 months, 1 year and 2 years. The thesis concludes that the fitting performance of the BEKK is better than DCC in their case, the difference might due to the number of the parameters of BEKK model is comparatively more, so that the BEKK has a better capanility in explaning the information hidden in the hostory data. In opposite, the DCC model has an advantage over the BEKK model in the area of forecasting as the DCC model is more parsimonious than BEKK model. From my understanding means that if we compare with deviance or AIC/BIC the DCC will be more accurate. However, this paper will compare as well since forex market is not bond market.
[**R - Time Series** : Comandos R para análises de séries temporais](https://rpubs.com/EconFin/mgarch) is a website to introduce the multivariate GARCH models (in Portuguese language).
<span style='color:goldenrod'>*Currency Hedging Strategies Using Dynamic Multivariate GARCH*</span> compares DCC, BEKK, CCC and VARMA-AGARCH models to examine the conditional volatilities among the spot and two distint futures maturities, namely near-month and next-to-near-month contracts. The estimated conditionl covariances matrices from these models were used to calculate the optimal portfolios weights and optimal hedge ratios.^[Kindly refer to ] The empirical results in the paper reveal that there are not big differences either the near-month or next-to-near-month contract is used for hedge spot position on currencies. They also reveal that hedging ratios are lower for near-month contract when the USD/EUR and USD/JPY exchange rates are anlyzed. This result is explained in terms of the higher correlation between spot prices and the next-to-near-month future prices than that with near-month contract and additionally because of the lower volatility of the long maturity futures. Finally across all currencies and error densities, the CCC and VARMA-AGARCH models provide similar results in terms of hedging ratios, portfolio variance reduction and hedging effectiveness. Some difference might appear when the DCC and BEKK models are used. Below is the table summary of the paper.
```{r, echo=FALSE}
dfm1 <- data_frame(
Model = c('CCC'),
Currency = c('EURS', 'GBPS', 'JPYS'),
AIC = c(2.738605, 2.247209, 2.827915))
dfm2 <- data_frame(
Model = c('VARMA-AGARCH'),
Currency = c('EURS', 'GBPS', 'JPYS'),
AIC = c(2.734926, 2.241061, 2.828964))
dfm3 <- data_frame(
Model = c('DCC'),
Currency = c('EURS', 'GBPS', 'JPYS'),
AIC = c(2.721337, 2.205663, 2.784974))
dfm4 <- data_frame(
Model = c('BEKK'),
Currency = c('EURS', 'GBPS', 'JPYS'),
AIC = c(2.735964, 2.212324, 2.788730))
dfm <- list(dfm1, dfm2, dfm3, dfm4) %>%
bind_rows %>%
mutate_if(is.character, as.factor) %>%
arrange(Currency)
rm(dfm1, dfm2, dfm3, dfm4)
dfm %>%
kable(caption = 'Comparison Summary') %>%
kable_styling(bootstrap_options = c('striped', 'hover', 'condensed', 'responsive')) %>%
group_rows('EURS', 1, 4, label_row_css = 'background-color: #003399; color: #fff;') %>%
group_rows('GBPS', 5, 8, label_row_css = 'background-color: #003399; color: #fff;') %>%
group_rows('JPYS', 9, 12, label_row_css = 'background-color: #003399; color: #fff;') %>%
scroll_box(width = '100%', height = '400px')
```
*Table 3.1.1 : comparison of the models.*
Table above shows DCC model is the best fit model.
<span style='color:goldenrod'>*Do We Really Need Both BEKK and DCC - A Tale of Two Multivariate GARCH Models*</span> compares few models and final model should be based on model performance within the appropriate framework in which they are used (such as covariance, correlation forecasting, risk monitoringm or portfolio allocation, to cite the most relevant), the paper concludes that the cDCC (constant DCC) model^[Similar with paper <span style='color:goldenrod'>*Aielli (2010)*</span> who suggest using cDCC model insted of the DCC model of <span style='color:goldenrod'>*Engle (2002)*</span>. Similar with papers <span style='color:goldenrod'>*Engle et al. (2008)*</span> and <span style='color:goldenrod'>*Engle Engle and Kelly (2009)*</span>.] and BEKK model.
<span style='color:goldenrod'>*Forecasting the Daily Dynamic Hedge Ratios by GARCH Models - Evidence from the Agricultural Futures Markets*</span> compares few models which are bivariate GARCH, BEKK GARCH, GARCH-X, BEKK-X, Q-GARCH and GARCH-GJR in agricultural futures markets. The paper reveals that the BEKK model dominates others models for storable wheat and soybean for both forecasting horizons, and the asymmetric GJR andQ-GARCH models does the best forecasting performance for the non-storable products, live cattle and live hogs.
<span style='color:goldenrod'>*Dynamic Portfolio Optimization using Generalized Dynamic Conditional Heteroskedastic Factor Models*</span> studies the portfolio selection problem based on a generalized dynamic factor model (GDFM) with conditional heteroskedasticity in the idiosyncratic components. We propose a Generalized Smooth Transition Conditional Correlation (GSTCC) model for the idiosyncratic components combined with the GDFM. Among all the multivariate GARCH models that the authors propose, the generalized smooth transition conditional correlation provides the best result.
![](www/ROI-DPO-03.jpg)
![](www/ROI-DPO-04.jpg)
I try to surf over internet and the model has no yet widely use. Here I can only use the CCC, DCC models but the best performance GSTCC is not yet available in r packages. The `cccgarch` has STCC model but there has no examples to use it. I roughly read over the `ccgarch` package and noticed that all parameters required in matrix format which is only suitable for advance user use.
<span style='color:goldenrod'>*Forecasting Conditional Correlation for Exchange Rates using Multivariate GARCH Models with Historical Value-at-Risk Application*</span> compares the VaR for trade in USDSEK in T+1 and T+10 with intraday 30 minutes time interval. When comparing the BEKK and DCC model, the BEKK seems to perform better than the DCC in both forecasting conditional correlation and predicting VaR. On the contrary, the BEKK is much more computationally demanding, which most certainly would be even more noticeable when the number of assets increase.
![](www/USDSEK-VaR01.jpg)
![](www/USDSEK-VaR02.jpg)
## Parameter Selection
```{r dcc1, echo=FALSE, eval=FALSE}
## ---------- eval = FALSE --------------------
### ========= using cluster for sampling ===============
fit <- llply(na.omit(Cl(mbase[['USDJPY']])), function(x){
armaOrder = opt_arma(x)
xspec = ugarchspec(
variance.model = list(
model = 'gjrGARCH', garchOrder = c(1, 1),
submodel = NULL, external.regressors = NULL,
variance.targeting = FALSE),
mean.model = list(
armaOrder = armaOrder[c(1, 3)],
include.mean = TRUE, archm = FALSE,
archpow = 1, arfima = TRUE,
external.regressors = NULL,
archex = FALSE),
fixed.pars = list(arfima = armaOrder[2]),
distribution.model = 'snorm')
uspec = multispec(replicate(4, xspec))
spec1 = dccspec(uspec = uspec, dccOrder = c(1, 1),
model='aDCC', distribution = 'mvt')
cl = makePSOCKcluster(4)
multf = multifit(uspec, x, cluster = cl)
fit1 = dccfit(spec1, data = x, solver = 'hybrid',
fit.control = list(eval.se = TRUE),
fit = multf, cluster = cl)
return(fit1)
})
```
My initially workable models result.
```{r wdcc-aic}
workable.dcc <- readRDS('data/fx/pt.dcc.rds')
#'@ dcc.AIC <- ldply(workable.dcc, function(x) {
#'@ ldply(x, function(y) {
#'@ list.select(y, AIC) %>%
#'@ data.frame %>% t %>% data.frame %>%
#'@ mutate(includes.Op = c(TRUE, FALSE))
#'@ }) %>% rename(.solver = .id)
#'@ }) %>%
#'@ dplyr::select(.id, .solver, includes.Op, Akaike, Bayes, Shibata, Hannan.Quinn)
dcc.AIC <- ldply(workable.dcc, function(x) {
zz <- ldply(x, function(y) {
zz <- ldply(y, function(z) {
z$AIC %>%
data.frame %>% t %>% data.frame
})
names(zz)[1] <- 'includes.Op'
zz
})
names(zz)[1] <- '.solver'
zz
})
dcc.AIC %>%
arrange(Akaike, Bayes) %>%
kable(caption = 'Akaike Information Criteria') %>%
kable_styling(bootstrap_options = c('striped', 'hover', 'condensed', 'responsive')) %>%
scroll_box(width = '100%', height = '400px')
```
*Table 3.2.1.1 : AIC comparison.*
From above table, `r unlist(dcc.AIC$Akaike) %>% .[which.min(.)] %>% names` with `r unlist(dcc.AIC$Akaike) %>% .[which.min(.)]` is the best fitted model.
```{r dcc-llh}
dcc.logLik <- ldply(workable.dcc, function(x) {
zz = ldply(x, function(y) {
zz = ldply(y, function(z) {
attributes(z$fit)$mfit$llh
})
names(zz) <- c('includes.Op', 'log.Likelihood')
zz
})
names(zz)[1] <- '.solver'
zz
})
dcc.logLik %>%
arrange(log.Likelihood) %>%
kable(caption = 'Log-Likelihood') %>%
kable_styling(bootstrap_options = c('striped', 'hover', 'condensed', 'responsive')) %>%
scroll_box(width = '100%', height = '400px')
```
*Table 3.2.1.2 : Log-Likelihood comparison.*
### Close Price
```{r bk-dcc, eval=FALSE}
## ------- eval ----------
## Possible multivariate models.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp', 'nlminb', 'lbfgs', 'gosolnp')
## Includes the open price or not.
bk.base <- llply(mbase, Cl)
bk.base %<>% do.call(cbind, .) %>% na.omit
## Statistical modelling
bk.dcc <- llply(md, function(x) {
dm <- llply(sv, function(y) {
fit <- tryCatch(
mv_fx(bk.base, .model = x, .solver = y,
.include.Op = FALSE, .Cl.only = TRUE),
error = function(e) cat(paste0('bk.', x, '.', y, ' error.\n')))
if (!is.null('fit')) {
eval(parse(text = paste0(
"saveRDS(fit, 'data/fx/", paste0('bk.', x, '.', y), ".rds')")))
cat(paste0('bk.', x, '.', y, ' saved.\n'))
}
})
names(dm) <- sv
dm
})
names(bk.dcc) <- md
```
I executed above coding and there are quite some models occured errors. The `FDCC` models do faced error even though change all possible solvers. Below I read presaved data which executed above.
```{r read-bkdcc}
fls <- list.files('data/fx', pattern = '^bk.') %>% str_replace_all('.rds', '')
bk.dcc <- sapply(fls, function(x) readRDS(paste0('data/fx/', x, '.rds'))) %>%
filterNull
```
Here I tried to compare the AIC values. The lowest value will be best fit model.
```{r bkdcc-aic}
##compare AIC values.
dcc.AIC <- sapply(bk.dcc, function(x) data.frame(t(x$AIC))) %>%
t %>% data.frame(.id = rownames(.)) %>%
separate(.id, c('.id', '.model', '.solver')) %>%
dplyr::select(.id, .model, .solver, Akaike, Bayes, Shibata, Hannan.Quinn) %>%
unnest
rownames(dcc.AIC) <- NULL
dcc.AIC %>%
arrange(Akaike, Bayes) %>%
kable(caption = 'Akaike Information Criteria') %>%
kable_styling(bootstrap_options = c('striped', 'hover', 'condensed', 'responsive')) %>%
scroll_box(width = '100%')#, height = '400px')
```
*Table 3.2.3.1 : AIC comparison.*
From above table, `r unlist(dcc.AIC$Akaike) %>% .[which.min(.)] %>% names` with `r unlist(dcc.AIC$Akaike) %>% .[which.min(.)]` is the best fitted model.
After that, look at the log-likehood figure as well to compare the correlation among models. The highest value will be best fit model.
```{r bkdcc-logLik}
##compare AIC values.
dcc.logLik <- sapply(bk.dcc, function(x) attributes(x$fit)$mfit$llh) %>%
t %>% t %>% data.frame(.id = rownames(.)) %>%
separate(.id, c('.id', '.model', '.solver'))
rownames(dcc.logLik) <- NULL
names(dcc.logLik)[1] <- 'log.Likelihood'
dcc.logLik %<>% dplyr::select(.id, .model, .solver, log.Likelihood)
dcc.logLik %>%
arrange(log.Likelihood) %>%
kable(caption = 'Log-Likelihood') %>%
kable_styling(bootstrap_options = c('striped', 'hover', 'condensed', 'responsive'))
```
*Table 3.2.3.2 : Log-Likelihood comparison.*
```{r bkdcc-roll}
## Possible multivariate models.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp', 'nlminb', 'lbfgs', 'gosolnp')
## Includes the open price or not.
bk.base <- llply(mbase, Cl)
bk.base %<>% do.call(cbind, .) %>% na.omit
## Statistical modelling
bk.dcc <- llply(md, function(x) {
dm <- llply(sv, function(y) {
fit <- tryCatch(
mv_fx(bk.base, .model = x, .solver = y,
.include.Op = FALSE, .Cl.only = TRUE, .roll = TRUE),
error = function(e) cat(paste0('roll.bk.', x, '.', y, ' error.\n')))
if (!is.null('fit')) {
eval(parse(text = paste0(
"saveRDS(fit, 'data/fx/", paste0('roll.bk.', x, '.', y), ".rds')")))
cat(paste0('roll.bk.', x, '.', y, ' saved.\n'))
}
})
names(dm) <- sv
dm
})
names(bk.dcc) <- md
```
### Hi-Lo Price
#### Single Currency
Multivariate modelling for single currency. Here I tried to seperate to 2 type of forecasting dataset which are `OHLC` and `HLC` to know if includes the open price will be more accurate or not.
```{r pt-dcc, eval=FALSE}
## ------------- eval ---------------
## Possible multivariate models.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp', 'nlminb', 'lbfgs', 'gosolnp')
op <- c(TRUE, FALSE)
## Includes the open price or not.
pt.base <- mbase[['USDJPY']][,1:4]
## Statistical modelling
pt.dcc <- llply(md, function(x) {
dm <- llply(sv, function(y) {
TF <- llply(op, function(z) {
fit <- tryCatch(
mv_fx(pt.base, .model = x, .solver = y,
.include.Op = z, .Cl.only = FALSE),
error = function(e)
cat(paste0('pt.', x, '.', y, '.', z,' error.\n')))
if (!is.null('fit')) {
eval(parse(text = paste0(
"saveRDS(fit, 'data/fx/",
paste0('pt.', x, '.', y, '.', z), ".rds')")))
cat(paste0('pt.', x, '.', y, '.', z, ' saved.\n'))
}
})
names(TF) <- op
TF
})
names(dm) <- sv
dm
})
names(pt.dcc) <- md
```
I executed above coding and there are quite some models occured errors. The `FDCC` models do faced error even though change all possible solvers. Below I read presaved data which executed above.
```{r read-ptdcc}
fls <- list.files('data/fx', pattern = '^pt.[^dcc]') %>% str_replace_all('.rds', '')
pt.dcc <- sapply(fls, function(x) readRDS(paste0('data/fx/', x, '.rds'))) %>%
filterNull
```
Here I tried to compare the AIC values. The lowest value will be best fit model.
```{r ptdcc-aic}
##compare AIC values.
dcc.AIC <- sapply(pt.dcc, function(x) data.frame(t(data.frame(x$AIC)))) %>%
t %>% data.frame(.id = rownames(.)) %>%
separate(.id, c('.id', '.model', '.solver', 'includes.Op')) %>%
dplyr::select(.id, .model, .solver, includes.Op, Akaike, Bayes, Shibata, Hannan.Quinn) %>% unnest
rownames(dcc.AIC) <- NULL
dcc.AIC %>%
arrange(Akaike, Bayes) %>%
kable(caption = 'Akaike Information Criteria') %>%
kable_styling(bootstrap_options = c('striped', 'hover', 'condensed', 'responsive')) %>%
scroll_box(width = '100%', height = '400px')
```
*Table 3.2.4.1 : AIC comparison.*
From above table, `r unlist(dcc.AIC$Akaike) %>% .[which.min(.)] %>% names` with `r unlist(dcc.AIC$Akaike) %>% .[which.min(.)]` is the best fitted model. After that, look at the log-likehood figure as well to compare the correlation among models. The highest value will be best fit model.
```{r ptdcc-logLik}
##compare AIC values.
dcc.logLik <- sapply(pt.dcc, function(x) attributes(x$fit)$mfit$llh) %>%
t %>% t %>% data.frame(.id = rownames(.)) %>%
separate(.id, c('.id', '.model', '.solver', 'includes.Op'))
rownames(dcc.logLik) <- NULL
names(dcc.logLik)[1] <- 'log.Likelihood'
dcc.logLik %<>% dplyr::select(.id, .model, .solver, includes.Op, log.Likelihood)
dcc.logLik %>%
arrange(log.Likelihood) %>%
kable(caption = 'Log-Likelihood') %>%
kable_styling(bootstrap_options = c('striped', 'hover', 'condensed', 'responsive'))
```
*Table 3.2.4.2 : Log-Likelihood comparison.*
The model `r dcc.logLik %>% dplyr::filter(log.Likelihood == max(log.Likelihood)) %>% unite(.id, .id:includes.Op) %>% .$.id %>% str_replace_all('_', '.')` which highest logLik value `r dcc.logLik$log.Likelihood[which.max(dcc.logLik$log.Likelihood)]` is the best fitted model for correlation.
```{r ptdcc-roll, eval=FALSE}
## ------------- eval ---------------
## Possible multivariate models.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp', 'nlminb', 'lbfgs', 'gosolnp')
op <- c(TRUE, FALSE)
## Includes the open price or not.
pt.base <- mbase[['USDJPY']][,1:4]
## Statistical modelling
pt.dcc <- llply(md, function(x) {
dm <- llply(sv, function(y) {
TF <- llply(op, function(z) {
fit <- tryCatch(
mv_fx(pt.base, .model = x, .solver = y,
.include.Op = z, .Cl.only = FALSE, .roll = TRUE),
error = function(e)
cat(paste0('roll.pt.', x, '.', y, '.', z,' error.\n')))
if (!is.null('fit')) {
eval(parse(text = paste0(
"saveRDS(fit, 'data/fx/",
paste0('roll.pt.', x, '.', y, '.', z), ".rds')")))
cat(paste0('roll.pt.', x, '.', y, '.', z, ' saved.\n'))
}
})
names(TF) <- op
TF
})
names(dm) <- sv
dm
})
names(pt.dcc) <- md
```
#### Currency Basket
Multivariate modelling for a basket of currencies for `Cl` will compares in following section. The `HL` and `HLC` will be in another paper.
### Concludes Parameter Selection
I initially wonder if I need to includes the open price in the models. Therefore I tried to compare above models. However the open price might not in use the my trading strategy. Therefore here I skip it. Here I seperates to 3 selection for trading:
- Hi-Lo
- Hi-Lo-Cl
- Cl
From previous univariate models comparison, gjrGARCH almost be the most accurate across all mentioned currencies. Due to the MSE of USDJPY will be higher than other currency, here I use USDJPY to save the time to compare the models. Above solver shows that the `solnp` and `gosolnp` will be more accurate, here I only use these 2 solvers. I skip the `Open Price` because it will not use in either be punter nor banker.
![](www/Cl-Op.jpg)
*Source : [转载]詹姆斯-哈里斯-西蒙斯(James Harris Simons)*
<span style='color:goldenrod'>*[转载]詹姆斯-哈里斯-西蒙斯(James Harris Simons)*</span> describe the open price of future market and the close price of last day was highly related. There will be another research (if any). However I tried to use previous day's price to model in `VAR=TRUE`.
## DCC
### Abtract of DDC
Due to article <span style='color:goldenrod'>*The GARCH DCC Model and 2 Stage DCCMVT Estimation*</span>^[Kindly refer to [Reference] for further reading.] compares the `model = c('DCC', 'aDCC')` but not `model = 'FDCC'` with all distributions and concludes that `aDCC` with `distribution = 'mvt'` is the best fit model and distribution for multivariate GARCH model. Here I directly use `mvt` but in different `solver` parameters.
The paper [Binary.com Interview Q1 - Comparison of Univariate GARCH Models](https://rpubs.com/englianhu/binary-Q1Uni-GARCH) describes the GARCH orders. [How to identify the ARCH and GARCH lag length in dynamic conditional correlation GARCH model?](https://stats.stackexchange.com/questions/136302/how-to-identify-the-arch-and-garch-lag-length-in-dynamic-conditional-correlation?answertab=votes#tab-top) describes the GARCH(1,1) and also DCC-GARCH as well.
<span style='color:goldenrod'>*Multivariate DCC-GARCH Model*</span> introduce the DCC and CCC models. In all tests for marginal goodness of fit the DCC-GARCH with skew Student's t-distributed errors outperformed the DCC-GARCH with Gaussian and Student's t-distributed errors. Comparing the DCC-GARCH model with the CCC-GARCH model using the Kupiec test showed that the DCC-GARCH model gave a better fit to the data.
#### VAR and Robust
Below models will set `VAR=TRUE` <s>and `robust=FALSE`</s> and `VAR=FALSE` to test if it is more accurate.
> If you have a multivariate conditional mean specification (i.e. VAR) then you cannot have a univariate conditional mean specification (arma model)...they are mutually exclusive. In short, do not enter anything for mean.model in ugarchspec (include.mean is automatically set to FALSE if VAR is selected).
*source : [rmgarch:dccforecast() and mregfor](http://r.789695.n4.nabble.com/rmgarch-dccforecast-and-mregfor-td4675161.html) or [how to test significance of VAR coefficients in DCC GARCH Fit](http://r.789695.n4.nabble.com/how-to-test-significance-of-VAR-coefficients-in-DCC-GARCH-Fit-td4472274.html)*
> Currently the DCCfit object (returned from running dccfit) does not return all the information on the VAR (coefficients can be extracted by looking at the model slot and 'varcoef' list i.e. fit at model$varcoef).
>
> A better approach is to first estimate the VAR model using the function 'varxfit' in the package which returns the standard errors and all relevant information, and then passing this returned object to the dccfit routine (example follows).
```
#################
library(rmgarch)
data(dji30ret)
Data = dji30ret[, 1:3, drop = FALSE]
vfit = varxfit(X=Data, p=1, exogen = NULL, robust = FALSE,
gamma = 0.25, delta = 0.01, nc = 10, ns = 500, postpad = "constant")
uspec = ugarchspec(mean.model = list(armaOrder = c(0,0), include.mean =
FALSE), variance.model = list(garchOrder = c(1,1), model = "sGARCH"),
distribution.model = "norm")
spec = dccspec(uspec = multispec( replicate(3, uspec) ), VAR = TRUE,
lag = 1, dccOrder = c(1,1), asymmetric = FALSE, distribution = "mvnorm")
fit = dccfit(spec, data = Data, fit.control = list(eval.se=TRUE),
VAR.fit = vfit)
#################
```
> The package also includes for convenience the 'varxfilter', 'varxforecast' and 'varxsim' functions which are used by the multivariate garch routines internally.
>
> As mentioned in the documentation, a comprehensive list of examples are included in the 'inst/rmgarch.tests' folder of the package.
>
> Regards,
>
> Alexios
*source : [[R-SIG-Finance] how to test significance of VAR coefficients in DCC GARCH Fit](https://stat.ethz.ch/pipermail/r-sig-finance/2012q1/009792.html)*
```{r dcc-var, eval=FALSE}
.VARs = c(TRUE, FALSE)
#.rb = c(TRUE, FALSE)
```
### Hi-Lo
#### `DCC` and `VAR=FALSE`
```{r DCC-HLVARF, message=FALSE, warning=FALSE, eval=FALSE}
## ------------- Simulate mv_fx() ----------------------
## mv_fx just made the model and some argument flexible.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp')#, 'gosolnp')
## Hi-Lo.
Hi.base <- llply(mbase['USDJPY'], Hi)
Lo.base <- llply(mbase['USDJPY'], Lo)
HiLo.base <- c(Hi.base, Lo.base) %>% do.call(cbind, .) %>% na.omit
## only use USDJPY trading day.
timeID <- HiLo.base %>%
index %>% ymd %>%
.[. >= timeID0] %>%
c(., xts::last(.) + days(1))
tmID <- list.files('data/fx/USDJPY',
pattern = '^DCC.GARCH.USDJPY.HL.[0-9]{4}-[0-9]{2}-[0-9]{2}.rds') %>%
str_extract_all('[0-9]{4}-[0-9]{2}-[0-9]{2}') %>%
unlist %>% ymd
baseDT <- ymd('2013-01-01')
timeID %<>% .[!. %in% tmID] %>% .[-1]
timeID %<>% .[. > baseDT]
DCC.GARCH.USDJPY <- list()
for (dt in timeID) {
for (i in seq(cr_code[7])) {
smp <- HiLo.base#[[names(cr_code)[i]]]
timeID2 <- c(index(smp), xts::last(index(smp)) + days(1))
if (dt %in% timeID2) {
dtr <- xts::last(index(smp[index(smp) < dt]), 1) #tail(..., 1)
dtr %<>% .[. > baseDT]
smp <- smp[paste0(dtr %m-% years(1), '/', dtr)]
DCC.GARCH.USDJPY[[i]] <- tryCatch({ldply(md[1], function(y) {
df = tryCatch(
mv_fx(smp, .model = y, .solver = 'solnp', .currency = cr_code[7],#[i],
.price_type = 'HL', .VAR = FALSE, .cluster = .cl),
error = function(e) cat(paste0(y, '.HL.', 'solnp', ' error.\n')))
df = data.frame(Date = index(df$latestPrice[1]),
Type = paste0(names(df$latestPrice), '.', y),
df$latestPrice, df$forecastPrice, t(df$AIC),
VaR = df$forecastVaR)
names(df) %<>% str_replace_all('[0-9]{4}.[0-9]{2}.[0-9]{2}', 'T1')
df
})}, error = function(e) NULL)
if (is.null(DCC.GARCH.USDJPY[[i]])) {
subdir <- 'USDJPY'
} else {
subdir <- substr(names(DCC.GARCH.USDJPY[[i]])[3], 1, 6)
}
if (!dir.exists(paste0('data/fx/', subdir)))
dir.create(paste0('data/fx/', subdir))
saveRDS(DCC.GARCH.USDJPY[[i]], paste0(
'data/fx/', subdir, '/DCC.GARCH.USDJPY.HL.',
unique(DCC.GARCH.USDJPY[[i]]$Date), '.rds'))
cat(paste0(
'data/fx/', subdir, '/DCC.GARCH.USDJPY.HL.',
unique(DCC.GARCH.USDJPY[[i]]$Date), '.rds saved!\n'))
}
}; rm(i)
}
```
#### `aDCC` and `VAR=FALSE`
```{r aDCC-HLVARF, message=FALSE, warning=FALSE, eval=FALSE}
## ------------- Simulate mv_fx() ----------------------
## mv_fx just made the model and some argument flexible.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp')#, 'gosolnp')
## Hi-Lo.
Hi.base <- llply(mbase['USDJPY'], Hi)
Lo.base <- llply(mbase['USDJPY'], Lo)
HiLo.base <- c(Hi.base, Lo.base) %>% do.call(cbind, .) %>% na.omit
## only use USDJPY trading day.
timeID <- HiLo.base %>%
index %>% ymd %>%
.[. >= timeID0] %>%
c(., xts::last(.) + days(1))
tmID <- list.files('data/fx/USDJPY',
pattern = '^aDCC.GARCH.USDJPY.HL.[0-9]{4}-[0-9]{2}-[0-9]{2}.rds') %>%
str_extract_all('[0-9]{4}-[0-9]{2}-[0-9]{2}') %>%
unlist %>% ymd
baseDT <- ymd('2013-01-01')
timeID %<>% .[!. %in% tmID] %>% .[-1]
timeID %<>% .[. > baseDT]
aDCC.GARCH.USDJPY <- list()
for (dt in timeID) {
for (i in seq(cr_code[7])) {
smp <- HiLo.base#[[names(cr_code)[i]]]
timeID2 <- c(index(smp), xts::last(index(smp)) + days(1))
if (dt %in% timeID2) {
dtr <- xts::last(index(smp[index(smp) < dt]), 1) #tail(..., 1)
dtr %<>% .[. > baseDT]
smp <- smp[paste0(dtr %m-% years(1), '/', dtr)]
aDCC.GARCH.USDJPY[[i]] <- tryCatch({ldply(md[2], function(y) {
df = tryCatch(
mv_fx(smp, .model = y, .solver = 'solnp', .currency = cr_code[7],#[i],
.price_type = 'HL', .VAR = FALSE, .cluster = .cl),
error = function(e) cat(paste0(y, '.HL.', 'solnp', ' error.\n')))
df = data.frame(Date = index(df$latestPrice[1]),
Type = paste0(names(df$latestPrice), '.', y),
df$latestPrice, df$forecastPrice, t(df$AIC),
VaR = df$forecastVaR)
names(df) %<>% str_replace_all('[0-9]{4}.[0-9]{2}.[0-9]{2}', 'T1')
df
})}, error = function(e) NULL)
if (is.null(aDCC.GARCH.USDJPY[[i]])) {
subdir <- 'USDJPY'
} else {
subdir <- substr(names(aDCC.GARCH.USDJPY[[i]])[3], 1, 6)
}
if (!dir.exists(paste0('data/fx/', subdir)))
dir.create(paste0('data/fx/', subdir))
saveRDS(aDCC.GARCH.USDJPY[[i]], paste0(
'data/fx/', subdir, '/aDCC.GARCH.USDJPY.HL.',
unique(aDCC.GARCH.USDJPY[[i]]$Date), '.rds'))
cat(paste0(
'data/fx/', subdir, '/aDCC.GARCH.USDJPY.HL.',
unique(aDCC.GARCH.USDJPY[[i]]$Date), '.rds saved!\n'))
}
}; rm(i)
}
```
#### `FDCC` and `VAR=FALSE`
```{r FDCC-HLVARF, message=FALSE, warning=FALSE, eval=FALSE}
## ------------- Simulate mv_fx() ----------------------
## mv_fx just made the model and some argument flexible.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp')#, 'gosolnp')
## Hi-Lo.
Hi.base <- llply(mbase['USDJPY'], Hi)
Lo.base <- llply(mbase['USDJPY'], Lo)
HiLo.base <- c(Hi.base, Lo.base) %>% do.call(cbind, .) %>% na.omit
## only use USDJPY trading day.
timeID <- HiLo.base %>%
index %>% ymd %>%
.[. >= timeID0] %>%
c(., xts::last(.) + days(1))
tmID <- list.files('data/fx/USDJPY',
pattern = '^FDCC.GARCH.USDJPY.HL.[0-9]{4}-[0-9]{2}-[0-9]{2}.rds') %>%
str_extract_all('[0-9]{4}-[0-9]{2}-[0-9]{2}') %>%
unlist %>% ymd
baseDT <- ymd('2013-01-01')
timeID %<>% .[!. %in% tmID] %>% .[-1]
timeID %<>% .[. > baseDT]
FDCC.GARCH.USDJPY <- list()
for (dt in timeID) {
for (i in seq(cr_code[7])) {
smp <- HiLo.base#[[names(cr_code)[i]]]
timeID2 <- c(index(smp), xts::last(index(smp)) + days(1))
if (dt %in% timeID2) {
dtr <- xts::last(index(smp[index(smp) < dt]), 1) #tail(..., 1)
dtr %<>% .[. > baseDT]
smp <- smp[paste0(dtr %m-% years(1), '/', dtr)]
FDCC.GARCH.USDJPY[[i]] <- tryCatch({ldply(md[3], function(y) {
df = tryCatch(
mv_fx(smp, .model = y, .solver = 'solnp', .currency = cr_code[7],#[i],
.price_type = 'HL', .VAR = FALSE, .cluster = .cl),
error = function(e) cat(paste0(y, '.HL.', 'solnp', ' error.\n')))
df = data.frame(Date = index(df$latestPrice[1]),
Type = paste0(names(df$latestPrice), '.', y),
df$latestPrice, df$forecastPrice, t(df$AIC),
VaR = df$forecastVaR)
names(df) %<>% str_replace_all('[0-9]{4}.[0-9]{2}.[0-9]{2}', 'T1')
df
})}, error = function(e) NULL)
if (is.null(FDCC.GARCH.USDJPY[[i]])) {
subdir <- 'USDJPY'
} else {
subdir <- substr(names(FDCC.GARCH.USDJPY[[i]])[3], 1, 6)
}
if (!dir.exists(paste0('data/fx/', subdir)))
dir.create(paste0('data/fx/', subdir))
saveRDS(FDCC.GARCH.USDJPY[[i]], paste0(
'data/fx/', subdir, '/FDCC.GARCH.USDJPY.HL.',
unique(FDCC.GARCH.USDJPY[[i]]$Date), '.rds'))
cat(paste0(
'data/fx/', subdir, '/FDCC.GARCH.USDJPY.HL.',
unique(FDCC.GARCH.USDJPY[[i]]$Date), '.rds saved!\n'))
}
}; rm(i)
}
```
### Hi-Lo-Cl
#### `DCC` and `VAR=FALSE`
```{r DCC-HLCVARF, message=FALSE, warning=FALSE, eval=FALSE}
## ------------- Simulate mv_fx() ----------------------
## mv_fx just made the model and some argument flexible.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp')#, 'gosolnp')
## Hi-Lo-Cl.
Hi.base <- llply(mbase['USDJPY'], Hi)
Lo.base <- llply(mbase['USDJPY'], Lo)
Cl.base <- llply(mbase['USDJPY'], Cl)
HiLoCl.base <- c(Hi.base, Lo.base, Cl.base) %>%
do.call(cbind, .) %>% na.omit
rm(Hi.base, Lo.base, Cl.base)
## only use USDJPY trading day.
timeID <- HiLoCl.base %>% index %>% ymd %>%
.[. >= timeID0] %>% c(., xts::last(.) + days(1))
tmID <- list.files('data/fx/USDJPY',
pattern = '^DCC.GARCH.USDJPY.HLC.[0-9]{4}-[0-9]{2}-[0-9]{2}.rds') %>%
str_extract_all('[0-9]{4}-[0-9]{2}-[0-9]{2}') %>%
unlist %>% ymd
baseDT <- ymd('2013-01-01')
timeID %<>% .[!. %in% tmID] %>% .[-1]
timeID %<>% .[. > baseDT]
DCC.GARCH.USDJPY <- list()
for (dt in timeID) {
for (i in seq(cr_code[7])) {
smp <- HiLoCl.base#[[names(cr_code)[i]]]
timeID2 <- c(index(smp), xts::last(index(smp)) + days(1))
if (dt %in% timeID2) {
dtr <- xts::last(index(smp[index(smp) < dt]), 1) #tail(..., 1)
dtr %<>% .[. > baseDT]
smp <- smp[paste0(dtr %m-% years(1), '/', dtr)]
DCC.GARCH.USDJPY[[i]] <- tryCatch({llply(md[1], function(y) {
df = tryCatch(
mv_fx(smp, .model = y, .solver = 'solnp', .currency = cr_code[7],#[i],
.price_type = 'HLC', .VAR = FALSE, .cluster = .cl),
error = function(e) cat(paste0(y, '.HLC.', 'solnp', ' error.\n')))
res = suppressAll(data.frame(Date = index(df$latestPrice[1]),
Type = paste0(names(df$latestPrice), '.', y),
df$latestPrice, df$forecastPrice, t(df$AIC)))
VaR = df$forecastVaR
names(res) %<>% str_replace_all('[0-9]{4}.[0-9]{2}.[0-9]{2}', 'T1')
names(VaR) %<>% str_replace_all('[0-9]{4}.[0-9]{2}.[0-9]{2}', 'T1')
return(list(res = res, VaR = VaR))
})[[1]]}, error = function(e) NULL)
if (is.null(DCC.GARCH.USDJPY[[i]])) {
subdir <- 'USDJPY'
} else {
subdir <- substr(names(DCC.GARCH.USDJPY[[i]]$res)[3], 1, 6)
}
if (!dir.exists(paste0('data/fx/', subdir)))
dir.create(paste0('data/fx/', subdir))
saveRDS(DCC.GARCH.USDJPY[[i]], paste0(
'data/fx/', subdir, '/DCC.GARCH.USDJPY.HLC.',
unique(DCC.GARCH.USDJPY[[i]]$res$Date), '.rds'))
cat(paste0(
'data/fx/', subdir, '/DCC.GARCH.USDJPY.HLC.',
unique(DCC.GARCH.USDJPY[[i]]$res$Date), '.rds saved!\n'))
}
}; rm(i)
}
```
#### `aDCC` and `VAR=FALSE`
```{r aDCC-HLCVARF, message=FALSE, warning=FALSE, eval=FALSE}
## ------------- Simulate mv_fx() ----------------------
## mv_fx just made the model and some argument flexible.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp')#, 'gosolnp')
## Hi-Lo-Cl.
Hi.base <- llply(mbase['USDJPY'], Hi)
Lo.base <- llply(mbase['USDJPY'], Lo)
Cl.base <- llply(mbase['USDJPY'], Cl)
HiLoCl.base <- c(Hi.base, Lo.base, Cl.base) %>%
do.call(cbind, .) %>% na.omit
rm(Hi.base, Lo.base, Cl.base)
## only use USDJPY trading day.
timeID <- HiLoCl.base %>% index %>% ymd %>%
.[. >= timeID0] %>% c(., xts::last(.) + days(1))
tmID <- list.files('data/fx/USDJPY',
pattern = '^aDCC.GARCH.USDJPY.HLC.[0-9]{4}-[0-9]{2}-[0-9]{2}.rds') %>%
str_extract_all('[0-9]{4}-[0-9]{2}-[0-9]{2}') %>%
unlist %>% ymd
baseDT <- ymd('2013-01-01')
timeID %<>% .[!. %in% tmID] %>% .[-1]
timeID %<>% .[. > baseDT]
aDCC.GARCH.USDJPY <- list()
for (dt in timeID) {
for (i in seq(cr_code[7])) {
smp <- HiLoCl.base#[[names(cr_code)[i]]]
timeID2 <- c(index(smp), xts::last(index(smp)) + days(1))
if (dt %in% timeID2) {
dtr <- xts::last(index(smp[index(smp) < dt]), 1) #tail(..., 1)
dtr %<>% .[. > baseDT]
smp <- smp[paste0(dtr %m-% years(1), '/', dtr)]
aDCC.GARCH.USDJPY[[i]] <- tryCatch({llply(md[2], function(y) {
df = tryCatch(
mv_fx(smp, .model = y, .solver = 'solnp', .currency = cr_code[7],#[i],
.price_type = 'HLC', .VAR = FALSE, .cluster = .cl),
error = function(e) cat(paste0(y, '.HLC.', 'solnp', ' error.\n')))
res = suppressAll(data.frame(Date = index(df$latestPrice[1]),
Type = paste0(names(df$latestPrice), '.', y),
df$latestPrice, df$forecastPrice, t(df$AIC)))
VaR = df$forecastVaR
names(res) %<>% str_replace_all('[0-9]{4}.[0-9]{2}.[0-9]{2}', 'T1')
names(VaR) %<>% str_replace_all('[0-9]{4}.[0-9]{2}.[0-9]{2}', 'T1')
return(list(res = res, VaR = VaR))
})[[1]]}, error = function(e) NULL)
if (is.null(aDCC.GARCH.USDJPY[[i]])) {
subdir <- 'USDJPY'
} else {
subdir <- substr(names(aDCC.GARCH.USDJPY[[i]]$res)[3], 1, 6)
}
if (!dir.exists(paste0('data/fx/', subdir)))
dir.create(paste0('data/fx/', subdir))
saveRDS(aDCC.GARCH.USDJPY[[i]], paste0(
'data/fx/', subdir, '/aDCC.GARCH.USDJPY.HLC.',
unique(aDCC.GARCH.USDJPY[[i]]$res$Date), '.rds'))
cat(paste0(
'data/fx/', subdir, '/aDCC.GARCH.USDJPY.HLC.',
unique(aDCC.GARCH.USDJPY[[i]]$res$Date), '.rds saved!\n'))
}
}; rm(i)
}
```
#### `FDCC` and `VAR=FALSE`
```{r FDCC-HLCVARF, message=FALSE, warning=FALSE, eval=FALSE}
## ------------- Simulate mv_fx() ----------------------
## mv_fx just made the model and some argument flexible.
md <- c('DCC', 'aDCC', 'FDCC')
sv <- c('solnp')#, 'gosolnp')
## Hi-Lo-Cl.
Hi.base <- llply(mbase['USDJPY'], Hi)
Lo.base <- llply(mbase['USDJPY'], Lo)
Cl.base <- llply(mbase['USDJPY'], Cl)
HiLoCl.base <- c(Hi.base, Lo.base, Cl.base) %>%
do.call(cbind, .) %>% na.omit
rm(Hi.base, Lo.base, Cl.base)
## only use USDJPY trading day.
timeID <- HiLoCl.base %>% index %>% ymd %>%
.[. >= timeID0] %>% c(., xts::last(.) + days(1))
tmID <- list.files('data/fx/USDJPY',
pattern = '^FDCC.GARCH.USDJPY.HLC.[0-9]{4}-[0-9]{2}-[0-9]{2}.rds') %>%
str_extract_all('[0-9]{4}-[0-9]{2}-[0-9]{2}') %>%
unlist %>% ymd
baseDT <- ymd('2013-01-01')
timeID %<>% .[!. %in% tmID] %>% .[-1]
timeID %<>% .[. > baseDT]
FDCC.GARCH.USDJPY <- list()
for (dt in timeID) {
for (i in seq(cr_code[7])) {
smp <- HiLoCl.base#[[names(cr_code)[i]]]
timeID2 <- c(index(smp), xts::last(index(smp)) + days(1))
if (dt %in% timeID2) {
dtr <- xts::last(index(smp[index(smp) < dt]), 1) #tail(..., 1)
dtr %<>% .[. > baseDT]
smp <- smp[paste0(dtr %m-% years(1), '/', dtr)]
FDCC.GARCH.USDJPY[[i]] <- tryCatch({llply(md[3], function(y) {
df = tryCatch(
mv_fx(smp, .model = y, .solver = 'solnp', .currency = cr_code[7],#[i],
.price_type = 'HLC', .VAR = FALSE, .cluster = .cl),
error = function(e) cat(paste0(y, '.HLC.', 'solnp', ' error.\n')))