-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathML_TVP_DFM_estimate.py
More file actions
1648 lines (1382 loc) · 67.7 KB
/
Copy pathML_TVP_DFM_estimate.py
File metadata and controls
1648 lines (1382 loc) · 67.7 KB
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
"""
Multi-Level TVP-DFM Gibbs Estimation
This file contains functions for estimating a multi-level dynamic factor model
with time-varying loadings and stochastic volatility as used in Del Negro and
Otrok (2008). The main function is "gibbs", which uses the defined conditional
posterior samplers to generate draws from the model's joint posterior, and
uses those to compute the time-varying variance decompositions.
Functions:
----------
* Sigma_comp : computes part of the variance of the first p observations
of an AR(p) process
* Psi_comp : computes part of the density kernel for sampling the
AR parameters of series i
* Psi_0_comp : computes part of the density kernel for sampling the
AR parameters of a factor
* S_i_comp : computes part of the variance of the first p observations
of series i
* var_arsv_comp : computes path of variance of AR process with stochastic
volatility from t=1 onwards
* a_s2_i_sampler : draws constants and non time-varying variance components
* phi_i_sampler : draws AR parameters in idiosyncratic processes
* phi_0_sampler : draws AR parameters in factor processes
* s2_eta_i_sampler : draws innovation variances of loading processes
* s2_zeta_sampler : draws innovation variances of stochastic volatility
processes of series or factors
* f_w_sampler : draws world factor
* f_k_sampler : draws group k factor
* b_i_sampler : draws world or group loadings
* h_i_sampler : draws stochastic volatility components of series i
* h_0_sampler : draws stochastic volatility components of factors
* gibbs : performs the Gibbs sampling procedure using the above
sampling functions and returns a dictionary of Gibbs draws
Imports:
--------
* pandas
* numpy
* datetime
References:
-----------
Del Negro, M. & Otrok, C. (2008). Dynamic Factor Models with Time-Varying
Parameters: Measuring Changes in International Business Cycles (Staff Report
No. 326). Federal Reserve Bank of New York.
DOI: https://dx.doi.org/10.2139/ssrn.1136163
Kim, S., Shephard, N. & Chib, S. (1998). Stochastic Volatility: Likelihood
Inference and Comparison with ARCH Models. Review of Economic Studies, 65(3),
361–393. DOI: https://doi.org/10.1111/1467-937X.00050
Omori, Y., Chib, S., Shephard, N. \& Nakajima, J. (2007). Stochastic Volatility
with Leverage: Fast and Efficient Likelihood Inference. Journal of Econometrics,
140(2), 425–449. DOI: https://doi.org/10.1016/j.jeconom.2006.07.008
Otrok, C. & Whiteman, C. H. (1998). Bayesian Leading Indicators: Measuring and
Predicting Economic Conditions in Iowa. International Economic Review, 39(4),
997–1014. DOI: https://doi.org/10.2307/2527349
"""
# import packages
import pandas as pd
import numpy as np
from datetime import datetime
## Functions used in Samplers -------------------------------------------------
# Compute Sigma_i
def Sigma_comp(phi_i):
'''
Compute Sigma_i part of covariance matrix of first p observations of AR(p)
process. See Otrok & Whiteman (1998) p.1001.
phi_i : vector of AR(p) paremeters in error process of series i (px1)
'''
# define lag order p
p = len(phi_i)
# create companion matrix
Phi_i = np.zeros((p,p))
Phi_i[0] = phi_i
if p>1:
Phi_i[1:,:p-1] = np.identity(p-1)
# define e = (1,0,...,0)'(1,0,...,0)
e = np.zeros((p,p))
e[0,0] = 1
# compute and return Sigma
return np.dot(np.linalg.pinv(np.identity(p**2)-np.kron(Phi_i, Phi_i)),
e.flatten()).reshape((p,p), order='F')
# Compute Psi_i
def Psi_comp(y_i, f_w, f_k, a_i, b_w_i, b_k_i, phi_i, eh_i, s2_i, p):
'''
Compute Psi(phi_i) part of density kernel for sampling AR parameters phi_i
of error series i. See Del Negro & Otrok (2008) pp.29-31.
y_i : vector of observations on series i (Tx1)
f_w : vector of world factor values (Tx1)
f_k : vector of group factor values (Tx1)
a_i : intercept of series i
b_w_i : vector of world loadings of series i (Tx1)
b_k_i : vector of group loadings of series i (Tx1)
phi_i : vector of AR(p) paremeters for error process of series i (px1)
eh_i : vector of SV part of error process of series i (Tx1)
s2_i : non time-varying component of innovation variance of series i
p : order of AR(p) error process
'''
# comupte S_i
S_i = S_i_comp(phi_i=phi_i, eh_i=eh_i, p=p)
# compute corresponding inverted Cholesky factor
Q_i_inv = np.linalg.pinv(np.linalg.cholesky(S_i))
# define y_i1_tilde and x_i1_tilde
y_i1_tilde = y_i[:p] - b_w_i[:p]*f_w[:p] - b_k_i[:p]*f_k[:p]
x_i1_tilde = np.ones(p)
# compute y_i1_tilde_star
y_i1_tilde_star = np.dot(Q_i_inv, y_i1_tilde)
# compute part of Psi_i (part in exponential)
err_i = y_i1_tilde_star - a_i*x_i1_tilde
Psi_i_part = -(1/(2*s2_i)) * np.dot(np.dot(err_i.transpose(), np.linalg.pinv(S_i)), err_i)
# compute and return Psi_i
return np.linalg.det(S_i)**(-0.5)*np.exp(Psi_i_part)
# Compute Psi_0
def Psi_0_comp(f, phi_0, s2_0, q):
'''
Compute Psi(phi_0) part of density kernel for sampling AR parameters phi_0
of factor processes. See Del Negro & Otrok (2008) p.31.
f : vector of factor values (Tx1)
phi_0 : vector of AR(q) paremeters in factor process (qx1)
s2_0 : non time-varying component of factor innovation variance
q : order of AR(q) factor process
'''
# compute Sigma_0
Sigma_0 = Sigma_comp(phi_0)
# compute part of Psi_0 (part in exponential)
Psi_0_part = -(1/(2*s2_0)) * np.dot(np.dot(f[:q].transpose(), np.linalg.pinv(Sigma_0)), f[:q])
# compute and return Psi_0
return np.linalg.det(Sigma_0)**(-0.5)*np.exp(Psi_0_part)
# Compute S_i
def S_i_comp(phi_i, eh_i, p):
'''
Compute S_i, part of variance of first p observations of series i.
phi_i : vector of AR(p) paremeters in error process of series i (px1)
eh_i : vector of SV part of error process of series i (Tx1)
p : order of AR(p) error process
'''
# create companion matrix
Phi_i = np.zeros((p,p))
Phi_i[0] = phi_i
if p>1:
Phi_i[1:,:p-1] = np.identity(p-1)
# define e_1 = [1 0 ... 0]'
e_1 = np.zeros(p)
e_1[0] = 1
# compute Z_i matrix
Z_i = np.zeros((p,p))
for j in range(p):
Z_i[:,j] = eh_i[p-1-j] * np.dot(np.linalg.matrix_power(Phi_i,j), e_1)
# compute Sigma_i
Sigma_i = Sigma_comp(phi_i)
# comupte S_i
Phi_i_p = np.linalg.matrix_power(Phi_i,p)
S_i = np.dot(np.dot(Phi_i_p, Sigma_i), Phi_i_p.transpose()) + np.dot(Z_i,Z_i.transpose())
# return S_i
return S_i
# Compute variances of AR process with stochastic volatility
def var_arsv_comp(phi, s2, h):
'''
Compute path of variances of AR process with stochastic volatility.
Needed for computation of variance decompositions. Assumes that no
stochastic volatility is present at t <= 0.
phi : array of AR coefficients
s2 : non time-varying variance part
h : random walk process of stochastic volatility components (Tx1)
'''
# get hyperparameters
T = len(h)
P = len(phi)
# compute time-varying variance part (e^h)**2
eh2 = np.exp(h)**2
# create companion matrix
Phi = np.zeros((P,P))
Phi[0,:] = phi
if P>1:
Phi[1:,:P-1] = np.identity(P-1)
# compute variance of u_tilde at time 0
var_u_tilde_0 = np.zeros((P,P))
var_u_tilde_0[0,0] = s2
# compute variance of process before SV (t<=0)
var_y_tilde = np.zeros((T+1,P,P))
var_y_tilde[0,:,:] = np.dot(np.linalg.inv(np.identity(P**2)-np.kron(Phi,Phi)),
var_u_tilde_0.flatten()).reshape((P,P), order='F')
# iteratively compute variance of process with SV (t>0)
var_y = np.zeros(T)
for t in range(T):
var_u_tilde_t = np.zeros((P,P))
var_u_tilde_t[0,0] = eh2[t]*s2
var_y_tilde[t+1,:,:] = (np.dot(np.dot(Phi, var_y_tilde[t,:,:]),
Phi.transpose())+var_u_tilde_t)
var_y[t] = var_y_tilde[t+1,0,0]
# return variance process
return var_y
## Conditional Distribution Samplers ------------------------------------------
# Sample a_i (intercepts) and s2_i (non time-varying variance components)
def a_s2_i_sampler(y_i, f_w, f_k, b_w_i, b_k_i, phi_i, eh_i, s2_i, a_bar_i,
A_bar_i, nu_bar_i, delta2_bar_i,T, p, RNG):
'''
Function for sampling intercepts a_i and non time-varying variance components
s^2_i. See Del Negro & Otrok (2008) pp. 29-30. The Inverse-Gamma prior on s^2_i
is parametrized as a Scaled-Inverse-Chi^2 distribution.
y_i : vector of observations on series i (Tx1)
f_w : vector of world factor values (Tx1)
f_k : vector of group factor values (Tx1)
b_w_i : vector of world loadings of series i (Tx1)
b_k_i : vector of group loadings of series i (Tx1)
phi_i : vector of AR(p) paremeters in error process of series i (px1)
eh_i : vector of SV part of error process of series i (Tx1)
s2_i : non time-varying component of innovation variance of series i
a_bar_i : mean of Normal prior on a_i
A_bar_i : precision of Normal prior on a_i
nu_bar_i : degrees of freedom of Inverse-Gamma prior on s^2_i
delta2_bar_i : scale parameter of Inverse-Gamma prior on s^2_i
T : number of time periods
p : order of AR(p) error process
RNG : numpy random number generator
'''
# comupte S_i
S_i = S_i_comp(phi_i=phi_i, eh_i=eh_i, p=p)
# compute corresponding inverted Cholesky factor
Q_i_inv = np.linalg.pinv(np.linalg.cholesky(S_i))
# define y_i1_tilde
y_i1_tilde = np.flip(y_i[:p] - b_w_i[:p]*f_w[:p] - b_k_i[:p]*f_k[:p])
# compute y_i1_tilde_star and x_i1_tilde_star
y_i1_tilde_star = np.dot(Q_i_inv, y_i1_tilde)
x_i1_tilde_star = np.dot(Q_i_inv, np.ones(p))
# define y_i2_tilde_star
y_i2_tilde_star = np.zeros(T-p)
y_i_esc = (y_i - b_w_i*f_w - b_k_i*f_k)/eh_i
for t in range(T-p):
y_i2_tilde_star[t] = y_i_esc[t+p] - np.sum(np.flip(phi_i)*y_i_esc[t:t+p])
# define x_i2_tilde_star
x_i2_tilde_star = (1 - np.sum(phi_i))/eh_i[p:]
# define y_i_tilde_star and x_i_tilde_star
y_i_tilde_star = np.hstack((y_i1_tilde_star, y_i2_tilde_star))
x_i_tilde_star = np.hstack((x_i1_tilde_star, x_i2_tilde_star))
# compute A_i_inv (variance of normal cond. posterior of a_i)
A_i_inv = 1/(A_bar_i + (1/s2_i)*np.dot(x_i_tilde_star.transpose(),x_i_tilde_star))
# compute mean of normal cond. posterior of a_i
mean_a_i = A_i_inv * (A_bar_i*a_bar_i + (1/s2_i)*np.dot(x_i_tilde_star.transpose(),y_i_tilde_star))
# sample new a_i
new_a_i = RNG.normal(mean_a_i, np.sqrt(A_i_inv))
# compute parameters of IG cond. posterior of s^2_i
e_i = y_i_tilde_star - new_a_i*x_i_tilde_star
nu = nu_bar_i + T
delta2 = (nu_bar_i*delta2_bar_i + np.dot(e_i.transpose(), e_i))/nu
# sample new s2_i
new_s2_i = (delta2*nu)/RNG.chisquare(nu)
# return new a_i and new s2_i
return new_a_i, new_s2_i
# Sample phi_i (AR coefficients in idiosyncratic processes)
def phi_i_sampler(y_i, f_w, f_k, a_i, b_w_i, b_k_i, phi_i, eh_i, s2_i,
phi_bar_i, V_bar_i, T, p, RNG):
'''
Function for sampling phi_i, the vector of AR(p) paremeters in the
error process of series i. See Del Negro & Otrok (2008) pp. 30-31.
y_i : vector of observations on series i (Tx1)
f_w : vector of world factor values (Tx1)
f_k : vector of group factor values (Tx1)
a_i : intercept of series i
b_w_i : vector of world loadings of series i (Tx1)
b_k_i : vector of group loadings of series i (Tx1)
phi_i : vector of AR(p) paremeters in error process of series i
(previous draw)
eh_i : vector of SV part of error process of series i (Tx1)
s2_i : non time-varying component of innovation variance of series i
phi_bar_i : mean vector of Normal prior on phi_i (px1)
V_bar_i : precision matrix of Normal prior on phi_i (pxp)
T : number of time periods
p : order of AR(p) error process
RNG : numpy random number generator
'''
# compute e_i_t
e_i_t = y_i - a_i - b_w_i*f_w - b_k_i*f_k
# compute e_i
e_i = e_i_t[p:] / eh_i[p:]
# compute E_i
E_i = np.zeros((T-p,p))
for j in range(p):
E_i[:,j] = e_i_t[p-(j+1):-(j+1)] / eh_i[p:]
# compute variance of normal part of cond. posterior of phi_i
V_i_inv = np.linalg.pinv(V_bar_i + (1/s2_i)*np.dot(E_i.transpose(),E_i))
# compute mean of normal part of cond. posterior of phi_i
mean_phi_i = np.dot(V_i_inv, (np.dot(V_bar_i,phi_bar_i) +
(1/s2_i)*np.dot(E_i.transpose(),e_i)))
# set indicator for stationarity and counter for tries
stationary = 0
iter = 0
# draw phi_i candidate until stationary or max. iter reached (50)
while not stationary:
# draw phi_i candidate
phi_i_new = mean_phi_i + np.dot(np.linalg.cholesky(V_i_inv),
RNG.normal(size=p))
# get roots of coefficients of corresponding lag polynomial
roots = np.roots(np.append(-np.flip(phi_i_new), 1))
# check for stationarity
if all(i >= 1.001 for i in abs(roots)):
# consider candidate if condition met
stationary = 1
else:
iter = iter + 1
if iter > 50:
# take previous value if stationarity not met after 50 tries
phi_i_new = phi_i
stationary = 1
# if no new draw was generated return previous phi_i
if all(phi_i_new == phi_i):
return phi_i
# if new draw was generated decide if to keep it
else:
# compute previous and new Psi_i
Psi_i_old = Psi_comp(y_i=y_i, f_w=f_w, f_k=f_k, a_i=a_i, b_w_i=b_w_i,
b_k_i=b_k_i, phi_i=phi_i, eh_i=eh_i, s2_i=s2_i,
p=p)
Psi_i_new = Psi_comp(y_i=y_i, f_w=f_w, f_k=f_k, a_i=a_i, b_w_i=b_w_i,
b_k_i=b_k_i, phi_i=phi_i_new, eh_i=eh_i, s2_i=s2_i,
p=p)
# accept or reject new draw
if Psi_i_old == 0:
accept = 1
else:
accept = RNG.uniform() < min(Psi_i_new/Psi_i_old, 1)
# return new or old draw of phi_i
return phi_i_new * accept + phi_i * (1-accept)
# Sample phi_0 (AR coefficients in factor processes)
def phi_0_sampler(f, phi_0, eh_0, s2_0, phi_bar_0, V_bar_0, T, q, RNG):
'''
Function for sampling phi_0, the vector of AR(q) paremeters for the
factor process. See Del Negro & Otrok (2008) pp. 30-31.
f : vector of factor values (Tx1)
phi_0 : vector of AR(q) paremeters in factor process (qx1) (previous draw)
eh_0 : vector of SV part of factor process (Tx1)
s2_0 : non time-varying component of factor innovation variance
phi_bar_0 : mean vector of Normal prior on phi_0 (qx1)
V_bar_0 : precision matrix of Normal prior on phi_0 (qxq)
T : number of time periods
q : order of AR(q) factor process
RNG : numpy random number generator
'''
# compute e_0
e_0 = f[q:] / eh_0[q:]
# compute E_0
E_0 = np.zeros((T-q,q))
for j in range(q):
E_0[:,j] = f[q-(j+1):-(j+1)] / eh_0[q:]
# compute variance of normal part of cond. posterior of phi_0
V_0_inv = np.linalg.pinv(V_bar_0 + (1/s2_0)*np.dot(E_0.transpose(),E_0))
# compute mean of normal part of cond. posterior of phi_0
mean_phi_0 = np.dot(V_0_inv, (np.dot(V_bar_0,phi_bar_0) +
(1/s2_0)*np.dot(E_0.transpose(),e_0)))
# set indicator for stationarity and counter for tries
stationary = 0
iter = 0
# draw phi_0 candidate until stationary or max. iter reached (50)
while not stationary:
# draw phi_i candidate
phi_0_new = mean_phi_0 + np.dot(np.linalg.cholesky(V_0_inv),
RNG.normal(size=q))
# get roots of coefficients of corresponding lag polynomial
roots = np.roots(np.append(-np.flip(phi_0_new), 1))
# check for stationarity
if all(i >= 1.001 for i in abs(roots)):
# consider candidate if condition met
stationary = 1
else:
iter = iter + 1
if iter > 50:
# take previous value if stationarity not met after 50 tries
phi_0_new = phi_0
stationary = 1
# if no new draw was generated return previous phi_0
if all(phi_0_new == phi_0):
return phi_0
# if new draw was generated decide if to keep it
else:
# compute previous and new Psi_0
Psi_0_old = Psi_0_comp(f=f, phi_0=phi_0, s2_0=s2_0, q=q)
Psi_0_new = Psi_0_comp(f=f, phi_0=phi_0_new, s2_0=s2_0, q=q)
# accept or reject new draw
if Psi_0_old == 0:
accept = 1
else:
accept = RNG.uniform() < min(Psi_0_new/Psi_0_old, 1)
# return new or old draw of phi_0
return phi_0_new * accept + phi_0 * (1-accept)
# Sample s2_eta_i (innovation variance of loading processes)
def s2_eta_i_sampler(b_i, nu_eta_bar_i, delta2_eta_bar_i, T, RNG):
'''
Function for sampling s^2_eta_i, the variance of the innovations
to the law of motions of the loadings. See Del Negro & Otrok (2008) p.11.
The Inverse-Gamma prior on s^2_eta_i is parametrized as a
Scaled-Inverse-Chi^2 distribution.
b_i : vector of loadings of series i (Tx1)
nu_eta_bar_i : degrees of freedom of Inverse-Gamma prior on s^2_eta_i
delta2_eta_bar_i : scale parameter of Inverse-Gamma prior on s^2_eta_i
T : number of time periods
RNG : numpy random number generator
'''
# compute posterior parameters
nu_eta = nu_eta_bar_i + T
delta2_eta = (nu_eta_bar_i*delta2_eta_bar_i +
np.sum((b_i[1:]-b_i[:-1])**2))/nu_eta
# draw and return new s2_eta_i
return (delta2_eta*nu_eta)/RNG.chisquare(nu_eta)
# Sample s2_zeta_i and s2_zeta_0 (innovation variance of SV processes)
def s2_zeta_sampler(h_i, nu_zeta_bar, delta2_zeta_bar, T, RNG):
'''
Function for sampling s^2_zeta_i and s^2_zeta_0, the variance of the
innovations to the law of motions of the stochastic volatilities.
See Del Negro & Otrok (2008) pp.11-12. The Inverse-Gamma priors are
parametrized as Scaled-Inverse-Chi^2 distributions.
h_i : vector of SV part of error process of series i or factor
nu_zeta_bar : degrees of freedom of Inverse-Gamma prior on s^2_zeta_i
(and on s^2_zeta_0)
delta2_zeta_bar : scale parameter of Inverse-Gamma prior on s^2_eta_i
(and on s^2_zeta_0)
T : number of time periods
RNG : numpy random number generator
'''
# compute posterior parameters
nu_zeta = nu_zeta_bar + T
delta2_zeta = (nu_zeta_bar*delta2_zeta_bar +
(h_i[0]**2 + np.sum((h_i[1:]-h_i[:-1])**2)))/nu_zeta
# draw and return new s2_zeta
return (delta2_zeta*nu_zeta)/RNG.chisquare(nu_zeta)
# Sample f_w (world factor)
def f_w_sampler(y, f_K, select_k, a, b_w, b_k, phi_w, phi, eh_w, eh,
s2_w, s2, T, n, p, q, RNG):
'''
Function for sampling world factor using Carter & Kohn Algorithm.
See Del Negro & Otrok (2008) pp.12-13. Assumes that q-1 = p, where
q is order of AR factor process and p is order of AR process of
idiosyncratic components.
y : matrix of observed series (Txn)
f_K : matrix of group factors (TxK)
select_k : list of group indicators (1xn)
a : vector of intercepts (nx1)
b_w : matrix of world loadings (Txn)
b_k : matrix of group loadings (Txn)
phi_w : vector of AR(q) paremeters in world factor process (qx1)
phi : matrix of AR(p) parameters in error processes (pxn)
eh_w : vector of SV part of world factor process (Tx1)
eh : matrix of SV part of error processes (Txn)
s2_w : non time-varying component of world factor innovation variance
s2 : vector of non time-varying components of innovation variances (nx1)
T : number of time periods
n : number of observed series
p : order of AR(p) error process
q : order of AR(q) factor process
RNG : numpy random number generator
'''
# create companion matrix
Phi_0 = np.zeros((q,q))
Phi_0[0] = phi_w
if q>1:
Phi_0[1:,:q-1] = np.identity(q-1)
# compute y_tilde_star
y_x = np.zeros((T,n))
for i in range(n):
y_x[:,i] = y[:,i] - b_k[:,i]*f_K[:,select_k[i]]
y_tilde_star = np.zeros((n, T-p))
for t in range(p,T):
for i in range(n):
y_tilde_star[i,t-p] = y_x[t,i] - np.sum(np.flip(phi[:,i]) *
y_x[t-p:t,i])
# compute a_tilde_star
a_tilde_star = np.zeros(n)
for i in range(n):
a_tilde_star[i] = a[i] - np.sum(phi[:,i] * a[i])
## START of copmuting initial conditions for Kalman Filter ---
# unconditional mean and variance of f_tilde_t
Q_0 = np.zeros((q,q))
Q_0[0,0] = s2_w
f_tilde_00 = np.zeros(q)
s_tilde_00 = np.dot(np.linalg.pinv(np.identity(q**2)-np.kron(Phi_0, Phi_0)),
Q_0.flatten()).reshape((q,q), order='F')
# I_y
I_y = np.zeros((p,n,n))
for j in range(p):
I_y[j,:,:] = np.identity(n)
I_y = np.vstack(I_y)
# B_bar_t for t = 1,...,p
B_bar = np.zeros((p,n,q))
for j in range(p):
B_bar[j,:,0] = b_w[j,:]
# B_y
B_y = np.zeros((p,n,q))
for j in range(p):
B_y[j,:,:] = np.dot(B_bar[-(j+1),:,:], np.linalg.matrix_power(Phi_0, p-j))
B_y = np.vstack(B_y)
# U_y
U_y = np.zeros((p,p,n,q))
for i in range(p):
for j in range(p-i):
U_y[j,j+i,:,:] = np.dot(B_bar[-(j+1),:,:],
np.linalg.matrix_power(Phi_0, i))
U_y = U_y.swapaxes(1,2).reshape((p*n,p*q))
# U_f
U_f = np.zeros((p,q,q))
for j in range(p):
U_f[j,:,:] = np.linalg.matrix_power(Phi_0, j)
U_f = np.hstack(U_f)
# s2_i*S_i for all i = 1,...,n
S = np.zeros((n,p,p))
for i in range(n):
S[i,:,:] = s2[i] * S_i_comp(phi_i=phi[:,i], eh_i=eh[:,i], p=p)
# Sigma_e_p1
Sigma_e_p1 = np.zeros((p,p,n,n))
for k in range(p):
for l in range(p):
Sigma_e_p1[k,l,:,:] = np.diag(S[:,k,l])
Sigma_e_p1 = Sigma_e_p1.swapaxes(1,2).reshape((p*n,p*n))
# Sigma_0
Sigma_0 = np.zeros((p*q, p*q))
for j in range(p):
Sigma_0[j*q,j*q] = s2_w * (eh_w[p-(j+1)]**2)
# y_tilde_p1
y_tilde_p1 = np.zeros((p,n))
for j in range(p):
y_tilde_p1[j,:] = y_x[p-(j+1),:]
y_tilde_p1 = y_tilde_p1.flatten()
# conditional mean and variance of f_tilde_p (computed in parts)
Phi_0_p = np.linalg.matrix_power(Phi_0, p)
fs1 = (np.dot(np.dot(Phi_0_p, s_tilde_00), B_y.transpose()) +
np.dot(np.dot(U_f, Sigma_0), U_y.transpose()))
fs2 = (np.dot(np.dot(B_y, s_tilde_00), B_y.transpose()) +
np.dot(np.dot(U_y, Sigma_0), U_y.transpose()))
fs3 = np.dot(fs1, np.linalg.pinv(fs2 + Sigma_e_p1))
f1 = np.dot(Phi_0_p, f_tilde_00)
f2 = y_tilde_p1 - np.dot(I_y, a) - np.dot(B_y, f_tilde_00)
ss1 = np.dot(np.dot(Phi_0_p, s_tilde_00), Phi_0_p.transpose())
ss2 = np.dot(np.dot(U_f, Sigma_0), U_f.transpose())
f_tilde_pp = f1 + np.dot(fs3, f2)
s_tilde_pp = ss1 + ss2 - np.dot(fs3, fs1.transpose())
## END of computing initial conditions for Kalman Filter ---
# empty arrays to store results of Kalman Filter
f_tilde_tt_store = np.zeros((T-p+1, q))
s_tilde_tt_store = np.zeros((T-p+1, q, q))
# assign initial conditions to storage
f_tilde_tt_store[0,:] = f_tilde_pp
s_tilde_tt_store[0,:,:] = s_tilde_pp
## START of Kalman Filter ---
# start loop from t=p+1 to T (note: Python indexes from 0)
for t in range(p, T):
# compute variances of innovations
Q_t = np.zeros((q,q))
Q_t[0,0] = s2_w * (eh_w[t]**2)
R_t = np.diag(s2 * (eh[t,:]**2))
# compute B_star_t
B_star_t = np.zeros((n, p+1))
B_star_t[:,0] = b_w[t,:]
for j in range(1,p+1):
B_star_t[:,j] = -b_w[t-j,:] * phi[j-1,:]
# forecast f_tilde_t
f_tilde_tt1 = np.dot(Phi_0, f_tilde_tt_store[t-p,:])
s_tilde_tt1 = np.dot(np.dot(Phi_0, s_tilde_tt_store[t-p,:,:]),
Phi_0.transpose()) + Q_t
# forecast y_tilde_star_t
y_tilde_star_tt1 = a_tilde_star + np.dot(B_star_t,f_tilde_tt1)
g_tt1 = np.dot(np.dot(B_star_t,s_tilde_tt1), B_star_t.transpose()) + R_t
# update forecast of f_tilde_t
K_t = np.dot(np.dot(s_tilde_tt1,B_star_t.transpose()),
np.linalg.pinv(g_tt1))
f_tilde_tt = f_tilde_tt1 + np.dot(K_t, (y_tilde_star[:,t-p] -
y_tilde_star_tt1))
s_tilde_tt = s_tilde_tt1 - np.dot(np.dot(K_t,B_star_t), s_tilde_tt1)
# store results
f_tilde_tt_store[t-p+1,:] = f_tilde_tt
s_tilde_tt_store[t-p+1,:,:] = s_tilde_tt
## END of Kalman Filter ---
# draw and store f_T from N(f_tilde_TT(1), s_tilde_TT(1,1))
f_store = np.zeros(T)
if s_tilde_tt_store[-1,0,0]>0:
f_store[-1] = (f_tilde_tt_store[-1,0] +
np.sqrt(s_tilde_tt_store[-1,0,0]) * RNG.normal())
else:
f_store[-1] = f_tilde_tt_store[-1,0] + 1e-6 * RNG.normal()
# move backwards in time and draw remaining f_t
for t in range(2, T-p+1):
# get mean and variance of N(f_tilde_ttpl1, s_tilde_ttpl1)
g_star_t = np.dot(np.dot(Phi_0[0,:], s_tilde_tt_store[-t,:,:]),
Phi_0[0,:].transpose()) + s2_w * (eh_w[-t+1]**2)
K_star_t = np.dot(s_tilde_tt_store[-t,:,:], Phi_0[0,:].transpose())/g_star_t
f_tilde_ttpl1 = f_tilde_tt_store[-t,:] + np.dot(K_star_t, (f_store[-t+1] -
np.dot(Phi_0[0,:], f_tilde_tt_store[-t,:])))
s_tilde_ttpl1 = s_tilde_tt_store[-t,:,:] - np.dot(np.outer(K_star_t,Phi_0[0,:]),
s_tilde_tt_store[-t,:,:])
# draw and store f_t
if s_tilde_ttpl1[0,0]>0:
f_store[-t] = f_tilde_ttpl1[0] + np.sqrt(s_tilde_ttpl1[0,0]) * RNG.normal()
else:
f_store[-t] = f_tilde_ttpl1[0] + 1e-6 * RNG.normal()
# draw first q in one go (f_1,...,f_q)
if t==(T-p):
try:
f_store[:q] = np.flip(f_tilde_ttpl1 + np.dot(np.linalg.cholesky(s_tilde_ttpl1),
RNG.normal(size=q)))
except:
shift = np.identity(q)*(-min(np.linalg.eigvals(s_tilde_ttpl1))+1e-6)
f_store[:q] = np.flip(f_tilde_ttpl1 + np.dot(np.linalg.cholesky(s_tilde_ttpl1+shift),
RNG.normal(size=q)))
# return new f
return f_store
# Sample f_k (group factor)
def f_k_sampler(y, f_w, a, b_w, b_k, phi_k, phi, eh_k, eh, s2_k, s2,
T, p, q, RNG):
'''
Function for sampling group k factor using Carter & Kohn Algorithm.
See Del Negro & Otrok (2008) pp.12-13. Assumes that q-1 = p, where
q is order of AR factor process and p is order of AR process of
idiosyncratic components.
y : matrix of observed series that belong to group k (Txn_k)
f_w : vector of world factor (Tx1)
a : vector of intercepts (n_kx1)
b_w : matrix of world loadings (Txn_k)
b_k : matrix of group loadings (Txn_k)
phi_k : vector of AR(q) paremeters in group k factor process (qx1)
phi : matrix of AR(p) parameters in error processes (pxn_k)
eh_k : vector of SV part of group k factor process (Tx1)
eh : matrix of SV part of error processes (Txn_k)
s2_k : non time-varying component of group k factor innovation variance
s2 : vector of non time-varying components of innovation variances (n_kx1)
T : number of time periods
p : order of AR(p) error process
q : order of AR(q) factor process
RNG : numpy random number generator
'''
# get number of observed series in group k
n_k = y.shape[1]
# create companion matrix
Phi_0 = np.zeros((q,q))
Phi_0[0] = phi_k
if q>1:
Phi_0[1:,:q-1] = np.identity(q-1)
# compute y_tilde_star
y_x = np.zeros((T,n_k))
for i in range(n_k):
y_x[:,i] = y[:,i] - b_w[:,i]*f_w
y_tilde_star = np.zeros((n_k, T-p))
for t in range(p,T):
for i in range(n_k):
y_tilde_star[i,t-p] = y_x[t,i] - np.sum(np.flip(phi[:,i]) *
y_x[t-p:t,i])
# compute a_tilde_star
a_tilde_star = np.zeros(n_k)
for i in range(n_k):
a_tilde_star[i] = a[i] - np.sum(phi[:,i] * a[i])
## START of computing initial conditions for Kalman Filter ---
# unconditional mean and variance of f_tilde_t
Q_0 = np.zeros((q,q))
Q_0[0,0] = s2_k
f_tilde_00 = np.zeros(q)
s_tilde_00 = np.dot(np.linalg.pinv(np.identity(q**2)-np.kron(Phi_0, Phi_0)),
Q_0.flatten()).reshape((q,q), order='F')
# I_y
I_y = np.zeros((p,n_k,n_k))
for j in range(p):
I_y[j,:,:] = np.identity(n_k)
I_y = np.vstack(I_y)
# B_bar_t for t = 1,...,p
B_bar = np.zeros((p,n_k,q))
for j in range(p):
B_bar[j,:,0] = b_k[j,:]
# B_y
B_y = np.zeros((p,n_k,q))
for j in range(p):
B_y[j,:,:] = np.dot(B_bar[-(j+1),:,:],
np.linalg.matrix_power(Phi_0, p-j))
B_y = np.vstack(B_y)
# U_y
U_y = np.zeros((p,p,n_k,q))
for i in range(p):
for j in range(p-i):
U_y[j,j+i,:,:] = np.dot(B_bar[-(j+1),:,:],
np.linalg.matrix_power(Phi_0, i))
U_y = U_y.swapaxes(1,2).reshape((p*n_k,p*q))
# U_f
U_f = np.zeros((p,q,q))
for j in range(p):
U_f[j,:,:] = np.linalg.matrix_power(Phi_0, j)
U_f = np.hstack(U_f)
# s2_i*S_i for all i in group k
S = np.zeros((n_k,p,p))
for i in range(n_k):
S[i,:,:] = s2[i] * S_i_comp(phi_i=phi[:,i], eh_i=eh[:,i], p=p)
# Sigma_e_p1
Sigma_e_p1 = np.zeros((p,p,n_k,n_k))
for k in range(p):
for l in range(p):
Sigma_e_p1[k,l,:,:] = np.diag(S[:,k,l])
Sigma_e_p1 = Sigma_e_p1.swapaxes(1,2).reshape((p*n_k,p*n_k))
# Sigma_0
Sigma_0 = np.zeros((p*q, p*q))
for j in range(p):
Sigma_0[j*q,j*q] = s2_k * (eh_k[p-(j+1)]**2)
# y_tilde_p1
y_tilde_p1 = np.zeros((p,n_k))
for j in range(p):
y_tilde_p1[j,:] = y_x[p-(j+1),:]
y_tilde_p1 = y_tilde_p1.flatten()
# conditional mean and variance of f_tilde_p (computed in parts)
Phi_0_p = np.linalg.matrix_power(Phi_0, p)
fs1 = (np.dot(np.dot(Phi_0_p, s_tilde_00), B_y.transpose()) +
np.dot(np.dot(U_f, Sigma_0), U_y.transpose()))
fs2 = (np.dot(np.dot(B_y, s_tilde_00), B_y.transpose()) +
np.dot(np.dot(U_y, Sigma_0), U_y.transpose()))
fs3 = np.dot(fs1, np.linalg.pinv(fs2 + Sigma_e_p1))
f1 = np.dot(Phi_0_p, f_tilde_00)
f2 = y_tilde_p1 - np.dot(I_y, a) - np.dot(B_y, f_tilde_00)
ss1 = np.dot(np.dot(Phi_0_p, s_tilde_00), Phi_0_p.transpose())
ss2 = np.dot(np.dot(U_f, Sigma_0), U_f.transpose())
f_tilde_pp = f1 + np.dot(fs3, f2)
s_tilde_pp = ss1 + ss2 - np.dot(fs3, fs1.transpose())
## END of computing initial conditions for Kalman Filter ---
# empty arrays to store results of Kalman Filter
f_tilde_tt_store = np.zeros((T-p+1, q))
s_tilde_tt_store = np.zeros((T-p+1, q, q))
# assign initial conditions to storage
f_tilde_tt_store[0,:] = f_tilde_pp
s_tilde_tt_store[0,:,:] = s_tilde_pp
## START of Kalman Filter ---
# start loop from t=p+1 to T (note: Python indexes from 0)
for t in range(p, T):
# compute variances of innovations
Q_t = np.zeros((q,q))
Q_t[0,0] = s2_k * (eh_k[t]**2)
R_t = np.diag(s2 * (eh[t,:]**2))
# compute B_star_t
B_star_t = np.zeros((n_k, p+1))
B_star_t[:,0] = b_k[t,:]
for j in range(1,p+1):
B_star_t[:,j] = -b_k[t-j,:] * phi[j-1,:]
# forecast f_tilde_t
f_tilde_tt1 = np.dot(Phi_0, f_tilde_tt_store[t-p,:])
s_tilde_tt1 = np.dot(np.dot(Phi_0, s_tilde_tt_store[t-p,:,:]),
Phi_0.transpose()) + Q_t
# forecast y_tilde_star_t
y_tilde_star_tt1 = a_tilde_star + np.dot(B_star_t,f_tilde_tt1)
g_tt1 = np.dot(np.dot(B_star_t,s_tilde_tt1), B_star_t.transpose()) + R_t
# update forecast of f_tilde_t
K_t = np.dot(np.dot(s_tilde_tt1,B_star_t.transpose()), np.linalg.pinv(g_tt1))
f_tilde_tt = f_tilde_tt1 + np.dot(K_t, (y_tilde_star[:,t-p] -
y_tilde_star_tt1))
s_tilde_tt = s_tilde_tt1 - np.dot(np.dot(K_t,B_star_t), s_tilde_tt1)
# store results
f_tilde_tt_store[t-p+1,:] = f_tilde_tt
s_tilde_tt_store[t-p+1,:,:] = s_tilde_tt
## END of Kalman Filter ---
# draw and store f_T from N(f_tilde_TT(1), s_tilde_TT(1,1))
f_store = np.zeros(T)
if s_tilde_tt_store[-1,0,0]>0:
f_store[-1] = (f_tilde_tt_store[-1,0] +
np.sqrt(s_tilde_tt_store[-1,0,0]) * RNG.normal())
else:
f_store[-1] = f_tilde_tt_store[-1,0] + 1e-6 * RNG.normal()
# move backwards in time and draw remaining f_t
for t in range(2, T-p+1):
# get mean and variance of N(f_tilde_ttpl1, s_tilde_ttpl1)
g_star_t = np.dot(np.dot(Phi_0[0,:], s_tilde_tt_store[-t,:,:]),
Phi_0[0,:].transpose()) + s2_k * (eh_k[-t+1]**2)
K_star_t = np.dot(s_tilde_tt_store[-t,:,:], Phi_0[0,:].transpose())/g_star_t
f_tilde_ttpl1 = f_tilde_tt_store[-t,:] + np.dot(K_star_t, (f_store[-t+1] -
np.dot(Phi_0[0,:], f_tilde_tt_store[-t,:])))
s_tilde_ttpl1 = s_tilde_tt_store[-t,:,:] - np.dot(np.outer(K_star_t,Phi_0[0,:]),
s_tilde_tt_store[-t,:,:])
# draw and store f_t
if s_tilde_ttpl1[0,0]>0:
f_store[-t] = f_tilde_ttpl1[0] + np.sqrt(s_tilde_ttpl1[0,0]) * RNG.normal()
else:
f_store[-t] = f_tilde_ttpl1[0] + 1e-6 * RNG.normal()
# draw first q in one go (f_1,...,f_q)
if t==(T-p):
try:
f_store[:q] = np.flip(f_tilde_ttpl1 + np.dot(np.linalg.cholesky(s_tilde_ttpl1),
RNG.normal(size=q)))
except:
shift = np.identity(q)*(-min(np.linalg.eigvals(s_tilde_ttpl1))+1e-6)
f_store[:q] = np.flip(f_tilde_ttpl1 + np.dot(np.linalg.cholesky(s_tilde_ttpl1+shift),
RNG.normal(size=q)))
# return new f
return f_store
# Sample b_w_i and b_k_i (world and group factor loadings)
def b_i_sampler(y_i, f, f_x, a_i, b_x_i, phi_i, eh_i, s2_i, s2_eta_i,
b_bar_i, B_bar_i, T, p, RNG):
'''
Function for sampling b_w_i or b_k_i, the random walk processes of world or
group loadings of series i, using Carter & Kohn Algorithm. See Del Negro &
Otrok (2008) pp.13-14 and 33-34.
y_i : vector of observations on series i (Tx1)
f : vector of factor values (Tx1)
(loadings on this factor are being estimated)
f_x : vector of factor values (other factor) (Tx1)
a_i : intercept of series i
b_x_i : vector of loadings on other factor, f_x (Tx1)
phi_i : vector of AR(p) paremeters in error process of series i (px1)
eh_i : vector of SV part of error process of series i (Tx1)
s2_i : non time-varying component of variance of error process of series i
s2_eta_i : variance of innovations to law of motions of loadings
b_bar_i : mean of Normal prior on b_i_0
B_bar_i : precision of Normal prior on b_i_0
T : number of time periods
p : order of AR(p) error process
RNG : numpy random number generator
'''
# compute y_star_i (t = p+1, ..., T)
y_x_i = y_i - b_x_i*f_x
y_star_i = np.zeros(T-p)
for t in range(p,T):
y_star_i[t-p] = y_x_i[t] - np.sum(np.flip(phi_i) * y_x_i[t-p:t])
# compute a_star_i
a_star_i = a_i - np.sum(phi_i * a_i)
## START of computing initial conditions for Kalman Filter ---
# unconditional mean and variance of b_i_0 (from prior)
b_bar_i_0 = b_bar_i
s_bar_i_0 = 1/B_bar_i
# needed parameters
I_y = np.ones(p)
B_y = np.flip(f[:p])
U_y = np.zeros((p,p))
for j in range(p):
U_y[j,j:] = np.repeat(f[p-(j+1)], p-j)
B_b = np.ones(p+1)
U_b = np.zeros((p+1, p))
for j in range(p):
U_b[:j+1,j] = np.ones(j+1)
# compute S_i
S_i = S_i_comp(phi_i=phi_i, eh_i=eh_i, p=p)
# conditional mean and variance of b_tilde_i_p (computed in parts)
b1 = (np.outer(B_b*s_bar_i_0, B_y.transpose()) +
s2_eta_i * np.dot(U_b, U_y.transpose()))
b2 = (np.outer(B_y*s_bar_i_0, B_y.transpose()) +
s2_eta_i * np.dot(U_y, U_y.transpose())) + s2_i*S_i
b3 = np.flip(y_x_i[:p]) - I_y*a_i - B_y*b_bar_i_0
b4 = np.dot(b1, np.linalg.pinv(b2))