├── MatlabRoutines ├── ReplicaForniGambetti │ ├── cols.m │ ├── rows.m │ ├── center.m │ ├── MyFind.m │ ├── GF.mat │ ├── codeGF.mat │ ├── transGF.mat │ ├── standardize.m │ ├── DfmCholImp.m │ ├── aicbic.m │ ├── swdftest.m │ ├── ExplainedVariances.m │ ├── CumImp.m │ ├── DfmCholIdent.m │ ├── principalcomponents.m │ ├── testnfac.m │ ├── baingdftest.m │ ├── confband.m │ ├── VAR_str.m │ ├── companion.m │ ├── woldimpulse.m │ ├── myvar.m │ ├── invertepolynomialmatrix.m │ ├── DoSubPlots.m │ ├── baingcriterion.m │ ├── DoEverything.m │ ├── uhligcumulatedforwardpremium.m │ ├── DfmCholBlockBoot.m │ ├── dfactest.m │ ├── myols.m │ ├── DfmRawImp.m │ ├── CholeskyBoot.m │ ├── HL2.m │ └── replicaForniGambettiRevision.m ├── .DS_Store ├── VAR │ ├── data.mat │ ├── VarStr.m │ ├── companion.m │ ├── bvarNew.m │ ├── CholeskyBoot.m │ ├── BQBoot.m │ └── bkfilter.m ├── FAVAR │ ├── FAVARCholImp.m │ ├── standardize.m │ ├── ortotest.m │ ├── FAVARCholIdent.m │ ├── VarParameters.m │ ├── aicbic.m │ ├── principalcomponents.m │ ├── GenerateNewSeries.m │ ├── FAVARRaw.m │ ├── FAVAR.m │ ├── VAR_str.m │ ├── woldimpulse.m │ ├── FAVARLR.m │ ├── myvar.m │ ├── varMio.m │ ├── woldimpulseLR.m │ ├── FAVARLRBlockBoot.m │ ├── FAVARLRBoot.m │ ├── myols.m │ └── GrangerBootOSCroux.m └── TVC-VAR │ ├── DiscreteDraw.m │ ├── MixingKSC.m │ ├── CHOFAC.M │ ├── VAR_str.m │ ├── companion.m │ ├── INNOVM.M │ ├── iwpQ.m │ ├── GIBBS1.M │ ├── GIBBS1Reg.m │ ├── kfR1RegTvc.m │ ├── kfR.m │ ├── SUR.M │ └── TVCGibbsSampling.m ├── .DS_Store ├── README.md ├── Class V - Factor Model ├── GF.mat ├── Macro_SS___Factor_Models.pdf ├── standardize.m ├── PC.m ├── SUR.m ├── VAR.m ├── bootstrapchol.m └── prctile.m ├── Lectures ├── L2_Into_2015_print.pdf ├── L3_Into_2015_print.pdf ├── L1_Intro_2018_print.pdf └── L4_Intro_2015_print.pdf ├── Class IV - Proxy SVARs ├── GKdata.mat ├── Macro_SS___Proxy_SVARs.pdf ├── SUR.m ├── VAR.m ├── OLS.m ├── bootstrapchol.m ├── bootstrapVARIVnewmonthly.m └── GKreplication.m ├── Class III - Sign Restrictions ├── GS10.mat ├── GDPMA.mat ├── tenyrs.mat ├── APWW20081.mat ├── newtrialAP.mat ├── Macro_SS___A_Bayesian_VAR_with_Sign_Restrictions.pdf ├── qr_dec.m ├── SUR.m ├── VAR.m ├── BVAR.m ├── mvnrnd1.m └── bvarsignexample.m ├── Class I - Estimating VARs with MATLAB ├── data.mat ├── Macro_SS___Estimating_VARs.pdf ├── SUR.m ├── VAR.m ├── bootstrapVAR.m ├── estimatingVAR.m └── prctile.m └── Class II - Short-Run and Long-Run Restrictions ├── datastruc.mat ├── Macro_SS___Structural_VARs.pdf ├── VAR.m ├── SUR.m ├── bootstrapVAR.m ├── bootstrapBQ.m ├── bootstrapchol.m ├── prctile.m └── structuralVAR.m /MatlabRoutines/ReplicaForniGambetti/cols.m: -------------------------------------------------------------------------------- 1 | function col=cols(x); 2 | [row,col]=size(x); 3 | -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/rows.m: -------------------------------------------------------------------------------- 1 | function row=rows(x); 2 | [row,col]=size(x); 3 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/.DS_Store -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/center.m: -------------------------------------------------------------------------------- 1 | function XC = center(X) 2 | [T n] = size(X); 3 | XC = X - ones(T,1)*(sum(X)/T); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Empirical-time-series-methods-for-macroeconomic-analysis 2 | Barcelona GSE Macroeconomics Summer School 2018 course 3 | -------------------------------------------------------------------------------- /MatlabRoutines/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/MatlabRoutines/.DS_Store -------------------------------------------------------------------------------- /MatlabRoutines/VAR/data.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/MatlabRoutines/VAR/data.mat -------------------------------------------------------------------------------- /Class V - Factor Model/GF.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class V - Factor Model/GF.mat -------------------------------------------------------------------------------- /Lectures/L2_Into_2015_print.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Lectures/L2_Into_2015_print.pdf -------------------------------------------------------------------------------- /Lectures/L3_Into_2015_print.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Lectures/L3_Into_2015_print.pdf -------------------------------------------------------------------------------- /Class IV - Proxy SVARs/GKdata.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class IV - Proxy SVARs/GKdata.mat -------------------------------------------------------------------------------- /Lectures/L1_Intro_2018_print.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Lectures/L1_Intro_2018_print.pdf -------------------------------------------------------------------------------- /Lectures/L4_Intro_2015_print.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Lectures/L4_Intro_2015_print.pdf -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/MyFind.m: -------------------------------------------------------------------------------- 1 | function y=MyFind(x); 2 | y=[]; 3 | for i=1:size(x) 4 | if x(i)~=0 5 | y=[y; x(i)]; 6 | end 7 | end -------------------------------------------------------------------------------- /Class III - Sign Restrictions/GS10.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class III - Sign Restrictions/GS10.mat -------------------------------------------------------------------------------- /Class III - Sign Restrictions/GDPMA.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class III - Sign Restrictions/GDPMA.mat -------------------------------------------------------------------------------- /Class III - Sign Restrictions/tenyrs.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class III - Sign Restrictions/tenyrs.mat -------------------------------------------------------------------------------- /Class III - Sign Restrictions/APWW20081.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class III - Sign Restrictions/APWW20081.mat -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/GF.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/MatlabRoutines/ReplicaForniGambetti/GF.mat -------------------------------------------------------------------------------- /Class I - Estimating VARs with MATLAB/data.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class I - Estimating VARs with MATLAB/data.mat -------------------------------------------------------------------------------- /Class III - Sign Restrictions/newtrialAP.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class III - Sign Restrictions/newtrialAP.mat -------------------------------------------------------------------------------- /MatlabRoutines/FAVAR/FAVARCholImp.m: -------------------------------------------------------------------------------- 1 | function [imp, chi,sh] = FAVARCholImp(X, Z, variables,k, h) 2 | [BB, chi,rsh] = FAVARRaw(X, Z, k,h); 3 | [imp sh] = FAVARCholIdent(BB,variables,rsh); 4 | -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/codeGF.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/MatlabRoutines/ReplicaForniGambetti/codeGF.mat -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/transGF.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/MatlabRoutines/ReplicaForniGambetti/transGF.mat -------------------------------------------------------------------------------- /Class IV - Proxy SVARs/Macro_SS___Proxy_SVARs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class IV - Proxy SVARs/Macro_SS___Proxy_SVARs.pdf -------------------------------------------------------------------------------- /Class V - Factor Model/Macro_SS___Factor_Models.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class V - Factor Model/Macro_SS___Factor_Models.pdf -------------------------------------------------------------------------------- /Class V - Factor Model/standardize.m: -------------------------------------------------------------------------------- 1 | function [y, M, s,MM,ss] = standardize(x); 2 | s = std(x); 3 | M = mean(x); 4 | ss = ones(size(x , 1) , 1)*s; 5 | MM = ones(size(x , 1) , 1)*M; 6 | y = (x - MM)./ss; -------------------------------------------------------------------------------- /Class II - Short-Run and Long-Run Restrictions/datastruc.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class II - Short-Run and Long-Run Restrictions/datastruc.mat -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/standardize.m: -------------------------------------------------------------------------------- 1 | function [y, M, s,MM,ss] = standardize(x); 2 | s = std(x); 3 | M = mean(x); 4 | ss = ones(size(x , 1) , 1)*s; 5 | MM = ones(size(x , 1) , 1)*M; 6 | y = (x - MM)./ss; -------------------------------------------------------------------------------- /Class I - Estimating VARs with MATLAB/Macro_SS___Estimating_VARs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class I - Estimating VARs with MATLAB/Macro_SS___Estimating_VARs.pdf -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/DfmCholImp.m: -------------------------------------------------------------------------------- 1 | function [imp, chi,sh] = DfmCholImp(data, variables, r,k, h) 2 | q = length(variables); 3 | [BB, chi,rsh] = DfmRawImp(data,q,r,k,h); 4 | [imp sh] = DfmCholIdent(BB,variables,rsh); 5 | -------------------------------------------------------------------------------- /Class V - Factor Model/PC.m: -------------------------------------------------------------------------------- 1 | function [pc,A,L]=PC(data,npc) 2 | 3 | % Function that computes the principal components: 4 | 5 | Sigma = cov(data); 6 | opts.disp = 0; 7 | [ A, L ] = eigs(Sigma,npc,'LM',opts); 8 | pc = data*A; 9 | 10 | end 11 | -------------------------------------------------------------------------------- /Class II - Short-Run and Long-Run Restrictions/Macro_SS___Structural_VARs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class II - Short-Run and Long-Run Restrictions/Macro_SS___Structural_VARs.pdf -------------------------------------------------------------------------------- /Class III - Sign Restrictions/Macro_SS___A_Bayesian_VAR_with_Sign_Restrictions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anorring/Empirical-time-series-methods-for-macroeconomic-analysis/HEAD/Class III - Sign Restrictions/Macro_SS___A_Bayesian_VAR_with_Sign_Restrictions.pdf -------------------------------------------------------------------------------- /MatlabRoutines/FAVAR/standardize.m: -------------------------------------------------------------------------------- 1 | function [y, M, s,MM,ss] = standardize(x,w); 2 | if nargin == 1 3 | w = ones(1,size(x,2)); 4 | end 5 | s = std(x)./w; 6 | M = mean(x); 7 | ss = ones(size(x , 1) , 1)*s; 8 | MM = ones(size(x , 1) , 1)*M; 9 | y = (x - MM)./ss; -------------------------------------------------------------------------------- /MatlabRoutines/VAR/VarStr.m: -------------------------------------------------------------------------------- 1 | %Creates matrices for VAR(k) 2 | function [Y,X] = VarStr(y,c,k) 3 | [T N]=size(y); 4 | 5 | Y = y(k+1:T,:); 6 | 7 | X=[]; 8 | 9 | for j=1:k, 10 | X=[X y(k+1-j:T-j,:)]; 11 | end 12 | 13 | if c == 1 14 | X=[ones(size(X,1),1) X]; 15 | end 16 | -------------------------------------------------------------------------------- /Class III - Sign Restrictions/qr_dec.m: -------------------------------------------------------------------------------- 1 | %%% QR factorization with non-negative diagonals in R: 2 | 3 | function [Q,R] = qr_dec(drawW) 4 | 5 | [Q,R] = qr(drawW); 6 | 7 | for i = 1:size(drawW,1) 8 | 9 | if R(i,i)<0 10 | R(i,:)=-R(i,:); 11 | Q(:,i)=-Q(:,i); 12 | 13 | end 14 | end -------------------------------------------------------------------------------- /MatlabRoutines/TVC-VAR/DiscreteDraw.m: -------------------------------------------------------------------------------- 1 | function y=DiscreteDraw(p) 2 | n=length(p); 3 | a=rand(1,1); 4 | [b c]=sort(p); 5 | pr=cumsum(p(c)); 6 | j=1; 7 | while j<=n 8 | r=(a0; 39 | test1(iepsilon)=min(find(dum1==1)); 40 | end; 41 | if sum(dum2 )>0; 42 | test2(iepsilon)=min(find(dum2==1)); 43 | end; 44 | end; % end iepsilon; 45 | 46 | s=diag(s); 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/myols.m: -------------------------------------------------------------------------------- 1 | % A=myols(y,x), where y is a vector, x is a matrix, performs ols 2 | % estimates of the regression of y on the columns of x. 3 | % A is a 2 x (k+1) matrix, where k is the number of 4 | % columns of x, having the parameter estimates on the first 5 | % line and the standard errors on the second. 6 | % In the last column, the first element is the estimated variance of 7 | % residuals and the second is the corrected R^2. 8 | % [A,u]=ols(y,x) produces the vector u of the residuals as a further 9 | % output. [A,u,fit]=ols(y,x) produces the fitted values. 10 | % [A,u,fit,v]=ols(y,x) produces the varcov matrix of the estimates. 11 | % 12 | function [ols,u,fit,v]=myols(y,x) 13 | par=inv(x'*x)*x'*y; %%% ols coeff 14 | fit=x*par; %%% fit 15 | u=y-fit; %%% residuals 16 | m=size(x); T=m(1); k=m(2); 17 | esu=u'*u/(T-k); 18 | r2=1-(u'*u)/(center(y)'*center(y)); %%% R2 19 | r2c=1-(1-r2)*(T-1)/(T-k); %%% adjusted R2 20 | v=esu*inv(x'*x); %%% varcov matrix of the estimates 21 | espar=sqrt(diag(v)); %%% standard errors 22 | ols=[par' esu; espar' r2c]; 23 |  -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/DfmRawImp.m: -------------------------------------------------------------------------------- 1 | % 2 | % B = DfmRawImp(X, q, r,k, h) 3 | % 4 | % produce la stima come descritto in Forni Lippi Reichlin 2003 5 | % delle impulse (non cumulate) relative al 6 | % panel X con rango statico r e dinamico q e h ritardi 7 | % B e' tridimensionale con la cross-sectional unit sulla prima, 8 | % il common shock sulla seconda, 9 | % il ritardo sulla terza dimensione. Le impulse in B corrispondono ad una 10 | % identificazione ortonormale, quale risulta determinata 11 | % dalla scelta degli autovettori operata dalla routine eigs. 12 | % 13 | % 14 | 15 | 16 | function [B, Chi, rsh] = DfmRawImp(X, q, r, k, h,weights) 17 | N = size(X, 2); 18 | if nargin == 5 19 | weights = ones(1,N); 20 | end 21 | T = size(X, 1); 22 | WW = diag(std(X)./weights); 23 | x = center(X)*(WW^-1); 24 | Gamma0 = cov(x); 25 | opt.disp = 0; 26 | [W, Lambda] = eigs(Gamma0, r,'LM',opt); 27 | F = x*W; 28 | chi = F*W'; 29 | Chi = chi*WW + ones(T,1)*mean(X); 30 | [BB, epsilon, coeff] = woldimpulse(F, k, h + 1); 31 | Sigma = cov(epsilon); 32 | [ K, MM ] = eigs(Sigma, q, 'LM',opt); 33 | M = diag(sqrt(diag(MM))); 34 | for lag = 1 : h + 1 35 | B(:, :, lag) = WW*W*BB(:, :, lag)*K*M; 36 | end 37 | rsh = epsilon*K*inv(M); 38 | 39 | 40 | -------------------------------------------------------------------------------- /Class III - Sign Restrictions/BVAR.m: -------------------------------------------------------------------------------- 1 | %%% BVAR - Diffuse/Uninformative Prior (Uniform -inf, +inf) 2 | %%% Author: Nicolo' Maffei Faccioli 3 | 4 | function [PI,BigA,Q,errornorm,fittednorm]=BVAR(y,p,c) 5 | 6 | [Traw,K]=size(y); 7 | 8 | T=Traw-p; 9 | 10 | [pi_hat,Y,X,~,~,err]=VAR(y,p,c); % ML = OLS estimate 11 | 12 | sigma=err'*err; % SSE 13 | 14 | % Draw Q from IW ~ (S,v), where v = T-(K*p+1)-K-1 : 15 | 16 | Q=iwishrnd(sigma,T-size(X,2)-K-1); 17 | 18 | % Compute the Kronecker product Q x inv(X'X) and vectorize the matrix 19 | % pi_hat in order to obtain vec(pi_hat): 20 | 21 | XX=kron(Q,inv(X'*X)); 22 | s=size(pi_hat)'; 23 | vec_pi_hat=reshape(pi_hat,s(1)*s(2),1); 24 | 25 | % Draw PI from a multivariate normal distribution with mean vec(pi_hat) 26 | % and variance Q x inv(X'X): 27 | 28 | PI=mvnrnd1(vec_pi_hat,XX,1); 29 | PI=PI'; 30 | PI=reshape(PI,[K*p+c,K]); % reshape PI such that Y=X*PI+e, i.e. PI is (K*p+c)x(K). 31 | 32 | % Create the companion form representation matrix A: 33 | 34 | BigA=[PI(1+c:end,:)'; eye(K*p-K) zeros(K*p-K,K)]; % (K*p)x(K*p) matrix 35 | 36 | % Store errors and fitted values: 37 | 38 | errornorm=Y-X*PI; 39 | fittednorm=X*PI; 40 | 41 | end 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /MatlabRoutines/TVC-VAR/kfR.m: -------------------------------------------------------------------------------- 1 | function [S0,P0,P1] = KFR(Y,X,Q,R,SI,PI,T,N,L,c); 2 | 3 | % function [S0,P0,P1] = KFR(Y,X,Q,B,H,SI,PI,T,N,L); 4 | 5 | % This file performs the forward kalman filter recursions 6 | % for the random coefficients VAR. R is time varying, depening 7 | % on the stochastic volatilities: R = inv(B)*H(t)*B 8 | 9 | % C is zero 10 | 11 | % SI,PI are the initial values for the recursions, S(1|0) and P(1|0) 12 | 13 | S0 = zeros(N*(c+N*L),T); % current estimate of the state, S(t|t) 14 | P0 = zeros(N*(c+N*L),N*(c+N*L),T); % current estimate of the covariance matrix, P(t|t) 15 | P1 = zeros(N*(c+N*L),N*(c+N*L),T); % one-step ahead covariance matrix, P(t|t-1) 16 | 17 | % 18 | %BI = inv(B); 19 | 20 | % date 1 21 | P1(:,:,1) = PI; % P(1|0) 22 | %R = BI*diag(H(2,:))*BI'; % H is shifted one period rel to observables 23 | K = (P1(:,:,1)*X(:,:,1))*inv( X(:,:,1)'*P1(:,:,1)*X(:,:,1) + R(:,:,1)); % K(1) 24 | P0(:,:,1) = P1(:,:,1) - K*(X(:,:,1)'*P1(:,:,1)); % P(1|1) 25 | S0(:,1) = SI + K*( Y(:,1) - X(:,:,1)'*SI ); % S(1|1) 26 | 27 | % Iterating through the rest of the sample 28 | for i = 2:T, 29 | P1(:,:,i) = P0(:,:,i-1) + Q; % P(t|t-1) 30 | % R = BI*diag(H(i+1,:))*BI'; 31 | K = (P1(:,:,i)*X(:,:,i))*inv( X(:,:,i)'*P1(:,:,i)*X(:,:,i) + R(:,:,i)); % K(t) 32 | P0(:,:,i) = P1(:,:,i) - K*(X(:,:,i)'*P1(:,:,i)); % P(t|t) 33 | S0(:,i) = S0(:,i-1) + K*( Y(:,i) - X(:,:,i)'*S0(:,i-1) ); % S(t|t) 34 | end 35 | -------------------------------------------------------------------------------- /MatlabRoutines/TVC-VAR/SUR.M: -------------------------------------------------------------------------------- 1 | % sur.m 2 | function [theta,Vtheta,Vu] = sur(Y,X,T); 3 | 4 | % function [theta,Vtheta,Vu] = sur(Y,X,T); 5 | 6 | % offline 2-step SUR 7 | 8 | % Y is a N by T matrix, with the row indicating equations, and column 9 | % indicating time periods, i.e, column j is the observation of Y 10 | % at time j. 11 | 12 | % X is a tensor object, with dimension(K_1+k_2+...K_N) by N by T, 13 | % where K_i is the number of independent variables for equation i, 14 | % and T indicates time as above. For page t, we have (cap)X_t' as 15 | % in equation (1.2) in Notes. So page t records observations of right 16 | % hand side variables for N equations at time t. 17 | 18 | % initialize moment matrices 19 | [ry,cy] = size(Y); 20 | [rx,cx,px] = size(X); 21 | 22 | Mxx = zeros(rx,rx); 23 | Mxy = zeros(rx,1); 24 | 25 | % 1st stage estimates; weighting matrix = I 26 | for t = 1:T, 27 | Mxx = Mxx + X(:,:,t)*X(:,:,t)'; 28 | Mxy = Mxy + X(:,:,t)*Y(:,t); 29 | end 30 | theta = inv(Mxx)*Mxy; 31 | 32 | % 1st stage residuals 33 | e = zeros(ry,T); 34 | for t = 1:T, 35 | e(:,t) = Y(:,t) - X(:,:,t)'*theta; 36 | end 37 | 38 | % 2nd stage estimates; weighting matrix = inv(cov(e)) 39 | W = inv(cov(e')); 40 | Mxx = zeros(rx,rx); 41 | Mxy = zeros(rx,1); 42 | for t = 1:T, 43 | Mxx = Mxx + X(:,:,t)*W*X(:,:,t)'; 44 | Mxy = Mxy + X(:,:,t)*W*Y(:,t); 45 | end 46 | theta = inv(Mxx)*Mxy; 47 | 48 | % 2nd stage residuals 49 | for t = 1:T, 50 | e(:,t) = Y(:,t) - X(:,:,t)'*theta; 51 | end 52 | 53 | Vu = cov(e'); 54 | W = inv(Vu); 55 | 56 | Mxx = zeros(rx,rx); 57 | for t = 1:T, 58 | Mxx = Mxx + X(:,:,t)*W*X(:,:,t)'; 59 | end 60 | 61 | Vtheta = inv(Mxx); -------------------------------------------------------------------------------- /Class II - Short-Run and Long-Run Restrictions/bootstrapVAR.m: -------------------------------------------------------------------------------- 1 | function [HighC,LowC]=bootstrapVAR(data,hor,c,iter,conf,p,n) 2 | 3 | % Function to perform bootstrap method 4 | % Author: Nicolo' Maffei Faccioli 5 | 6 | % Step 1: 7 | 8 | [pi_hat,~,~,Y_initial,~,err]=VAR(data,p,c); 9 | 10 | T=length(data)-length(Y_initial); % Data after losing lags 11 | 12 | if c==1 13 | cons=pi_hat(1,:)'; 14 | PI=pi_hat(2:end,:)'; 15 | else cons=0; 16 | PI=pi_hat'; 17 | end 18 | 19 | ExtraBigC=zeros(hor,n*n,iter); 20 | 21 | for j=1:iter 22 | 23 | % STEP 2: generate a new sample with bootstrap 24 | 25 | Y_new=zeros(T,n); 26 | Y_in= reshape(flipud(Y_initial)',1,[]); % 1*(n*p) row vector of [y_0 ... y_-p+1] 27 | for i=1:T; 28 | Y_new(i,:)= cons' + Y_in*PI' + err(randi(T),:); 29 | Y_in=[Y_new(i,:) Y_in(1:n*(p-1))]; 30 | end 31 | Data_new=[Y_initial ; Y_new]; % Add the p initial lags to recreate the sample 32 | 33 | % STEP 3: Esimate VAR(p) with new sample and obtain IRF: 34 | 35 | [pi_hat_c,~,~,~,~,~]=VAR(Data_new,p,c); 36 | 37 | if c==1 38 | BigA_c=[pi_hat_c(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np+1 x np+1 matrix 39 | else BigA_c=[pi_hat_c'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np x np matrix 40 | end 41 | 42 | C_c=zeros(n,n,hor); 43 | 44 | for l=1:hor 45 | BigC_c=BigA_c^(l-1); 46 | C_c(:,:,l)=BigC_c(1:n,1:n); % Impulse response functions of the Wold representation (Bootstrap) 47 | end 48 | 49 | C_c_1= reshape(permute(C_c,[3 2 1]),hor,n*n,[]); 50 | ExtraBigC(:,:,j)=C_c_1; 51 | 52 | end 53 | 54 | % Create bands: 55 | 56 | LowC=zeros(hor,n*n); 57 | HighC=zeros(hor,n*n); 58 | 59 | for k=1:n 60 | for j=1:n 61 | Cmin = prctile(ExtraBigC(:,j+n*k-n,:),(100-conf)/2,3); %16th percentile 62 | LowC(:,j+n*k-n) = Cmin; %lower band 63 | Cmax = prctile(ExtraBigC(:,j+n*k-n,:),(100+conf)/2,3); %84th percentile 64 | HighC(:,j+n*k-n) = Cmax; %upper band 65 | end 66 | end 67 | 68 | end 69 | 70 | -------------------------------------------------------------------------------- /Class I - Estimating VARs with MATLAB/bootstrapVAR.m: -------------------------------------------------------------------------------- 1 | function [HighC,LowC]=bootstrapVAR(data,hor,c,iter,conf,p,n) 2 | 3 | % Function to perform bootstrap method 4 | % Author: Nicolo' Maffei Faccioli 5 | 6 | % Step 1: estimate and store 7 | 8 | [pi_hat,~,~,Y_initial,~,err]=VAR(data,p,c); 9 | 10 | T=length(data)-length(Y_initial); % Data after losing lags 11 | 12 | if c==1 13 | cons=pi_hat(1,:)'; 14 | PI=pi_hat(2:end,:)'; 15 | else cons=0; 16 | PI=pi_hat'; 17 | end 18 | 19 | ExtraBigC=zeros(hor,n*n,iter); 20 | 21 | for j=1:iter 22 | 23 | % STEP 2: generate a new sample with bootstrap 24 | 25 | Y_new=zeros(T,n); 26 | Y_in= reshape(flipud(Y_initial)',1,[]); % 1*(n*p) row vector of [y_0 ... y_-p+1] 27 | for i=1:T; 28 | Y_new(i,:)= cons' + Y_in*PI' + err(randi(T),:); 29 | Y_in=[Y_new(i,:) Y_in(1:n*(p-1))]; 30 | end 31 | Data_new=[Y_initial ; Y_new]; % Add the p initial lags to recreate the sample 32 | 33 | % STEP 3: Esimate VAR(p) with new sample and obtain IRF: 34 | 35 | [pi_hat_c,~,~,~,~,~]=VAR(Data_new,p,c); 36 | 37 | if c==1 38 | BigA_c=[pi_hat_c(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np+1 x np+1 matrix 39 | else BigA_c=[pi_hat_c'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np x np matrix 40 | end 41 | 42 | C_c=zeros(n,n,hor); 43 | 44 | for l=1:hor 45 | BigC_c=BigA_c^(l-1); 46 | C_c(:,:,l)=BigC_c(1:n,1:n); % Impulse response functions of the Wold representation (Bootstrap) 47 | end 48 | 49 | C_c_1= reshape(permute(C_c,[3 2 1]),hor,n*n,[]); 50 | ExtraBigC(:,:,j)=C_c_1; 51 | 52 | end 53 | 54 | % Create bands: 55 | 56 | LowC=zeros(hor,n*n); 57 | HighC=zeros(hor,n*n); 58 | 59 | for k=1:n 60 | for j=1:n 61 | Cmin = prctile(ExtraBigC(:,j+n*k-n,:),(100-conf)/2,3); %16th percentile 62 | LowC(:,j+n*k-n) = Cmin; %lower band 63 | Cmax = prctile(ExtraBigC(:,j+n*k-n,:),(100+conf)/2,3); %84th percentile 64 | HighC(:,j+n*k-n) = Cmax; %upper band 65 | end 66 | end 67 | 68 | end 69 | 70 | -------------------------------------------------------------------------------- /Class III - Sign Restrictions/mvnrnd1.m: -------------------------------------------------------------------------------- 1 | function r = mvnrnd1(mu,sigma,cases); 2 | % modified matlab code 3 | % generates random draws even with covariance matrices which are almost 4 | % singular, which may happen at some point in the iteration procedure 5 | 6 | %MVNRND Random matrices from the multivariate normal distribution. 7 | % R = MVNRND(MU,SIGMA,CASES) returns a matrix of random numbers chosen 8 | % from the multivariate normal distribution with mean vector, MU, and 9 | % covariance matrix, SIGMA. CASES is the number of rows in R. 10 | % 11 | % SIGMA is a symmetric positive semi-definite matrix with size equal 12 | % to the length of MU. 13 | 14 | % B.A. Jones 6-30-94 15 | % Copyright 1993-2000 The MathWorks, Inc. 16 | % $Revision: 2.9 $ $Date: 2000/06/02 16:54:14 $ 17 | 18 | 19 | [m1 n1] = size(mu); 20 | c = max([m1 n1]); 21 | if m1 .* n1 ~= c 22 | error('Mu must be a vector.'); 23 | end 24 | 25 | [m n] = size(sigma); 26 | if m ~= n 27 | error('Sigma must be square'); 28 | end 29 | 30 | if m ~= c 31 | error('The length of mu must equal the number of rows in sigma.'); 32 | end 33 | 34 | [T p] = chol(sigma); 35 | if p > 0 36 | % The input covariance has some type of perfect correlation. 37 | % If it is positive semi-definite, we can still proceed. 38 | % Find a factor T that has the property sigma == T' * T. 39 | % Unlike a Cholesky factor, this T is not necessarily triangular 40 | % or even square. 41 | T = mvnfactor(sigma); 42 | end 43 | 44 | if m1 == c 45 | mu = mu'; 46 | end 47 | 48 | mu = mu(ones(cases,1),:); 49 | 50 | r = randn(cases,size(T,1)) * T + mu; 51 | 52 | %--------------------------------------- 53 | function T = mvnfactor(sigma) 54 | % MVNFACTOR Do Cholesky-like decomposition, allowing zero eigenvalues 55 | % SIGMA must be symmetric. In general T is not square or triangular. 56 | 57 | [U,D] = eig((sigma+sigma')/2); 58 | D = diag(D); 59 | tol = max(D) * length(D) * eps; 60 | t = (D > tol); 61 | D = D(t); 62 | T = diag(sqrt(D)) * U(:,t)'; 63 | -------------------------------------------------------------------------------- /MatlabRoutines/VAR/CholeskyBoot.m: -------------------------------------------------------------------------------- 1 | function [cirf CholBoot] = CholeskyBoot(y,p,H,c,MaxBoot,cl,ind,opt) 2 | if nargin<8 3 | opt=0; 4 | end 5 | n=size(y,2); 6 | %_____________________________________ 7 | % OLS estimates 8 | %_____________________________________ 9 | [Y X] = VarStr(y,c,p); % yy and XX all the sample 10 | T=size(Y,1); 11 | Bols=inv(X'*X)*X'*Y; 12 | VecB=reshape(Bols,n*(n*p+1),1); 13 | B=companion(VecB,p,n,c); 14 | C=Bols(1,:)'; 15 | u=Y-X*Bols; 16 | CovU=cov(u); 17 | u=u'; 18 | % impulse response functions 19 | for h=1:H 20 | irf(:,:,h)=B^(h-1); 21 | cirf(:,:,h)=irf(1:n,1:n,h)*chol(CovU)'; 22 | end 23 | 24 | %_____________________________________ 25 | % Bootstrapping 26 | %_____________________________________ 27 | 28 | for i=1:MaxBoot 29 | 30 | % generate new series 31 | for t=1:T 32 | if t==1 33 | YB(:,1)=X(1,2:end)'; 34 | else 35 | a=fix(rand(1,1)*size(u,2))+1; 36 | uu=u(:,a); 37 | YB(:,t)=[C;zeros(n*p-n,1)]+B*YB(:,t-1)+[uu;zeros(n*p-n,1)]; 38 | end 39 | end 40 | 41 | % estimate the new VAR 42 | yb=YB(1:n,:)'; 43 | [Yn Xn] = VarStr(yb,c,p); % yy and XX all the sample 44 | 45 | T=size(Yn,1); 46 | Bolsn=inv(Xn'*Xn)*Xn'*Yn; 47 | CovUBoot(:,:,i)=cov(Yn-Xn*Bolsn); 48 | VecBn=reshape(Bolsn,n*(n*p+1),1); 49 | Bn=companion(VecBn,p,n,c); 50 | 51 | % impulse response functions 52 | for h=1:H 53 | irfBoot(:,:,h,i)=Bn^(h-1); 54 | % cholesky 55 | CholBoot(:,:,h,i)=irfBoot(1:n,1:n,h,i)*chol(CovUBoot(:,:,i))'; 56 | end 57 | end 58 | cirf(ind,:,:)=cumsum(cirf(ind,:,:),3); 59 | CholBoot(ind,:,:,:)=cumsum(CholBoot(ind,:,:,:),3); 60 | if opt==1 61 | k=0; 62 | figure(2) 63 | for ii=1:n 64 | for jj=1:n 65 | k=k+1; 66 | subplot(n,n,k),plot(1:H,squeeze(cirf(ii,jj,:)),'k',... 67 | 1:H,squeeze(prctile(CholBoot(ii,jj,:,:),[16 84],4)),':k'),axis tight 68 | end 69 | end 70 | end 71 | -------------------------------------------------------------------------------- /Class V - Factor Model/bootstrapchol.m: -------------------------------------------------------------------------------- 1 | function [HighD,LowD]=bootstrapchol(data,hor,c,iter,conf,p,n) 2 | 3 | % Function to perform bootstrap method 4 | % Author: Nicolo' Maffei Faccioli 5 | 6 | % Step 1: 7 | 8 | [pi_hat,~,~,Y_initial,~,err]=VAR(data,p,c); 9 | 10 | T=length(data)-length(Y_initial); % Data after losing lags 11 | 12 | if c==1 13 | cons=pi_hat(1,:)'; 14 | PI=pi_hat(2:end,:)'; 15 | else cons=0; 16 | PI=pi_hat'; 17 | 18 | end 19 | 20 | ExtraBigD=zeros(hor,n*n,iter); 21 | 22 | for j=1:iter 23 | 24 | % STEP 2: generate a new sample with bootstrap 25 | 26 | Y_new=zeros(T,n); 27 | Y_in= reshape(flipud(Y_initial)',1,[]); % 1*(n*p) row vector of [y_0 ... y_-p+1] 28 | for i=1:T; 29 | Y_new(i,:)= cons' + Y_in*PI' + err(randi(T),:); 30 | Y_in=[Y_new(i,:) Y_in(1:n*(p-1))]; 31 | end 32 | Data_new=[Y_initial ; Y_new]; % Add the p initial lags to recreate the sample 33 | 34 | % STEP 3: Esimate VAR(p) with new sample and obtain IRF: 35 | 36 | [pi_hat_c,~,~,~,~,err_c]=VAR(Data_new,p,c); 37 | 38 | if c==1 39 | BigA_c=[pi_hat_c(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np+1 x np+1 matrix 40 | else BigA_c=[pi_hat_c'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np x np matrix 41 | end 42 | 43 | t=length(Data_new)-n*p-n; % -p lags for n variables and -n constants 44 | omega=(err_c'*err_c)./t; %estimate of omega 45 | S=chol(omega,'lower'); %cholesky factorization, lower triangular matrix 46 | 47 | C_c=zeros(n,n,hor); 48 | 49 | for l=1:hor 50 | BigC_c=BigA_c^(l-1); 51 | C_c(:,:,l)=BigC_c(1:n,1:n)*S; % Impulse response functions of the Wold representation (Bootstrap) 52 | end 53 | 54 | C_c_1= reshape(permute(C_c,[3 2 1]),hor,n*n,[]); 55 | %ExtraBigC(:,:,j)=reshape(C_c_1,[hor p]); 56 | ExtraBigD(:,:,j)=C_c_1; 57 | end 58 | 59 | % Create bands: 60 | 61 | LowD=zeros(hor,n*n); 62 | HighD=zeros(hor,n*n); 63 | 64 | for k=1:n 65 | for j=1:n 66 | Dmin = prctile(ExtraBigD(:,j+n*k-n,:),(100-conf)/2,3); %16th percentile 67 | LowD(:,j+n*k-n) = Dmin; %lower band 68 | Dmax = prctile(ExtraBigD(:,j+n*k-n,:),(100+conf)/2,3); %84th percentile 69 | HighD(:,j+n*k-n) = Dmax; %upper band 70 | end 71 | end 72 | 73 | end 74 | 75 | -------------------------------------------------------------------------------- /Class IV - Proxy SVARs/bootstrapchol.m: -------------------------------------------------------------------------------- 1 | function [HighD,LowD]=bootstrapchol(data,hor,c,iter,conf,p,n) 2 | 3 | % Function to perform bootstrap method 4 | % Author: Nicolo' Maffei Faccioli 5 | 6 | % Step 1: 7 | 8 | [pi_hat,~,~,Y_initial,~,err]=VAR(data,p,c); 9 | 10 | T=length(data)-length(Y_initial); % Data after losing lags 11 | 12 | if c==1 13 | cons=pi_hat(1,:)'; 14 | PI=pi_hat(2:end,:)'; 15 | else cons=0; 16 | PI=pi_hat'; 17 | 18 | end 19 | 20 | ExtraBigD=zeros(hor,n*n,iter); 21 | 22 | for j=1:iter 23 | 24 | % STEP 2: generate a new sample with bootstrap 25 | 26 | Y_new=zeros(T,n); 27 | Y_in= reshape(flipud(Y_initial)',1,[]); % 1*(n*p) row vector of [y_0 ... y_-p+1] 28 | for i=1:T; 29 | Y_new(i,:)= cons' + Y_in*PI' + err(randi(T),:); 30 | Y_in=[Y_new(i,:) Y_in(1:n*(p-1))]; 31 | end 32 | Data_new=[Y_initial ; Y_new]; % Add the p initial lags to recreate the sample 33 | 34 | % STEP 3: Esimate VAR(p) with new sample and obtain IRF: 35 | 36 | [pi_hat_c,~,~,~,~,err_c]=VAR(Data_new,p,c); 37 | 38 | if c==1 39 | BigA_c=[pi_hat_c(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np+1 x np+1 matrix 40 | else BigA_c=[pi_hat_c'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np x np matrix 41 | end 42 | 43 | t=length(Data_new)-n*p-n; % -p lags for n variables and -n constants 44 | omega=(err_c'*err_c)./t; %estimate of omega 45 | S=chol(omega,'lower')'; %cholesky factorization, lower triangular matrix 46 | 47 | C_c=zeros(n,n,hor); 48 | 49 | for l=1:hor 50 | BigC_c=BigA_c^(l-1); 51 | C_c(:,:,l)=BigC_c(1:n,1:n)*S; % Impulse response functions of the Wold representation (Bootstrap) 52 | end 53 | 54 | C_c_1= reshape(permute(C_c,[3 2 1]),hor,n*n,[]); 55 | %ExtraBigC(:,:,j)=reshape(C_c_1,[hor p]); 56 | ExtraBigD(:,:,j)=C_c_1; 57 | end 58 | 59 | % Create bands: 60 | 61 | LowD=zeros(hor,n*n); 62 | HighD=zeros(hor,n*n); 63 | 64 | for k=1:n 65 | for j=1:n 66 | Dmin = prctile(ExtraBigD(:,j+n*k-n,:),(100-conf)/2,3); %16th percentile 67 | LowD(:,j+n*k-n) = Dmin; %lower band 68 | Dmax = prctile(ExtraBigD(:,j+n*k-n,:),(100+conf)/2,3); %84th percentile 69 | HighD(:,j+n*k-n) = Dmax; %upper band 70 | end 71 | end 72 | 73 | end 74 | 75 | -------------------------------------------------------------------------------- /Class II - Short-Run and Long-Run Restrictions/bootstrapBQ.m: -------------------------------------------------------------------------------- 1 | function [HighC,LowC]=bootstrapBQ(data,hor,c,iter,conf,p,n) 2 | 3 | % Function to perform bootstrap method 4 | % Author: Nicolo' Maffei Faccioli 5 | 6 | % Step 1: 7 | 8 | [pi_hat,~,~,Y_initial,~,err]=VAR(data,p,c); 9 | 10 | T=length(data)-length(Y_initial); % Data after losing lags 11 | 12 | if c==1 13 | cons=pi_hat(1,:)'; 14 | PI=pi_hat(2:end,:)'; 15 | else cons=0; 16 | PI=pi_hat'; 17 | 18 | end 19 | 20 | ExtraBigC=zeros(hor,n*n,iter); 21 | 22 | for j=1:iter 23 | 24 | % STEP 2: generate a new sample with bootstrap 25 | 26 | Y_new=zeros(T,n); 27 | Y_in= reshape(flipud(Y_initial)',1,[]); % 1*(n*p) row vector of [y_0 ... y_-p+1] 28 | for i=1:T; 29 | Y_new(i,:)= cons' + Y_in*PI' + err(randi(T),:); 30 | Y_in=[Y_new(i,:) Y_in(1:n*(p-1))]; 31 | end 32 | Data_new=[Y_initial ; Y_new]; % Add the p initial lags to recreate the sample 33 | 34 | % STEP 3: Esimate VAR(p) with new sample and obtain IRF: 35 | 36 | [pi_hat_c,~,~,~,~,err_c]=VAR(Data_new,p,c); 37 | 38 | if c==1 39 | BigA_c=[pi_hat_c(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np+1 x np+1 matrix 40 | else BigA_c=[pi_hat_c'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np x np matrix 41 | end 42 | 43 | C_c=zeros(n,n,hor); 44 | 45 | for l=1:hor 46 | BigC_c=BigA_c^(l-1); 47 | C_c(:,:,l)=BigC_c(1:n,1:n); % Impulse response functions of the Wold representation (Bootstrap) 48 | end 49 | 50 | t=length(Data_new)-n*p-n; % -p lags for n variables and -n constants 51 | omega=(err_c'*err_c)./t; %estimate of omega 52 | A1=sum(C_c,3); 53 | S=chol(A1*omega*A1')'; 54 | K=A1\S; 55 | 56 | F=zeros(n,n,hor); 57 | 58 | for i=1:hor 59 | F(:,:,i)=C_c(:,:,i)*K; 60 | end 61 | 62 | F_1= reshape(permute(F,[3 2 1]),hor,n*n,[]); 63 | ExtraBigC(:,:,j)=F_1; 64 | 65 | end 66 | 67 | % Create bands: 68 | 69 | LowC=zeros(hor,n*n); 70 | HighC=zeros(hor,n*n); 71 | 72 | for k=1:n 73 | for j=1:n 74 | Cmin = prctile(ExtraBigC(:,j+n*k-n,:),(100-conf)/2,3); %16th percentile 75 | LowC(:,j+n*k-n) = Cmin; %lower band 76 | Cmax = prctile(ExtraBigC(:,j+n*k-n,:),(100+conf)/2,3); %84th percentile 77 | HighC(:,j+n*k-n) = Cmax; %upper band 78 | end 79 | end 80 | 81 | end 82 | 83 | -------------------------------------------------------------------------------- /Class II - Short-Run and Long-Run Restrictions/bootstrapchol.m: -------------------------------------------------------------------------------- 1 | function [HighD,LowD]=bootstrapchol(data,hor,c,iter,conf,p,n) 2 | 3 | % Function to perform bootstrap method 4 | % Author: Nicolo' Maffei Faccioli 5 | 6 | % typos: re-download 7 | 8 | % Step 1: 9 | 10 | [pi_hat,~,~,Y_initial,~,err]=VAR(data,p,c); 11 | 12 | T=length(data)-length(Y_initial); % Data after losing lags 13 | 14 | if c==1 15 | cons=pi_hat(1,:)'; 16 | PI=pi_hat(2:end,:)'; 17 | else cons=0; 18 | PI=pi_hat'; 19 | 20 | end 21 | 22 | ExtraBigD=zeros(hor,n*n,iter); 23 | 24 | for j=1:iter 25 | 26 | % STEP 2: generate a new sample with bootstrap 27 | 28 | Y_new=zeros(T,n); 29 | Y_in= reshape(flipud(Y_initial)',1,[]); % 1*(n*p) row vector of [y_0 ... y_-p+1] 30 | for i=1:T; 31 | Y_new(i,:)= cons' + Y_in*PI' + err(randi(T),:); 32 | Y_in=[Y_new(i,:) Y_in(1:n*(p-1))]; 33 | end 34 | Data_new=[Y_initial ; Y_new]; % Add the p initial lags to recreate the sample 35 | 36 | % STEP 3: Esimate VAR(p) with new sample and obtain IRF: 37 | 38 | [pi_hat_c,~,~,~,~,err_c]=VAR(Data_new,p,c); 39 | 40 | if c==1 41 | BigA_c=[pi_hat_c(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np+1 x np+1 matrix 42 | else BigA_c=[pi_hat_c'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np x np matrix 43 | end 44 | 45 | t=length(Data_new)-n*p-n; % -p lags for n variables and -n constants 46 | omega=(err_c'*err_c)./t; %estimate of omega 47 | S=chol(omega,'lower'); %cholesky factorization, lower triangular matrix 48 | 49 | C_c=zeros(n,n,hor); 50 | 51 | for l=1:hor 52 | BigC_c=BigA_c^(l-1); 53 | C_c(:,:,l)=BigC_c(1:n,1:n)*S; % Impulse response functions of the Wold representation (Bootstrap) 54 | end 55 | 56 | C_c_1= reshape(permute(C_c,[3 2 1]),hor,n*n,[]); 57 | %ExtraBigC(:,:,j)=reshape(C_c_1,[hor p]); 58 | ExtraBigD(:,:,j)=C_c_1; 59 | end 60 | 61 | % Create bands: 62 | 63 | LowD=zeros(hor,n*n); 64 | HighD=zeros(hor,n*n); 65 | 66 | for k=1:n 67 | for j=1:n 68 | Dmin = prctile(ExtraBigD(:,j+n*k-n,:),(100-conf)/2,3); %16th percentile 69 | LowD(:,j+n*k-n) = Dmin; %lower band 70 | Dmax = prctile(ExtraBigD(:,j+n*k-n,:),(100+conf)/2,3); %84th percentile 71 | HighD(:,j+n*k-n) = Dmax; %upper band 72 | end 73 | end 74 | 75 | end 76 | 77 | -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/CholeskyBoot.m: -------------------------------------------------------------------------------- 1 | function [cirf csirfBoot] = CholeskyBoot(y,p,H,c,MaxBoot,cl,ind,opt) 2 | if nargin<8 3 | opt=0; 4 | end 5 | n=size(y,2); % number of variables 6 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 7 | %%%% OLS estimates 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | [Y X] = VAR_str(y,c,p); % yy and XX all the sample 10 | T=size(Y,1); 11 | Bols=inv(X'*X)*X'*Y; 12 | VecB=reshape(Bols,n*(n*p+1),1); 13 | B=companion(VecB,p,n,c); 14 | %C=VecB(1:n*p+c:end); 15 | C=Bols(1,:)'; 16 | %%%% residuals 17 | % for t=1:T 18 | % XX(:,:,t)=kron(eye(n),X(t,:)'); 19 | % u(:,t)=Y(t,:)'-XX(:,:,t)'*VecB; 20 | % end 21 | u=Y-X*Bols; 22 | CovU=cov(u); 23 | u=u'; 24 | %%%% impulse response functions 25 | for h=1:H 26 | irf(:,:,h)=B^(h-1); 27 | cirf(:,:,h)=irf(1:n,1:n,h)*chol(CovU)'; 28 | end 29 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | %%%% Bootstrapping 31 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 32 | for i=1:MaxBoot 33 | %i 34 | %%%% generate new series 35 | for t=1:T 36 | if t==1 37 | YB(:,1)=X(1,2:end)'; 38 | else 39 | a=fix(rand(1,1)*size(u,2))+1; 40 | uu=u(:,a); 41 | YB(:,t)=[C;zeros(n*p-n,1)]+B*YB(:,t-1)+[uu;zeros(n*p-n,1)]; 42 | end 43 | end 44 | 45 | %%%% estimate the new VAR 46 | yb=YB(1:n,:)'; 47 | [Yn Xn] = VAR_str(yb,c,p); % yy and XX all the sample 48 | 49 | T=size(Yn,1); 50 | Bolsn=inv(Xn'*Xn)*Xn'*Yn; 51 | CovUBoot(:,:,i)=cov(Yn-Xn*Bolsn); 52 | VecBn=reshape(Bolsn,n*(n*p+1),1); 53 | Bn=companion(VecBn,p,n,c); 54 | 55 | %%%% impulse response functions 56 | for h=1:H 57 | irfBoot(:,:,h,i)=Bn^(h-1); 58 | %%%% cholesky 59 | CholBoot(:,:,h,i)=irfBoot(1:n,1:n,h,i)*chol(CovUBoot(:,:,i))'; 60 | end 61 | end 62 | lb=round(MaxBoot*(1-cl)/2); 63 | ub=round(MaxBoot*(cl+(1-cl)/2)); 64 | me=round(MaxBoot*.5); 65 | 66 | cirf(ind,:,:)=cumsum(cirf(ind,:,:),3); 67 | CholBoot(ind,:,:,:)=cumsum(CholBoot(ind,:,:,:),3); 68 | csirfBoot=sort(CholBoot,4); 69 | 70 | if opt==1 71 | k=0; 72 | figure(2) 73 | for ii=1:n 74 | for jj=1:n 75 | k=k+1; 76 | subplot(n,n,k),plot(1:H,squeeze(cirf(ii,jj,:)),'k',... 77 | 1:H,squeeze(csirfBoot(ii,jj,:,[lb ub])),':k'),axis tight%,1:H,squeeze(mean(csirfBoot(ii,jj,:,:),4)),'--k'),axis tight 78 | end 79 | end 80 | end 81 | -------------------------------------------------------------------------------- /Class IV - Proxy SVARs/bootstrapVARIVnewmonthly.m: -------------------------------------------------------------------------------- 1 | function [HighH,LowH]=bootstrapVARIVnewmonthly(data,hor,c,cc,iter,conf,p,n,Z) 2 | 3 | % Function to perform bootstrap method 4 | % Author: Nicolo' Maffei Faccioli 5 | 6 | % Step 1: 7 | 8 | [pi_hat,~,~,Y_initial,~,err]=VAR(data,p,c); 9 | 10 | T=length(data)-size(Y_initial,1); % Data after losing lags 11 | 12 | if c==1 13 | cons=pi_hat(1,:)'; 14 | PI=pi_hat(2:end,:)'; 15 | else, cons=0; 16 | PI=pi_hat'; 17 | 18 | end 19 | 20 | ExtraBigC=zeros(hor,n,iter); 21 | 22 | for j=1:iter 23 | 24 | % STEP 2: generate a new sample with bootstrap 25 | 26 | % Wild bootstrap based on simple distribution (~Rademacher) 27 | rr = 1-2*(rand(T,1)>0.5); 28 | u=zeros(length(err),size(err,2)); 29 | 30 | for k=1:n 31 | u(:,k) = err(:,k).*rr; 32 | end 33 | 34 | Znew = Z.*rr; 35 | Znew(isnan(Znew))=[]; 36 | 37 | Y_new=zeros(T,n); 38 | Y_in= reshape(flipud(Y_initial)',1,[]); % 1*(n*p) row vector of [y_0 ... y_-p+1] 39 | for i=1:T 40 | Y_new(i,:)= cons' + Y_in*PI' + u(i,:); 41 | Y_in=[Y_new(i,:) Y_in(1:n*(p-1))]; 42 | end 43 | Data_new=[Y_initial ; Y_new]; % Add the p initial lags to recreate the sample 44 | 45 | % STEP 3: Esimate VAR(p) with new sample and obtain IRF: 46 | 47 | [pi_hat_c,~,~,~,~,err_c]=VAR(Data_new,p,c); 48 | 49 | eps_p=err_c(length(data)-p-length(Z)+1:end,end); 50 | eps_q=err_c(length(data)-p-length(Z)+1:end,1:end-1); 51 | 52 | ols_instr=OLS(eps_p,Znew,cc); 53 | 54 | if cc==1 55 | u_hat_p=[ones(length(Znew),1),Znew]*ols_instr; 56 | else, u_hat_p=Znew*ols_instr; 57 | end 58 | 59 | sq_sp=(u_hat_p'*u_hat_p)\u_hat_p'*eps_q; 60 | 61 | s=[sq_sp,1]; 62 | 63 | if c==1 64 | BigA_c=[pi_hat_c(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np+1 x np+1 matrix 65 | else, BigA_c=[pi_hat_c'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, np x np matrix 66 | end 67 | 68 | C_c=zeros(n,n,hor); 69 | H=zeros(n,1,hor); 70 | 71 | for l=1:hor 72 | BigC_c=BigA_c^(l-1); 73 | C_c(:,:,l)=BigC_c(1:n,1:n); 74 | H(:,:,l)=C_c(:,:,l)*s'; % Impulse response functions of the IV Wold representation (Bootstrap) 75 | end 76 | 77 | C_c_1= reshape(permute(H,[3 2 1]),hor,n,[]); 78 | ExtraBigC(:,:,j)=C_c_1; 79 | 80 | end 81 | 82 | % Create bands: 83 | 84 | LowH=zeros(hor,n); 85 | HighH=zeros(hor,n); 86 | 87 | for k=1:n 88 | Cmin = prctile(ExtraBigC(:,k,:),(100-conf)/2,3); %16th percentile 89 | LowH(:,k) = Cmin; %lower band 90 | Cmax = prctile(ExtraBigC(:,k,:),(100+conf)/2,3); %84th percentile 91 | HighH(:,k) = Cmax; %upper band 92 | end 93 | 94 | end 95 | 96 | -------------------------------------------------------------------------------- /MatlabRoutines/VAR/BQBoot.m: -------------------------------------------------------------------------------- 1 | function [bqirf bqsirfBoot] = BQBoot(y,p,H,c,MaxBoot,cl,ind,opt) 2 | n=size(y,2); % number of variables 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | %%%% OLS estimates 5 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 6 | [Y X] = VAR_str(y,c,p); % yy and XX all the sample 7 | T=size(Y,1); 8 | Bols=inv(X'*X)*X'*Y; 9 | VecB=reshape(Bols,n*(n*p+1),1); 10 | B=companion(VecB,p,n,c); 11 | C=Bols(1,:)'; 12 | u=Y-X*Bols; 13 | CovU=cov(u); 14 | u=u'; 15 | %%%% impulse response functions 16 | im=inv(eye(size(B,1))-B); 17 | SSigma=zeros(n*p,n*p); 18 | SSigma(1:n,1:n)=CovU; 19 | CS=im*SSigma*im'; 20 | CC=chol(CS(1:n,1:n))'; 21 | S=inv(im(1:n,1:n))*CC; 22 | 23 | for h=1:H 24 | irf(:,:,h)=B^(h-1); 25 | bqirf(:,:,h)=irf(1:n,1:n,h)*S; 26 | end 27 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 28 | %%%% Bootstrapping 29 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | for i=1:MaxBoot 31 | %i 32 | %%%% generate new series 33 | for t=1:T 34 | if t==1 35 | YB(:,1)=X(1,2:end)'; 36 | else 37 | a=fix(rand(1,1)*size(u,2))+1; 38 | uu=u(:,a); 39 | YB(:,t)=[C;zeros(n*p-n,1)]+B*YB(:,t-1)+[uu;zeros(n*p-n,1)]; 40 | end 41 | end 42 | 43 | %%%% estimate the new VAR 44 | yb=YB(1:n,:)'; 45 | [Yn Xn] = VAR_str(yb,c,p); % yy and XX all the sample 46 | 47 | T=size(Yn,1); 48 | Bolsn=inv(Xn'*Xn)*Xn'*Yn; 49 | CovUBoot=cov(Yn-Xn*Bolsn); 50 | VecBn=reshape(Bolsn,n*(n*p+1),1); 51 | Bn=companion(VecBn,p,n,c); 52 | 53 | imBoot=inv(eye(size(Bn,1))-Bn); 54 | SSigmaBoot=zeros(n*p,n*p); 55 | SSigmaBoot(1:n,1:n)=CovUBoot; 56 | CSBoot=imBoot*SSigmaBoot*imBoot'; 57 | CCBoot=chol(CSBoot(1:n,1:n))'; 58 | SBoot=inv(imBoot(1:n,1:n))*CCBoot; 59 | 60 | %%%% impulse response functions 61 | for h=1:H 62 | irfBoot(:,:,h,i)=Bn^(h-1); 63 | %%%% cholesky 64 | BQBoot(:,:,h,i)=irfBoot(1:n,1:n,h,i)*SBoot; 65 | end 66 | end 67 | lb=round(MaxBoot*(1-cl)/2); 68 | ub=round(MaxBoot*(cl+(1-cl)/2)); 69 | me=round(MaxBoot*.5); 70 | 71 | bqirf(ind,:,:)=cumsum(bqirf(ind,:,:),3); 72 | BQBoot(ind,:,:,:)=cumsum(BQBoot(ind,:,:,:),3); 73 | bqsirfBoot=sort(BQBoot,4); 74 | 75 | if opt==1 76 | k=0; 77 | figure(2) 78 | for ii=1:n 79 | for jj=1:n 80 | k=k+1; 81 | subplot(n,n,k),plot(1:H,squeeze(bqirf(ii,jj,:)),'k',... 82 | 1:H,squeeze(bqsirfBoot(ii,jj,:,[lb ub])),':k'),axis tight%,1:H,squeeze(mean(csirfBoot(ii,jj,:,:),4)),'--k'),axis tight 83 | end 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /MatlabRoutines/VAR/bkfilter.m: -------------------------------------------------------------------------------- 1 | function [fX] = bkfilter(X,pl,pu) 2 | % 3 | % MATLAB COMMAND FOR BAND PASS FILTER: fX = bkfilter(X,pl,pu) 4 | % 5 | % This is a Matlab program that filters time series data using an approximation to the 6 | % band pass filter as discussed in the paper "The Band Pass Filter" by Lawrence J. 7 | % Christiano and Terry J. Fitzgerald (1999). 8 | % 9 | % Required Inputs: 10 | % X - series of data (T x 1) 11 | % pl - minimum period of oscillation of desired component 12 | % pu - maximum period of oscillation of desired component (2<=plMSFEpoint)/nboot; 99 | pvalreg = sum(reg>regpoint)/nboot; 100 | -------------------------------------------------------------------------------- /Class IV - Proxy SVARs/GKreplication.m: -------------------------------------------------------------------------------- 1 | %% Replication Trial: 2 | 3 | clc,clear; 4 | 5 | load 'GKdata.mat' 6 | 7 | % load('trialdata.mat') 8 | 9 | %% Estimate VAR and implement Cholesky : 10 | 11 | finaldata=[log(CPI)*100, log(INDPRO)*100, DGS1, ebpm]; 12 | 13 | %% 2) Estimate a VAR(12) with finaldata: 14 | 15 | % First of all, we have to create the T x n matrices of the SUR 16 | % representation, i.e. Y and X: 17 | 18 | n=size(finaldata,2); % # of variables 19 | p=12; % 12 lags 20 | c=1; 21 | 22 | [pi_hat,~,~,~,~,err]=VAR(finaldata,p,1); 23 | BigA=[pi_hat(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, npxnp matrix 24 | 25 | %% 3) Wold representation impulse responses: 26 | 27 | C=zeros(n,n,50); 28 | 29 | for j=1:50 30 | BigC=BigA^(j-1); 31 | C(:,:,j)=BigC(1:n,1:n); % Impulse response functions of the Wold representation 32 | end 33 | 34 | %% Cholesky: 35 | 36 | T=length(finaldata)-n*p-n; % -p lags for n variables and -n constants 37 | omega=(err'*err)./T; %estimate of omega 38 | S=chol(omega,'lower'); %cholesky factorization, lower triangular matrix 39 | 40 | D=zeros(n,n,50); 41 | for i=1:50 42 | D(:,:,i)=C(:,:,i)*S; %cholesky wold respesentation 43 | end 44 | 45 | D_wold=(reshape(permute(D,[3 2 1]),50,n*n,[])); 46 | 47 | % Bootstrap: 48 | 49 | hor=50; 50 | iter=1000; 51 | conf=95; 52 | 53 | [HighD,LowD]=bootstrapchol(finaldata,hor,c,iter,conf,p,n); % function that performs bootstrap 54 | 55 | % Plot: 56 | 57 | colorBNDS=[0.7 0.7 0.7]; 58 | VARnames={'One-Year Rate'; 'CPI'; 'IP'; 'Excess Bond Premium'}; 59 | 60 | figure2=figure(2); 61 | 62 | for j=[11,3,7,15;1:n] 63 | subplot(n,1,j(2)) 64 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighD(:,j(1)) ; flipud(LowD(:,j(1)))],... 65 | colorBNDS,'EdgeColor','None'); hold on; 66 | plot(0:hor-1,D_wold(:,j(1)),'LineWidth',3.5,'Color','k'); axis tight 67 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 68 | title(VARnames(j(2)),'FontWeight','bold') 69 | legend({'95% confidence bands','IRF'},'FontSize',15) 70 | set(gca,'FontSize',15) 71 | xlim([0 hor-1]); 72 | end 73 | 74 | 75 | %% Estimate VAR and implement GK : 76 | 77 | clc; clear; 78 | 79 | load 'GKdata.mat' 80 | 81 | finaldata=[log(CPI)*100, log(INDPRO)*100, ebpm, FEDFUNDS]; 82 | 83 | %% Estimate a VAR(12) with finaldata: 84 | 85 | % First of all, we have to create the T x n matrices of the SUR 86 | % representation, i.e. Y and X: 87 | 88 | n=size(finaldata,2); % # of variables 89 | p=12; % 12 lags 90 | c=1; % constant 91 | 92 | % First Step - Estimate VAR and store residuals: 93 | 94 | [pi_hat,Y,X,Y_initial,Yfit,err]=VAR(finaldata,p,c); 95 | BigA=[pi_hat(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, npxnp matrix 96 | 97 | 98 | %% 3) Wold representation impulse responses: 99 | 100 | C=zeros(n,n,50); 101 | 102 | for j=1:50 103 | BigC=BigA^(j-1); 104 | C(:,:,j)=BigC(1:n,1:n); % Impulse response functions of the Wold representation 105 | end 106 | 107 | %% External instrument: 108 | 109 | % Second Step - Two stage regression: 110 | 111 | eps_p=err(length(finaldata)-p-length(FF4)+1:end,end); 112 | eps_q=err(length(finaldata)-p-length(FF4)+1:end,1:end-1); 113 | 114 | Z = FF4; 115 | 116 | [ols_instr,stderr_ols,tstat_ols]=OLS(eps_p,Z,1); 117 | 118 | u_hat_p=[ones(length(Z),1),Z]*ols_instr; 119 | 120 | sq_sp=(u_hat_p'*u_hat_p)\u_hat_p'*eps_q; 121 | 122 | % Step 3 - Normalise s_p=1 and compute IRFs 123 | 124 | s=[sq_sp,1]; 125 | 126 | H=zeros(n,1,50); 127 | for i=1:50 128 | H(:,:,i)=C(:,:,i)*s'; % IV wold respesentation 129 | end 130 | 131 | H_wold=(reshape(permute(H,[3 2 1]),50,n,[])); 132 | 133 | c=1; 134 | cc=1; 135 | 136 | Z = [NaN(length(finaldata)-p-length(FF4),1);FF4]; 137 | 138 | % Bootstrap: 139 | 140 | hor=50; 141 | iter=1000; 142 | conf=95; 143 | 144 | [HighH,LowH]=bootstrapVARIVnewmonthly(finaldata,hor,c,cc,iter,conf,p,n,Z); 145 | 146 | % Plot: 147 | 148 | colorBNDS=[0.7 0.7 0.7]; 149 | VARnames={'One-Year Rate'; 'CPI'; 'IP'; 'Excess Bond Premium'}; 150 | 151 | figure3=figure(3); 152 | 153 | for j=[4,1,2,3;1:n] 154 | subplot(n,1,j(2)) 155 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighH(:,j(1)) ; flipud(LowH(:,j(1)))],... 156 | colorBNDS,'EdgeColor','None'); hold on; 157 | plot(0:hor-1,H_wold(:,j(1)),'LineWidth',3.5,'Color','k'); axis tight 158 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 159 | title(VARnames(j(2)),'FontWeight','bold') 160 | legend({'95% confidence bands','IRF'},'FontSize',15) 161 | set(gca,'FontSize',15) 162 | xlim([0 hor-1]); 163 | end 164 | 165 | -------------------------------------------------------------------------------- /Class I - Estimating VARs with MATLAB/estimatingVAR.m: -------------------------------------------------------------------------------- 1 | %%% Empirical Time Series Methods for Macroeconomic Analysis 2 | %%% Estimating VARs 3 | %%% Author: Nicolo' Maffei Faccioli 4 | 5 | %% Class Example: 6 | 7 | clc; clear; 8 | 9 | %% Import the data and create spread and GDP's growth rate: 10 | 11 | load 'data.mat' 12 | 13 | GDPC1gr=diff(log(GDPC1)).*100; % real GDP's growth rate 14 | spread=(GS10-FEDFUNDS); % spread between 10 yrs and FF 15 | 16 | finaldata=[GDPC1gr,spread(2:end)]; 17 | 18 | % Plot: 19 | 20 | DATE(1)=[]; % exclude the first date as we lost one observation by taking diff(log(.)) 21 | 22 | figure1=figure(1); 23 | plot([GDPC1gr spread(2:end)],'LineWidth',2), axis('tight') 24 | ylabel('GDPC1 growth rate and spread','FontWeight','Bold') 25 | xlabel('Year','FontWeight','Bold') 26 | legend('GDPC1 growth rate','spread GS10-FF','italic') 27 | title('Plot of US GDP growth rate and GS10-FF spread ','FontWeight','Bold') 28 | set(gca,'FontSize',15) 29 | set(gca,'Xtick',1:20:length(GDPC1gr),'XtickLabel',DATE(1:20:end)) % Changing what's on the x axis with the "dates" in form dd-mm-yy 30 | xtickangle(90) 31 | 32 | %% Estimate a VAR(4) with finaldata: 33 | 34 | % First of all, we have to create the T x n matrices of the SUR 35 | % representation, i.e. Y and X: 36 | 37 | n=2; % # of variables 38 | p=4; % 4 lags 39 | c=1; % including constant 40 | 41 | [pi_hat,Y,X,Y_initial,Yfit,err]=VAR(finaldata,p,c); % VAR estimation, c - constant 42 | 43 | pi_hat % the first row corresponds to the constant 44 | 45 | BigA=[pi_hat(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, npxnp matrix 46 | % start from 2 to exclude the constant, mistake --> error 47 | 48 | 49 | 50 | %% Wold representation impulse responses: 51 | 52 | C=zeros(n,n,20); 53 | 54 | for j=1:20 55 | BigC=BigA^(j-1); 56 | C(:,:,j)=BigC(1:n,1:n); % Impulse response functions of the Wold representation 57 | end 58 | 59 | C_wold=reshape(permute(C,[3 2 1]),20,n*n,[]); % "will make our life easier" 60 | 61 | % Bootstrap: 62 | 63 | hor=20; 64 | iter=1000; 65 | conf=68; 66 | 67 | [HighC,LowC]=bootstrapVAR(finaldata,hor,c,iter,conf,p,n); % function that performs bootstrap 68 | 69 | % Plot: 70 | 71 | colorBNDS=[0.7 0.7 0.7]; 72 | VARnames={'Real GDP growth'; 'Spread'}; 73 | 74 | figure2=figure(2); 75 | 76 | for k=1:n 77 | for j=1:n 78 | subplot(n,n,j+n*k-n) 79 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighC(:,j+n*k-n); flipud(LowC(:,j+n*k-n))],... 80 | colorBNDS,'EdgeColor','None'); hold on; 81 | plot(0:hor-1,C_wold(:,j+n*k-n),'LineWidth',3.5,'Color','k'); hold on; % the confidence bands 82 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 83 | title(VARnames{k}) 84 | legend({'68% confidence bands','IRF'},'FontSize',12) 85 | set(gca,'FontSize',15) 86 | xlim([0 hor-1]); 87 | end 88 | end 89 | 90 | 91 | %% One period ahead forecasts: 92 | 93 | % First of all, we have to estimate the parameters using an initial sample 94 | % of T_0=123: 95 | 96 | T_0=123; 97 | ldiff=length(finaldata)-T_0; 98 | forecasts1=zeros(ldiff,n); 99 | 100 | % Notice that here I make a loop that repeats the steps until the end of 101 | % the sample: 102 | 103 | for k=1:ldiff 104 | 105 | [pi_hat,Y,X,Y_initial,Yfit,err]=VAR(finaldata(1:123+k-1,:),p,1); 106 | Ylast= reshape(flipud(Y(end-p+1:end,:))',1,[]); 107 | forecasts1(k,:)=pi_hat(1,:)+Ylast*pi_hat(2:end,:); % 1 period ahead 108 | 109 | end 110 | 111 | y_hat11=[NaN(123,1); forecasts1(:,1)]; % here I include vectors of NaN in order to include both actual and forecasts in the same graph 112 | y_hat21=[NaN(123,1); forecasts1(:,2)]; 113 | 114 | 115 | figure3=figure(3); 116 | plot([GDPC1gr y_hat11],'LineWidth',2), axis('tight') 117 | ylabel('GDP growth rate','FontWeight','Bold') 118 | xlabel('Year','FontWeight','Bold') 119 | legend('GDP growth rate','VAR(4) forecast 1 period ahead','italic') 120 | title('Plot of US GDP growth rate and VAR(4) forecasts one periods ahead','FontWeight','Bold') 121 | set(gca,'FontSize',15) 122 | set(gca,'Xtick',1:20:length(GDPC1gr),'XtickLabel',DATE(1:20:end)) % Changing what's on the x axis with the "dates" in form dd-mm-yy 123 | xtickangle(90) 124 | 125 | figure4=figure(4); 126 | plot([spread(2:end) y_hat21],'LineWidth',2), axis('tight') 127 | ylabel('spread GS10-FF','FontWeight','Bold') 128 | xlabel('Year','FontWeight','Bold') 129 | legend('spread GS10-FF','VAR(4) forecast 1 period ahead','italic') 130 | title('Plot of spread GS10-FF and VAR(4) forecasts one periods ahead ','FontWeight','Bold') 131 | set(gca,'FontSize',15) 132 | set(gca,'Xtick',1:20:length(spread(2:end)),'XtickLabel',DATE(1:20:end)) % Changing what's on the x axis with the "dates" in form dd-mm-yy 133 | xtickangle(90) 134 | 135 | 136 | 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /Class V - Factor Model/prctile.m: -------------------------------------------------------------------------------- 1 | function y = prctile(x,p,dim) 2 | %PRCTILE Percentiles of a sample. 3 | % Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar 4 | % or a vector of percent values. When X is a vector, Y is the same size 5 | % as P, and Y(i) contains the P(i)-th percentile. When X is a matrix, 6 | % the i-th row of Y contains the P(i)-th percentiles of each column of X. 7 | % For N-D arrays, PRCTILE operates along the first non-singleton 8 | % dimension. 9 | % 10 | % Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The 11 | % DIM'th dimension of Y has length LENGTH(P). 12 | % 13 | % Percentiles are specified using percentages, from 0 to 100. For an N 14 | % element vector X, PRCTILE computes percentiles as follows: 15 | % 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N), 16 | % ..., 100*((N-0.5)/N) percentiles. 17 | % 2) Linear interpolation is used to compute percentiles for percent 18 | % values between 100*(0.5/N) and 100*((N-0.5)/N) 19 | % 3) The minimum or maximum values in X are assigned to percentiles 20 | % for percent values outside that range. 21 | % 22 | % PRCTILE treats NaNs as missing values, and removes them. 23 | % 24 | % Examples: 25 | % y = prctile(x,50); % the median of x 26 | % y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x 27 | % 28 | % See also IQR, MEDIAN, NANMEDIAN, QUANTILE. 29 | 30 | % Copyright 1993-2004 The MathWorks, Inc. 31 | % $Revision: 1.1.8.2 $ $Date: 2011/05/09 01:26:31 $ 32 | 33 | if ~isvector(p) || numel(p) == 0 || any(p < 0 | p > 100) || ~isreal(p) 34 | error(message('stats:prctile:BadPercents')); 35 | end 36 | 37 | % Figure out which dimension prctile will work along. 38 | sz = size(x); 39 | if nargin < 3 40 | dim = find(sz ~= 1,1); 41 | if isempty(dim) 42 | dim = 1; 43 | end 44 | dimArgGiven = false; 45 | else 46 | % Permute the array so that the requested dimension is the first dim. 47 | nDimsX = ndims(x); 48 | perm = [dim:max(nDimsX,dim) 1:dim-1]; 49 | x = permute(x,perm); 50 | % Pad with ones if dim > ndims. 51 | if dim > nDimsX 52 | sz = [sz ones(1,dim-nDimsX)]; 53 | end 54 | sz = sz(perm); 55 | dim = 1; 56 | dimArgGiven = true; 57 | end 58 | 59 | % If X is empty, return all NaNs. 60 | if isempty(x) 61 | if isequal(x,[]) && ~dimArgGiven 62 | y = nan(size(p),class(x)); 63 | else 64 | szout = sz; szout(dim) = numel(p); 65 | y = nan(szout,class(x)); 66 | end 67 | 68 | else 69 | % Drop X's leading singleton dims, and combine its trailing dims. This 70 | % leaves a matrix, and we can work along columns. 71 | nrows = sz(dim); 72 | ncols = prod(sz) ./ nrows; 73 | x = reshape(x, nrows, ncols); 74 | 75 | x = sort(x,1); 76 | nonnans = ~isnan(x); 77 | 78 | % If there are no NaNs, do all cols at once. 79 | if all(nonnans(:)) 80 | n = sz(dim); 81 | if isequal(p,50) % make the median fast 82 | if rem(n,2) % n is odd 83 | y = x((n+1)/2,:); 84 | else % n is even 85 | y = (x(n/2,:) + x(n/2+1,:))/2; 86 | end 87 | else 88 | q = [0 100*(0.5:(n-0.5))./n 100]'; 89 | xx = [x(1,:); x(1:n,:); x(n,:)]; 90 | y = zeros(numel(p), ncols, class(x)); 91 | y(:,:) = interp1q(q,xx,p(:)); 92 | end 93 | 94 | % If there are NaNs, work on each column separately. 95 | else 96 | % Get percentiles of the non-NaN values in each column. 97 | y = nan(numel(p), ncols, class(x)); 98 | for j = 1:ncols 99 | nj = find(nonnans(:,j),1,'last'); 100 | if nj > 0 101 | if isequal(p,50) % make the median fast 102 | if rem(nj,2) % nj is odd 103 | y(:,j) = x((nj+1)/2,j); 104 | else % nj is even 105 | y(:,j) = (x(nj/2,j) + x(nj/2+1,j))/2; 106 | end 107 | else 108 | q = [0 100*(0.5:(nj-0.5))./nj 100]'; 109 | xx = [x(1,j); x(1:nj,j); x(nj,j)]; 110 | y(:,j) = interp1q(q,xx,p(:)); 111 | end 112 | end 113 | end 114 | end 115 | 116 | % Reshape Y to conform to X's original shape and size. 117 | szout = sz; szout(dim) = numel(p); 118 | y = reshape(y,szout); 119 | end 120 | % undo the DIM permutation 121 | if dimArgGiven 122 | y = ipermute(y,perm); 123 | end 124 | 125 | % If X is a vector, the shape of Y should follow that of P, unless an 126 | % explicit DIM arg was given. 127 | if ~dimArgGiven && isvector(x) 128 | y = reshape(y,size(p)); 129 | end 130 | -------------------------------------------------------------------------------- /Class I - Estimating VARs with MATLAB/prctile.m: -------------------------------------------------------------------------------- 1 | function y = prctile(x,p,dim) 2 | %PRCTILE Percentiles of a sample. 3 | % Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar 4 | % or a vector of percent values. When X is a vector, Y is the same size 5 | % as P, and Y(i) contains the P(i)-th percentile. When X is a matrix, 6 | % the i-th row of Y contains the P(i)-th percentiles of each column of X. 7 | % For N-D arrays, PRCTILE operates along the first non-singleton 8 | % dimension. 9 | % 10 | % Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The 11 | % DIM'th dimension of Y has length LENGTH(P). 12 | % 13 | % Percentiles are specified using percentages, from 0 to 100. For an N 14 | % element vector X, PRCTILE computes percentiles as follows: 15 | % 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N), 16 | % ..., 100*((N-0.5)/N) percentiles. 17 | % 2) Linear interpolation is used to compute percentiles for percent 18 | % values between 100*(0.5/N) and 100*((N-0.5)/N) 19 | % 3) The minimum or maximum values in X are assigned to percentiles 20 | % for percent values outside that range. 21 | % 22 | % PRCTILE treats NaNs as missing values, and removes them. 23 | % 24 | % Examples: 25 | % y = prctile(x,50); % the median of x 26 | % y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x 27 | % 28 | % See also IQR, MEDIAN, NANMEDIAN, QUANTILE. 29 | 30 | % Copyright 1993-2004 The MathWorks, Inc. 31 | % $Revision: 1.1.8.2 $ $Date: 2011/05/09 01:26:31 $ 32 | 33 | if ~isvector(p) || numel(p) == 0 || any(p < 0 | p > 100) || ~isreal(p) 34 | error(message('stats:prctile:BadPercents')); 35 | end 36 | 37 | % Figure out which dimension prctile will work along. 38 | sz = size(x); 39 | if nargin < 3 40 | dim = find(sz ~= 1,1); 41 | if isempty(dim) 42 | dim = 1; 43 | end 44 | dimArgGiven = false; 45 | else 46 | % Permute the array so that the requested dimension is the first dim. 47 | nDimsX = ndims(x); 48 | perm = [dim:max(nDimsX,dim) 1:dim-1]; 49 | x = permute(x,perm); 50 | % Pad with ones if dim > ndims. 51 | if dim > nDimsX 52 | sz = [sz ones(1,dim-nDimsX)]; 53 | end 54 | sz = sz(perm); 55 | dim = 1; 56 | dimArgGiven = true; 57 | end 58 | 59 | % If X is empty, return all NaNs. 60 | if isempty(x) 61 | if isequal(x,[]) && ~dimArgGiven 62 | y = nan(size(p),class(x)); 63 | else 64 | szout = sz; szout(dim) = numel(p); 65 | y = nan(szout,class(x)); 66 | end 67 | 68 | else 69 | % Drop X's leading singleton dims, and combine its trailing dims. This 70 | % leaves a matrix, and we can work along columns. 71 | nrows = sz(dim); 72 | ncols = prod(sz) ./ nrows; 73 | x = reshape(x, nrows, ncols); 74 | 75 | x = sort(x,1); 76 | nonnans = ~isnan(x); 77 | 78 | % If there are no NaNs, do all cols at once. 79 | if all(nonnans(:)) 80 | n = sz(dim); 81 | if isequal(p,50) % make the median fast 82 | if rem(n,2) % n is odd 83 | y = x((n+1)/2,:); 84 | else % n is even 85 | y = (x(n/2,:) + x(n/2+1,:))/2; 86 | end 87 | else 88 | q = [0 100*(0.5:(n-0.5))./n 100]'; 89 | xx = [x(1,:); x(1:n,:); x(n,:)]; 90 | y = zeros(numel(p), ncols, class(x)); 91 | y(:,:) = interp1q(q,xx,p(:)); 92 | end 93 | 94 | % If there are NaNs, work on each column separately. 95 | else 96 | % Get percentiles of the non-NaN values in each column. 97 | y = nan(numel(p), ncols, class(x)); 98 | for j = 1:ncols 99 | nj = find(nonnans(:,j),1,'last'); 100 | if nj > 0 101 | if isequal(p,50) % make the median fast 102 | if rem(nj,2) % nj is odd 103 | y(:,j) = x((nj+1)/2,j); 104 | else % nj is even 105 | y(:,j) = (x(nj/2,j) + x(nj/2+1,j))/2; 106 | end 107 | else 108 | q = [0 100*(0.5:(nj-0.5))./nj 100]'; 109 | xx = [x(1,j); x(1:nj,j); x(nj,j)]; 110 | y(:,j) = interp1q(q,xx,p(:)); 111 | end 112 | end 113 | end 114 | end 115 | 116 | % Reshape Y to conform to X's original shape and size. 117 | szout = sz; szout(dim) = numel(p); 118 | y = reshape(y,szout); 119 | end 120 | % undo the DIM permutation 121 | if dimArgGiven 122 | y = ipermute(y,perm); 123 | end 124 | 125 | % If X is a vector, the shape of Y should follow that of P, unless an 126 | % explicit DIM arg was given. 127 | if ~dimArgGiven && isvector(x) 128 | y = reshape(y,size(p)); 129 | end 130 | -------------------------------------------------------------------------------- /Class II - Short-Run and Long-Run Restrictions/prctile.m: -------------------------------------------------------------------------------- 1 | function y = prctile(x,p,dim) 2 | %PRCTILE Percentiles of a sample. 3 | % Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar 4 | % or a vector of percent values. When X is a vector, Y is the same size 5 | % as P, and Y(i) contains the P(i)-th percentile. When X is a matrix, 6 | % the i-th row of Y contains the P(i)-th percentiles of each column of X. 7 | % For N-D arrays, PRCTILE operates along the first non-singleton 8 | % dimension. 9 | % 10 | % Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The 11 | % DIM'th dimension of Y has length LENGTH(P). 12 | % 13 | % Percentiles are specified using percentages, from 0 to 100. For an N 14 | % element vector X, PRCTILE computes percentiles as follows: 15 | % 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N), 16 | % ..., 100*((N-0.5)/N) percentiles. 17 | % 2) Linear interpolation is used to compute percentiles for percent 18 | % values between 100*(0.5/N) and 100*((N-0.5)/N) 19 | % 3) The minimum or maximum values in X are assigned to percentiles 20 | % for percent values outside that range. 21 | % 22 | % PRCTILE treats NaNs as missing values, and removes them. 23 | % 24 | % Examples: 25 | % y = prctile(x,50); % the median of x 26 | % y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x 27 | % 28 | % See also IQR, MEDIAN, NANMEDIAN, QUANTILE. 29 | 30 | % Copyright 1993-2004 The MathWorks, Inc. 31 | % $Revision: 1.1.8.2 $ $Date: 2011/05/09 01:26:31 $ 32 | 33 | if ~isvector(p) || numel(p) == 0 || any(p < 0 | p > 100) || ~isreal(p) 34 | error(message('stats:prctile:BadPercents')); 35 | end 36 | 37 | % Figure out which dimension prctile will work along. 38 | sz = size(x); 39 | if nargin < 3 40 | dim = find(sz ~= 1,1); 41 | if isempty(dim) 42 | dim = 1; 43 | end 44 | dimArgGiven = false; 45 | else 46 | % Permute the array so that the requested dimension is the first dim. 47 | nDimsX = ndims(x); 48 | perm = [dim:max(nDimsX,dim) 1:dim-1]; 49 | x = permute(x,perm); 50 | % Pad with ones if dim > ndims. 51 | if dim > nDimsX 52 | sz = [sz ones(1,dim-nDimsX)]; 53 | end 54 | sz = sz(perm); 55 | dim = 1; 56 | dimArgGiven = true; 57 | end 58 | 59 | % If X is empty, return all NaNs. 60 | if isempty(x) 61 | if isequal(x,[]) && ~dimArgGiven 62 | y = nan(size(p),class(x)); 63 | else 64 | szout = sz; szout(dim) = numel(p); 65 | y = nan(szout,class(x)); 66 | end 67 | 68 | else 69 | % Drop X's leading singleton dims, and combine its trailing dims. This 70 | % leaves a matrix, and we can work along columns. 71 | nrows = sz(dim); 72 | ncols = prod(sz) ./ nrows; 73 | x = reshape(x, nrows, ncols); 74 | 75 | x = sort(x,1); 76 | nonnans = ~isnan(x); 77 | 78 | % If there are no NaNs, do all cols at once. 79 | if all(nonnans(:)) 80 | n = sz(dim); 81 | if isequal(p,50) % make the median fast 82 | if rem(n,2) % n is odd 83 | y = x((n+1)/2,:); 84 | else % n is even 85 | y = (x(n/2,:) + x(n/2+1,:))/2; 86 | end 87 | else 88 | q = [0 100*(0.5:(n-0.5))./n 100]'; 89 | xx = [x(1,:); x(1:n,:); x(n,:)]; 90 | y = zeros(numel(p), ncols, class(x)); 91 | y(:,:) = interp1q(q,xx,p(:)); 92 | end 93 | 94 | % If there are NaNs, work on each column separately. 95 | else 96 | % Get percentiles of the non-NaN values in each column. 97 | y = nan(numel(p), ncols, class(x)); 98 | for j = 1:ncols 99 | nj = find(nonnans(:,j),1,'last'); 100 | if nj > 0 101 | if isequal(p,50) % make the median fast 102 | if rem(nj,2) % nj is odd 103 | y(:,j) = x((nj+1)/2,j); 104 | else % nj is even 105 | y(:,j) = (x(nj/2,j) + x(nj/2+1,j))/2; 106 | end 107 | else 108 | q = [0 100*(0.5:(nj-0.5))./nj 100]'; 109 | xx = [x(1,j); x(1:nj,j); x(nj,j)]; 110 | y(:,j) = interp1q(q,xx,p(:)); 111 | end 112 | end 113 | end 114 | end 115 | 116 | % Reshape Y to conform to X's original shape and size. 117 | szout = sz; szout(dim) = numel(p); 118 | y = reshape(y,szout); 119 | end 120 | % undo the DIM permutation 121 | if dimArgGiven 122 | y = ipermute(y,perm); 123 | end 124 | 125 | % If X is a vector, the shape of Y should follow that of P, unless an 126 | % explicit DIM arg was given. 127 | if ~dimArgGiven && isvector(x) 128 | y = reshape(y,size(p)); 129 | end 130 | -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/HL2.m: -------------------------------------------------------------------------------- 1 | 2 | function [q, o_log, o,rr,rs] = HL2(panel, kmax, cmax, nmin, penalty) 3 | % 4 | 5 | % cmax : c = [0:cmax], e.g cmax = 3 6 | % 7 | % penalty : 8 | % p1 = ((M/T)^0.5 + M^(-2) + n^(-1))*log(min([(T/M)^0.5; M^2; n])) 9 | % p2 = (min([(T/M)^0.5; M^2; n])).^(-1/2) 10 | % p3 = (min([(T/M)^0.5; M^2; n])).^(-1)*log(min([(T/M)^0.5; M^2; n])) 11 | % 12 | %-------------------------------------------------------------------------- 13 | % 14 | % 15 | % 16 | % 17 | 18 | 19 | [T,n] = size(panel); 20 | x = standardize(panel); 21 | [a Ns]=sort(rand(n,1)); 22 | x = x(:,Ns); 23 | s=0; 24 | 25 | 26 | for N = nmin:round((n-nmin)/10):n 27 | s=s+1; 28 | tau = round(N*T/n); 29 | M = 2*round(sqrt(tau)); 30 | eigv = subr_1(x(end-tau+1:end,1:N), M); 31 | eigv = (eigv >0).*eigv; 32 | IC1 = flipud(cumsum(flipud(eigv))); 33 | IC1 = IC1(1:kmax+1,:); 34 | [a1,a2] = size(IC1); 35 | 36 | 37 | p = ((M/tau)^0.5 + M^(-2) + N^(-1))*log(min([(tau/M)^0.5; M^2; N]))*ones(a1,a2); 38 | 39 | if penalty == 'p2' 40 | p = (min([(tau/M)^0.5; M^2; N])).^(-1/2)*ones(a1,a2); 41 | elseif penalty == 'p3' 42 | p = (min([(tau/M)^0.5; M^2; N])).^(-1)*log(min([(tau/M)^0.5; M^2; N]))*ones(a1,a2); 43 | end 44 | 45 | 46 | for c = 1:floor(cmax*100) 47 | cc = c/100; 48 | 49 | IC_log = log(IC1./N) + kron([0:kmax]',ones(1,a2)).*p*cc; 50 | IC = (IC1./N) + kron([0:kmax]',ones(1,a2)).*p*cc; 51 | 52 | [rr,rs]=find((IC_log == ones(kmax+1,1)*min(IC_log))==1); 53 | o_log(s,c)=rr-1; 54 | 55 | [rr,rs]=find((IC == ones(kmax+1,1)*min(IC))==1); 56 | o(s,c)=rr-1; 57 | end %c 58 | end %n 59 | 60 | 61 | g1 = find(std(o) == 0); 62 | f1 = find(o(end, g1) < kmax); 63 | if numel(f1) > 0; 64 | q1 = o(end, g1(f1(1)) ); 65 | else 66 | q1=999; 67 | end 68 | g2 = find(std(o_log) == 0); 69 | f2 = find(o_log(end, g2) < kmax); 70 | if numel(f2) > 0 71 | q2 = o_log(end, g2(f2(1)) ); 72 | else 73 | q2=999; 74 | end 75 | q = [q1 q2]; 76 | 77 | set(0,'DefaultLineLineWidth',2); 78 | cr=[1:floor(cmax*100)]'/100; 79 | 80 | % %figure 81 | % %subplot(2,1,1) 82 | % %plot(cr,o(end,:),'r-') 83 | % axis tight 84 | % xlabel('c') 85 | % legend('q^{*T}_{c;n}') 86 | % title('estimated number of factors, IC_1 - nolog criterion') 87 | % 88 | % subplot(2,1,2) 89 | % plot(cr,std(o),'b-') 90 | % xlabel('c') 91 | % axis tight 92 | % legend('S_c') 93 | % title('S_c, IC_1 - nolog criterion') 94 | % 95 | % 96 | % figure 97 | % 98 | % subplot(2,1,1) 99 | % 100 | % plot(cr,o_log(end,:),'r-') 101 | % axis tight 102 | % xlabel('c') 103 | % legend('q^{*T}_{c;n}') 104 | % title('estimated number of factors, IC_2 - log criterion') 105 | % 106 | % subplot(2,1,2) 107 | % plot(cr,std(o_log),'b-') 108 | % xlabel('c') 109 | % axis tight 110 | % legend('S_c') 111 | % title('S_c, IC_2 - log criterion') 112 | 113 | 114 | 115 | 116 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 117 | 118 | function E = subr_1(x, M) 119 | 120 | %x = center(x); 121 | % define some useful quantities 122 | [T,N] = size(x); 123 | w = M; 124 | W = 2*w+1; 125 | % compute covariances 126 | SS = zeros(W,N*N); 127 | for k = 1:w+1, 128 | Sk = center(x(k:T,:))'*center(x(1:T+1-k,:))/(T-k); 129 | S_k = Sk'; 130 | % the x(:) creates a column vector from the matrix x columnwise 131 | SS(w-k+2,:) = S_k(:)'; 132 | SS(w+k,:) = Sk(:)'; 133 | end 134 | 135 | 136 | % compute the spectral matrix in w points (S) 137 | % [0:2*pi/W:4*pi*w/W] 138 | %Factor = exp(-sqrt(-1)*(-w:w)'*(0:2*pi/W:4*pi*w/W)); 139 | 140 | 141 | freq = [0:2*pi/W:pi]; 142 | Factor = exp(-sqrt(-1)*(-w:w)'*freq); 143 | 144 | ww = 1 - abs([-w:w])/(w+1); 145 | 146 | % multiply first line of SS by ww(1) 147 | % multiply second line of SS by ww(2) 148 | 149 | S = diag(ww)*SS(1:W,:); 150 | 151 | % inverse to the (:) operation 152 | % S = reshape(S'*Factor,N,N*W); 153 | 154 | S = reshape(S'*Factor,N,N*(w+1)); 155 | 156 | % compute the eigenvalues 157 | eigenvalues = zeros(N,w+1); 158 | D = eig(S(:,1:N)); 159 | eigenvalues(:,1) = flipud(sort(real(D))); 160 | 161 | for j = 1:w, 162 | D = eig(S(:,j*N+1:(j+1)*N)); 163 | eigenvalues(:,1+j) = flipud(sort(real(D))); 164 | end 165 | %eigenvalues 166 | %[eigenvalues(:,1) eigenvalues(:,2:jj+1)*2] 167 | E = [eigenvalues(:,1) eigenvalues(:,2:w+1)*2]*ones(w+1,1)/(2*w+1); 168 | 169 | 170 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 171 | 172 | function XC = center(X) 173 | 174 | [T n] = size(X); 175 | XC = X - ones(T,1)*mean(X); 176 | XC = XC./kron(ones(T,1),std(XC)); 177 | 178 | 179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /MatlabRoutines/ReplicaForniGambetti/replicaForniGambettiRevision.m: -------------------------------------------------------------------------------- 1 | load GF 2 | load codeGF 3 | load transGF 4 | codeGF(83:87) = 0; 5 | codeGF(71) = 1; 6 | x = standardize(GF); 7 | % the number of static and dynamic factors 8 | % static factors (Bai Ng 2002) 9 | [PC,IC] = baingcriterion(x,25); 10 | [minimum,rhat] = min(IC(:,2)); 11 | Fhat = principalcomponents(x,rhat); 12 | % number of lags in the VAR 13 | %[AIC, BIC, e] = aicbic(Fhat,9); 14 | % dynamic factors (Bai Ng 2007, SW 2005) 15 | k = 2; 16 | nrepli=500; 17 | baingqhat = baingdftest(x,rhat,k); 18 | swqhat = swdftest(x,rhat,k); 19 | % dynamic factors (Hallin Liska 2007) 20 | %q1 = HL2(x, 16, 1.5, 30, 'p1'); 21 | %q2 = HL2(x, 16, 1.5, 30, 'p2'); 22 | %q3 = HL2(x, 16, 1.5, 30, 'p3'); 23 | %HLqhat = [q1;q2;q3]; 24 | % no of dyn fractors with r static factors according to Bai Ng 2007 25 | rhat 26 | %HLqhat 27 | baingqhat 28 | swqhat 29 | intv = [5 96 75 106]; 30 | iv = [107:109 105 89 67 71 3 72 65 54 62 19 44 47 22 20 25 30 ]; 31 | 32 | %%%% construct labels 33 | for i=1:size(GF,2) 34 | titoli(i,:)=[' ']; 35 | end 36 | titoli(intv,:)= ... 37 | [' Ind. production '; 38 | ' CPI '; 39 | ' Federal funds rate '; 40 | ' Swi/US real ER ']; 41 | 42 | titoli(iv,:)= ... 43 | [' Jap/US real ER '; 44 | ' UK/US real ER '; 45 | ' Can/US real ER '; 46 | ' Earnings '; 47 | ' PPI '; 48 | ' M2 '; 49 | ' Loans '; 50 | ' Real pers. consumption '; 51 | ' Consumer credit '; 52 | ' Orders '; 53 | ' Housing starts '; 54 | ' Inventories '; 55 | ' Capacity utilization '; 56 | ' Hours '; 57 | ' Hours manufacturing '; 58 | ' Employment '; 59 | ' Vacancies '; 60 | ' Unemployment '; 61 | ' Unemployment rate ']; 62 | 63 | [virf vbootirf] = CholeskyBoot(GF(:,intv),9,49,1,nrepli,.8,[1 2 ],0); 64 | for i=1:size(vbootirf,4), 65 | vbootirf(:,:,:,i)=vbootirf(:,:,:,i)/vbootirf(3,3,1,i)*0.5; 66 | end 67 | 68 | % vbootirf=vbootirf/virf(3,3,1)*0.5; 69 | 70 | virf=virf/virf(3,3,1)*0.5; 71 | 72 | varirf = confband(vbootirf,virf,.8); 73 | 74 | varirf([1 2 4],:,:,:)=varirf([1 2 4],:,:,:)*100; 75 | 76 | [irf, v, stdv, meanv,chi,sh,ci,bootci,imp,bootimp] =DoEverything(GF, intv, rhat, k, 52, codeGF,nrepli); 77 | 78 | for i=1:size(bootci,4), 79 | bootci(:,:,:,i)=bootci(:,:,:,i)/bootci(75,3,1,i)*0.5; 80 | end 81 | 82 | % bootci=bootci/ci(75,3,1)*0.5; 83 | 84 | ci=ci/ci(75,3,1)*0.5; 85 | 86 | irf = confband(bootci, ci, .8); 87 | 88 | 89 | [canada,japan,uk] = uhligcumulatedforwardpremium(irf,0); 90 | commonvar = var(chi)./var(GF); 91 | 92 | index5=MyFind([1:112]'.*(transGF==5)') 93 | index4=MyFind([1:112]'.*(transGF==4)') 94 | index=sort([index5;index4]); 95 | 96 | irf(index,:,:,:)=irf(index,:,:,:)*100; 97 | 98 | 99 | % figure(1); 100 | % DoSubPlots(varirf,2,2,[1 2 3 4],3,titoli(intv,:)); 101 | 102 | [vvar, stdvar] = ExplainedVariances(vbootirf,virf, 3); 103 | expvariancevar = [vvar(:,1) stdvar(:,1) vvar(:,7) stdvar(:,7) vvar(:,13) stdvar(:,13) vvar(:,49) stdvar(:,49)] 104 | 105 | % figure(2); 106 | % DoSubPlots(irf,2,2,intv,3,titoli); 107 | 108 | figure(1); 109 | DoSubPlots([varirf;irf],4,2,[1 9 2 100 3 79 4 110],3); 110 | 111 | 112 | expvariancedfm = [v(intv,1) stdv(intv,1) v(intv,6) stdv(intv,6) v(intv,12) stdv(intv,12) v(intv,48) stdv(intv,48)] 113 | expvariancedfm2 = [v(iv,1) stdv(iv,1) v(iv,6) stdv(iv,6) v(iv,12) stdv(iv,12) v(iv,48) stdv(iv,48)]; 114 | %expvariance = [expvariancevar; expvariancedfm] 115 | figure(2); 116 | subplot(3,2,2),plot(1:size(irf,3)-1,canada(:,[1 3]),'k:', 'LineWidth',.5); 117 | hold on; 118 | plot(1:size(irf,3)-1,canada(:,2),'k', 'LineWidth',2); 119 | title(['Canada/US UIP']); 120 | axis tight; hold off; 121 | subplot(3,2,4), plot(1:size(irf,3)-1,japan(:,[1 3]),'k:', 'LineWidth',.5); 122 | hold on; 123 | plot(1:size(irf,3)-1,japan(:,2),'k', 'LineWidth',2); 124 | title(['Japan/US UIP']); 125 | axis tight; hold off; 126 | subplot(3,2,6), plot(1:size(irf,3)-1,uk(:,[1 3]),'k:', 'LineWidth',.5); 127 | hold on; 128 | plot(1:size(irf,3)-1,uk(:,2),'k', 'LineWidth',2); 129 | title(['UK/US UIP']); 130 | axis tight; hold off 131 | subplot(3,2,1),plot(1:size(irf,3),squeeze(irf(109,3,:,[1 3])),'k:', 'LineWidth',1); 132 | title(['Canada/US real exchange rate']); 133 | hold on; 134 | plot(1:size(irf,3),squeeze(irf(109,3,:,2)),'k', 'LineWidth',1.5); 135 | axis tight; hold off 136 | subplot(3,2,3),plot(1:size(irf,3),squeeze(irf(107,3,:,[1 3])),'k:', 'LineWidth',1); 137 | title(['Japan/US real exchange rate']); 138 | hold on; 139 | plot(1:size(irf,3),squeeze(irf(107,3,:,2)),'k', 'LineWidth',1.5); 140 | axis tight; hold off 141 | subplot(3,2,5),plot(1:size(irf,3),-squeeze(irf(108,3,:,[1 3])),'k:', 'LineWidth',1); 142 | title(['UK/US real exchange rate']); 143 | hold on; 144 | plot(1:size(irf,3),-squeeze(irf(108,3,:,2)),'k', 'LineWidth',1.5); 145 | axis tight; hold off 146 | 147 | 148 | %%%%%% old figures 149 | % figure(4); 150 | % DoSubPlots(irf,2,2,[105 89 67 71],3,titoli); 151 | % figure(5); 152 | % DoSubPlots(irf,3,2,[3 72 65 54 62 19],3,titoli); 153 | % figure(6); 154 | % DoSubPlots(irf,3,2,[44 47 22 20 25 30 ],3,titoli); 155 | 156 | figure(3); 157 | DoSubPlots(irf,5,3,[105 89 67 71 3 72 65 54 62 44 47 22 20 25 30],3,titoli); 158 | 159 | nsfactors = [4 10 16 ]; 160 | nlags = [8 3 2]; 161 | for j = 1:3 162 | [imp3, chi3] = DfmCholImp(GF, intv, nsfactors(j),nlags(j), 48); 163 | cimp3 = CumImp(imp3, codeGF); 164 | cimp3(108,3,:) = -cimp3(108,3,:); 165 | cimp3cr(:,j,:) = squeeze(cimp3([96 106:109],3,:))*100; 166 | cimp3cr(:,j,:) = cimp3cr(:,j,:)/cimp3(75,3,1)*0.5; 167 | end 168 | 169 | figure(4) 170 | for j=1:4 171 | for k=1:3 172 | subplot(4,3,3*(j-1)+k) 173 | plot(squeeze(cimp3cr(j+1,k,:))','k'), 174 | axis tight 175 | if j==1 & k==1 176 | ylabel(titoli(106,:)) 177 | title('4 static factors') 178 | end 179 | if j==1 & k==2 180 | title('10 static factors') 181 | end 182 | if j==1 & k==3 183 | title('16 static factors') 184 | end 185 | if j==2 & k==1 186 | ylabel(titoli(107,:)) 187 | end 188 | if j==3 & k==1 189 | ylabel(titoli(108,:)) 190 | end 191 | if j==4 & k==1 192 | ylabel(titoli(109,:)) 193 | end 194 | end 195 | end 196 | 197 | % figures for appendix 198 | [irf, v, stdv, meanv,chi,sh,ci,bootci,imp,bootimp] =DoEverything(GF, intv, rhat, k, 52, codeGF,10); 199 | 200 | ci=ci/ci(75,3,1)*0.5; 201 | ci(index,:,:)=ci(index,:,:)*100; 202 | ci(108,:,:)=-ci(108,:,:); 203 | 204 | [irf2, v2, stdv2, meanv2, chi2, sh2, ci2, bootci2] =DoEverything(GF, [intv 107:109], rhat, 2, 52, codeGF,10); 205 | 206 | ci2=ci2/ci2(75,3,1)*0.5; 207 | ci2(index,:,:)=ci2(index,:,:)*100; 208 | ci2(108,:,:)=-ci2(108,:,:); 209 | 210 | [irf3, v3, stdv3, meanv3, chi3, sh3, ci3, bootci3] =DoEverything(GF, [intv ], 10, 2, 52, codeGF,10); 211 | 212 | ci3=ci3/ci3(75,3,1)*0.5; 213 | ci3(index,:,:)=ci3(index,:,:)*100; 214 | ci3(108,:,:)=-ci3(108,:,:); 215 | 216 | figure(5); 217 | idx=[intv 107:109 54 65 19 22 30]; 218 | for i=1:12 219 | subplot(4,3,i),plot(1:49,squeeze(ci(idx(i),3,:)),'k',... 220 | 1:49,squeeze(ci2(idx(i),3,:)),':k',... 221 | 1:49,squeeze(ci3(idx(i),3,:)),'--k'),title(titoli(idx(i),:)) 222 | end 223 | % ,'LineWidth',1.5 224 | % for j = 1: 16 225 | % [imp4, chi4] = DfmCholImp(GF, intv,j+3,ceil(30/(j+3)), 48); 226 | % cimp4 = CumImp(imp4, codeGF); 227 | % a = cumsum(cimp4.^2,3); 228 | % v4 = squeeze(a(:,3,:))./squeeze(sum(a,2)); 229 | % t4(:,j) = v4([intv 107:109],[ 48]); 230 | % end 231 | -------------------------------------------------------------------------------- /Class III - Sign Restrictions/bvarsignexample.m: -------------------------------------------------------------------------------- 1 | %%% Bayesian VAR - Sign Restrictions 2 | %%% Author: Nicol� Maffei Faccioli 3 | 4 | %% Importing the data: 5 | 6 | clc; clear; 7 | 8 | load 'newtrialAP.mat' 9 | load 'APWW20081.mat' 10 | load 'GDPMA.mat' 11 | load 'GS10.mat' 12 | load 'tenyrs.mat' 13 | 14 | % Asset Purchase Announcements: 15 | 16 | DATES{83, 1}(1) = "01/11/2014"; 17 | DATES{84, 1}(1) = "01/12/2014"; 18 | 19 | figure1=figure(1); 20 | plot(APWW20081(1:end-5),'LineWidth',3.5), axis tight 21 | ylabel('US AP Announcements','FontWeight','Bold') 22 | xlabel('Year','FontWeight','Bold') 23 | legend('AP Announcements','Error','italic') 24 | title('Plot of US Asset Purchase Announcements ($bn) ','FontWeight','Bold') 25 | set(gca,'Xtick',1:5:length(APWW20081(1:end-5)),'XtickLabel',DATES(1:5:end)) % Changing what's on the x axis with the "dates" in form dd-mm-yy 26 | set(gca,'FontSize',16) 27 | xtickangle(90) 28 | grid on 29 | 30 | %% Estimating a Bayesian VAR(2) with Gibbs Sampler: 31 | 32 | y=[log(GDPMA(1:end-24))*100, log(CPI(1:end-24))*100, APWW20081(1:end)./143.839, GS10(1:end-24), log(SP500(1:end-24))*100]; 33 | 34 | [T,n]=size(y); 35 | p=2; % # of lags 36 | c=1; % include constant | if c=0, no constant 37 | 38 | % Draws set up: 39 | 40 | sel=2; 41 | maxdraws=3000; 42 | b_sel=1001:sel:maxdraws; % exclude the first 1000 draws 43 | drawfin=size(b_sel,2); % number of stored draws 44 | 45 | % Set up the loop for each draw : 46 | 47 | PI=zeros(n*p+c,n,maxdraws+1); 48 | BigA=zeros(n*p,n*p,maxdraws+1); 49 | Q=zeros(n,n,maxdraws+1); 50 | errornorm=zeros(T-p,n,maxdraws+1); 51 | fittednorm=zeros(T-p,n,maxdraws+1); 52 | 53 | for i=1:maxdraws+1 54 | 55 | [PI(:,:,i),BigA(:,:,i),Q(:,:,i),errornorm(:,:,i),fittednorm(:,:,i)]=BVAR(y,p,c); 56 | 57 | end 58 | 59 | %% Sign Restricted IRFs: 60 | 61 | hor=48; 62 | restr=1; % # of restricted periods (1 = on impact) after the shock 63 | candidateirf=zeros(n,n,hor,drawfin); % candidate impulse response 64 | 65 | % Discard the first draws: 66 | 67 | BigA=BigA(:,:,b_sel); 68 | Q=Q(:,:,b_sel); 69 | 70 | % Set up 4-D matrices for IRFs to be filled in the loop: 71 | 72 | C=zeros(n,n,hor,drawfin); 73 | D=zeros(n,n,hor,drawfin); 74 | 75 | 76 | h = waitbar(0,'Please wait, some fantastic results are coming ...'); 77 | 78 | for k=1:drawfin 79 | 80 | for j=1:48 81 | BigC=BigA(:,:,k)^(j-1); 82 | C(:,:,j,k)=BigC(1:n,1:n); % Impulse response functions of the Wold representation 83 | end 84 | 85 | % Cholesky factorization: 86 | 87 | S=chol(Q(:,:,k),'lower'); % lower triangular matrix 88 | 89 | for i=1:48 90 | D(:,:,i,k)=C(:,:,i,k)*S; % Cholesky Wold respesentation 91 | end 92 | 93 | % Sign Restrictions Loop: 94 | 95 | control=0; 96 | 97 | while control==0 98 | 99 | % STEP 1: 100 | 101 | W=mvnrnd(zeros(n),eye(n)); % draw an independent standard normal nxn matrix 102 | [Qr,~]=qr_dec(W); % QR decomposition with the with the diagonal or R normalized to be positive 103 | 104 | % STEP 2 - Compute candidate IRFs: 105 | 106 | for i=1:hor 107 | candidateirf(:,:,i,k)=D(:,:,i,k)*Qr'; 108 | end 109 | 110 | % STEP 3 - Check if the candidates satisfy all the sign restrictions: 111 | 112 | % N.B. : In what follows, following RWZ (2010), I use, to gain 113 | % efficiency, the fact that changing the sign of any of the columns of 114 | % matrix Q results in another orthogonal matrix. If all of the 115 | % candidate IRFs have wrong signs, then, by changing the sign of, say, 116 | % column j of Q, we obtain a new rotation matrix that, multiplied by D 117 | % will give us a candidate that satisfies the sign restrictions. 118 | 119 | %=== Responses to a Supply Shock: 120 | 121 | a = (candidateirf(1,1,1:restr,k) > 0) .* (candidateirf(2,1,1:restr,k) < 0) .* (candidateirf(4,1,1:restr,k) > 0) .* (candidateirf(5,1,1:restr,k) > 0); 122 | if (max(a)==0) 123 | %--- Swiching the sign of the shock. 124 | am = (candidateirf(1,1,1:restr,k) < 0) .* (candidateirf(2,1,1:restr,k) > 0) .* (candidateirf(4,1,1:restr,k) < 0) .* (candidateirf(5,1,1:restr,k) < 0); 125 | 126 | if (min(am)==0) 127 | continue; %The restrictions are not satisfied. Go the beginning to redraw. 128 | else 129 | %--- Normalizing according to the switched sign. 130 | Qr(1,:) = -Qr(1,:); 131 | end 132 | elseif (min(a)==0) 133 | continue; %The restrictions are not satisfied. Go the beginning to redraw. 134 | end 135 | 136 | %=== Responses to a Demand shock: 137 | 138 | a = (candidateirf(1,2,1:restr,k) > 0) .* (candidateirf(2,2,1:restr,k) > 0) .* (candidateirf(4,2,1:restr,k) > 0) .* (candidateirf(5,2,1:restr,k) > 0); 139 | if (max(a)==0) 140 | %--- Swiching the sign of the shock and normalize. 141 | am = (candidateirf(1,2,1:restr,k) < 0) .* (candidateirf(2,2,1:restr,k) < 0) .* (candidateirf(4,2,1:restr,k) < 0) .* (candidateirf(5,2,1:restr,k) < 0); 142 | if (min(am)==0) 143 | continue; %The restrictions are not satisfied. Go the beginning to redraw. 144 | else 145 | %--- Normalizing according to the switched sign. 146 | Qr(2,:) = -Qr(2,:); 147 | end 148 | elseif (min(a)==0) 149 | continue; %The restrictions are not satisfied. Go the beginning to redraw. 150 | end 151 | 152 | %=== Responses to an AP shock: 153 | 154 | a = (candidateirf(1,3,1:restr,k) > 0) .* (candidateirf(2,3,1:restr,k) > 0) .* (candidateirf(3,3,1:restr,k) > 0).* (candidateirf(4,3,1:restr,k) < 0).* (candidateirf(5,3,1:restr,k) > 0); 155 | if (max(a)==0) 156 | %--- Swiching the sign of the shock and normalize. 157 | am = (candidateirf(1,3,1:restr,k) < 0) .* (candidateirf(2,3,1:restr,k) < 0) .* (candidateirf(3,3,1:restr,k) < 0).* (candidateirf(4,3,1:restr,k) > 0).* (candidateirf(5,3,1:restr,k) < 0); 158 | if (min(am)==0) 159 | continue; %The restrictions are not satisfied. Go the beginning to redraw. 160 | else 161 | %--- Normalizing according to the switched sign. 162 | Qr(3,:) = -Qr(3,:); 163 | end 164 | elseif (min(a)==0) 165 | continue; %The restrictions are not satisfied. Go the beginning to redraw. 166 | end 167 | 168 | %--- Terminating condition: all restrictions are satisfied. 169 | 170 | control=1; 171 | 172 | end 173 | 174 | %--- Given the properly selected Q matrix, compute the responses that 175 | % satisfy all the sign restrictions and store these: 176 | 177 | for i=1:hor 178 | candidateirf(:,:,i,k)=D(:,:,i,k)*Qr'; 179 | end 180 | 181 | waitbar(k/drawfin,h,sprintf('Please wait, cool results are on the way! Percentage completed %2.2f',(k/drawfin)*100)) 182 | 183 | end 184 | 185 | %% Reshape the matrices into a 3D object: 186 | 187 | % For each draw, compute a matrix with the IRFs for each variable and each 188 | % shock for the entire horizon considered, i.e. hor x n*n for the # of 189 | % draws: 190 | 191 | candidateirf_wold=zeros(hor,n*n,drawfin); 192 | 193 | for k=1:drawfin 194 | 195 | candidateirf_wold(:,:,k)=(reshape(permute(candidateirf(:,:,:,k),[3 2 1]),hor,n*n,[])); 196 | 197 | end 198 | 199 | % Create Probability Bands: 200 | 201 | conf=68; 202 | 203 | LowD=zeros(hor,n*n); 204 | MiddleD=zeros(hor,n*n); 205 | HighD=zeros(hor,n*n); 206 | 207 | for k=1:n 208 | for j=1:n 209 | Dmin = prctile(candidateirf_wold(:,j+n*k-n,:),(100-conf)/2,3); %16th percentile 210 | LowD(:,j+n*k-n) = Dmin; %lower band 211 | Dmiddle=prctile(candidateirf_wold(:,j+n*k-n,:),50,3); %50th percentile 212 | MiddleD(:,j+n*k-n) = Dmiddle; %lower band 213 | Dmax = prctile(candidateirf_wold(:,j+n*k-n,:),(100+conf)/2,3); %84th percentile 214 | HighD(:,j+n*k-n) = Dmax; %upper band 215 | end 216 | end 217 | 218 | % Plot: 219 | 220 | colorBNDS=[0.7 0.7 0.7]; 221 | VARnames={ 'GDP'; 'CPI';'AP Announcements'; '10 yrs'; 'Real Equity Prices'}; 222 | 223 | figure2=figure(2); 224 | 225 | for k=1:n 226 | for j=1:n 227 | subplot(n,n,j+n*k-n) 228 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighD(:,j+n*k-n); flipud(LowD(:,j+n*k-n))],... 229 | colorBNDS,'EdgeColor','None'); hold on; 230 | plot(0:hor-1,MiddleD(:,j+n*k-n),'LineWidth',3.5,'Color','k'); hold on; 231 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 232 | title(VARnames{k}) 233 | %legend({'68% confidence bands','IRF'},'FontSize',12) 234 | set(gca,'FontSize',15) 235 | xlim([0 hor-1]); 236 | end 237 | end 238 | 239 | 240 | 241 | -------------------------------------------------------------------------------- /Class II - Short-Run and Long-Run Restrictions/structuralVAR.m: -------------------------------------------------------------------------------- 1 | %%% Empirical Time Series Methods for Macroeconomic Analysis 2 | %%% Structural VARs 3 | %%% Author: Nicolo' Maffei Faccioli 4 | 5 | %% Class Example: 6 | 7 | clc; clear; 8 | 9 | %% Import the data and create spread and GDP's growth rate: 10 | 11 | load 'datastruc.mat' 12 | 13 | finaldata=[TFPgr(2:end),diff(stockprices)]; % stockprices is already in logs 14 | 15 | %% Estimate a VAR(4) with finaldata: 16 | 17 | % First of all, we have to create the T x n matrices of the SUR 18 | % representation, i.e. Y and X: 19 | 20 | n=2; % # of variables 21 | p=4; % 4 lags 22 | c=1; % including constant 23 | 24 | [pi_hat,Y,X,Y_initial,Yfit,err]=VAR(finaldata,p,c); % VAR estimation 25 | 26 | BigA=[pi_hat(2:end,:)'; eye(n*p-n) zeros(n*p-n,n)]; % BigA companion form, npxnp matrix 27 | 28 | %% Wold representation impulse responses + Cholesky: 29 | 30 | C=zeros(n,n,20); 31 | 32 | for j=1:20 33 | BigC=BigA^(j-1); 34 | C(:,:,j)=BigC(1:n,1:n); % Impulse response functions of the Wold representation 35 | end 36 | 37 | C_wold=reshape(permute(C,[3 2 1]),20,n*n,[]); 38 | 39 | % Bootstrap: 40 | 41 | hor=20; 42 | iter=1000; 43 | conf=68; 44 | 45 | [HighC,LowC]=bootstrapVAR(finaldata,hor,c,iter,conf,p,n); % function that performs bootstrap 46 | 47 | colorBNDS=[0.7 0.7 0.7]; 48 | VARnames={'TFP growth'; 'SP500 growth'}; 49 | 50 | figure2=figure(2); 51 | 52 | for k=1:n 53 | for j=1:n 54 | subplot(n,n,j+n*k-n) 55 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighC(:,j+n*k-n); flipud(LowC(:,j+n*k-n))],... 56 | colorBNDS,'EdgeColor','None'); hold on; 57 | plot(0:hor-1,C_wold(:,j+n*k-n),'LineWidth',3.5,'Color','k'); hold on; 58 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 59 | title(VARnames{k}) 60 | legend({'68% confidence bands','IRF'},'FontSize',12) 61 | set(gca,'FontSize',15) 62 | xlim([0 hor-1]); 63 | end 64 | end 65 | 66 | % Cholesky: 67 | 68 | T=length(Y)-n*p-n; % -p lags for n variables and -n constants 69 | omega=(err'*err)./T; %estimate of omega 70 | S=chol(omega,'lower'); %cholesky factorization, lower triangular matrix 71 | 72 | D=zeros(n,n,20); 73 | for i=1:20 74 | D(:,:,i)=C(:,:,i)*S; %cholesky wold respesentation 75 | end 76 | 77 | D_wold=(reshape(permute(D,[3 2 1]),20,n*n,[])); 78 | 79 | [HighD,LowD]=bootstrapchol(finaldata,hor,c,iter,conf,p,n); % function that performs bootstrap for cholesky 80 | 81 | % Plot: 82 | 83 | figure3=figure(3); 84 | 85 | for k=1:n 86 | for j=1:n 87 | subplot(n,n,j+n*k-n) 88 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighD(:,j+n*k-n); flipud(LowD(:,j+n*k-n))],... 89 | colorBNDS,'EdgeColor','None'); hold on; 90 | plot(0:hor-1,D_wold(:,j+n*k-n),'LineWidth',3.5,'Color','k'); hold on; 91 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 92 | title(VARnames{k}) 93 | legend({'68% confidence bands','IRF'},'FontSize',12) 94 | set(gca,'FontSize',15) 95 | xlim([0 hor-1]); 96 | end 97 | end 98 | 99 | %% News Shock: 100 | 101 | eta=S\err'; 102 | 103 | % Plot: 104 | 105 | DATES(1)=[]; 106 | 107 | figure4=figure(4); 108 | plot([eta(2,:)' err(:,2)],'LineWidth',1), axis('tight') 109 | ylabel('News shock and Error','FontWeight','Bold') 110 | xlabel('Year','FontWeight','Bold') 111 | legend('Cholesky','Error','italic') 112 | title('Plot of News Shock (Cholesky) vs. Error ','FontWeight','Bold') 113 | set(gca,'Xtick',1:60:length(eta),'XtickLabel',DATES(1:60:end)) % Changing what's on the x axis with the "dates" in form dd-mm-yy 114 | 115 | %% Blanchard & Quah - Long-run restriction: 116 | 117 | A1=sum(C,3); 118 | S=chol(A1*omega*A1')'; 119 | K=A1\S; 120 | F=zeros(2,2,20); 121 | 122 | for i=1:20 123 | F(:,:,i)=C(:,:,i)*K; 124 | end 125 | 126 | F_wold=reshape(permute(F, [3 2 1]),[],n*n); 127 | 128 | [HighF,LowF]=bootstrapBQ(finaldata,hor,1,iter,conf,p,n); 129 | 130 | figure5=figure(5); 131 | 132 | for k=1:n 133 | for j=1:n 134 | subplot(n,n,j+n*k-n) 135 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighF(:,j+n*k-n); flipud(LowF(:,j+n*k-n))],... 136 | colorBNDS,'EdgeColor','None'); hold on; 137 | plot(0:hor-1,F_wold(:,j+n*k-n),'LineWidth',3.5,'Color','k'); hold on; 138 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 139 | title(VARnames{k}) 140 | legend({'68% confidence bands','IRF'},'FontSize',12) 141 | set(gca,'FontSize',15) 142 | xlim([0 hor-1]); 143 | end 144 | end 145 | 146 | w=K\err'; 147 | 148 | figure6=figure(6); 149 | plot([w(2,:)' err(:,2)],'LineWidth',1), axis('tight') 150 | ylabel('News shock and Error','FontWeight','Bold') 151 | xlabel('Year','FontWeight','Bold') 152 | legend('B&Q','Error','italic') 153 | title('Plot of News Shock (B&Q) vs. Error ','FontWeight','Bold') 154 | set(gca,'Xtick',1:60:length(eta),'XtickLabel',DATES(1:60:end)) % Changing what's on the x axis with the "dates" in form dd-mm-yy 155 | 156 | %% Cumulative Impulse Responses: 157 | 158 | % Cholesky: 159 | 160 | D_wold_cum=cumsum(D_wold); 161 | HighD_cum=cumsum(HighD); 162 | LowD_cum=cumsum(LowD); 163 | 164 | VARnames={'TFP'; 'SP500'}; 165 | 166 | figure7=figure(7); 167 | 168 | for k=1:n 169 | for j=1:n 170 | subplot(n,n,j+n*k-n) 171 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighD_cum(:,j+n*k-n); flipud(LowD_cum(:,j+n*k-n))],... 172 | colorBNDS,'EdgeColor','None'); hold on; 173 | plot(0:hor-1,D_wold_cum(:,j+n*k-n),'LineWidth',3.5,'Color','k'); hold on; 174 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 175 | title(VARnames{k}) 176 | legend({'68% confidence bands','IRF'},'FontSize',12) 177 | set(gca,'FontSize',15) 178 | xlim([0 hor-1]); 179 | end 180 | end 181 | 182 | % Blanchard and Quah: 183 | 184 | F_wold_cum=cumsum(F_wold); 185 | HighF_cum=cumsum(HighF); 186 | LowF_cum=cumsum(LowF); 187 | 188 | figure8=figure(8); 189 | 190 | for k=1:n 191 | for j=1:n 192 | subplot(n,n,j+n*k-n) 193 | fill([0:hor-1 fliplr(0:hor-1)]' ,[HighF_cum(:,j+n*k-n); flipud(LowF_cum(:,j+n*k-n))],... 194 | colorBNDS,'EdgeColor','None'); hold on; 195 | plot(0:hor-1,F_wold_cum(:,j+n*k-n),'LineWidth',3.5,'Color','k'); hold on; 196 | line(get(gca,'Xlim'),[0 0],'Color',[0 0 0],'LineStyle','-'); hold off; 197 | title(VARnames{k}) 198 | legend({'68% confidence bands','IRF'},'FontSize',12) 199 | set(gca,'FontSize',15) 200 | xlim([0 hor-1]); 201 | end 202 | end 203 | 204 | %% Variance Decomposition Analysis: 205 | 206 | % Cholesky: 207 | 208 | F_TFP=sum((D_wold(:,1)).*(D_wold(:,1)))+sum((D_wold(:,2)).*(D_wold(:,2))); 209 | F_SP=sum((D_wold(:,3)).*(D_wold(:,3)))+sum((D_wold(:,4)).*(D_wold(:,4))); 210 | decomposion_TFP1=sum((D_wold(:,1)).*(D_wold(:,1)))/F_TFP; 211 | decomposion_TFP2=sum((D_wold(:,2)).*(D_wold(:,2)))/F_TFP; 212 | decomposion_SP1=sum((D_wold(:,3)).*(D_wold(:,3)))/F_SP; 213 | decomposion_SP2=sum((D_wold(:,4)).*(D_wold(:,4)))/F_SP; 214 | 215 | table(decomposion_TFP1,decomposion_TFP2) 216 | table(decomposion_SP1, decomposion_SP2) 217 | 218 | % Blanchard & Quah: 219 | 220 | F_TFPBQ=sum((F_wold(:,1)).*(F_wold(:,1)))+sum((F_wold(:,2)).*(F_wold(:,2))); 221 | F_SPBQ=sum((F_wold(:,3)).*(F_wold(:,3)))+sum((F_wold(:,4)).*(F_wold(:,4))); 222 | decomposion_TFP1BQ=sum((F_wold(:,1)).*(F_wold(:,1)))/F_TFPBQ; 223 | decomposion_TFP2BQ=sum((F_wold(:,2)).*(F_wold(:,2)))/F_TFPBQ; 224 | decomposion_SP1BQ=sum((F_wold(:,3)).*(F_wold(:,3)))/F_SPBQ; 225 | decomposion_SP2BQ=sum((F_wold(:,4)).*(F_wold(:,4)))/F_SPBQ; 226 | 227 | table(decomposion_TFP1BQ,decomposion_TFP2BQ) 228 | table(decomposion_SP1BQ, decomposion_SP2BQ) 229 | 230 | %% Variance Decomposition: 231 | 232 | %MiddleDsquare=D_wold.^2; % For Cholesky, growth rates 233 | MiddleDsquare=F_wold_cum.^2; % For B&Q, growth rates 234 | 235 | %MiddleDsquare=D_wold_cum.^2; % For Cholesky, levels 236 | %MiddleDsquare=F_wold_cum.^2; % For B&Q, levels 237 | 238 | denom=zeros(hor,n); 239 | 240 | for k=[1:n;1:n:n*n] 241 | 242 | denom(:,k(1))=cumsum(sum(MiddleDsquare(:,k(2):k(2)+n-1),2)); 243 | 244 | end 245 | 246 | denomtot=zeros(hor,n*n); 247 | 248 | for k=[1:n;1:n:n*n] 249 | 250 | denomtot(:,k(2):k(2)+n-1)=denom(:,k(1)).*ones(hor,n); 251 | 252 | end 253 | 254 | vardec=zeros(hor,n); 255 | 256 | for j=1:n*n 257 | 258 | vardec(:,j)=cumsum(MiddleDsquare(:,j))./denomtot(:,j); 259 | 260 | end 261 | 262 | figure2=figure(2); 263 | 264 | % VARnames={'TFP growth'; 'SP500 growth'}; % growth rates 265 | VARnames={'TFP'; 'SP500'}; % levels 266 | 267 | 268 | 269 | for k=[1:n;1:n:n*n] 270 | subplot(1,n,k(1)) 271 | area(0:hor-1,vardec(:,k(2):k(2)+n-1),'LineWidth',1); hold on; 272 | legend({'TFP shock','SP500 shock'},'FontSize',13) 273 | set(gca,'FontSize',15) 274 | title(VARnames{k(1)}) 275 | xlim([0 hor-1]); 276 | ylim([0 1]) 277 | end 278 | 279 | -------------------------------------------------------------------------------- /MatlabRoutines/TVC-VAR/TVCGibbsSampling.m: -------------------------------------------------------------------------------- 1 | function [PB, PR, PQ, Q0]=TVCGibbsSampling(Y,L,maxgbit,burn,jump,para,years,init) 2 | 3 | %%%% Load parameters of KSC(98) 4 | MixingKSC 5 | 6 | %%%% Set parameters 7 | gbit = 1; 8 | post_index = 1; 9 | trs=1; 10 | trsMax=10; 11 | MaxEig=1.1; 12 | MaxRoot=MaxEig+1; 13 | c=1; % constant term 14 | 15 | T0=4*years; % period in the initial sample 4*8-L 16 | [yy xx] = VAR_str(Y(1:end,:),c,L); % yy and XX all the sample 17 | [TT r]=size(yy); 18 | 19 | for t=1:TT 20 | XX(:,:,t)=kron(eye(r),xx(t,:)'); 21 | end 22 | 23 | % y=yy(T0/2+1:end,:); 24 | % x=xx(T0/2+1:end,:); 25 | % X=XX(:,:,T0/2+1:end); 26 | y=yy(init:end,:); 27 | x=xx(init:end,:); 28 | X=XX(:,:,init:end); 29 | r=size(y,2); 30 | [T rp] = size(x); 31 | 32 | %%%% OLS in the pre sample 33 | [B0,VB0,R0] = sur(yy',XX,T0); 34 | resid=innovm(yy(1:T0,:)',xx(1:T0,:),B0*ones(1,T0),r,T0,L,c)'; % residuals 35 | 36 | %%%% Variance and mean of theta0 37 | VB0=1*VB0; 38 | 39 | %%%% Variance and mean of log(sigma0) 40 | H0=log(diag(sqrt(R0))); 41 | VH0=eye(r);%diag(diag(R0))*2; 42 | 43 | 44 | %%%% Mean and variance of alpha0 45 | 46 | co1=[]; 47 | co2=[]; 48 | for i=1:r-1 49 | dd=size(co1,1)+1:size(co1,1)+size(co2,1)+1; 50 | A0(dd)=inv(resid(:,1:i)'*resid(:,1:i))*resid(:,1:i)'*resid(:,i+1); 51 | VA0(dd,dd) = inv(resid(:,1:i)'*resid(:,1:i))*cov(resid(:,i+1)-resid(:,1:i)*A0(dd)'); 52 | co2=ones(i,1); 53 | co1=[co1;co2]; 54 | end 55 | A0=A0'; 56 | % covariance matrix of innovation in the off-diagonal elements 57 | U0=para(2)*VA0; 58 | dfU0=[2:r]; 59 | 60 | 61 | %%%% Scale matrix for the variance in coefficients innovations 62 | Q0=para(1)*VB0; 63 | % Q0(1,:)=0.5*Q0(1,:); 64 | % Q0(:,1)=0.5*Q0(:,1); 65 | % Q0(9,:)=0.5*Q0(9,:); 66 | % Q0(:,9)=0.5*Q0(:,9); 67 | 68 | df0=size(B0,1)+1; 69 | TQ0=df0*Q0; 70 | df = T+df0; 71 | 72 | %%%% Scale matrix for the variance in volatilities innovations 73 | W0=para(3)*eye(r); 74 | 75 | dfW0=r+1; 76 | 77 | %%%% Initialize Yhat, ystar,y2star 78 | dy = diff(y(:,1:r)); 79 | e(:,1:r) = dy - ones(T-1,1)*mean(dy); 80 | Yhat=[zeros(r,1) e']'; 81 | InitS=cov(Yhat); 82 | InitA=chol(InitS)'; 83 | ystar=inv(InitA*inv(diag(sqrt(diag(InitS)))))*Yhat'; 84 | y2star=[log(exp(H0).^2'); log(ystar(:,2:end)'.^2)]; 85 | 86 | %%%% Initialize states 87 | for i=1:r 88 | for t=1:T 89 | for j=1:7 90 | probs(j)=ksc(j,2)*normpdf(y2star(t,i),y2star(t,i)+ksc(j,3)-1.2704,ksc(j,4)); 91 | end 92 | s0(i,t)=DiscreteDraw(probs./sum(probs)); 93 | end 94 | end 95 | s=s0; 96 | 97 | %%%% Initialize variances 98 | U=U0; 99 | W=W0; 100 | Q=Q0; 101 | %R=R0; 102 | 103 | %%%% Coefficitent matrix in the state space for volatilities 104 | h=eye(r)*2; 105 | 106 | %%%%%%%% Initial draws: this is useful for the last part of the program 107 | P1(:,:,1) = VH0; % P(1|0) 108 | K = (P1(:,:,1))*h'*inv(h* P1(:,:,1)*h' + diag(ksc(s(:,1),4))); % K(1) 109 | P0(:,:,1) = P1(:,:,1) - K*h*P1(:,:,1); % P(1|1) 110 | S0(:,1) = H0 + K*( y2star(1,:)' - h*H0 - (ksc(s(:,1),3)-1.2074)); % S(1|1) 111 | for i = 2:T, 112 | P1(:,:,i) = P0(:,:,i-1) + W; % P(t|t-1) 113 | K = (P1(:,:,i))*h'*inv(h*P1(:,:,i)*h' + diag(ksc(s(:,i),4))); % K(t) 114 | P0(:,:,i) = P1(:,:,i) - K*h*(P1(:,:,i)); % P(t|t) 115 | S0(:,i) = S0(:,i-1) + K*( y2star(i,:)' - h*S0(:,i-1) - (ksc(s(:,i),3)-1.2704) ); % S(t|t) 116 | end 117 | wa = randn(r,T); 118 | % SA(:,T) = S0(:,T) + real(sqrtm(P0(:,:,T)))*wa(:,T); 119 | SA(:,T) = S0(:,T) + chol(P0(:,:,T))'*wa(:,T); 120 | for i = 1:T-1, 121 | PM = P0(:,:,T-i)*inv(P1(:,:,T-i+1)); 122 | P = P0(:,:,T-i) - PM*P0(:,:,T-i); 123 | SM = S0(:,T-i) + PM*(SA(:,T-i+1) - S0(:,T-i)); 124 | % SA(:,T-i) = SM + real(sqrtm(P))*wa(:,T-i); 125 | SA(:,T-i) = SM + chol(P)'*wa(:,T-i); 126 | end 127 | lh=SA'; 128 | H=exp(2*SA'); %% compute variance fr 129 | 130 | %%%% 2) Draw covariances 131 | TA=zeros(r*(r-1)/2,r*(r-1)/2); 132 | A=[]; 133 | AA=[]; 134 | for i=1:r-1 135 | % dd=i*(i-1)/2+1:i*(i+1)/2; 136 | dd=size(A,1)+1:size(A,1)+size(AA,1)+1; 137 | [AS0,AP0,AP1] = kfR1RegTvc(Yhat(:,i+1)',-Yhat(:,1:i)',U(dd,dd),H(:,i+1),A0(dd),VA0(dd,dd),T); 138 | AA = gibbs1Reg(Yhat(:,i+1),-Yhat(:,1:i),AS0,AP0,AP1,T,length(dd)); 139 | [TU(dd,dd),dfU] = iwpQ(AA,r,T,L,dfU0(i)*U0(dd,dd),dfU0(i)); 140 | A=[A;AA]; 141 | g=real(sqrtm(inv(TU(dd,dd)))); 142 | ug=randn(i,dfU); 143 | U(dd,dd) = inv(g*ug*ug'*g'); 144 | CH=A; 145 | clear AS0 AP0 AP1; 146 | end 147 | 148 | for t=1:T 149 | CF(:,:,t)= chofac(r,A(:,t)); 150 | R0(:,:,t) = inv(CF(:,:,t))*diag(H(t,:))*inv(CF(:,:,t))'; 151 | end 152 | R=R0; 153 | 154 | %%%% initial draw of states for AR coefficients 155 | [SS0,PP0,PP1] = kfR(y',X,Q0,R,B0,VB0,T,r,L,c); 156 | while MaxRoot>=MaxEig 157 | %[S0,P0,P1] = kfR(y',X,Q0,CF,H,B0,VB0,T,r,L); 158 | th_backward0 = gibbs1(y',X,SS0,PP0,PP1,T,r,L,c); 159 | %[th_backward0,P_backward0] = tvc_backward_filter(y,X,B0,VB0,R0,Q0,0); 160 | for j =1:T 161 | comp_mat = companion(th_backward0(:,j),L,r,c); 162 | AutVal(j) = max(abs(eig(comp_mat))); 163 | end 164 | MaxRoot=max(AutVal) 165 | end 166 | B=th_backward0; 167 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 168 | 169 | %%%% Initialize matrices of draws 170 | PQ=zeros(rp*r,rp*r,(maxgbit-burn)/jump); 171 | PR=zeros(r,r,T,(maxgbit-burn)/jump); 172 | PB=zeros(rp*r,T,(maxgbit-burn)/jump); 173 | PW=zeros(r,r,(maxgbit-burn)/jump); 174 | PU=zeros(r*(r-1)/2,r*(r-1)/2,(maxgbit-burn)/jump); 175 | Ps=zeros(r,T,(maxgbit-burn)/jump); 176 | PA=zeros(r*(r-1)/2,T,(maxgbit-burn)/jump); 177 | 178 | PQ(:,:,post_index)=Q; 179 | PR(:,:,:,post_index)=R; 180 | PB(:,:,post_index)=B; 181 | PW(:,:,post_index)=W; 182 | PU(:,:,post_index)=U; 183 | Ps(:,:,post_index)=s; 184 | PA(:,:,post_index)=A; 185 | 186 | 187 | %%%% Start the chain 188 | disp('begin MCMC') 189 | 190 | while gbit<=maxgbit 191 | gbit 192 | itnum=num2str(gbit); 193 | if itnum(size(itnum,2))==num2str(0) & itnum(size(itnum,2)-1)==num2str(0) 194 | disp(['Iteration ' num2str(gbit) ' Collected Draws ' num2str(post_index)... 195 | ' Done ' num2str(gbit/maxgbit*100) '% MaxEig ' num2str(max(AutVal)) ]) 196 | end 197 | 198 | %%%% 1) Draw stochastic volatilities 199 | P1(:,:,1) = VH0; % P(1|0) 200 | K = (P1(:,:,1))*h'*inv(h* P1(:,:,1)*h' + diag(ksc(s(:,1),4))); % K(1) 201 | P0(:,:,1) = P1(:,:,1) - K*h*P1(:,:,1); % P(1|1) 202 | S0(:,1) = H0 + K*( y2star(1,:)' - h*H0 - (ksc(s(:,1),3)-1.2074)); % S(1|1) 203 | for i = 2:T, 204 | P1(:,:,i) = P0(:,:,i-1) + W; % P(t|t-1) 205 | K = (P1(:,:,i))*h'*inv(h*P1(:,:,i)*h' + diag(ksc(s(:,i),4))); % K(t) 206 | P0(:,:,i) = P1(:,:,i) - K*h*(P1(:,:,i)); % P(t|t) 207 | S0(:,i) = S0(:,i-1) + K*( y2star(i,:)' - h*S0(:,i-1) - (ksc(s(:,i),3)-1.2704) ); % S(t|t) 208 | end 209 | wa = randn(r,T); 210 | % SA(:,T) = S0(:,T) + real(sqrtm(P0(:,:,T)))*wa(:,T); 211 | SA(:,T) = S0(:,T) + chol(P0(:,:,T))'*wa(:,T); 212 | 213 | for i = 1:T-1, 214 | PM = P0(:,:,T-i)*inv(P1(:,:,T-i+1)); 215 | P = P0(:,:,T-i) - PM*P0(:,:,T-i); 216 | SM = S0(:,T-i) + PM*(SA(:,T-i+1) - S0(:,T-i)); 217 | % SA(:,T-i) = SM + real(sqrtm(P))*wa(:,T-i); 218 | SA(:,T-i) = SM + chol(P)'*wa(:,T-i); 219 | end 220 | lh=SA'; 221 | H=exp(2*SA'); %% compute variance fr 222 | 223 | %%%% 2) Draw covariances 224 | TA=zeros(r*(r-1)/2,r*(r-1)/2); 225 | A=[]; 226 | AA=[]; 227 | for i=1:r-1 228 | % dd=i*(i-1)/2+1:i*(i+1)/2; 229 | dd=size(A,1)+1:size(A,1)+size(AA,1)+1; 230 | [AS0,AP0,AP1] = kfR1RegTvc(Yhat(:,i+1)',-Yhat(:,1:i)',U(dd,dd),H(:,i+1),A0(dd),VA0(dd,dd),T); 231 | AA = gibbs1Reg(Yhat(:,i+1),-Yhat(:,1:i),AS0,AP0,AP1,T,length(dd)); 232 | [TU(dd,dd),dfU] = iwpQ(AA,r,T,L,dfU0(i)*U0(dd,dd),dfU0(i)); 233 | A=[A;AA]; 234 | g=real(sqrtm(inv(TU(dd,dd)))); 235 | ug=randn(i,dfU); 236 | U(dd,dd) = inv(g*ug*ug'*g'); 237 | CH=A; 238 | clear AS0 AP0 AP1; 239 | end 240 | for t=1:T 241 | CF(:,:,t)= chofac(r,A(:,t)); 242 | R(:,:,t) = inv(CF(:,:,t))*diag(H(t,:))*inv(CF(:,:,t))'; 243 | end 244 | 245 | 246 | %%%% Draw VAR coefficients 247 | [SS0,PP0,PP1] = kfR(y',X,Q,R,B0,VB0,T,r,L,c); 248 | B = gibbs1(y',X,SS0,PP0,PP1,T,r,L,c); 249 | 250 | 251 | %%%% compute new Yhat 252 | Yhat=innovm(y',x,B,r,T,L,c)'; 253 | 254 | %%%% Compute new ystar 255 | for t=1:T 256 | ystar(:,t)=CF(:,:,t)*Yhat(t,:)'; 257 | end 258 | 259 | %%%% Compute new y2star 260 | y2star=log(ystar'.^2+0.001); 261 | 262 | %%%% Compute new probabilities 263 | for i=1:r 264 | for t=1:T 265 | for j=1:7 266 | probs(j)=ksc(j,2)*normpdf(y2star(t,i),2*SA(i,t)+ksc(j,3)-1.2704,ksc(j,4)); 267 | end 268 | s(i,t)=DiscreteDraw(probs./sum(probs)); 269 | end 270 | end 271 | 272 | %%%% Draw SV innovation variance 273 | [TW,dfW] = iwpQ(SA,r,T,L,dfW0*W0,dfW0); 274 | W = gibbs2Q(TW,dfW,r,0,1); 275 | 276 | %%%% Draw coefficients innovations variance 277 | [TQ,df] = iwpQ(B,r,T,L,TQ0,df0); 278 | Q = gibbs2Q(TQ,df,r,L,c); 279 | 280 | %%%% Check roots 281 | rootInd=1; 282 | timInd=T+1; 283 | while rootInd==1 & timInd<=T 284 | comp_mat = companion(B(:,timInd),L,r,c); 285 | AutVal = max(abs(eig(comp_mat))); 286 | if max(AutVal)>MaxEig & trsMaxEig & trs==trsMax 291 | disp('go back') 292 | Q=PQ(:,:,post_index); 293 | R=PR(:,:,:,post_index); 294 | B=PB(:,:,post_index); 295 | W=PW(:,:,post_index); 296 | U=PU(:,:,post_index); 297 | s=Ps(:,:,post_index); 298 | A=PA(:,:,post_index); 299 | Yhat=innovm(y',x,B,r,T,L,c)'; 300 | for t=1:T 301 | ystar(:,t)=chofac(r,A(:,t))*Yhat(t,:)'; 302 | end 303 | y2star=log(ystar'.^2+0.001); 304 | rootInd=0; 305 | trs=0; 306 | %disp('eccomi') 307 | elseif max(AutVal) burn 325 | check_index = (gbit-burn)/jump- fix((gbit-burn)/jump); 326 | if check_index == 0 327 | post_index = (gbit-burn)/jump+1; 328 | end 329 | PQ(:,:,post_index)=Q; 330 | PR(:,:,:,post_index)=R; 331 | PB(:,:,post_index)=B; 332 | PW(:,:,post_index)=W; 333 | PU(:,:,post_index)=U; 334 | Ps(:,:,post_index)=s; 335 | PA(:,:,post_index)=A; 336 | end 337 | gbit = gbit+1; 338 | end 339 | end 340 | --------------------------------------------------------------------------------