-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathFullcode.m
2207 lines (1921 loc) · 112 KB
/
Fullcode.m
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
dbstop if error
%%
%==================
% +++ Part One : EDA +++
%==================
% Load in the datase
load GrpAsgmData.mat
% Create the price matrix and return matrix
p_mat = [BX CTB PSX JNJ LBTYA];
clear BX CTB PSX JNJ LBTYA
% To gain a basic insight into the original dataset
shape_original = size(p_mat)
% Sepatate the dataset into the in-sample set (~80%) and forecast set (~20%)
s = round(0.8*shape_original(1));
is_p = p_mat(1:s, :);
f_p = p_mat(s+1:end, :);
shape_is = size(is_p)
shape_f = size(f_p)
% Plot the in-sample price series
figure; plot(Date(1:s), is_p); legend('BX', 'CTB', 'PSX', 'JNJ', 'LBTYA', 'location', 'northwest'); grid on;
datetick('x', 'mmm/yy'); title('In-sample Price Series for Five Stocks'); xlim([min(Date(2:s)) max(Date(2:s))])
% Create the return series for both in-sample and forecast price sets
full_ret = price2ret(p_mat);
is_ret = full_ret(1:round(0.8*length(full_ret)), :); %price2ret(is_p);
f_ret = full_ret(round(0.8*length(full_ret))+1:end, :); %price2ret(f_p);
shape_is = size(is_ret)
shape_f = size(f_ret)
% Plot the in-sample return series
figure; plot(Date(2:s), is_ret); legend('BX', 'CTB', 'PSX', 'JNJ', 'LBTYA', 'location','southwest'); grid on;
title('In-sample Return Series for Five Stocks'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))])
% Exploratory Data Analysis for in-sample returns
% (1) Descriptive Statistics
stocks = {'BX', 'CTB', 'PSX', 'JNJ', 'LBTYA'};
Mean = [mean(is_ret(:,1)); mean(is_ret(:,2)); mean(is_ret(:,3)); mean(is_ret(:,4)); mean(is_ret(:,5))];
Median = [median(is_ret(:,1)); median(is_ret(:,2)); median(is_ret(:,3)); median(is_ret(:,4)); median(is_ret(:,5))];
STD = [std(is_ret(:,1)); std(is_ret(:,2)); std(is_ret(:,3)); std(is_ret(:,4)); std(is_ret(:,5))];
MIN = [min(is_ret(:,1)); min(is_ret(:,2)); min(is_ret(:,3)); min(is_ret(:,4)); min(is_ret(:,5))];
MAX = [max(is_ret(:,1)); max(is_ret(:,2)); max(is_ret(:,3)); max(is_ret(:,4)); max(is_ret(:,5))];
SKEWNESS = [skewness(is_ret(:,1)); skewness(is_ret(:,2)); skewness(is_ret(:,3)); skewness(is_ret(:,4)); skewness(is_ret(:,5))];
KURTOSIS = [kurtosis(is_ret(:,1)); kurtosis(is_ret(:,2)); kurtosis(is_ret(:,3)); kurtosis(is_ret(:,4)); kurtosis(is_ret(:,5))];
stats_table = table(Mean, Median, STD, MIN, MAX, SKEWNESS, KURTOSIS, 'RowNames',stocks)
% Histograms of return series
figure; subplot(1,5,1); hist(is_ret(:,1), 50); title('Histogram of returns for BX');
subplot(1,5,2); hist(is_ret(:,2), 50); title('Histogram of returns for CTB');
subplot(1,5,3); hist(is_ret(:,3), 50); title('Histogram of returns for PSX');
subplot(1,5,4); hist(is_ret(:,4), 50); title('Histogram of returns for JNJ');
subplot(1,5,5); hist(is_ret(:,5), 50); title('Histogram of returns for LBTYA');
%
% for i = 1:5
% figure; hist(is_ret(:,i), 50); title(strcat('Histogram of returns for, ', stocks(i)));
% end
%%
%==================
% +++ Part Two Factor Model +++
%==================
% Conduct factor analysis with m=2 factors
[lam2_rets, psi2_rets, T2_ret, stats2_ret, F2_ret] = factoran(is_ret, 2, 'maxit', 1000, 'rotate', 'none'); % with 1000 iterations
% Display standardised factor loadings and specifc error variances
std_fl = table([lam2_rets(:,1)], [lam2_rets(:,2)], [psi2_rets], 'RowNames', stocks,...
'VariableNames',{'F1_Std_Loadings','F2_Std_Loadings','Error_Variance'})
% Display the two columns of actual factor loadings, then specific error
% variances, SER and adjusted R-squared for each industry series from the
% factor model
lam2_ret = lam2_rets;
lam2_ret(:,1) = lam2_rets(:,1).*(std(is_ret))';
lam2_ret(:,2) = lam2_rets(:,2).*(std(is_ret))';
psi2_ret = psi2_rets.*(var(is_ret))';
act_fl = table([lam2_ret(:,1)], [lam2_ret(:,2)], [psi2_ret], [sqrt(psi2_ret)], [(1-psi2_ret'./var(is_ret))'], ...
'VariableNames',{'F1_Loadings','F2_Loadings','Spc_Err_Var', 'SER', 'Adj_R2'}, 'RowNames', stocks)
% Overall amount of variance explained by the factor model
var_explained = (trace(cov(is_ret)) - sum(psi2_ret))/trace(cov(is_ret))
% Stats from the factor analysis
stats2_ret
% Estimated error variances, and sample variances, for each asset
err_var = table([psi2_ret], [var(is_ret)'], 'VariableNames',{'Est_Var','Sample_Var'}, 'RowNames', stocks)
% Combine those results
fa_table = table([lam2_ret(:,1)], [lam2_ret(:,2)],[psi2_ret],[var(is_ret)'],[sqrt(psi2_ret)],[(1-psi2_ret'./var(is_ret))'], ...
'VariableNames',{'F1_Loadings','F2_Loadings','Spc_Err_Var', 'Sam_Var', 'SER', 'Adj_R2'}, 'RowNames', stocks)
% Sample means and variance of 2 factors
mean_2f = mean(F2_ret)
var_2f = var(F2_ret)
% SER, R-squared and STD for each asset
est_table = table([sqrt(psi2_ret)], [(1-psi2_ret'./var(is_ret))'], [std(is_ret)'], 'RowNames', stocks, ...
'VariableNames',{'SER','R_squared', 'STD'})
% Plots
figure; subplot(3,1,1); plot(Date(2:s), is_ret);
title('In-sample Return Series for Five Stocks'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(3,1,2); plot(Date(2:s), F2_ret(:,1)); datetick('x', 'mmm/yy');
xlim([min(Date(2:s)) max(Date(2:s))]); title('In-sample Series for 1st Factor');
subplot(3,1,3); plot(Date(2:s), F2_ret(:,2)); datetick('x', 'mmm/yy');
xlim([min(Date(2:s)) max(Date(2:s))]); title('In-sample Series for 2nd Factor');
% Correlations between asset return and factors
corr_vbls = {'BX', 'CTB', 'PSX', 'JNJ', 'LBTYA', 'F1', 'F2'};
array2table(corr([is_ret F2_ret]), 'VariableNames', corr_vbls, 'RowNames', corr_vbls)
% Create biplot of two factors
figure; biplot(lam2_ret, 'varlabels', stocks, 'LineWidth', 2, 'Markersize', 20); title('Biplot for Unrotated Factors from MLE');
% Carry out factor rotation
rot_mle = rotatefactors(lam2_ret);
figure; biplot(rot_mle, 'varlabels', stocks, 'LineWidth', 2, 'Markersize', 20); title('Biplot for Rotated Factors from MLE');
% To further carry out Principal Component Analysis on the original return
% series
[pc_ret, score_ret, latent_ret] = pca(is_ret);
% Percentage variance and cumulative variance explained per component
pct_var = latent_ret./sum(latent_ret);
cum_var = cumsum(latent_ret)./sum(latent_ret);
pca_var = table([pct_var], [cum_var], 'RowNames', {'PC1', 'PC2', 'PC3', 'PC4', 'PC5'},...
'VariableNames', {'Pct_Var_Explained','Cum_Var_Explained'})
% Create biplot for PC1 & 2 as well as PC1 to 3
figure; biplot(pc_ret(:,1:2), 'varlabels', stocks, 'LineWidth', 1, 'Markersize', 20); title('2-D Biplot for Unrotated Factors from PCA');
figure; biplot(pc_ret(:,1:3), 'varlabels', stocks, 'LineWidth', 1, 'Markersize', 20); title('3-D Biplot for Unrotated Factors from PCA');
% Carry out factor rotation on the first three PCs
rot_pca = rotatefactors(pc_ret(:,1:3), 'Method','orthomax');
figure; biplot(rot_pca(:,1:2), 'varlabels', stocks, 'LineWidth', 1, 'Markersize', 20); title('2-D Biplot for Rotated Factors from PCA');
figure; biplot(rot_pca(:,1:3), 'varlabels', stocks, 'LineWidth', 1, 'Markersize', 20); title('3-D Biplot for Rotated Factors from PCA');
% Plot of 5 return series together along with first 3 components
figure; subplot(4,1,1); plot(Date(2:s), is_ret);
title('In-sample Return Series for Five Stocks'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(4,1,2); plot(Date(2:s), score_ret(:,1)); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title('In-sample Series for 1st Principal Component');
subplot(4,1,3); plot(Date(2:s), score_ret(:,2)); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title('In-sample Series for 2nd Principal Component');
subplot(4,1,4); plot(Date(2:s), score_ret(:,3)); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title('In-sample Series for 3rd Principal Component');
% Correlation table of all 5 components
corr_pca = {'PC1', 'PC2', 'PC3', 'PC4', 'PC5'};
array2table(corr(score_ret), 'VariableNames', corr_pca, 'RowNames', corr_pca)
% Since the first three factors capture most variance, we attempt to choose
% these three factors to construct a 3-factor model
xmat = [ones(length(is_ret), 1) score_ret(:,1:3)]; % Create X matrix for regression wifactorth the first three PCs
% Iterate over each returns series to fit the factor model
for i=1:5
[betas, betaCI, resid, residCI, stat] = regress(is_ret(:,i), xmat); % run OLS regression
reg_table(i,:) = table(betas(1),betaCI(1,:),betas(2),betaCI(2,:),betas(3),betaCI(3,:),...
betas(4),betaCI(4,:),sqrt(stat(4)),(1-stat(4)/var(is_ret(:,i))));
end
reg_table.Properties.VariableNames = {'Alpha','Alpha_95CI','B1','B1_95CI','B2','B2_95CI','B3','B3_95CI','SER','AdjR2'};
reg_table.Properties.RowNames = stocks
%%
%=========================================================
% +++ Part 3&4 build model and forecast(i) ad-hoc: +++
%=========================================================
ad_hoc_returns = zeros(length(f_ret),5);
for t=1:length(f_ret)
ret_is = full_ret(t:length(f_ret)+t-1,:);
ad_hoc_returns(t,:) = mean(ret_is(end-5:end,:));
end
rmse_adhoc =zeros(5,1);
mad_adhoc =zeros(5,1);
for i=1:5
[rmse_adhoc(i,1),mad_adhoc(i,1)]=getfa(ad_hoc_returns(:,i),f_ret(:,i))
end
%%
%===================================================
% +++ Part 3 build model and forecast(ii) ARMA: +++
%===================================================
lbqtestReturn_Pvalues_5 = zeros(5,1);
lbqtestReturn_Pvalues_10 = zeros(5,1);
lbqtestResiduals_Pvalues_15 = zeros(5,1);
lbqtestResiduals_Pvalues_20 = zeros(5,1);
SkewnessResiduals = zeros(5,1);
KurtosisResiduals = zeros(5,1);
jbtestResiduals_Pvalues = zeros(5,1);
bestp = zeros(5,1);
bestq = zeros(5,1);
minaic = zeros(5,1);
arma_returns = zeros(length(f_ret),5);
for i=1:5
series = is_ret(:,i);
%1. lbtest for all return series;
[H5, pval5] = lbqtest(series, 5, 0.05);
[H10, pval10] = lbqtest(series, 10, 0.05);
lbqtestReturn_Pvalues_5(i,1) = pval5;
lbqtestReturn_Pvalues_10(i,1) = pval10;
%2. find best p and q
[p,q,best]=getpq(series);
bestp(i,1) = p;
bestq(i,1) = q;
minaic(i,1) = best;
%3. estimate models
Mdl=arima(p,0,q);
[EstMdl,EstParamCov,logL,info] = estimate(Mdl,series); % estimates the model
%4. get residuals % df
[E0,V0] = infer(EstMdl,series);
%5. JB test
SkewnessResiduals(i,1) = skewness(E0);
KurtosisResiduals(i,1) = kurtosis(E0);
[h,pvalues] = jbtest(E0);
jbtestResiduals_Pvalues(i,1) = pvalues;
%6. lbqtestResidua 15 lags
[H15, pval15] = lbqtest(E0, 15, 0.05,15-p-q);
[H20, pval20] = lbqtest(E0, 20, 0.05,20-p-q);
lbqtestResiduals_Pvalues_15(i,1) = pval15;
lbqtestResiduals_Pvalues_20(i,1) = pval20;
%7. Moving horizon forecasts (update weekly);
[arma_returns(1,i)] = forecast(EstMdl,1,'Y0',series); % 1-period forecasts
for t=2:length(f_ret)
ret_is = full_ret(t:length(series)+t-1,i);
if mod(t,5)==0
Mdl=arima(p,0,q);[EstMdl,EstParamCov,logL,info] = estimate(Mdl,ret_is,'display','Off');
end
[arma_returns(t,i)] = forecast(EstMdl,1,'Y0',ret_is);
end
end
% Create Table to record the test results
final_results = array2table([bestp,bestq,minaic,lbqtestReturn_Pvalues_5, ...,
lbqtestReturn_Pvalues_10, lbqtestResiduals_Pvalues_15,lbqtestResiduals_Pvalues_20, ...,
jbtestResiduals_Pvalues,SkewnessResiduals,KurtosisResiduals]);
final_results.Properties.VariableNames = {'p' 'q' 'minimumaic' 'Pv_lbq_returns_5' 'Pv_lbq_returns_10' ...,
'Pv_lbq_residuals_15' 'Pv_lbq_residuals_20' 'Pv_JBtest_Err' 'Skewness_Err' 'Kurtosis_Err'};
final_results.Properties.RowNames = {'BX' 'CTB' 'JNJ' 'LBTYA' 'PSX'} % not reject H0
% Calculate RMSE and MAE
rmse_arma = zeros(5,1);
mad_arma = zeros(5,1);
for i=1:5
[rmse_arma(i,1),mad_arma(i,1)]=getfa(arma_returns(:,i),f_ret(:,i));
end
%% plot ARMA predicions:
for i=1:5
figure;plot(Date(s+1:end),arma_returns(:,i));hold on;
plot(Date(s+1:end),f_ret(:,i));
legend('ARMA','observations')
end
%%
%===================================================
% +++ Part 3 build model and forecast(iii) ARCH: +++
%===================================================
%ACF; LB; Engle's ARCH test(use PSX as example)
figure;subplot(3,1,1);plot(Date(2:s),is_ret(:,3));ylabel('log return')
title('In sample PSX returns'); % add title
subplot(3,1,2);autocorr(is_ret(:,3), 30);
title('In sample PSX returns ACF');
subplot(3,1,3);autocorr(power(is_ret(:,3),2), 30);
title('In sample PSX returns squares ACF');
%LBQtest on squared returns
[H5, pValue5, Qstat5, CriticalValue5] = lbqtest(is_ret(:,3).^2, 5, 0.05); % 5 lags
[H10, pValue10, Qstat10, CriticalValue10] = lbqtest(is_ret(:,3).^2, 10, 0.05); % 10 lags
results = array2table([[H5,pValue5,Qstat5,CriticalValue5];
[H10,pValue10,Qstat10,CriticalValue10]]);
results.Properties.VariableNames = {'Reject' 'Pvalue' 'statistics' 'CriticalValues'};
results.Properties.RowNames = {'5lags' '10lags'}
% all of test reject H0: ARCH effect exist
% ARCH test on mean-corrected returns
a=is_ret(:,3)-mean(is_ret(:,3));
[H5,pValue5,ARCHstat5,CriticalValue5] = archtest(a,5)
[H10,pValue10,ARCHstat10,CriticalValue10] = archtest(a,10)
% Reject H0!
results = array2table([[H5,pValue5,ARCHstat5,CriticalValue5]
[H10,pValue10,ARCHstat10,CriticalValue10]])
results.Properties.VariableNames = {'Reject' 'Pvalue' 'statistics' 'CriticalValues'};
results.Properties.RowNames = {'5lags' '10lags'}
% check normal-dist ARMA
LLF=0;aic1=0;sic1=0;
for p=1:20
Mdl = garch(0,p);Mdl.Offset=NaN;
[EstMdl,EstParamCov,logL,info] = estimate(Mdl,is_ret(:,3),'display','off');
aic1(p)=-2*logL+2*p;sic1(p)=-2*logL+log(length(is_ret(:,3)))*p;
end
figure;plot(aic1,'b+-');hold on;plot(sic1,'r+-');
title('AIC & SIC');legend('AIC','SIC');
[m,i]=min(aic1)
[m,i]=min(sic1)
%aic1 : p=10
%sic1 : p=10
Mdl = garch(0,10);Mdl.Offset=NaN;
EstMdl = estimate(Mdl,is_ret(:,3));
v10=infer(EstMdl,is_ret(:,3));s10=sqrt(v10); %infer the conditional variance and calculate standard deviations
a10 = is_ret(:,3)-EstMdl.Offset;
a1A=EstMdl.ARCH;
% assess the fit
e10=a10./s10; %standarised error
figure;subplot(2,1,1);plot(Date(2:s),e10);
title('ARCH(10) Standardised Residuals');
subplot(2,1,2);hist(e10,25)
title('Histogram of ARCH(10) Standardised Residuals');
% residuals and squared residuals acf
subplot(2,1,1);autocorr(e10);
title('ACF of ARCH(10) Standardised Residuals');
subplot(2,1,2);autocorr(e10.^2);
title('ACF of ARCH(10) Squared Standardised Residuals');
%qq plot
figure;
qqplot(e10);
title('QQ plot ARCH(10) Standardised Residuals');
[H, pValue, Qstat, CriticalValue] = lbqtest(e10, [15 20], 0.05, [5 10]);
% need AR term
% df: lags+17
%LB test on squared standardised residuals
[H, pValue, Qstat, CriticalValue] = lbqtest(e10.^2, [15 20], 0.05, [5 10]);
% dont need ARCH term
% JB test
[skewness(e10) kurtosis(e10)];
[h,p] = jbtest(e10);
% the results showing t-dist is better
%% ARCH with t-distribution (use PSX as example)
%
logL=0;aic1=0;sic1=0;
for p=1:20
Mdl = garch(0,p);Mdl.Offset=NaN;Mdl.Distribution='t';
[EstMdl,EstParamCov,logL,info] = estimate(Mdl,is_ret(:,3),'display','off');
aic1(p)=-2*logL+2*p;sic1(p)=-2*logL+log(length(is_ret(:,3)))*p;
end
figure;plot(aic1,'b+-');title('AIC & SIC for t-distribution ARCH models')
hold on;plot(sic1,'r+-');legend('AIC','SIC');
% sic =2; aic =10
[m,i]=min(sic1);
[m,i]=min(aic1);
% use aic
Mdl = garch(0,10);Mdl.Offset=NaN;Mdl.Distribution='t';
EstMdl = estimate(Mdl,is_ret(:,3));
v10t=infer(EstMdl,is_ret(:,3));s10t=sqrt(v10t); %infer the conditional variance and calculate standard deviations
a10t = is_ret(:,3)-EstMdl.Offset; %calculate innovations
a1At=EstMdl.ARCH; %store ARCH coefficients for later use
%plot conditional statistics
figure;subplot(3,1,1);plot(Date(2:s),a10t);
title('ARCH(10) t-dist Innovations');
subplot(3,1,2);plot(Date(2:s),s10t);
title('ARCH(10) t-dist Conditional Standard Deviations');
subplot(3,1,3);plot(Date(2:s),is_ret(:,3));
title('Log returns')
% plot the results
figure;plot(Date(2:s),is_ret(:,3),'c+-.');hold on;plot(Date(2:s),s10t);
xlim([Date(2) Date(s)]); % set range of x-axis
title('ARCH(1) Conditional Standard Deviations and BHP Returns');
legend('BX returns', 'conditional standard deviations','location',...
'South','Orientation','horizontal' );
% check the fitness:
e10t=a10t./s10t;
figure;subplot(2,1,1);plot(Date(2:s),e10t)
xlim([Date(2) Date(s)]); % set range of x-axis
title('ARCH(10)-t Standardised Residuals');
subplot(2,1,2);autocorr(e10t)
title('ACF of ARCH(10)-t Standardised Residuals');
%qq
figure;subplot(2,1,1);hist(e10t,25)
title('Histogram of ARCH(10)-t Standardised Residuals');
subplot(2,1,2);qqplot(e10t);
title('QQ plot ARCH(10)-t Standardised Residuals');
% transform t-errors to normal errors
df=EstMdl.Distribution.DoF; % Get estimated degree of freedom parameter
ge=norminv(tcdf(sqrt(df)/sqrt(df-2)*e10t,df)); % transform t-errors to normal errors
% Plot Transformed Standardised Residuals and ACF
figure;subplot(2,1,1);plot(Date(2:s),ge)
xlim([Date(2) Date(s)]); % set range of x-axis
title('ARCH(10)-t Transformed Standardised Residuals');
subplot(2,1,2);autocorr(ge)
title('ACF of ARCH(10)-t Transformed Standardised Residuals');
% Plot Histogram of Transformed Standardised Residuals and QQ plot
figure;subplot(2,1,1);hist(ge,25)
title('Histogram of ARCH(10)-t Transformed Standardised Residuals');
subplot(2,1,2);qqplot(ge);
title('QQ plot ARCH(10)-t Transformed Standardised Residuals');
% Plot ACF of Squared Transformed Standardised Residuals
figure;autocorr(ge.^2)
title('ACF of ARCH(10)-t Squared Transformed Standardised Residuals');
[H, pValue, Qstat, CriticalValue] = lbqtest(ge, [15 20], 0.05, [5 10])
% LB test on squared transformed standardised residuals
[H, pValue, Qstat, CriticalValue] = lbqtest(ge.^2, [15 20], 0.05, [5 10])
[skewness(ge) kurtosis(ge)]
[h,p] = jbtest(ge)
figure;plot(Date(2:s),s10,'b');
hold on;plot(Date(2:s),s10t,'r'); % set range of x-axis
legend('ARCH(10)','ARCH(10)-t');
title('Conditional Standard Deviations for Gaussian and t ARCH models');
%% ARCH predictions
lbqtestSquare_Return_Pvalues_5 = zeros(5,1);
lbqtestSquare_Return_Pvalues_10 = zeros(5,1);
ARCHtest_5 = zeros(5,1);
ARCHtest_10 = zeros(5,1);
bestp_t_dist = zeros(5,1);
minaic_t_dist = zeros(5,1);
minsic_t_dist = zeros(5,1);
lbqtestResiduals_t_dist_Pvalues_15 = zeros(5,1);
lbqtestResiduals_t_dist_Pvalues_20 = zeros(5,1);
lbqtestSquareRes_t_dist_Pvalues_15 = zeros(5,1);
lbqtestSquareRes_t_dist_Pvalues_20 = zeros(5,1);
SkewnessResiduals_t_dist = zeros(5,1);
KurtosisResiduals_t_dist = zeros(5,1);
jbtestResiduals_Pvalues_t_dist = zeros(5,1);
sigma = zeros(length(f_ret),5);
ARCH_VaR_f = zeros(length(f_ret),5);
SFAOgt = zeros(length(f_ret),5);
for i=1:5
series = is_ret(:,i);
%1. lbtest for all series;
[H5, pval5] = lbqtest(series.^2, 5, 0.05);
[H10, pval10] = lbqtest(series.^2, 10, 0.05);
lbqtestSquare_Return_Pvalues_5(i,1) = pval5;
lbqtestSquare_Return_Pvalues_10(i,1) = pval10;
% arch test
a=series-mean(series);
[H5,pValue_arch_5,ARCHstat5,CriticalValue5] = archtest(a,5);
[H10,pValue_arch_10,ARCHstat10,CriticalValue10] = archtest(a,10);
ARCHtest_5(i,1) = pValue_arch_5;
ARCHtest_10(i,1) = pValue_arch_10;
%2. find best p
logL=0;aic1=0;sic1=0;
for p=1:20
Mdl = garch(0,p);Mdl.Offset=NaN;Mdl.Distribution='t';
[EstMdl,EstParamCov,logL,info] = estimate(Mdl,series,'display','off');
aic1(p)=-2*logL+2*p;sic1(p)=-2*logL+log(length(series))*p;
end
[m_sic,i_sic]=min(sic1);
[m_aic,i_aic]=min(aic1);
bestp_t_dist(i,1) = i_aic;
minaic_t_dist(i,1) = m_aic;
minsic_t_dist(i,1) = m_sic;
%3. fit the arch(p) using AIC
Mdl = garch(0,i_aic);Mdl.Offset=NaN;Mdl.Distribution='t';
EstMdl = estimate(Mdl,series);
vpt=infer(EstMdl,series);spt=sqrt(vpt); %infer the conditional variance and calculate standard deviations
apt = series-EstMdl.Offset;
ept=apt./spt;
%4. transfrom the residuals to normal-dist
df=EstMdl.Distribution.DoF; % Get estimated degree of freedom parameter
ge=norminv(tcdf(sqrt(df)/sqrt(df-2)*ept,df));
[H, pValue_r, Qstat, CriticalValue] = lbqtest(ge, [15 20], 0.05, [5 10]);
lbqtestResiduals_t_dist_Pvalues_15(i,1) = pValue_r(1);
lbqtestResiduals_t_dist_Pvalues_20(i,1) = pValue_r(2);
[H, pValue_r2, Qstat, CriticalValue] = lbqtest(ge.^2, [15 20], 0.05, [5 10]);
lbqtestSquareRes_t_dist_Pvalues_15(i,1) = pValue_r2(1);
lbqtestSquareRes_t_dist_Pvalues_20(i,1) = pValue_r2(2);
%jb test
[h,p_jb] = jbtest(ge);
SkewnessResiduals_t_dist(i,1) =skewness(ge);
KurtosisResiduals_t_dist(i,1) =kurtosis(ge);
jbtestResiduals_Pvalues_t_dist(i,1) =p_jb;
%5. predictios VaR and sigma
for t=1:length(f_ret)
ret_is = full_ret(t:length(is_ret)+t-1,i);
if mod(t,5)==0|t==1
Mdl = garch(0,i_aic);Mdl.Offset=NaN;Mdl.Distribution='t'; %ARCH(5)
[EstMdl,EstParamCov,LLF,info]=estimate(Mdl,ret_is,'display','off');
%[E0,V0] = infer(EstMdl,series);
end
sigma(t,i)=forecast(EstMdl,1,'Y0',ret_is);
p0Gt=EstMdl.Offset;
dfGt = EstMdl.Distribution.DoF;
SFAOgt(t,i) = sqrt(sigma(t,i));
ARCH_VaR_f(t,i) = p0Gt+tinv(0.05,dfGt)*SFAOgt(t,i)*sqrt((dfGt-2)/dfGt);
end
end
% create table of the results
after = array2table([bestp_t_dist, minaic_t_dist,minsic_t_dist,lbqtestResiduals_t_dist_Pvalues_15 ...,
lbqtestResiduals_t_dist_Pvalues_20,lbqtestSquareRes_t_dist_Pvalues_15 ...,
lbqtestSquareRes_t_dist_Pvalues_20,SkewnessResiduals_t_dist ...,
KurtosisResiduals_t_dist,jbtestResiduals_Pvalues_t_dist]);
after.Properties.VariableNames = {'p' 'minimumAIC' 'minimumSIC' 'Pv_lb_ERR_15' 'Pv_lb_ERR_20' ...,
'Pv_lb_squ_ERR_15' 'Pv_lb_squ_ERR_20' 'kewness_Err' 'Kurtosis_Err' 'Pv_jb_ERR'};
after.Properties.RowNames = {'BX' 'CTB' 'PSX' 'JNJ' 'LBTYA' }
%%
%===================================================
% +++ Part 3 build model and forecast(iv) GARCH: +++
%===================================================
% Use AIC and BIC to choose a suitable GARCH(p,q) model with either Gaussian or Student-t errors.
aic0 = 0; bic0 = 0; aict0 = 0; bict0 = 0; LLF = 0;
for i=1:5
for p=1:5
for q=1:5
% GARCH(p,q) with Gaussian errors
mdlGG = garch(p,q); mdlGG.Offset = NaN; mdlGG.Distribution = 'Gaussian';
[EstMdl, EstParamCov, LLF, info] = estimate(mdlGG, is_ret(:,i), 'display', 'off');
aic0(p,q) = -2*LLF+2*(p+q);
bic0(p,q) = -2*LLF+log(length(is_ret))*(p+q);
[p_aic0opt, q_aic0opt] = find(aic0 == min(min(aic0)));
[p_bic0opt, q_bic0opt] = find(bic0 == min(min(bic0)));
% GARCH(p,q) with Student-t errors
mdlGT = garch(p,q); mdlGT.Offset = NaN; mdlGT.Distribution = 't';
[EstMdl, EstParamCov, LLF, info] = estimate(mdlGT, is_ret(:,i), 'display', 'off');
aict0(p,q) = -2*LLF+2*(p+q+1);
bict0(p,q) = -2*LLF+log(length(is_ret))*(p+q+1);
[p_aict0opt, q_aict0opt] = find(aict0 == min(min(aict0)));
[p_bict0opt, q_bict0opt] = find(bict0 == min(min(bict0)));
garch_optpq(i,:) = table([p_aic0opt, q_aic0opt, min(min(aic0))], ...
[p_bic0opt, q_bic0opt, min(min(bic0))], ...
[p_aict0opt, q_aict0opt, min(min(aict0))], ...
[p_bict0opt, q_bict0opt, min(min(bict0))]);
end
end
end
garch_optpq.Properties.VariableNames = {'GARCH_AIC','GARCH_BIC','GARCH_t_AIC','GARCH_t_BIC'};
garch_optpq.Properties.RowNames = stocks
%===================================================
% +++ Part 3 build model and forecast(v) AR-GARCH: +++
%===================================================
% Use AIC and BIC to choose a suitable AR(1)-GARCH(p,q) or AR(2)-GARCH(p,q) model with either Gaussian or Student-t errors.
aic1 = 0; bic1 = 0; aict1 = 0; bict1 = 0; aic2 = 0; bic2 = 0; aict2 = 0; bict2 = 0;LLF = 0;
for i=1:5
for p=1:5
for q=1:5
% AR(1)-GARCH(p,q) with Gaussian errors
mdlAGG = arima('ARLags', 1, 'Variance', garch(p,q)); mdlAGG.Distribution = 'Gaussian';
[EstMdl, EstParamCov, LLF, info] = estimate(mdlAGG, is_ret(:,i), 'display', 'off');
aic1(p,q) = -2*LLF+2*(p+q+1);
bic1(p,q) = -2*LLF+log(length(is_ret))*(p+q+1);
[p_aic1opt, q_aic1opt] = find(aic1 == min(min(aic1)));
[p_bic1opt, q_bic1opt] = find(bic1 == min(min(bic1)));
% AR(1)-GARCH(p,q) with Studnet-t errors
mdlAGT = arima('ARLags', 1, 'Variance', garch(p,q)); mdlAGG.Distribution = 't';
[EstMdl, EstParamCov, LLF, info] = estimate(mdlAGT, is_ret(:,i), 'display', 'off');
aict1(p,q) = -2*LLF+2*(p+q+2);
bict1(p,q) = -2*LLF+log(length(is_ret))*(p+q+2);
[p_aict1opt, q_aict1opt] = find(aict1 == min(min(aict1)));
[p_bict1opt, q_bict1opt] = find(bict1 == min(min(bict1)));
% AR(2)-GARCH(p,q) with Gaussian errors
mdlAGG = arima('ARLags', 2, 'Variance', garch(p,q)); mdlAGG.Distribution = 'Gaussian';
[EstMdl, EstParamCov, LLF, info] = estimate(mdlAGG, is_ret(:,i), 'display', 'off');
aic2(p,q) = -2*LLF+2*(p+q+2);
bic2(p,q) = -2*LLF+log(length(is_ret))*(p+q+2);
[p_aic2opt, q_aic2opt] = find(aic2 == min(min(aic2)));
[p_bic2opt, q_bic2opt] = find(bic2 == min(min(bic2)));
% AR(2)-GARCH(p,q) with Studnet-t errors
mdlAGT = arima('ARLags', 2, 'Variance', garch(p,q)); mdlAGG.Distribution = 't';
[EstMdl, EstParamCov, LLF, info] = estimate(mdlAGT, is_ret(:,i), 'display', 'off');
aict2(p,q) = -2*LLF+2*(p+q+3);
bict2(p,q) = -2*LLF+log(length(is_ret))*(p+q+3);
[p_aict2opt, q_aict2opt] = find(aict2 == min(min(aict2)));
[p_bict2opt, q_bict2opt] = find(bict2 == min(min(bict2)));
argarch_optpq(i,:) = table([p_aic1opt, q_aic1opt, min(min(aic1))], ...
[p_bic1opt, q_bic1opt, min(min(bic1))], ...
[p_aict1opt, q_aict1opt, min(min(aict1))], ...
[p_bict1opt, q_bict1opt, min(min(bict1))], ...
[p_aic2opt, q_aic2opt, min(min(aic2))], ...
[p_bic2opt, q_bic2opt, min(min(bic2))], ...
[p_aict2opt, q_aict2opt, min(min(aict2))], ...
[p_bict2opt, q_bict2opt, min(min(bict2))]);
end
end
end
argarch_optpq.Properties.VariableNames = {'AR1_GARCH_AIC','AR1_GARCH_BIC',...
'AR1_GARCH_t_AIC','AR1_GARCH_t_BIC', 'AR2_GARCH_AIC','AR2_GARCH_BIC', ...
'AR2_GARCH_t_AIC','AR2_GARCH_t_BIC'};
argarch_optpq.Properties.RowNames = stocks
%===================================================
% +++ Part 3 build model and forecast(vi) GJR-GARCH: +++
%===================================================
% Use AIC and BIC to choose a suitable GJR-GARCH(p,q) model with either Gaussian or Student-t errors.
aic3 = 0; bic3 = 0; aict3 = 0; bict3 = 0; LLF = 0;
for i=1:5
for p=1:5
for q=1:5
% GJR-GARCH(p,q) with Gaussian errors
mdlGJR = gjr(p,q); mdlGJR.Offset = NaN; mdlGJR.Distribution = 'Gaussian';
[EstMdl, EstParamCov, LLF, info] = estimate(mdlGJR, is_ret(:,i), 'display', 'off');
aic3(p,q) = -2*LLF+2*(p+q);
bic3(p,q) = -2*LLF+log(length(is_ret))*(p+q);
[p_aic3opt, q_aic3opt] = find(aic3 == min(min(aic3)));
[p_bic3opt, q_bic3opt] = find(bic3 == min(min(bic3)));
% GJR-GARCH(p,q) with Student-t errors
mdlGJRt = gjr(p,q); mdlGJRt.Distribution='t'; mdlGJRt.Offset=NaN; % specify model
[EstMdl,EstParamCov,LLF,info] = estimate(mdlGJRt, is_ret(:,i), 'display', 'off');
aict3(p,q) = -2*LLF+2*(p+q+1);
bict3(p,q) = -2*LLF+log(length(is_ret))*(p+q+1);
[p_aict3opt, q_aict3opt] = find(aict3 == min(min(aict3)));
[p_bict3opt, q_bict3opt] = find(bict3 == min(min(bict3)));
gjrgarch_optpq(i,:) = table([p_aic3opt, q_aic3opt, min(min(aic3))], ...
[p_bic3opt, q_bic3opt, min(min(bic3))], ...
[p_aict3opt, q_aict3opt, min(min(aict3))], ...
[p_bict3opt, q_bict3opt, min(min(bict3))]);
end
end
end
gjrgarch_optpq.Properties.VariableNames = {'GJR_GARCH_AIC','GJR_GARCH_BIC','GJR_GARCH_t_AIC','GJR_GARCH_t_BIC'};
gjrgarch_optpq.Properties.RowNames = stocks
%%
% Then, we choose to fit GARCH(1,1)-t to all series, as chosen by BIC
% AND, we choose to fit AR-GARCH(p,q)-t to different series by AIC
% AND, we choose to fit GJR-GARCH(1,1)-t to all series, as chosen by BIC
% Create variables to store conditional variance for each model
sigGt = zeros(length(is_ret), 1);
sigAGt = zeros(length(is_ret), 1);
sigGJRt = zeros(length(is_ret), 1);
for i=1:5
% Fit the GARCH(1,1)-t model to PSX series
mdlGT = garch(1,1); mdlGT.Offset = NaN; mdlGT.Distribution = 't';
[EstMdl_gt, EstParamCov, LLF, info] = estimate(mdlGT, is_ret(:,i));
% Infer the conditional variance and calculate standard deviations
v = infer(EstMdl_gt, is_ret(:,i)); sd = sqrt(v);
invt = is_ret(:,i) - EstMdl_gt.Offset; % Innovation calculation
s_rsd = invt./sd; % Standardised residuals
sigGt = [sigGt sd];
% Plot the standardised residuals, conditional standard deviations and log returns
figure; subplot(3,1,1); plot(Date(2:s), s_rsd);
title(strcat('GARCH(1,1)-t Standardised Residuals,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(3,1,2); plot(Date(2:s), sd);
title(strcat('GARCH(1,1)-t Conditional Standard Deviations,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(3,1,3); plot(Date(2:s), is_ret(:,i));
title(strcat('Log Returns,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
figure; plot(Date(2:s), is_ret(:,i), 'c'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
hold on; plot(Date(2:s), sd, 'r'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title(strcat('Log Returns and GARCH(1,1)-t Conditional Standard Deviations,', stocks(i)));
legend('Log returns', 'Conditional standard deviations', 'location','south','orientation','horizontal');
df = EstMdl_gt.Distribution.DoF;
% Assess fit to data
e1 = sqrt(df)/sqrt(df-2)*s_rsd; % This should have a Student-t with df degrees of freedom
eg = norminv(tcdf(e1, df)); % Transform to normal errors for diagnostic analysis
figure; subplot(2,1,1); plot(Date(2:s), eg);
title(strcat('GARCH(1,1)-t Standardised Residuals,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title(strcat('GARCH(1,1)-t Transformed Standardised Residuals,', stocks(i)));
subplot(2,1,2); autocorr(eg);
figure; subplot(2,1,1); hist(eg, 30);
title(strcat('Histogram of GARCH(1,1)-t Transformed Standardised Residuals,', stocks(i)));
subplot(2,1,2); qqplot(eg);
title(strcat('Q-Q Plot of GARCH(1,1)-t Transformed Standardised Residuals, ', stocks(i)));
figure; autocorr(eg.^2);
title(strcat('ACF of GARCH(1,1)-t Squared Transformed Standardised Residuals, ', stocks(i)));
% LB test on standardised residuals
[H_gt1,pValue_gt1,Qstat_gt1,CriVal_gt1] = lbqtest(eg, [7, 12], 0.05, [5 10]);
% LB test on squared standardised residuals
[H_gt2,pValue_gt2,Qstat_gt2,CriVal_gt2] = lbqtest(eg.^2, [7, 12], 0.05, [5 10]);
% JB test
skewness_gt = skewness(eg); kurtosis_gt = kurtosis(eg);
[h_gt, p_gt] = jbtest(eg);
garch_fit(i,:) = table(pValue_gt1(1),pValue_gt1(2),pValue_gt2(1),pValue_gt2(2),p_gt,skewness_gt,kurtosis_gt);
if i==1
% Fit the AR(1)-GARCH(1,1)-t model to BX series
mdlAGT_bx = arima('ARLags', 1, 'Variance', garch(1,1), 'Distribution', 'T');
[EstMdl_agt_bx, EstParamCov, LLF, info] = estimate(mdlAGT_bx, is_ret(:,i));
% Infer the conditional variance and calculate standard deviations
[e_agt_bx, v_agt_bx, logL] = infer(EstMdl_agt_bx, is_ret(:,i));
sd = sqrt(v_agt_bx);
s_rsd = e_agt_bx./sd; % Standardised residuals
df = EstMdl_agt_bx.Distribution.DoF;
elseif i==2
% Fit the AR(1)-GARCH(5,1)-t model to CTB series
mdlAGT_ctb = arima('ARLags', 1, 'Variance', garch(5,1), 'Distribution', 'T');
[EstMdl_agt_ctb, EstParamCov, LLF, info] = estimate(mdlAGT_ctb, is_ret(:,i));
% Infer the conditional variance and calculate standard deviations
[e_agt_ctb, v_agt_ctb, logL] = infer(EstMdl_agt_ctb, is_ret(:,i));
sd = sqrt(v_agt_ctb);
s_rsd = e_agt_ctb./sd; % Standardised residuals
df = EstMdl_agt_ctb.Distribution.DoF;
elseif i==3
% Fit the AR(1)-GARCH(4,2)-t model to PSX series
mdlAGT_psx = arima('ARLags', 1, 'Variance', garch(4,2), 'Distribution', 'T');
[EstMdl_agt_psx, EstParamCov, LLF, info] = estimate(mdlAGT_psx, is_ret(:,i));
% Infer the conditional variance and calculate standard deviations
[e_agt_psx, v_agt_psx, logL] = infer(EstMdl_agt_psx, is_ret(:,i));
sd = sqrt(v_agt_psx);
s_rsd = e_agt_psx./sd; % Standardised residuals
df = EstMdl_agt_psx.Distribution.DoF;
elseif i==4
% Fit the AR(1)-GARCH(1,1)-t model to JNJ series
mdlAGT_jnj = arima('ARLags', 1, 'Variance', garch(1,1), 'Distribution', 'T');
[EstMdl_agt_jnj, EstParamCov, LLF, info] = estimate(mdlAGT_jnj, is_ret(:,i));
% Infer the conditional variance and calculate standard deviations
[e_agt_jnj, v_agt_jnj, logL] = infer(EstMdl_agt_jnj, is_ret(:,i));
sd = sqrt(v_agt_jnj);
s_rsd = e_agt_jnj./sd; % Standardised residuals
df = EstMdl_agt_jnj.Distribution.DoF;
else
% Fit the AR(1)-GARCH(1,3)-t model to LBYTA series
mdlAGT_lbyta = arima('ARLags', 1, 'Variance', garch(1,3), 'Distribution', 'T');
[EstMdl_agt_lbyta, EstParamCov, LLF, info] = estimate(mdlAGT_lbyta, is_ret(:,i));
% Infer the conditional variance and calculate standard deviations
[e_agt_lbyta, v_agt_lbyta, logL] = infer(EstMdl_agt_lbyta, is_ret(:,i));
sd = sqrt(v_agt_lbyta);
s_rsd = e_agt_lbyta./sd; % Standardised residuals
df = EstMdl_agt_lbyta.Distribution.DoF;
end
sigAGt = [sigAGt sd];
% Plot the standardised residuals, conditional standard deviations and log returns
figure; subplot(3,1,1); plot(Date(2:s), s_rsd);
title(strcat('AR(1)-GARCH-t Standardised Residuals,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(3,1,2); plot(Date(2:s), sd);
title(strcat('AR(1)-GARCH-t Conditional Standard Deviations,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(3,1,3); plot(Date(2:s), is_ret(:,i));
title(strcat('Log Returns,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
figure; plot(Date(2:s), is_ret(:,i), 'c'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
hold on; plot(Date(2:s), sd, 'r'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title(strcat('Log Returns and AR(1)-GARCH-t Conditional Standard Deviations,', stocks(i)));
legend('Log returns', 'Conditional standard deviations', 'location','south','orientation','horizontal');
% Assess fit to data
e1 = sqrt(df)/sqrt(df-2)*s_rsd; % This should have a Student-t with df degrees of freedom
eg = norminv(tcdf(e1, df)); % Transform to normal errors for diagnostic analysis
figure; subplot(2,1,1); plot(Date(2:s), eg);
title(strcat('AR(1)-GARCH-t Standardised Residuals,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title(strcat('AR(1)-GARCH-t Transformed Standardised Residuals,', stocks(i)));
subplot(2,1,2); autocorr(eg);
figure; subplot(2,1,1); hist(eg, 30);
title(strcat('Histogram of AR(1)-GARCH-t Transformed Standardised Residuals,', stocks(i)));
subplot(2,1,2); qqplot(eg);
title(strcat('Q-Q Plot of AR(1)-GARCH-t Transformed Standardised Residuals, ', stocks(i)));
figure; autocorr(eg.^2);
title(strcat('ACF of AR(1)-GARCH-t Squared Transformed Standardised Residuals, ', stocks(i)));
if i==1 || i==4
% LB test on standardised residuals
[H_agt1,pValue_agt1,Qstat_agt1,CriVal_agt1] = lbqtest(eg, [8, 13], 0.05, [5 10]);
% LB test on squared standardised residuals
[H_agt2,pValue_agt2,Qstat_agt2,CriVal_agt2] = lbqtest(eg.^2, [8, 13], 0.05, [5 10]);
elseif i==2 || i==3
% LB test on standardised residuals
[H_agt1,pValue_agt1,Qstat_agt1,CriVal_agt1] = lbqtest(eg, [12, 17], 0.05, [5 10]);
% LB test on squared standardised residuals
[H_agt2,pValue_agt2,Qstat_agt2,CriVal_agt2] = lbqtest(eg.^2, [12, 17], 0.05, [5 10]);
else
% LB test on standardised residuals
[H_agt1,pValue_agt1,Qstat_agt1,CriVal_agt1] = lbqtest(eg, [10, 15], 0.05, [5 10]);
% LB test on squared standardised residuals
[H_agt2,pValue_agt2,Qstat_agt2,CriVal_agt2] = lbqtest(eg.^2, [10, 15], 0.05, [5 10]);
end
% JB test
skewness_agt = skewness(eg); kurtosis_agt = kurtosis(eg);
[h_agt, p_agt] = jbtest(eg);
argarch_fit(i,:) = table(pValue_agt1(1),pValue_agt1(2),pValue_agt2(1),pValue_agt2(2),p_agt,skewness_agt,kurtosis_agt);
% Fit the GJR-GARCH(1,1)-t model to PSX series
mdlGJRt = gjr(1,1); mdlGJRt.Offset = NaN; mdlGJRt.Distribution = 't';
[EstMdl_gjrt, EstParamCov, LLF, info] = estimate(mdlGJRt, is_ret(:,i));
% Infer the conditional variance and calculate standard deviations
v = infer(EstMdl_gjrt, is_ret(:,i)); sd = sqrt(v);
invt = is_ret(:,i) - EstMdl_gjrt.Offset; % Innovation calculation
s_rsd = invt./sd; % Standardised residuals
sigGJRt = [sigGJRt sd]; aGJt = invt; sigGJt = sd;
% Plot the standardised residuals, conditional standard deviations and log returns
figure; subplot(3,1,1); plot(Date(2:s), s_rsd);
title(strcat('GJR-GARCH(1,1)-t Standardised Residuals,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(3,1,2); plot(Date(2:s), sd);
title(strcat('GJR-GARCH(1,1)-t Conditional Standard Deviations,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
subplot(3,1,3); plot(Date(2:s), is_ret(:,i));
title(strcat('Log Returns,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
figure; plot(Date(2:s), is_ret(:,i), 'c'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
hold on; plot(Date(2:s), sd, 'r'); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title(strcat('Log Returns and GJR-GARCH(1,1)-t Conditional Standard Deviations,', stocks(i)));
legend('Log returns', 'Conditional standard deviations', 'location','south','orientation','horizontal');
df = EstMdl_gjrt.Distribution.DoF;
% Assess fit to data
e1 = sqrt(df)/sqrt(df-2)*s_rsd; % This should have a Student-t with df degrees of freedom
eg = norminv(tcdf(e1, df)); % Transform to normal errors for diagnostic analysis
figure; subplot(2,1,1); plot(Date(2:s), eg);
title(strcat('GJR-GARCH(1,1)-t Standardised Residuals,', stocks(i))); datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
title(strcat('GJR-GARCH(1,1)-t Transformed Standardised Residuals,', stocks(i)));
subplot(2,1,2); autocorr(eg);
figure; subplot(2,1,1); hist(eg, 30);
title(strcat('Histogram of GJR-GARCH(1,1)-t Transformed Standardised Residuals,', stocks(i)));
subplot(2,1,2); qqplot(eg);
title(strcat('Q-Q Plot of GJR-GARCH(1,1)-t Transformed Standardised Residuals, ', stocks(i)));
figure; autocorr(eg.^2);
title(strcat('ACF of GJR-GARCH(1,1)-t Squared Transformed Standardised Residuals, ', stocks(i)));
% LB test on standardised residuals
[H_gt1,pValue_gt1,Qstat_gt1,CriVal_gt1] = lbqtest(eg, [9, 14], 0.05, [5 10]);
% LB test on squared standardised residuals
[H_gt2,pValue_gt2,Qstat_gt2,CriVal_gt2] = lbqtest(eg.^2, [9, 14], 0.05, [5 10]);
% JB test
skewness_gt = skewness(eg); kurtosis_gt = kurtosis(eg);
[h_gt, p_gt] = jbtest(eg);
gjrgarch_fit(i,:) = table(pValue_gt1(1),pValue_gt1(2),pValue_gt2(1),pValue_gt2(2),p_gt,skewness_gt,kurtosis_gt);
% To further create NIC plots for GJR-GARCH(1,1)-t
if i==2 || i==3
% Get required estimated GJR model coefficients
a1GJt=cell2mat(EstMdl_gjrt.ARCH); b1GJt=cell2mat(EstMdl_gjrt.GARCH);
g1GJt=cell2mat(EstMdl_gjrt.Leverage);
dfGJt=EstMdl_gjrt.Distribution.DoF;
a0GJt=EstMdl_gjrt.Constant;
% Caculate values for NIC plot
a=min(aGJt):0.01:max(aGJt); % range of plot
sg=var(aGJt); % sample variance of innovations
sigt = a0GJt+a1GJt*a.^2+b1GJt*sg+(g1GJt.*(a<0)).*(a.^2); % asymmetric curve values
sigt2=a0GJt+(a1GJt+g1GJt/2)*a.^2+b1GJt*sg; % symmetric curve values
% NIC plot for a(t-1)
figure; plot(a,sigt); axis([min(aGJt) max(aGJt) 0 max(sigt)]); hold on;
plot(a,sigt2,'r--'); legend('Asymmetric Curve','Symmetric Curve'); title(strcat('GJR-GARCH-t NIC curve for a(t-1),', stocks(i)));
% Compare precited conditional standard deviation values following positive and negative shocks of size 2
a=-2; sigtm2=a0GJt+a1GJt*a^2+b1GJt*sg+(g1GJt*(a<0))*(a^2);
a=2; sigta2=a1GJt+a1GJt*a^2+b1GJt*sg+(g1GJt*(a<0))*(a^2);
[sigtm2 sigta2 sigtm2/sigta2];
% calculate NIC curve - now plotted against standardised shocks
eps=aGJt./sigGJt;
e=min(eps):0.01:max(eps);
a=sqrt(sg)*e;
sigt=a0GJt+a1GJt*a.^2+b1GJt*sg+(g1GJt.*(a<0)).*(a.^2);
sigt2=a0GJt+(a1GJt+g1GJt/2)*a.^2+b1GJt*sg;
% Create NIC plot for e(t-1)
figure; plot(e,sigt); axis([min(e) max(e) 0 max(sigt)]); hold on;
plot(e,sigt2,'r--'); legend('Asymmetric Curve','Symmetric Curve'); title(strcat('GJR-t NIC curve for e(t-1),', stocks(i)));
end
% Create Plots for conditional standard deviations for different models
% in different series.
figure; plot(Date(2:s), sigGt(:, i+1), 'y', 'LineWidth', 2); hold on;
plot(Date(2:s), sigAGt(:, i+1), 'b', 'LineWidth', 2); hold on;
plot(Date(2:s), sigGJRt(:,i+1), 'r', 'LineWidth', 2);
title(strcat('Conditional Standard Deviations for GARCH-t, AR-GARCH-t and GJR-t,', stocks(i)));
datetick('x', 'mmm/yy'); xlim([min(Date(2:s)) max(Date(2:s))]);
legend('GARCH-t', 'AR-GARCH-t', 'GJR-GARCH-t', 'location', 'northwest');
end
% Decorate the table summarizing fit details
garch_fit.Properties.VariableNames = {'pVal_LBtest_Err_5','pVal_LBtest_Err_10','pVal_LBtest_SqarErr_5','pVal_LBtest_SqarErr_10',...
'pVal_JBtest_Err','Skewness_Err','Kurtosis_Err'};
garch_fit.Properties.RowNames = stocks
argarch_fit.Properties.VariableNames = {'pVal_LBtest_Err_5','pVal_LBtest_Err_10','pVal_LBtest_SqarErr_5','pVal_LBtest_SqarErr_10',...
'pVal_JBtest_Err','Skewness_Err','Kurtosis_Err'};
argarch_fit.Properties.RowNames = stocks
gjrgarch_fit.Properties.VariableNames = {'pVal_LBtest_Err_5','pVal_LBtest_Err_10','pVal_LBtest_SqarErr_5','pVal_LBtest_SqarErr_10',...
'pVal_JBtest_Err','Skewness_Err','Kurtosis_Err'};
gjrgarch_fit.Properties.RowNames = stocks
% Delete the first column in each conditional variance for later plotting
sigGt(:,1) = []; sigAGt(:,1) = []; sigGJRt(:,1) = [];
%%
%====================================================
% +++ Part Four (i) voltility forecast measurement +++
%====================================================
% Generate forecasts for returns and volatility
% Initialise vectors for keeping return and volatility forecasts
sig_bx = 0; sig_ctb = 0; sig_psx = 0; sig_jnj = 0; sig_lbyta = 0;
ret_bx = 0; ret_ctb = 0; ret_psx = 0; ret_jnj = 0; ret_lbyta = 0;
upper_bx = 0; upper_ctb = 0; upper_psx = 0; upper_jnj = 0; upper_lbyta = 0;
lower_bx = 0; lower_ctb = 0; lower_psx = 0; lower_jnj = 0; lower_lbyta = 0;
% Initialise vectors for storing VaR forecasts
VaR1_bx = 0; VaR1_ctb = 0; VaR1_psx = 0; VaR1_jnj = 0; VaR1_lbyta = 0;
VaR5_bx = 0; VaR5_ctb = 0; VaR5_psx = 0; VaR5_jnj = 0; VaR5_lbyta = 0;
% Specify models for each series
mdlGT = garch(1,1); mdlGT.Distribution = 't'; mdlGT.Offset = NaN;
mdlAGT_bx = arima('ARLags', 1, 'Variance', garch(1,1), 'Distribution', 'T');
mdlAGT_ctb = arima('ARLags', 1, 'Variance', garch(5,1), 'Distribution', 'T');
mdlAGT_psx = arima('ARLags', 1, 'Variance', garch(4,2), 'Distribution', 'T');
mdlAGT_jnj = arima('ARLags', 1, 'Variance', garch(1,1), 'Distribution', 'T');
mdlAGT_lbyta = arima('ARLags', 1, 'Variance', garch(1,3), 'Distribution', 'T');
mdlGJRt = gjr(1,1); mdlGJRt.Distribution = 't'; mdlGJRt.Offset = NaN;
for t=1:length(f_ret)
% Create the training set to fit models
series_fit = full_ret(t:t+length(is_ret)-1, :);
% Fit or Re-fit the model at specified period
if mod(t, 5) == 0 || t == 1
% 1. BX series
% GARCH(1,1) model
[EstMdl_gt_bx, EstParamCov, LLF, info] = estimate(mdlGT, series_fit(:,1), 'display', 'off');
v_gt_bx = infer(EstMdl_gt_bx, series_fit(:,1));
sd_gt_bx = sqrt(v_gt_bx); dfGt_bx = EstMdl_gt_bx.Distribution.DoF;
% AR(1)-GARCH(1,1) model
[EstMdl_agt_bx, EstParamCov, LLF, info] = estimate(mdlAGT_bx, series_fit(:,1), 'display', 'off');
[e_agt_bx, v_agt_bx, logL] = infer(EstMdl_agt_bx, series_fit(:,1));
sd_agt_bx = sqrt(v_agt_bx); dfAGt_bx = EstMdl_agt_bx.Distribution.DoF;
% GJR-GARCH(1,1) MODEL
[EstMdl_gjrt_bx, EstParamCov, LLF, info] = estimate(mdlGJRt, series_fit(:,1), 'display', 'off');
v_gjrt_bx = infer(EstMdl_gjrt_bx, series_fit(:,1));
sd_gjrt_bx = sqrt(v_gjrt_bx); dfGJRt_bx = EstMdl_gjrt_bx.Distribution.DoF;
% Save phi0 = constant in mean equations
p0Gt_bx = EstMdl_gt_bx.Offset; p0GJRt_bx = EstMdl_gjrt_bx.Offset;
% 2. CTB series
% GARCH(1,1) model
[EstMdl_gt_ctb, EstParamCov, LLF, info] = estimate(mdlGT, series_fit(:,2), 'display', 'off');
v_gt_ctb = infer(EstMdl_gt_ctb, series_fit(:,2));
sd_gt_ctb = sqrt(v_gt_ctb); dfGt_ctb = EstMdl_gt_ctb.Distribution.DoF;