diff --git a/MatlabFiles/a0asfun.m b/MatlabFiles/a0asfun.m index 5054ea5f1c20ab121f1be6f547fc60076a73a0ee..7672e9f589b7967848a9f7e8bc4f65199c7df3d3 100644 --- a/MatlabFiles/a0asfun.m +++ b/MatlabFiles/a0asfun.m @@ -1,50 +1,49 @@ -function of = a0asfun(x,s,nobs,nvar,a0indx) -% General program to setup A0 matrix with asymmetric prior (as) and compute the posterior -% function of = a0asfun(x,s,nobs,nvar,a0indx) -- negative logPosterior -% Note: columns correspond to equations -% x (parameter vector), -% s (diag(S1,...,Sm)): note, as in "a0lhfun", already divided by "nobs" -% nobs (no of obs), -% nvar (no of variables), -% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds -% to an equation) -% -% Copyright (c) December 1997 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -a0 = zeros(nvar); -a0(a0indx) = x; -% Note: each column in a0 corresponds to an equation!! -% -%%ada = chol(a0'*a0); -%%ada = log(abs(diag(ada))); -%%ada = sum(ada); -% ** TZ, 10/15/96, the above two lines can be improved by the following three lines -[a0l,a0u] = lu(a0); -%ada=diag(abs(a0u)); -%ada=sum(log(ada)); -ada = sum(log(abs(diag(a0u)))); - -% -%tra = sum(i=1:m){a0(:,i)'*Si*a0(:,i)} -tra = 0.0; -for i=1:nvar - tra = tra + a0(:,i)'*s{i}*a0(:,i); -end - -of = -nobs*ada + nobs*.5*tra; \ No newline at end of file +function of = a0asfun(x,s,nobs,nvar,a0indx) +% General program to setup A0 matrix with asymmetric prior (as) and compute the posterior +% function of = a0asfun(x,s,nobs,nvar,a0indx) -- negative logPosterior +% Note: columns correspond to equations +% x (parameter vector), +% s (diag(S1,...,Sm)): note, as in "a0lhfun", already divided by "nobs" +% nobs (no of obs), +% nvar (no of variables), +% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds +% to an equation) +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +a0 = zeros(nvar); +a0(a0indx) = x; +% Note: each column in a0 corresponds to an equation!! +% +%%ada = chol(a0'*a0); +%%ada = log(abs(diag(ada))); +%%ada = sum(ada); +% ** TZ, 10/15/96, the above two lines can be improved by the following three lines +[a0l,a0u] = lu(a0); +%ada=diag(abs(a0u)); +%ada=sum(log(ada)); +ada = sum(log(abs(diag(a0u)))); + +% +%tra = sum(i=1:m){a0(:,i)'*Si*a0(:,i)} +tra = 0.0; +for i=1:nvar + tra = tra + a0(:,i)'*s{i}*a0(:,i); +end + +of = -nobs*ada + nobs*.5*tra; diff --git a/MatlabFiles/a0asgrad.m b/MatlabFiles/a0asgrad.m index 581b85aec71120b212ca96e50100eaf198cee45a..0a5252297dc14c8706aa4c3e4b90b0043ba6c2f5 100644 --- a/MatlabFiles/a0asgrad.m +++ b/MatlabFiles/a0asgrad.m @@ -1,42 +1,42 @@ -function [g,badg] = a0asgrad(x,s,nobs,nvar,a0indx); -% Computes analytical gradient for use in csminwel.m -% function [g,badg] = a0asgrad(x,s,nobs,nvar,a0indx); -% -% x (parameter vector), -% s (diag(S1,...,Sm)): note, as in "a0lhfun", already divided by "nobs" -% nobs (no of obs), -% nvar (no of variables), -% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds -% to an equation) -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -a0 = zeros(nvar); -%%g = zeros(nvar*nvar,1); % 4/27/97: not necessary. -badg = 0; - -a0(a0indx) = x; - -b1=-nobs*inv(a0'); -b2 = zeros(nvar,nvar); -for i=1:nvar - b2(:,i) = nobs*s{i}*a0(:,i); -end - -%b = -nobs*inv(a') + nobs*s*a; -b = b1(:)+b2(:); -g = b(a0indx); \ No newline at end of file +function [g,badg] = a0asgrad(x,s,nobs,nvar,a0indx); +% Computes analytical gradient for use in csminwel.m +% function [g,badg] = a0asgrad(x,s,nobs,nvar,a0indx); +% +% x (parameter vector), +% s (diag(S1,...,Sm)): note, as in "a0lhfun", already divided by "nobs" +% nobs (no of obs), +% nvar (no of variables), +% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds +% to an equation) +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +a0 = zeros(nvar); +%%g = zeros(nvar*nvar,1); % 4/27/97: not necessary. +badg = 0; + +a0(a0indx) = x; + +b1=-nobs*inv(a0'); +b2 = zeros(nvar,nvar); +for i=1:nvar + b2(:,i) = nobs*s{i}*a0(:,i); +end + +%b = -nobs*inv(a') + nobs*s*a; +b = b1(:)+b2(:); +g = b(a0indx); diff --git a/MatlabFiles/a0freefun.m b/MatlabFiles/a0freefun.m index d625e40a9bc2af3c15c431c82bafbc3ac66d6372..5c7d5b200274e57fe771dc985e869250ff837395 100644 --- a/MatlabFiles/a0freefun.m +++ b/MatlabFiles/a0freefun.m @@ -1,61 +1,61 @@ -function of = a0freefun(b,Ui,nvar,n0,fss,H0inv) -% of = a0freefun(b,Ui,nvar,n0,fss,H0inv) -% -% Negative logPosterior function for squeesed A0 free parameters, which are b's in the WZ notation -% Note: columns correspond to equations -% -% b: sum(n0)-by-1 vector of A0 free parameters -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -% fss: nSample-lags (plus ndobs if dummies are included) -% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, -% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. -%---------------- -% of: objective function (negative logPosterior) -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -b=b(:); - -A0 = zeros(nvar); -n0cum = cumsum(n0); -tra = 0.0; -for kj = 1:nvar - if kj==1 - bj = b(1:n0(kj)); - A0(:,kj) = Ui{kj}*bj; - tra = tra + 0.5*bj'*H0inv{kj}*bj; % negative exponential term - else - bj = b(n0cum(kj-1)+1:n0cum(kj)); - A0(:,kj) = Ui{kj}*bj; - tra = tra + 0.5*bj'*H0inv{kj}*bj; % negative exponential term - end -end - -[A0l,A0u] = lu(A0); - -ada = -fss*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T - -of = ada + tra; +function of = a0freefun(b,Ui,nvar,n0,fss,H0inv) +% of = a0freefun(b,Ui,nvar,n0,fss,H0inv) +% +% Negative logPosterior function for squeesed A0 free parameters, which are b's in the WZ notation +% Note: columns correspond to equations +% +% b: sum(n0)-by-1 vector of A0 free parameters +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +% fss: nSample-lags (plus ndobs if dummies are included) +% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, +% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. +%---------------- +% of: objective function (negative logPosterior) +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +b=b(:); + +A0 = zeros(nvar); +n0cum = cumsum(n0); +tra = 0.0; +for kj = 1:nvar + if kj==1 + bj = b(1:n0(kj)); + A0(:,kj) = Ui{kj}*bj; + tra = tra + 0.5*bj'*H0inv{kj}*bj; % negative exponential term + else + bj = b(n0cum(kj-1)+1:n0cum(kj)); + A0(:,kj) = Ui{kj}*bj; + tra = tra + 0.5*bj'*H0inv{kj}*bj; % negative exponential term + end +end + +[A0l,A0u] = lu(A0); + +ada = -fss*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T + +of = ada + tra; diff --git a/MatlabFiles/a0freegrad.m b/MatlabFiles/a0freegrad.m index 7f1255156e5470e6e7292980f2c9bcf661054769..4a86e491e381c4177946b0f72b0a0de6ca6e8369 100644 --- a/MatlabFiles/a0freegrad.m +++ b/MatlabFiles/a0freegrad.m @@ -1,66 +1,66 @@ -function [g,badg] = a0freegrad(b,Ui,nvar,n0,fss,H0inv) -% [g,badg] = a0freegrad(b,Ui,nvar,n0,fss,H0inv) -% -% Analytical gradient for a0freefun.m in use of csminwel.m -% b: sum(n0)-by-1 vector of A0 free parameters -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -% fss: nSample-lags (plus ndobs if dummies are included) -% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, -% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. -%--------------- -% g: sum(n0)-by-1 analytical gradient for a0freefun.m -% badg: 0, the value that is used in csminwel.m -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -b=b(:); - -A0 = zeros(nvar); -n0cum = cumsum(n0); -g = zeros(n0cum(end),1); -badg = 0; - -for kj = 1:nvar - if kj==1 - bj = b(1:n0(kj)); - g(1:n0(kj)) = H0inv{kj}*bj; - A0(:,kj) = Ui{kj}*bj; - else - bj = b(n0cum(kj-1)+1:n0cum(kj)); - g(n0cum(kj-1)+1:n0cum(kj)) = H0inv{kj}*bj; - A0(:,kj) = Ui{kj}*bj; - end -end -B=inv(A0'); - -for ki = 1:sum(n0) - if ki<=n0(1) - g(ki) = g(ki) - fss*B(:,1)'*Ui{1}(:,ki); - else - n = max(find( (ki-n0cum)>0 ))+1; % note, 1<n<nvar - g(ki) = g(ki) - fss*B(:,n)'*Ui{n}(:,ki-n0cum(n-1)); - end -end +function [g,badg] = a0freegrad(b,Ui,nvar,n0,fss,H0inv) +% [g,badg] = a0freegrad(b,Ui,nvar,n0,fss,H0inv) +% +% Analytical gradient for a0freefun.m in use of csminwel.m +% b: sum(n0)-by-1 vector of A0 free parameters +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +% fss: nSample-lags (plus ndobs if dummies are included) +% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, +% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. +%--------------- +% g: sum(n0)-by-1 analytical gradient for a0freefun.m +% badg: 0, the value that is used in csminwel.m +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +b=b(:); + +A0 = zeros(nvar); +n0cum = cumsum(n0); +g = zeros(n0cum(end),1); +badg = 0; + +for kj = 1:nvar + if kj==1 + bj = b(1:n0(kj)); + g(1:n0(kj)) = H0inv{kj}*bj; + A0(:,kj) = Ui{kj}*bj; + else + bj = b(n0cum(kj-1)+1:n0cum(kj)); + g(n0cum(kj-1)+1:n0cum(kj)) = H0inv{kj}*bj; + A0(:,kj) = Ui{kj}*bj; + end +end +B=inv(A0'); + +for ki = 1:sum(n0) + if ki<=n0(1) + g(ki) = g(ki) - fss*B(:,1)'*Ui{1}(:,ki); + else + n = max(find( (ki-n0cum)>0 ))+1; % note, 1<n<nvar + g(ki) = g(ki) - fss*B(:,n)'*Ui{n}(:,ki-n0cum(n-1)); + end +end diff --git a/MatlabFiles/a0impsmp.m b/MatlabFiles/a0impsmp.m index d3b1a92c101901e3b7d6ef987e33a0a0b8895ef1..8b5ceaf31163ea568e1a75f2eb52b245a9b1200e 100644 --- a/MatlabFiles/a0impsmp.m +++ b/MatlabFiles/a0impsmp.m @@ -1,99 +1,99 @@ -function [xdraw,mphv,sm,timeminutes] = a0impsmp(xinput) -% [xdraw,mphv,sm,timeminutes] = a0impsmp(xinput) -% Export the simulated pdfs of draws of only selected parameters -% with importance sampling techniques -% -% xinput{1}: nfp -- total number of free parameters -% xinput{2}: nvar -- number of variables -% xinput{3}: xhat -- ML estimate of free parameters in A0 -% xinput{4}: hess1 -- Hessian of -logLH for importance sampling -% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest -% to select variables, always check idmat0 to make sure. -% When Indxv=[], xdraw is empty as well. When IndxGgraph=1, it plots -% (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, -% (3) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences -% (5) scattered plot of 1st and 2nd for al sequences. -% xinput{6}: imndraws=nstarts*ndraws2 -% xinput{7}: a0indx -- index number for non-zero elements in A0 -% xinput{8}: tdf -- degrees of freedom for t-distribution -% xinput{9}: nbuffer -- interval for printing, plotting, and saving -% xinput{10}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation -% Already divided by "fss." -% xinput{11}: scf -- reduction scale factor for Metropolis jumping kernel -% xinput{12}: Hsr1 -- square root of covariance matrix for free elements in A0 (nfp-by-nfp) -% for importance sampling. -% xinput{13}: fss -- effective sample size == nSample-lags+# of dummy observations -%------------------ -% xdraw: imndraws-by-length(Indxv) matrix of draws; -% empty if Indxv is empty. -% timeminutes: minutes used for this simulation -% mphv: imndraws-by-1 vector of unscaled weights -% sm: sum of the weights -% -% Written by Tao Zha 1999 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess1=xinput{4}; Indxv=xinput{5}; -imndraws=xinput{6}; a0indx=xinput{7}; tdf=xinput{8}; nbuffer=xinput{9}; -Sbd=xinput{10}; scf=xinput{11}; Hsr1=xinput{12}; fss=xinput{13}; - - -sm = 0.0; -mphv=zeros(imndraws,1); -if isempty(Indxv) - xdraw=[]; -else - xdraw=zeros(imndraws,length(Indxv)); %<<>> draws of selected variables -end - -tic -for draws=1:imndraws - % - if ~mod(draws,nbuffer) - draws - % fwriteid = fopen('outA0.bin','a'); - % count = fwrite(fwriteid,A0hatw,'double'); - % status = fclose('all'); - end - - - %** draw free elements Avh in A0 and hyperparameters from t-dist - Avhz1 = Hsr1\randn(nfp,1); % normal draws - csq=randn(tdf,1); - csq=sum(csq .* csq); - Avhz = xhat+Avhz1/sqrt(csq/tdf); % Robert, p.382 - - % *** compute weights *** - % * t-dist density, having taken log - tdhz = -0.5*(length(Avhz)+tdf)*log(1+(Avhz-xhat)'*(hess1*(Avhz-xhat))/tdf); - % * actual density, having taken log - hAvhz = a0asfun(Avhz,Sbd,fss,nvar,a0indx); - hAvhz = -hAvhz; % converted to logLH - - % * mph: m prim hat in Kloek & van Dijk, p.5 - mph = exp(hAvhz-tdhz-scf); % scf: scaling factor to prevent overflow - mphv(draws) = mph; - - sm=sm+mph; - % * matrix of draws for selected variables - if ~isempty(Indxv) - xdraw(draws,:) = Avhz(Indxv)'; - end - % -end -timeminutes = toc/60 +function [xdraw,mphv,sm,timeminutes] = a0impsmp(xinput) +% [xdraw,mphv,sm,timeminutes] = a0impsmp(xinput) +% Export the simulated pdfs of draws of only selected parameters +% with importance sampling techniques +% +% xinput{1}: nfp -- total number of free parameters +% xinput{2}: nvar -- number of variables +% xinput{3}: xhat -- ML estimate of free parameters in A0 +% xinput{4}: hess1 -- Hessian of -logLH for importance sampling +% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest +% to select variables, always check idmat0 to make sure. +% When Indxv=[], xdraw is empty as well. When IndxGgraph=1, it plots +% (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, +% (3) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences +% (5) scattered plot of 1st and 2nd for al sequences. +% xinput{6}: imndraws=nstarts*ndraws2 +% xinput{7}: a0indx -- index number for non-zero elements in A0 +% xinput{8}: tdf -- degrees of freedom for t-distribution +% xinput{9}: nbuffer -- interval for printing, plotting, and saving +% xinput{10}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation +% Already divided by "fss." +% xinput{11}: scf -- reduction scale factor for Metropolis jumping kernel +% xinput{12}: Hsr1 -- square root of covariance matrix for free elements in A0 (nfp-by-nfp) +% for importance sampling. +% xinput{13}: fss -- effective sample size == nSample-lags+# of dummy observations +%------------------ +% xdraw: imndraws-by-length(Indxv) matrix of draws; +% empty if Indxv is empty. +% timeminutes: minutes used for this simulation +% mphv: imndraws-by-1 vector of unscaled weights +% sm: sum of the weights +% +% Written by Tao Zha 1999 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess1=xinput{4}; Indxv=xinput{5}; +imndraws=xinput{6}; a0indx=xinput{7}; tdf=xinput{8}; nbuffer=xinput{9}; +Sbd=xinput{10}; scf=xinput{11}; Hsr1=xinput{12}; fss=xinput{13}; + + +sm = 0.0; +mphv=zeros(imndraws,1); +if isempty(Indxv) + xdraw=[]; +else + xdraw=zeros(imndraws,length(Indxv)); %<<>> draws of selected variables +end + +tic +for draws=1:imndraws + % + if ~mod(draws,nbuffer) + draws + % fwriteid = fopen('outA0.bin','a'); + % count = fwrite(fwriteid,A0hatw,'double'); + % status = fclose('all'); + end + + + %** draw free elements Avh in A0 and hyperparameters from t-dist + Avhz1 = Hsr1\randn(nfp,1); % normal draws + csq=randn(tdf,1); + csq=sum(csq .* csq); + Avhz = xhat+Avhz1/sqrt(csq/tdf); % Robert, p.382 + + % *** compute weights *** + % * t-dist density, having taken log + tdhz = -0.5*(length(Avhz)+tdf)*log(1+(Avhz-xhat)'*(hess1*(Avhz-xhat))/tdf); + % * actual density, having taken log + hAvhz = a0asfun(Avhz,Sbd,fss,nvar,a0indx); + hAvhz = -hAvhz; % converted to logLH + + % * mph: m prim hat in Kloek & van Dijk, p.5 + mph = exp(hAvhz-tdhz-scf); % scf: scaling factor to prevent overflow + mphv(draws) = mph; + + sm=sm+mph; + % * matrix of draws for selected variables + if ~isempty(Indxv) + xdraw(draws,:) = Avhz(Indxv)'; + end + % +end +timeminutes = toc/60 diff --git a/MatlabFiles/a0lhfun.m b/MatlabFiles/a0lhfun.m index a4f7e824af3afab2ef99c2bff69f06bc513fc594..80b392db634e49cd128b0b6202e8a7548c94ff53 100644 --- a/MatlabFiles/a0lhfun.m +++ b/MatlabFiles/a0lhfun.m @@ -1,55 +1,55 @@ -function of = a0lhfun(x,s,nobs,nvar,a0indx) -% of = a0lhfun(x,s,nobs,nvar,a0indx) -- negative logLH -% Note: columns correpond to equations -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector), -% s (covariance matrix of innovations): note already divided by "nobs" -% nobs (no of obs), -% nvar (no of variables), -% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds -% to an equation) -% written by Eric Leeper -% Copyright (C) 1997-2012 Eric Leeper -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -a0 = zeros(nvar); -a0(a0indx) = x; -% Note: each column in a0 corresponds to an equation!! -% -%%ada = chol(a0'*a0); -%%ada = log(abs(diag(ada))); -%%ada = sum(ada); -% ** TZ, 10/15/96, the above two lines can be improved by the following three lines -[a0l,a0u] = lu(a0); -%ada=diag(abs(a0u)); -%ada=sum(log(ada)); -ada = sum(log(abs(diag(a0u)))); - -% -%tra = trace(a0'*s*a0); -tra = reshape(s,nvar*nvar,1)'*reshape(a0*a0',nvar*nvar,1); -%if ada == 0 -% of = 1.0; -% else -% of = -nobs*ada + nobs*.5*tra; -%end -% commented out by T.Z. for there appears no sense of using "if-end" - - -of = -nobs*ada + nobs*.5*tra; \ No newline at end of file +function of = a0lhfun(x,s,nobs,nvar,a0indx) +% of = a0lhfun(x,s,nobs,nvar,a0indx) -- negative logLH +% Note: columns correpond to equations +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector), +% s (covariance matrix of innovations): note already divided by "nobs" +% nobs (no of obs), +% nvar (no of variables), +% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds +% to an equation) +% written by Eric Leeper +% +% Copyright (C) 1997-2012 Eric Leeper +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +a0 = zeros(nvar); +a0(a0indx) = x; +% Note: each column in a0 corresponds to an equation!! +% +%%ada = chol(a0'*a0); +%%ada = log(abs(diag(ada))); +%%ada = sum(ada); +% ** TZ, 10/15/96, the above two lines can be improved by the following three lines +[a0l,a0u] = lu(a0); +%ada=diag(abs(a0u)); +%ada=sum(log(ada)); +ada = sum(log(abs(diag(a0u)))); + +% +%tra = trace(a0'*s*a0); +tra = reshape(s,nvar*nvar,1)'*reshape(a0*a0',nvar*nvar,1); +%if ada == 0 +% of = 1.0; +% else +% of = -nobs*ada + nobs*.5*tra; +%end +% commented out by T.Z. for there appears no sense of using "if-end" + + +of = -nobs*ada + nobs*.5*tra; diff --git a/MatlabFiles/a0lhgh.m b/MatlabFiles/a0lhgh.m index 42390d267bc3ac86108040198fee0e9140cb3e02..0b8b6e7184bd942446607e9898ff38e3069afcca 100644 --- a/MatlabFiles/a0lhgh.m +++ b/MatlabFiles/a0lhgh.m @@ -1,34 +1,34 @@ -function g = a0lhgh(x0,s,nobs,nvar,a0indx); -%function g = a0lhgh(x0,s,nobs,nvar,a0indx); -% computes the hessian with analytical gradient provided -% x0 (parameter vector), -% s (covariance matrix of innovations): note divided by "nobs" -% nobs (no of obs), -% nvar (no of variables), -% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds -% to an equation) -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -%%a = zeros(nvar*nvar,1); -a = zeros(nvar); -g = zeros(nvar*nvar,1); -badg = 0; -a(a0indx) = x0; -b = -nobs*inv(a') + nobs*s*a; -b = reshape(b,nvar*nvar,1); -g = b(a0indx); \ No newline at end of file +function g = a0lhgh(x0,s,nobs,nvar,a0indx); +%function g = a0lhgh(x0,s,nobs,nvar,a0indx); +% computes the hessian with analytical gradient provided +% x0 (parameter vector), +% s (covariance matrix of innovations): note divided by "nobs" +% nobs (no of obs), +% nvar (no of variables), +% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds +% to an equation) +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +%%a = zeros(nvar*nvar,1); +a = zeros(nvar); +g = zeros(nvar*nvar,1); +badg = 0; +a(a0indx) = x0; +b = -nobs*inv(a') + nobs*s*a; +b = reshape(b,nvar*nvar,1); +g = b(a0indx); diff --git a/MatlabFiles/a0lhgrad.m b/MatlabFiles/a0lhgrad.m index 4f5478b1331fb1b3e28232546da099200855ac1c..fba69e8de7c9a8363d3344ba98f4e42c3f2ac88a 100644 --- a/MatlabFiles/a0lhgrad.m +++ b/MatlabFiles/a0lhgrad.m @@ -1,36 +1,36 @@ -function [g,badg] = a0lhgrad(x0,s,nobs,nvar,a0indx); -%function [g,badg] = a0lhgrad(x0,s,nobs,nvar,a0indx); -% computes analytical gradient for use in csminwel.m -% x0 (parameter vector), -% s (covariance matrix of innovations): note divided by "nobs" -% nobs (no of obs), -% nvar (no of variables), -% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds -% to an equation) -% -% Written by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -%%a = zeros(nvar*nvar,1); -a = zeros(nvar); -%%g = zeros(nvar*nvar,1); % 4/27/97: not necessary. TAZ -badg = 0; -a(a0indx) = x0; -b = -nobs*inv(a') + nobs*s*a; -b = reshape(b,nvar*nvar,1); -g = b(a0indx); +function [g,badg] = a0lhgrad(x0,s,nobs,nvar,a0indx); +%function [g,badg] = a0lhgrad(x0,s,nobs,nvar,a0indx); +% computes analytical gradient for use in csminwel.m +% x0 (parameter vector), +% s (covariance matrix of innovations): note divided by "nobs" +% nobs (no of obs), +% nvar (no of variables), +% a0indx (matrix indicating the free parameters in A0, and each column in A0 corresponds +% to an equation) +% +% Written by Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +%%a = zeros(nvar*nvar,1); +a = zeros(nvar); +%%g = zeros(nvar*nvar,1); % 4/27/97: not necessary. TAZ +badg = 0; +a(a0indx) = x0; +b = -nobs*inv(a') + nobs*s*a; +b = reshape(b,nvar*nvar,1); +g = b(a0indx); diff --git a/MatlabFiles/a0onlysim.m b/MatlabFiles/a0onlysim.m index b152bedc9e5404b38a3e88aa911a332a1ead7436..8975c97413b070765da1106cc21d18c6ec7f8dd0 100644 --- a/MatlabFiles/a0onlysim.m +++ b/MatlabFiles/a0onlysim.m @@ -1,286 +1,286 @@ -function [xdraw,timeminutes,nswitch] = a0onlysim(xinput) -% [xdraw,timeminutes,nswitch] = a0onlysim(xinput) -% Export and plot the simulated pdfs of draws of only selected parameters; -% Print and save Gelman's measures of B and W for all parameters; -% Ref: Waggoner and Zha "Does Normalization Matter for Inference" -% See note Forecast (2) -% -% xinput{1}: nfp -- total number of free parameters -% xinput{2}: nvar -- number of variables -% xinput{3}: xhat -- ML estimate of free parameters in A0 -% xinput{4}: hess1 -- Hessian of -logLH -% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest -% to select variables, always check idmat0 to make sure. -% When Indxv=[], xdraw is empty as well. When IndxGgraph=1, it plots -% (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, -% (3) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences -% (5) scattered plot of 1st and 2nd for al sequences. -% xinput{6}: IndxGraph - 1: plot graphs; 0: no graphs -% xinput{7}: idmat0 -- Index for non-zero elements in A0 with column to equation -% xinput{8}: nstarts -- # of starting points in Gibbs sampling -% xinput{9}: ndraws1 -- # of 1st loop to be discarded -% xinput{10}: ndraws2 -- # of 2nd loop for saving A0 draws -% xinput{11}: imndraws=nstarts*ndraws2 -% xinput{12}: a0indx -- index number for non-zero elements in A0 -% xinput{13}: tdf -- degrees of freedom for t-distribution -% xinput{14}: nbuffer -- interval for printing, plotting, and saving -% xinput{15}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation -% Already divided by "fss." -% xinput{16}: nSample -- the original sample size including lags -% xinput{17}: IndxNmlr -- index for which normalization rule to choose -% xinput{18}: IndxGibbs -- index for WZ Gibbs; 1; Gibbs; 0: Metropolis -% xinput{19}: scf -- reduction scale factor for Metropolis jumping kernel -% xinput{20}: H_sr -- square root of the inverse of the covariance matrix -% for free elements in A0 (nfp-by-nfp) -% xinput{21}: fss -- effective sample size == nSample-lags+# of dummy observations -%------------------ -% xdraw: nstarts*ndraws2-by-length(Indxv) matrix of draws; -% empty if Indxv=[] -% timeminutes: minutes used for this simulation -% -% Written by Tao Zha 1999 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess=xinput{4}; Indxv=xinput{5}; -IndxGraph=xinput{6}; idmat0=xinput{7}; nstarts=xinput{8}; ndraws1=xinput{9}; ndraws2=xinput{10}; -imndraws=xinput{11}; a0indx=xinput{12}; tdf=xinput{13}; nbuffer=xinput{14}; Sbd=xinput{15}; -nSample = xinput{16}; IndxNmlr=xinput{17}; IndxGibbs=xinput{18}; scf=xinput{19}; H_sr=xinput{20}; -fss=xinput{21}; - -if IndxGraph>length(Indxv) - disp(' ') - warning('when IndxGraph=1, Indxv must have at least 1 elements') - disp('Press ctrl-c to abort') - pause -end - -Avhx_bs = zeros(nfp,1); -Avhx_bm = zeros(nfp,1); -Avhx_bj = zeros(nfp,1); -Avhx_cj = zeros(nfp,1); -Avhx_cm = zeros(nfp,1); -A0_h = zeros(nvar); -A0gbs = A0_h; % drawn A0 in Gibbs sampling -Avhxm = zeros(nfp,1); -Avhxs = Avhxm; -A0xhat = zeros(nvar); -A0xhat(a0indx) = xhat; -% A0hatw = zeros(nvar^2,nbuffer); - -countJump = zeros(nstarts,1); - - -%=================================== -% Here begins with the big loop -%=================================== -H1 = chol(hess); % upper triangular so that H1' is a lower triangular decomp -baseW = H_sr; %inv(H1); %H_sr; % covariance matrix without scaling -nswitch=0; %<<>> total number of sign switches -A0inxhat = inv(A0xhat); % inverse of ML estimate -a0indx0 = find(idmat0==0); % index for all zero's in A0; -if isempty(Indxv) - xdraw=[]; -else - xdraw=zeros(imndraws,length(Indxv)); %<<>> draws of selected variables -end - - -[cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss); - -tic -for starts = 1:nstarts - starts - if starts == 1 - A0gbs(a0indx) = xhat; % from "load ..." - if ~IndxGibbs % Metropolist - Avhx = xhat; - hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); - hAvhx = -hAvhx; % converted to logLH - end - else - Avhx = baseW*randn(nfp,1); %H_sr*randn(nfp,1); % D: discarded sequence - csq=randn(tdf,1); - csq=sum(csq .* csq); - Avhx = xhat+Avhx/sqrt(csq/tdf); - %** Normalization by the choice of IndxNmlr - A0gbs(a0indx) = Avhx; - if ~IndxNmlr(5) - [A0gbs,jnk] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); - else - A0ingbs = inv(A0gbs); - [A0gbs,jnk,jnk1] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); - end - % - if ~IndxGibbs % Metropolist - Avhx = A0gbs(a0indx); - hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); - hAvhx = -hAvhx; % converted to logLH - end - end - % - Avhxmm = zeros(nfp,1); - Avhxss = zeros(nfp,1); - cJump = 0; - - for draws = 1:ndraws1 - if IndxGibbs - A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); - else % Metropolis - [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... - baseW,nfp,Sbd,fss,nvar,a0indx); - end - end - - wdraws=(starts-1)*ndraws2+0; - for draws = 1:ndraws2 - drawsc = (starts-1)*ndraws2+draws; - if IndxGibbs - A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); - A0gbs(a0indx0) = 0; % set all zeros in A0gbs clean to avoid possible cumulative round-off errors - else % Metropolis - [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... - baseW,nfp,Sbd,fss,nvar,a0indx); - A0gbs(a0indx) = Avhx; - end - - %*** call normalization so that A0_h is normalized - if ~IndxNmlr(5) - [A0_h,nswitch] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); - else - A0ingbs = inv(A0gbs); - [A0_h,nswitch,A0_hin] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); - end - Avhx_norm = A0_h(a0indx); - - Avhxm = Avhxm + Avhx_norm; % 1st step to overall mean of parameter - Avhxs = Avhxs + Avhx_norm.^2; % 1st step to overall 2nd moment of parameter - - %* compute the mean and 2nd moment - %** Getting average of variances W and variance of means B/n -- B_n - %* see Gelman, p.331, my Shock(0), 12-13, and my Forecast (2), 28-31 - if (nstarts>1) - Avhxmm = Avhxmm + Avhx_norm; % n*(phi_.j) - Avhxss = Avhxss + Avhx_norm.^2; % 1st step to (phi_ij) for fixed j - end - - if ~isempty(Indxv) - xdraw((starts-1)*ndraws2+draws,:) = Avhx_norm(Indxv)'; %<<>> - end - % A0hatw(:,drawsc-wdraws) = A0_h(:); - if ~mod(draws,nbuffer) - starts - draws - wdraws=drawsc - % fwriteid = fopen('outA0.bin','a'); - % count = fwrite(fwriteid,A0hatw,'double'); - % status = fclose('all'); - if IndxGraph - %** 1-d pdf plot - % figure(2) - % histpdfg(xdraw((starts-1)*ndraws2+(1:draws),1),50,[],[],[]); - % pause(1) - - %** 2-d scatterplot - figure(3) - plot(xdraw((starts-1)*ndraws2+(1:draws),1),... - xdraw((starts-1)*ndraws2+(1:draws),2),'.'); - drawnow - end - end - end - % - if ~IndxGibbs - countJump(starts,1) = cJump; - end - % - %** Getting average of variances W and variance of means B/n -- B_n - %** see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 - if (nstarts>1) - Avhx_aj = Avhxmm/ndraws2; % (phi_.j) - Avhx_bs = Avhx_bs + Avhx_aj.^2; % 1st step to 2nd moment of (phi_.j) - Avhx_bm = Avhx_bm + Avhx_aj; % 1st step to (phi_..) - % - Avhx_bj = Avhxss/ndraws2; % 2nd moment of (phi_ij) for fixed j - Avhx_cj = Avhx_bj - Avhx_aj.^2; % ((n-1)/n)*S^2_j - Avhx_cm = Avhx_cm + Avhx_cj; % sum of ((n-1)/n)*S^2_j across j - end -end -timend = toc - -if ~IndxGibbs - countJump = countJump/ndraws2 -end - -Avhxm = Avhxm/(imndraws); -Avhxs = Avhxs/(imndraws); -Avhxv = Avhxs - Avhxm.^2; -Avhxs = sqrt(Avhxv); % stardard deviation -A0hm = zeros(nvar); -A0hm(a0indx) = Avhxm % mean -A0hv = zeros(nvar); -A0hv(a0indx) = Avhxv; % varaince matrix -A0hs = zeros(nvar); -A0hs(a0indx) = Avhxs; % standar deviation - -%**** Getting Within-Sequence W and Between-Sequence B_n -% see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 -if (nstarts>1) - AvhxW = (ndraws2/(ndraws2-1))*Avhx_cm/nstarts; - % W: average of j within-sequence variances - AvhxB_n = (nstarts/(nstarts-1)) * ( Avhx_bs/nstarts - (Avhx_bm/nstarts).^2 ); - % B/n: variance of J within-sequence means - AvhxB = ndraws2*AvhxB_n; % B - % - B_W1 = AvhxB ./ AvhxW; - B1 = AvhxB; - W1 = AvhxW; - GR1 = sqrt((ndraws2-1)/ndraws2 + B_W1/ndraws2); - % measure of Gelman reduction; need not be 1 to be accurate, - % contrary to what Gelman claims - save outB_W B_W1 B1 W1 GR1 nstarts ndraws2 imndraws timend Avhxs ... - A0xhat A0hm A0hs A0hv IndxGibbs countJump nswitch - - titstr = ['J ' num2str(nstarts) ' n1 ' num2str(ndraws1) ... - ' n2 ' num2str(ndraws2) ' timend minutes ' num2str(timend/60)]; - disp(' ') - disp(titstr) - disp('B/W sqrt(B) sqrt(W) Std(A0) GR') - format short g - [B_W1 sqrt(B1) sqrt(W1) Avhxs GR1] -else - save outB_W nstarts ndraws2 imndraws timend Avhxs ... - A0xhat A0hm A0hs A0hv IndxGibbs countJump nswitch -end - -disp(' ') -disp('nswitch nswitch/imndraws -- # of sign switches') -[nswitch nswitch/imndraws] -disp(' ') -disp('timend/60 minutes') -timeminutes = timend/60 -nswitch=nswitch/imndraws; - -if IndxGraph - % - % figure(4) - % histpdfg(xdraw(:,1),50,[],[],[]); - % figure(5) - % plot(xdraw(:,3),xdraw(:,4),'.'); - % figure(6) - % plot(xdraw(:,1),xdraw(:,2),'.'); -end \ No newline at end of file +function [xdraw,timeminutes,nswitch] = a0onlysim(xinput) +% [xdraw,timeminutes,nswitch] = a0onlysim(xinput) +% Export and plot the simulated pdfs of draws of only selected parameters; +% Print and save Gelman's measures of B and W for all parameters; +% Ref: Waggoner and Zha "Does Normalization Matter for Inference" +% See note Forecast (2) +% +% xinput{1}: nfp -- total number of free parameters +% xinput{2}: nvar -- number of variables +% xinput{3}: xhat -- ML estimate of free parameters in A0 +% xinput{4}: hess1 -- Hessian of -logLH +% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest +% to select variables, always check idmat0 to make sure. +% When Indxv=[], xdraw is empty as well. When IndxGgraph=1, it plots +% (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, +% (3) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences +% (5) scattered plot of 1st and 2nd for al sequences. +% xinput{6}: IndxGraph - 1: plot graphs; 0: no graphs +% xinput{7}: idmat0 -- Index for non-zero elements in A0 with column to equation +% xinput{8}: nstarts -- # of starting points in Gibbs sampling +% xinput{9}: ndraws1 -- # of 1st loop to be discarded +% xinput{10}: ndraws2 -- # of 2nd loop for saving A0 draws +% xinput{11}: imndraws=nstarts*ndraws2 +% xinput{12}: a0indx -- index number for non-zero elements in A0 +% xinput{13}: tdf -- degrees of freedom for t-distribution +% xinput{14}: nbuffer -- interval for printing, plotting, and saving +% xinput{15}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation +% Already divided by "fss." +% xinput{16}: nSample -- the original sample size including lags +% xinput{17}: IndxNmlr -- index for which normalization rule to choose +% xinput{18}: IndxGibbs -- index for WZ Gibbs; 1; Gibbs; 0: Metropolis +% xinput{19}: scf -- reduction scale factor for Metropolis jumping kernel +% xinput{20}: H_sr -- square root of the inverse of the covariance matrix +% for free elements in A0 (nfp-by-nfp) +% xinput{21}: fss -- effective sample size == nSample-lags+# of dummy observations +%------------------ +% xdraw: nstarts*ndraws2-by-length(Indxv) matrix of draws; +% empty if Indxv=[] +% timeminutes: minutes used for this simulation +% +% Written by Tao Zha 1999 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess=xinput{4}; Indxv=xinput{5}; +IndxGraph=xinput{6}; idmat0=xinput{7}; nstarts=xinput{8}; ndraws1=xinput{9}; ndraws2=xinput{10}; +imndraws=xinput{11}; a0indx=xinput{12}; tdf=xinput{13}; nbuffer=xinput{14}; Sbd=xinput{15}; +nSample = xinput{16}; IndxNmlr=xinput{17}; IndxGibbs=xinput{18}; scf=xinput{19}; H_sr=xinput{20}; +fss=xinput{21}; + +if IndxGraph>length(Indxv) + disp(' ') + warning('when IndxGraph=1, Indxv must have at least 1 elements') + disp('Press ctrl-c to abort') + pause +end + +Avhx_bs = zeros(nfp,1); +Avhx_bm = zeros(nfp,1); +Avhx_bj = zeros(nfp,1); +Avhx_cj = zeros(nfp,1); +Avhx_cm = zeros(nfp,1); +A0_h = zeros(nvar); +A0gbs = A0_h; % drawn A0 in Gibbs sampling +Avhxm = zeros(nfp,1); +Avhxs = Avhxm; +A0xhat = zeros(nvar); +A0xhat(a0indx) = xhat; +% A0hatw = zeros(nvar^2,nbuffer); + +countJump = zeros(nstarts,1); + + +%=================================== +% Here begins with the big loop +%=================================== +H1 = chol(hess); % upper triangular so that H1' is a lower triangular decomp +baseW = H_sr; %inv(H1); %H_sr; % covariance matrix without scaling +nswitch=0; %<<>> total number of sign switches +A0inxhat = inv(A0xhat); % inverse of ML estimate +a0indx0 = find(idmat0==0); % index for all zero's in A0; +if isempty(Indxv) + xdraw=[]; +else + xdraw=zeros(imndraws,length(Indxv)); %<<>> draws of selected variables +end + + +[cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss); + +tic +for starts = 1:nstarts + starts + if starts == 1 + A0gbs(a0indx) = xhat; % from "load ..." + if ~IndxGibbs % Metropolist + Avhx = xhat; + hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); + hAvhx = -hAvhx; % converted to logLH + end + else + Avhx = baseW*randn(nfp,1); %H_sr*randn(nfp,1); % D: discarded sequence + csq=randn(tdf,1); + csq=sum(csq .* csq); + Avhx = xhat+Avhx/sqrt(csq/tdf); + %** Normalization by the choice of IndxNmlr + A0gbs(a0indx) = Avhx; + if ~IndxNmlr(5) + [A0gbs,jnk] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); + else + A0ingbs = inv(A0gbs); + [A0gbs,jnk,jnk1] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); + end + % + if ~IndxGibbs % Metropolist + Avhx = A0gbs(a0indx); + hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); + hAvhx = -hAvhx; % converted to logLH + end + end + % + Avhxmm = zeros(nfp,1); + Avhxss = zeros(nfp,1); + cJump = 0; + + for draws = 1:ndraws1 + if IndxGibbs + A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); + else % Metropolis + [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... + baseW,nfp,Sbd,fss,nvar,a0indx); + end + end + + wdraws=(starts-1)*ndraws2+0; + for draws = 1:ndraws2 + drawsc = (starts-1)*ndraws2+draws; + if IndxGibbs + A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); + A0gbs(a0indx0) = 0; % set all zeros in A0gbs clean to avoid possible cumulative round-off errors + else % Metropolis + [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... + baseW,nfp,Sbd,fss,nvar,a0indx); + A0gbs(a0indx) = Avhx; + end + + %*** call normalization so that A0_h is normalized + if ~IndxNmlr(5) + [A0_h,nswitch] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); + else + A0ingbs = inv(A0gbs); + [A0_h,nswitch,A0_hin] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); + end + Avhx_norm = A0_h(a0indx); + + Avhxm = Avhxm + Avhx_norm; % 1st step to overall mean of parameter + Avhxs = Avhxs + Avhx_norm.^2; % 1st step to overall 2nd moment of parameter + + %* compute the mean and 2nd moment + %** Getting average of variances W and variance of means B/n -- B_n + %* see Gelman, p.331, my Shock(0), 12-13, and my Forecast (2), 28-31 + if (nstarts>1) + Avhxmm = Avhxmm + Avhx_norm; % n*(phi_.j) + Avhxss = Avhxss + Avhx_norm.^2; % 1st step to (phi_ij) for fixed j + end + + if ~isempty(Indxv) + xdraw((starts-1)*ndraws2+draws,:) = Avhx_norm(Indxv)'; %<<>> + end + % A0hatw(:,drawsc-wdraws) = A0_h(:); + if ~mod(draws,nbuffer) + starts + draws + wdraws=drawsc + % fwriteid = fopen('outA0.bin','a'); + % count = fwrite(fwriteid,A0hatw,'double'); + % status = fclose('all'); + if IndxGraph + %** 1-d pdf plot + % figure(2) + % histpdfg(xdraw((starts-1)*ndraws2+(1:draws),1),50,[],[],[]); + % pause(1) + + %** 2-d scatterplot + figure(3) + plot(xdraw((starts-1)*ndraws2+(1:draws),1),... + xdraw((starts-1)*ndraws2+(1:draws),2),'.'); + drawnow + end + end + end + % + if ~IndxGibbs + countJump(starts,1) = cJump; + end + % + %** Getting average of variances W and variance of means B/n -- B_n + %** see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 + if (nstarts>1) + Avhx_aj = Avhxmm/ndraws2; % (phi_.j) + Avhx_bs = Avhx_bs + Avhx_aj.^2; % 1st step to 2nd moment of (phi_.j) + Avhx_bm = Avhx_bm + Avhx_aj; % 1st step to (phi_..) + % + Avhx_bj = Avhxss/ndraws2; % 2nd moment of (phi_ij) for fixed j + Avhx_cj = Avhx_bj - Avhx_aj.^2; % ((n-1)/n)*S^2_j + Avhx_cm = Avhx_cm + Avhx_cj; % sum of ((n-1)/n)*S^2_j across j + end +end +timend = toc + +if ~IndxGibbs + countJump = countJump/ndraws2 +end + +Avhxm = Avhxm/(imndraws); +Avhxs = Avhxs/(imndraws); +Avhxv = Avhxs - Avhxm.^2; +Avhxs = sqrt(Avhxv); % stardard deviation +A0hm = zeros(nvar); +A0hm(a0indx) = Avhxm % mean +A0hv = zeros(nvar); +A0hv(a0indx) = Avhxv; % varaince matrix +A0hs = zeros(nvar); +A0hs(a0indx) = Avhxs; % standar deviation + +%**** Getting Within-Sequence W and Between-Sequence B_n +% see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 +if (nstarts>1) + AvhxW = (ndraws2/(ndraws2-1))*Avhx_cm/nstarts; + % W: average of j within-sequence variances + AvhxB_n = (nstarts/(nstarts-1)) * ( Avhx_bs/nstarts - (Avhx_bm/nstarts).^2 ); + % B/n: variance of J within-sequence means + AvhxB = ndraws2*AvhxB_n; % B + % + B_W1 = AvhxB ./ AvhxW; + B1 = AvhxB; + W1 = AvhxW; + GR1 = sqrt((ndraws2-1)/ndraws2 + B_W1/ndraws2); + % measure of Gelman reduction; need not be 1 to be accurate, + % contrary to what Gelman claims + save outB_W B_W1 B1 W1 GR1 nstarts ndraws2 imndraws timend Avhxs ... + A0xhat A0hm A0hs A0hv IndxGibbs countJump nswitch + + titstr = ['J ' num2str(nstarts) ' n1 ' num2str(ndraws1) ... + ' n2 ' num2str(ndraws2) ' timend minutes ' num2str(timend/60)]; + disp(' ') + disp(titstr) + disp('B/W sqrt(B) sqrt(W) Std(A0) GR') + format short g + [B_W1 sqrt(B1) sqrt(W1) Avhxs GR1] +else + save outB_W nstarts ndraws2 imndraws timend Avhxs ... + A0xhat A0hm A0hs A0hv IndxGibbs countJump nswitch +end + +disp(' ') +disp('nswitch nswitch/imndraws -- # of sign switches') +[nswitch nswitch/imndraws] +disp(' ') +disp('timend/60 minutes') +timeminutes = timend/60 +nswitch=nswitch/imndraws; + +if IndxGraph + % + % figure(4) + % histpdfg(xdraw(:,1),50,[],[],[]); + % figure(5) + % plot(xdraw(:,3),xdraw(:,4),'.'); + % figure(6) + % plot(xdraw(:,1),xdraw(:,2),'.'); +end diff --git a/MatlabFiles/adapt.m b/MatlabFiles/adapt.m deleted file mode 100644 index 1f8ba86a753062ea6895c3b76f49995415326404..0000000000000000000000000000000000000000 --- a/MatlabFiles/adapt.m +++ /dev/null @@ -1,49 +0,0 @@ -function Q = adapt(f,a,b,tol,trace,varargin) -%ADAPT Numerically evaluate integral using adaptive Simpson rule. -% -% Q = ADAPT('F',A,B) approximates the integral of F(X) from A to B -% to machine precision. 'F' is a string containing the name of the -% function. Function F must return a vector of output values if given -% a vector of input values. -% -% Q = ADAPT('F',A,B,TOL) integrates to a relative error of TOL. -% -% Q = ADAPT('F',A,B,TOL,TRACE) displays the left end point of the -% current interval, the interval length and the partial integral. -% -% Q = ADAPT('F',A,B,TOL,TRACE,P1,P2,...) allows coefficients P1, ... -% to be passed directly to function F: G = F(X,P1,P2,...). -% To use default values for TOL or TRACE, you may pass in the empty -% matrix ([]). -% -% See also QUAD, QUAD8, DBLQUAD. - -% % Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (nargin < 4), tol = []; end; -if (nargin < 5), trace = []; end; -if (isempty(tol)), tol = 10*eps; end; -if (isempty(trace)), trace = 0; end; - -x = [a (a+b)/2 b]; -y = feval(f, x, varargin{:}); -fa = y(1); fm = y(2); fb = y(3); -is = (b - a)/6 * (fa + 4*fm + fb); -s = sign(is); if (s == 0), s = 1; end; -is = s*(abs(is) + b - a)/2*tol/eps; -Q = adaptstp(f, a, b, fa, fm, fb, is, trace, varargin{:}); \ No newline at end of file diff --git a/MatlabFiles/adaptstp.m b/MatlabFiles/adaptstp.m deleted file mode 100644 index 6075b7993bfeda37e7d82e1aa1944c02772c28e6..0000000000000000000000000000000000000000 --- a/MatlabFiles/adaptstp.m +++ /dev/null @@ -1,43 +0,0 @@ -function Q = adaptstp (f, a, b, fa, fm, fb, is, trace, varargin) -%ADAPTSTP Recursive function used by ADAPT. -% -% Q = ADAPTSTP('F',A,B,FA,FM,FB,IS,TRACE) tries to -% approximate the integral of f(x) from a to b to within a -% relative error of IS/int(..)*eps. F is a string containing -% the name of f. The remaining arguments are generated by adapt -% or by the recursion. -% -% See also ADAPT. - -% Author: Walter Gander, 05/20/97 -% Copyright (C) 1997 Walter Gander -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -m = (a + b)/2; h = (b - a)/4; -x = [a + h, b - h]; -y = feval(f, x, varargin{:}); -fml = y(1); fmr = y(2); -i1 = h/1.5 * (fa + 4*fm + fb); -i2 = h/3 * (fa + 4*(fml + fmr) + 2*fm + fb); -i1 = (16*i2 - i1)/15; -if (is + (i1-i2) == is), - Q = i1; - if (trace), disp([a b-a Q]), end; -else - Q = adaptstp (f, a, m, fa, fml, fm, is, trace, varargin{:}) + ... - adaptstp (f, m, b, fm, fmr, fb, is, trace, varargin{:}); -end; \ No newline at end of file diff --git a/MatlabFiles/betapar.m b/MatlabFiles/betapar.m index e79604d42cf4cf770ca311c7369c0da93ec62efc..a0c141d57f985ad9ae46f6a6f0b1ad61a8aab5fc 100644 --- a/MatlabFiles/betapar.m +++ b/MatlabFiles/betapar.m @@ -1,26 +1,26 @@ -function f = betapar(ab, XLO, XUP, PLO, PUP); - -% The function takes as inputs the parameters ab=[a, b] of the Beta -% distribution, the bounds of the support [XLO, XUP], the the corresponding -% probability of the bounds [PLO, PUP] and returns the residual value f. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -a = ab(1); b = ab(2); -f1 = PLO - betacdf(XLO, a, b); -f2 = PUP - betacdf(XUP, a, b); -f = [f1, f2]; +function f = betapar(ab, XLO, XUP, PLO, PUP); + +% The function takes as inputs the parameters ab=[a, b] of the Beta +% distribution, the bounds of the support [XLO, XUP], the the corresponding +% probability of the bounds [PLO, PUP] and returns the residual value f. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +a = ab(1); b = ab(2); +f1 = PLO - betacdf(XLO, a, b); +f2 = PUP - betacdf(XUP, a, b); +f = [f1, f2]; diff --git a/MatlabFiles/bfgsi.m b/MatlabFiles/bfgsi.m index b56fe3662be6d5ec4dc88906c886cdc072e78e5e..7d94746726f8d13e30af7f96cfe241e5f578dae6 100644 --- a/MatlabFiles/bfgsi.m +++ b/MatlabFiles/bfgsi.m @@ -1,46 +1,44 @@ -function H = bfgsi(H0,dg,dx) -% H = bfgsi(H0,dg,dx) -% dg is previous change in gradient; dx is previous change in x; -% 6/8/93 version that updates inverse hessian instead of hessian -% itself. -% Copyright by Christopher Sims 1996. This material may be freely -% reproduced and modified. - -% Copyright (C) 1996 Christopher Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. -dispIndx = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) - -if size(dg,2)>1 - dg=dg'; -end -if size(dx,2)>1 - dx=dx'; -end -Hdg = H0*dg; -dgdx = dg'*dx; -if (abs(dgdx) >1e-12) - H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx; -else - if dispIndx - disp('bfgs update failed.') - disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]); - disp(['dg''*dx = ' num2str(dgdx)]) - disp(['|H*dg| = ' num2str(Hdg'*Hdg)]) - end - H=H0; -end -save H.dat H +function H = bfgsi(H0,dg,dx) +% H = bfgsi(H0,dg,dx) +% dg is previous change in gradient; dx is previous change in x; +% 6/8/93 version that updates inverse hessian instead of hessian +% itself. +% +% +% Copyright (C) 1996 Christopher A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% +dispIndx = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) + +if size(dg,2)>1 + dg=dg'; +end +if size(dx,2)>1 + dx=dx'; +end +Hdg = H0*dg; +dgdx = dg'*dx; +if (abs(dgdx) >1e-12) + H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx; +else + if dispIndx + disp('bfgs update failed.') + disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]); + disp(['dg''*dx = ' num2str(dgdx)]) + disp(['|H*dg| = ' num2str(Hdg'*Hdg)]) + end + H=H0; +end +save H.dat H diff --git a/MatlabFiles/binread.m b/MatlabFiles/binread.m index d9f6c930b9466a5d07336ea27a88c8ec06566857..806f2fce8e0da0aa8bbecfc4baeac3a4ac164c48 100644 --- a/MatlabFiles/binread.m +++ b/MatlabFiles/binread.m @@ -1,31 +1,31 @@ -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. -nbuffer = 10; -ndraws=3*nbuffer; - -n=3; -yhatw = zeros(n^2,ndraws); -seldraw = [3 7]; - -[fid,message]=fopen('outyhat.bin') -%[xd,count]=fread(fid,[n^2,length(seldraw)],'double'); % (1) working -[xd,count]=fread(fid,inf,'single'); % (2) working. with 'single' or 'double' -fid -message -count -%xdd=reshape(xd,n^2,length(seldraw)) % (1) working -xdd=reshape(xd,n^2,ndraws) % (2) working \ No newline at end of file +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% +nbuffer = 10; +ndraws=3*nbuffer; + +n=3; +yhatw = zeros(n^2,ndraws); +seldraw = [3 7]; + +[fid,message]=fopen('outyhat.bin') +%[xd,count]=fread(fid,[n^2,length(seldraw)],'double'); % (1) working +[xd,count]=fread(fid,inf,'single'); % (2) working. with 'single' or 'double' +fid +message +count +%xdd=reshape(xd,n^2,length(seldraw)) % (1) working +xdd=reshape(xd,n^2,ndraws) % (2) working diff --git a/MatlabFiles/binwrite.m b/MatlabFiles/binwrite.m index 20e46d64baaa062bfb321406fca8b2af9de2dd38..3607ac4ec0a6364e2ef773cf2119eafd15200256 100644 --- a/MatlabFiles/binwrite.m +++ b/MatlabFiles/binwrite.m @@ -1,36 +1,36 @@ -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. -nbuffer = 10; -ndraws=3*nbuffer; - -n=3; -yhatw = zeros(n^2,nbuffer); - -wdraws=0; -for draws=1:ndraws - tmp = draws*ones(n); - yhatw(:,draws-wdraws) = tmp(:); - - if ~mod(draws,nbuffer) - wdraws=draws - - fwriteid = fopen('outyhat.bin','a'); - count = fwrite(fwriteid,yhatw,'single'); % 'single' or 'double' - status = fclose('all'); - end -end - +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% +nbuffer = 10; +ndraws=3*nbuffer; + +n=3; +yhatw = zeros(n^2,nbuffer); + +wdraws=0; +for draws=1:ndraws + tmp = draws*ones(n); + yhatw(:,draws-wdraws) = tmp(:); + + if ~mod(draws,nbuffer) + wdraws=draws + + fwriteid = fopen('outyhat.bin','a'); + count = fwrite(fwriteid,yhatw,'single'); % 'single' or 'double' + status = fclose('all'); + end +end + diff --git a/MatlabFiles/calyrqm.m b/MatlabFiles/calyrqm.m index 5c94aa34feb37157e794b8ca804646cd1ed6c599..69512a1caabdac0d0b0d76e70d3e0f45bf3126fa 100644 --- a/MatlabFiles/calyrqm.m +++ b/MatlabFiles/calyrqm.m @@ -1,74 +1,74 @@ -function [Myrqm,nMyrqm] = calyrqm(q_m,Byrqm,Eyrqm) -% [Myrqm,nMyrqm] = calyrqm(q_m,Byrqm,Eyrqm) -% -% Given the beginning and end years and quarters (months), export a matrix of all years and -% quarters (months) for these years and in between -% -% q_m: 4 if quarterly and 12 if monthly -% Byrqm: [year quarter(month)] -- all integers, the begining year and quarter (month) -% Eyrqm: [year quarter(month)] -- all integers, the end year and quarter (month) -%------------------- -% Myrqm: matrix of all years and quarters (months) between and incl. Byrqm and Eyrqm -% nMyrqm: number of data points incl. Byrqm and Eyrqm -% -% Tao Zha, April 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if ~isempty(find(Byrqm-round(Byrqm))) | (q_m-round(q_m)) | ~isempty(find(Byrqm-round(Byrqm))) - error('argin qm, Byrqm, or Eyrqm must of integer') -elseif Byrqm(1)>Eyrqm(1) - error('Eyrqm(1) must be equal to or greater than Byrqm(1)') -elseif Byrqm(1)==Eyrqm(1) - if Byrqm(2)>Eyrqm(2) - error('Eyrqm(2) must be equal to or greater than Byrqm(2) because of the same year') - end -end - - -Yr = Byrqm(1)+[0:Eyrqm(1)-Byrqm(1)]'; - -if length(Yr)>=2 % there are years and quarters (months) between Byrqm and Eyrqm - n=length(Yr)-2; - C=zeros(n*q_m,2); - C(:,1) = kron(Yr(2:end-1),ones(q_m,1)); - C(:,2) = kron(ones(n,1),[1:q_m]'); - - %* initialize a matrix of years and quarters (months) including Byrqm and Eyrqm - Myrqm = zeros((q_m-Byrqm(2)+1)+Eyrqm(2)+n*q_m,2); - - %* Years in between - n1=q_m-Byrqm(2)+1; - n2=Eyrqm(2); - Myrqm(n1+1:end-n2,:) = C; - %* Beginning year - for k=1:n1 - Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; - end - %* End year - for k=1:n2 - Myrqm(end-Eyrqm(2)+k,:) = [Eyrqm(1) k]; - end -else %* all the data are in the same calendar year - n1=Eyrqm(2)-Byrqm(2)+1; - Myrqm = zeros(n1,2); - for k=1:n1 - Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; - end -end - -nMyrqm = size(Myrqm,1); +function [Myrqm,nMyrqm] = calyrqm(q_m,Byrqm,Eyrqm) +% [Myrqm,nMyrqm] = calyrqm(q_m,Byrqm,Eyrqm) +% +% Given the beginning and end years and quarters (months), export a matrix of all years and +% quarters (months) for these years and in between +% +% q_m: 4 if quarterly and 12 if monthly +% Byrqm: [year quarter(month)] -- all integers, the begining year and quarter (month) +% Eyrqm: [year quarter(month)] -- all integers, the end year and quarter (month) +%------------------- +% Myrqm: matrix of all years and quarters (months) between and incl. Byrqm and Eyrqm +% nMyrqm: number of data points incl. Byrqm and Eyrqm +% +% Tao Zha, April 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if ~isempty(find(Byrqm-round(Byrqm))) | (q_m-round(q_m)) | ~isempty(find(Byrqm-round(Byrqm))) + error('argin qm, Byrqm, or Eyrqm must of integer') +elseif Byrqm(1)>Eyrqm(1) + error('Eyrqm(1) must be equal to or greater than Byrqm(1)') +elseif Byrqm(1)==Eyrqm(1) + if Byrqm(2)>Eyrqm(2) + error('Eyrqm(2) must be equal to or greater than Byrqm(2) because of the same year') + end +end + + +Yr = Byrqm(1)+[0:Eyrqm(1)-Byrqm(1)]'; + +if length(Yr)>=2 % there are years and quarters (months) between Byrqm and Eyrqm + n=length(Yr)-2; + C=zeros(n*q_m,2); + C(:,1) = kron(Yr(2:end-1),ones(q_m,1)); + C(:,2) = kron(ones(n,1),[1:q_m]'); + + %* initialize a matrix of years and quarters (months) including Byrqm and Eyrqm + Myrqm = zeros((q_m-Byrqm(2)+1)+Eyrqm(2)+n*q_m,2); + + %* Years in between + n1=q_m-Byrqm(2)+1; + n2=Eyrqm(2); + Myrqm(n1+1:end-n2,:) = C; + %* Beginning year + for k=1:n1 + Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; + end + %* End year + for k=1:n2 + Myrqm(end-Eyrqm(2)+k,:) = [Eyrqm(1) k]; + end +else %* all the data are in the same calendar year + n1=Eyrqm(2)-Byrqm(2)+1; + Myrqm = zeros(n1,2); + for k=1:n1 + Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; + end +end + +nMyrqm = size(Myrqm,1); diff --git a/MatlabFiles/cfore.m b/MatlabFiles/cfore.m index c3e06510aa2a4edaf39eb6cd465fa8f619dbc1dc..b37cb7962024fa679201df609e479a155ff8504d 100644 --- a/MatlabFiles/cfore.m +++ b/MatlabFiles/cfore.m @@ -1,481 +1,481 @@ -% 10/24/97 -% Distance Method of Waggoner and Zha -% Modified from Sims and Zha's code -% Copyright (c) 1997 Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** ONLY UNDER UNIX SYSTEM -%path(path,'/usr2/f1taz14/mymatlab') - - -%global xxhp Hm1t Hm1 Hm SpH FRESHFUNCTION -% -%* ================================================= -%* ====== Beginning of the script ================== -%* ================================================= -% -%* The available data considered -% -q_m = 12; % quarters or months -yrBin=59; % beginning of the year -qmBin=1; % begining of the quarter or month -yrFin=97; % final year -qmFin=12; % final quarter -%tnvar = 2; % total number of variables -nData=(yrFin-yrBin)*q_m + (qmFin-qmBin+1); -% total number of the available data -- this is all you have -% -%* Load data and series -% -load xd24a % the default name for the variable is "xdd". -[nt,ndv]=size(xdd); -if nt~=nData - warning(sprintf('nt=%d, Caution: not equal to the length in the data',nt)); - %disp(sprintf('nt=%d, Caution: not equal to the length in the data',nt)); - return -end -%1 CPI-U -%2 FFR -%3 T-bill3 -%4 Treasure note 10 -%5 M2 -%6 M1 -%7 Nominal PCE -%8 real PCE -%9 Unemployment Rate -%10 IMF Commodity Price Index -%11 Civilians Employed: 16 & over -%12 Nonfarm Payroll Employment -%13 IP -%14 Retail Sales (Nominal) -%15 NAPM Composit Index -%16 Total Reserves -%17 PPI-finished goods -%18 PPI-Crude materials -%19 PPI-Crude materials less energy -%20 CRB Spot Commodity Index -- all commodities -%21 CRB Spot Commodity Index -- raw industrials -%22 PCE price index -%23 rgdpmon Real GDP (monthly, chain $92) -%24 dgdpmon Deflator GDP (monthly, chain $92) - - -%1 IMF CP -%2 M2 -%3 FFR -%3 real GDP -%4 CPI-U -%5 U - -%>>>>>>>>>>>>>>>>>> -logindx = [1 5:8 10:14 16:24]; -xdd(:,logindx) = log(xdd(:,logindx)); -pctindx = [2:4 9 15]; -xdd(:,pctindx)=.01*xdd(:,pctindx); % make it a general term for the following use -% -vlist = [10 5 2 23 1 9]; % regarding "xdd", IMF-CP, M2, FFR, GDP, CPI, U -vlistlog = [1 2 4 5]; % subset of "vlist" -vlistper = [3 6]; % subset of "vlist" -%<<<<<<<<<<<<<<<<<<< - -idfile='iden6'; - -xlab = {'Inf' - 'MS' - 'FFR' - 'y' - 'P' - 'U'}; - -ylab = {'Pcm' - 'M2' - 'FFR' - 'y' - 'P' - 'U'}; - -xdd_per = xdd(:,vlist); - -x1 = 'Pcm'; -x2 = 'M2'; -x3 = 'FFR'; -x4 = 'GDP'; -x5 = 'CPI'; -x6 = 'U'; -x7 = 'R10'; - - -baddata = find(isnan(xdd_per)); -if ~isempty(baddata) - warning('Some data are actually unavailable.') - disp('Hit any key to continue, or ctrl-c to abort') - pause -end -% - -%* A specific sample is considered for estimation -%* Sample period 59:7-82:9, forecast period 82:10-84:9 -yrStart=59; -qmStart=1; -[yrEnd,qmEnd,forep,forepy,forelabel] = pararc; -nSample=(yrEnd-yrStart)*q_m + (qmEnd-qmStart+1); -if qmEnd == q_m % end of the year - nSampleCal=nSample; % Cal: calendar year -else - nSampleCal=(yrEnd-1-yrStart)*q_m + (q_m-qmStart+1); % Cal: calendar year -end - -%* More script variables -% -lags = 13; % <<>> -% automatic decay code (monthly data), only two options: lags = 6 or 13 -forepq = forep/3; % quarterly -actup = 5*48; % <<>> actual periods before forecasting (20 years) -%actup = 12*floor(nSample/12); % <<>> actual periods before forecasting (8 years) -actup = 48; % <<>> actual periods before forecasting (4 years) -actupq = actup/3; % quarterly -actupy = actup/12; % four years -imstp = 48; % <<>> impulse responses (4 years) -ninv = 1000; % the number of intervals for counting impulse responses -nhp = 6; % <<>> number of hyperparameters for estimation -%%scf = 2.4/sqrt(nvar); % scf^2*Sigma (covaraince) -scf = 0.25; % scf^2*Sigma (covaraince) -ndraws1=15; % 1500, 1st part of Monte Carlo draws -ndraws2=2*ndraws1; % 2nd part of Monte Carlo draws -ndraws=3*ndraws2 % a total number of Monte Carlo draws -nstarts=3; % number of starting points -imndraws = nstarts*ndraws2; -tdf = 3; % degrees of freedom for t-dist -ga = tdf/2; % asymmetry parameter in Gamma -gb = 2/tdf; % normalized parameter in Gamma -% -%* ================================================= -%* ====== End of the script ======================== -%* ================================================= - - -if (q_m==12) - nStart=(yrStart-yrBin)*12+qmStart-qmBin; % positive number of months at the start - nEnd=(yrEnd-yrFin)*12+qmEnd-qmFin; % negative number of months towards end -elseif (q_m==4) - nStart=(yrStart-yrBin)*4+qmStart-qmBin; % positive number of months at the start - nEnd=(yrEnd-yrFin)*4+qmEnd-qmFin; % negative number of months towards end -else - disp('Warning: this code is only good for monthly/quarterly data!!!') - return -end -% -if nEnd>0 | nStart<0 - disp('Warning: this particular sample consider is out of bounds of the data!!!') - return -end -% -xdgel=xdd(nStart+1:nData+nEnd,vlist); % gel: general term for selected xdd -xdata=xdd(nStart+1:nData,vlist); - -[Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... - idmat0,idmatpp] = szasbvar(idfile,q_m,lags,nSample,nhp,xdgel); - -% * the largest matrix in this file <<>> -yforew = zeros(ndraws,forep*nvar); % preallocating -yforeqgw = zeros(ndraws,forepq*nvar); % preallocating -yforeCalygw = zeros(ndraws,forepy*nvar); % preallocating -% * the largest matrix in this file <<>> -%%imfcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count - -load idenml % xhat ghat fhat, etc. -%load outiden % xhat ghat fhat - -%================== -% Impulse responses first -%================== -%A0 = zeros(nvar); -%A0(a0indx)=xhat; -%A0(4,2) = -xhat(7); % output in MD -%A0(5,2)=-xhat(7); % price in MD -A0in = inv(A0); -swish = A0in'; % each row corresponds to an equation -%Bh = Hm1t; % no longer have Hm1t in this new szasbvar - -% ** impulse responses -nn = [nvar lags imstp]; -imf = zimpulse(Bh,swish,nn); % in the form that is congenial to RATS -%[vd,str,imf] = errors(Bh,swish,nn); - -scaleout = imcgraph(imf,nvar,imstp,xlab,ylab) - - -%%%% -%$$$ Out-of-sample forecasts. Note: Hm1t does not change with A0. -%%%% -% -% ** out-of-sample forecast, from 82:4 to 84:3 (flp+1:flp+forep) -% * updating the last row of X (phi) with the current (last row of) y. -phil = phi(size(phi,1),:); -phil(nvar+1:ncoef-1) = phil(1:ncoef-1-nvar); -phil(1:nvar) = y(size(y,1),:); -ylast = y(size(y,1),:); -indx12 = size(y,1)-q_m+1:size(y,1); -ylast12 = y(indx12,:); % last 12 months data -nn = [nvar lags forep]; -% -yfore = forecast(Bh,phil,nn); % forep-by-nvar - - -%>>>>>>>>>>>>>>> -yforel=yfore; -yforel(:,vlistlog) = exp(yfore(:,vlistlog)); -figure; -t2=1:forep; -for i = 1:nvar - subplot(nvar/2,2,i) - plot(t2,yforel(:,i),'--') - %title('solid-actual, dotted-forecast'); - %title(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) -end -%<<<<<<<<<<<<<<< - -%%%%%%%% -% -%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r. -% -%%%%%%%% - -nconstr=4; % q: 4 years -- 4*12 months -eq_ms = 2; % location of MS equation -%eq_ms = []; % all shocks -%*** initializing -stepcon=cell(nconstr,1); % initializing, value y conditioned -valuecon=zeros(nconstr,1); % initializing, value y conditioned -varcon=zeros(nconstr,1); % initializing, endogous variables conditioned -% -stepcon{1}=[1:12]'; % average over 12 months. -stepcon{2}=[13:24]'; % average over 12 months. -stepcon{3}=[25:36]'; % average over 12 months. -stepcon{4}=[37:48]'; % average over 12 months. -% -%for i=1:nconstr -% stepcon{i}=i; -%end -% -chk1 = mean(yfore(stepcon{1},3)) -chk2 = mean(yfore(stepcon{2},3)) -chk3 = mean(yfore(stepcon{3},3)) -chk4 = mean(yfore(stepcon{4},3)) -Ro=[chk1 chk2 chk3 chk4]; -% -chk1 = exp( (sum(yfore(stepcon{1},5))-sum(ylast12(:,5))) ./ q_m ) -chk2 = exp( (sum(yfore(stepcon{2},5))-sum(yfore(stepcon{1},5))) ./ q_m ) -chk3 = exp( (sum(yfore(stepcon{3},5))-sum(yfore(stepcon{2},5))) ./ q_m ) -chk4 = exp( (sum(yfore(stepcon{4},5))-sum(yfore(stepcon{3},5))) ./ q_m ) -% -%valuecon(:)=0.055; -% -%>>>>>>>>>>>>>>>>> E: Condition on funds rate path >>>>>>>>>>>>> Toggle -%delta=0.0010; -%valuecon(1) = mean(yfore(stepcon{1},3))+2*delta; -%valuecon(2) = mean(yfore(stepcon{2},3))+2*delta; -%valuecon(3) = mean(yfore(stepcon{3},3))-2*delta; -%valuecon(4) = mean(yfore(stepcon{4},3))-2*delta; -%valuecon(1) = 0.055; -%valuecon(2) = 0.050; -%valuecon(3) = 0.0475; -%valuecon(4) = 0.045; -%>>>>>>>>>>>>>>>>> E: Condition on funds rate path >>>>>>>>>>>>> -% -%<<<<<<<<<<<<<<<< B: Condition on inflation path <<<<<<<<<< Toggle -%delta=0.0010; -%valuecon(1)=mean(ylast12(:,5))+log(chk1-0*delta); -%valuecon(2)=valuecon(1)+log(chk2-2*delta); -%valuecon(3)=valuecon(2)+log(chk3-6*delta); -%valuecon(4)=valuecon(3)+log(chk4-12*delta); -% % 5: CPI; 2.5%: annual inflation over 12 months, geometric means -%$$$ very good results -- following -valuecon(1)=mean(ylast12(:,5))+log(chk1); -valuecon(2)=valuecon(1)+log(1.020); -valuecon(3)=valuecon(2)+log(1.02); -valuecon(4)=valuecon(3)+log(1.02); -% % 5: CPI; 2.5%: annual inflation over 12 months, geometric means -%<<<<<<<<<<<<<<<< E: Condition on inflation path <<<<<<<<<< - -nstepsm = 0; % initializing, the maximum step in all constraints -for i=1:nconstr - nstepsm = max([nstepsm max(stepcon{i})]); -end -varcon(:)=5; % 3: FFR; 5: CPI -% -imf3=reshape(imf,size(imf,1),nvar,nvar); - % imf3: row-steps, column-nvar responses, 3rd dimension-nvar shocks -imf3s=permute(imf3,[1 3 2]); - % imf3s: permuted so that row-steps, column-nvar shocks, - % 3rd dimension-nvar responses - -[yhat,Estr] = fidencond(valuecon,stepcon,varcon,nconstr,nstepsm,nvar,lags,... - yfore,imf3s,phil,Bh,eq_ms); - -chk1 = mean(yhat(stepcon{1},3)) -chk2 = mean(yhat(stepcon{2},3)) -chk3 = mean(yhat(stepcon{3},3)) -chk4 = mean(yhat(stepcon{4},3)) -Rh=[chk1 chk2 chk3 chk4]; - -chk1 = exp( (sum(yhat(stepcon{1},5))-sum(ylast12(:,5))) ./ q_m ) -chk2 = exp( (sum(yhat(stepcon{2},5))-sum(yhat(stepcon{1},5))) ./ q_m ) -chk3 = exp( (sum(yhat(stepcon{3},5))-sum(yhat(stepcon{2},5))) ./ q_m ) -chk4 = exp( (sum(yhat(stepcon{4},5))-sum(yhat(stepcon{3},5))) ./ q_m ) - -%chk1 = mean(yhat(1:12,3)) -%chk2 = mean(yhat(13:24,3)) -%chk3 = mean(yhat(25:36,3)) -%chk4 = mean(yhat(36:48,3)) -%Rh=[chk1 chk2 chk3 chk4]; - -%chk1 = exp( (sum(yhat(1:12,5))-sum(ylast12(:,5))) ./ q_m ) -%chk2 = exp( (sum(yhat(13:24,5))-sum(yhat(1:12,5))) ./ q_m ) -%chk3 = exp( (sum(yhat(25:36,5))-sum(yhat(13:24,5))) ./ q_m ) -%chk4 = exp( (sum(yhat(37:48,5))-sum(yhat(25:36,5))) ./ q_m ) - - -idiff=mean(yfore(:,3))-mean(yhat(:,3)) -mean(yfore(:,3)) -mean(yhat(:,3)) -figure -plot(1:48,yfore(:,3),1:48,yhat(:,3),':') -figure -plot(1:4,Ro,1:4,Rh,':') - -%>>>>>>>>>>>>>>> -yhatl=yhat; -yhatl(:,vlistlog) = exp(yhat(:,vlistlog)); -figure; -t2=1:forep; -for i = 1:nvar - subplot(nvar/2,2,i) - plot(t2,yhatl(:,i),'--') - %title('solid-actual, dotted-forecast'); - %title(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) -end -%<<<<<<<<<<<<<<< - - -% inputs needed. -%yfore=yhat; - -%=================================================== -%%% Converting to calendar years and all at level -%=================================================== -[yforeml,yforeqgml,yforeCalygml] = fore_cal(yhat,xdata,nvar,nSample,... - nSampleCal,forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog); - -%================== -% Note -%================= -% ? 1--median; l--lower bound; h--upper bound: between the bound: 2/3 probability -% yfore? % monthly, level -% yforeqg? % quarterly, growth rate -% yforeCalyg? % calendar year, growth rate - -%save outw ndraws yfore1 yforeqg1 yforeCalyg1 yforel yforeqgl yforeh yforeqgh ... -% yforeCalygl yforeCalygh IUbeta - -yforeCalygml - - -%---------------------------------------------------------------------- -%================= Graphics ===================== -%---------------------------------------------------------------------- -% - -%[yactCalyg,yforeCalygml,yAg,yFg] = fore_gh(xdata,nvar,nSample,nSampleCal,... -% yforeml,yforeqgml,yforeCalygml,actup,actupq,actupy,... -% vlist,vlistlog,vlistper,q_m,forep,ylab); - -xinput = cell(16,1); -xinput{1}=xdata; xinput{2}=nvar; xinput{3}=nSample; xinput{4}=nSampleCal; -xinput{5}=yforeml; xinput{6}=yforeqgml; xinput{7}=yforeCalygml; xinput{8}=actup; -xinput{9}=actupq; xinput{10}=actupy; xinput{11}=vlist; xinput{12}=vlistlog; -xinput{13}=vlistper; xinput{14}=q_m; xinput{15}=forep; xinput{16}=ylab; -[yactCalyg,yforeCalygml,yAg,yFg] = fore_gh(xinput); - - -% Key Macroeconomic Variables: GDP, CPI, U -%******* From Goldbook July 1-2, 1997 FOMC -yforeBlue = [ - 3.6 2.4 5.0 - 2.5 2.6 5.0 - ]; % real GDP, CPI-U, U, -yforeMacro = [ - 3.7 2.3 4.9 - 2.1 2.4 4.9 - ]; % real GDP, CPI-U, U -yforeGold = [ - 3.8 2.4 5.0 - 2.5 2.5 4.8 - 2.4 2.7 4.7 - ]; % real GDP, CPI-U, U -t3 = yAg+1:yAg+length(yforeBlue(:,1)); -t4 = yAg+1:yAg+length(yforeGold(:,1)); -% -keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 -count=0; -t1 = 1:yAg; -t2 = yAg:yAg+yFg; -for i = keyindx - count = count+1; - subplot(3,2,count) - %plot(t1,yactqg(:,i),t2,yforeqg(:,i),':') - if (i==3) | (i==2) - plot(t1,yactCalyg(:,i),t2,[yactCalyg(length(t1),i);yforeCalygml(:,i)],'--') - %title('solid-actual, dotted-forecast'); - %xlabel(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) - else - plot(t1,yactCalyg(:,i),t2,[yactCalyg(length(t1),i);yforeCalygml(:,i)],'--',... - t3,yforeBlue(:,count),'o',t3,yforeMacro(:,count),'d',... - t4,yforeGold(:,count),'^') - %title('solid-actual, dotted-forecast'); - %xlabel(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) - end -end - -actual=yactCalyg(:,keyindx) % GDP, CPI, U, M2 -mode=yforeCalygml(:,keyindx) % GDP, CPI, U, M2 -%low=yforeCalygl(:,keyindx) -%high=yforeCalygh(:,keyindx) -yforeBlue -yforeMacro -yforeGold \ No newline at end of file +% 10/24/97 +% Distance Method of Waggoner and Zha +% Modified from Sims and Zha's code +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** ONLY UNDER UNIX SYSTEM +%path(path,'/usr2/f1taz14/mymatlab') + + +%global xxhp Hm1t Hm1 Hm SpH FRESHFUNCTION +% +%* ================================================= +%* ====== Beginning of the script ================== +%* ================================================= +% +%* The available data considered +% +q_m = 12; % quarters or months +yrBin=59; % beginning of the year +qmBin=1; % begining of the quarter or month +yrFin=97; % final year +qmFin=12; % final quarter +%tnvar = 2; % total number of variables +nData=(yrFin-yrBin)*q_m + (qmFin-qmBin+1); +% total number of the available data -- this is all you have +% +%* Load data and series +% +load xd24a % the default name for the variable is "xdd". +[nt,ndv]=size(xdd); +if nt~=nData + warning(sprintf('nt=%d, Caution: not equal to the length in the data',nt)); + %disp(sprintf('nt=%d, Caution: not equal to the length in the data',nt)); + return +end +%1 CPI-U +%2 FFR +%3 T-bill3 +%4 Treasure note 10 +%5 M2 +%6 M1 +%7 Nominal PCE +%8 real PCE +%9 Unemployment Rate +%10 IMF Commodity Price Index +%11 Civilians Employed: 16 & over +%12 Nonfarm Payroll Employment +%13 IP +%14 Retail Sales (Nominal) +%15 NAPM Composit Index +%16 Total Reserves +%17 PPI-finished goods +%18 PPI-Crude materials +%19 PPI-Crude materials less energy +%20 CRB Spot Commodity Index -- all commodities +%21 CRB Spot Commodity Index -- raw industrials +%22 PCE price index +%23 rgdpmon Real GDP (monthly, chain $92) +%24 dgdpmon Deflator GDP (monthly, chain $92) + + +%1 IMF CP +%2 M2 +%3 FFR +%3 real GDP +%4 CPI-U +%5 U + +%>>>>>>>>>>>>>>>>>> +logindx = [1 5:8 10:14 16:24]; +xdd(:,logindx) = log(xdd(:,logindx)); +pctindx = [2:4 9 15]; +xdd(:,pctindx)=.01*xdd(:,pctindx); % make it a general term for the following use +% +vlist = [10 5 2 23 1 9]; % regarding "xdd", IMF-CP, M2, FFR, GDP, CPI, U +vlistlog = [1 2 4 5]; % subset of "vlist" +vlistper = [3 6]; % subset of "vlist" +%<<<<<<<<<<<<<<<<<<< + +idfile='iden6'; + +xlab = {'Inf' + 'MS' + 'FFR' + 'y' + 'P' + 'U'}; + +ylab = {'Pcm' + 'M2' + 'FFR' + 'y' + 'P' + 'U'}; + +xdd_per = xdd(:,vlist); + +x1 = 'Pcm'; +x2 = 'M2'; +x3 = 'FFR'; +x4 = 'GDP'; +x5 = 'CPI'; +x6 = 'U'; +x7 = 'R10'; + + +baddata = find(isnan(xdd_per)); +if ~isempty(baddata) + warning('Some data are actually unavailable.') + disp('Hit any key to continue, or ctrl-c to abort') + pause +end +% + +%* A specific sample is considered for estimation +%* Sample period 59:7-82:9, forecast period 82:10-84:9 +yrStart=59; +qmStart=1; +[yrEnd,qmEnd,forep,forepy,forelabel] = pararc; +nSample=(yrEnd-yrStart)*q_m + (qmEnd-qmStart+1); +if qmEnd == q_m % end of the year + nSampleCal=nSample; % Cal: calendar year +else + nSampleCal=(yrEnd-1-yrStart)*q_m + (q_m-qmStart+1); % Cal: calendar year +end + +%* More script variables +% +lags = 13; % <<>> +% automatic decay code (monthly data), only two options: lags = 6 or 13 +forepq = forep/3; % quarterly +actup = 5*48; % <<>> actual periods before forecasting (20 years) +%actup = 12*floor(nSample/12); % <<>> actual periods before forecasting (8 years) +actup = 48; % <<>> actual periods before forecasting (4 years) +actupq = actup/3; % quarterly +actupy = actup/12; % four years +imstp = 48; % <<>> impulse responses (4 years) +ninv = 1000; % the number of intervals for counting impulse responses +nhp = 6; % <<>> number of hyperparameters for estimation +%%scf = 2.4/sqrt(nvar); % scf^2*Sigma (covaraince) +scf = 0.25; % scf^2*Sigma (covaraince) +ndraws1=15; % 1500, 1st part of Monte Carlo draws +ndraws2=2*ndraws1; % 2nd part of Monte Carlo draws +ndraws=3*ndraws2 % a total number of Monte Carlo draws +nstarts=3; % number of starting points +imndraws = nstarts*ndraws2; +tdf = 3; % degrees of freedom for t-dist +ga = tdf/2; % asymmetry parameter in Gamma +gb = 2/tdf; % normalized parameter in Gamma +% +%* ================================================= +%* ====== End of the script ======================== +%* ================================================= + + +if (q_m==12) + nStart=(yrStart-yrBin)*12+qmStart-qmBin; % positive number of months at the start + nEnd=(yrEnd-yrFin)*12+qmEnd-qmFin; % negative number of months towards end +elseif (q_m==4) + nStart=(yrStart-yrBin)*4+qmStart-qmBin; % positive number of months at the start + nEnd=(yrEnd-yrFin)*4+qmEnd-qmFin; % negative number of months towards end +else + disp('Warning: this code is only good for monthly/quarterly data!!!') + return +end +% +if nEnd>0 | nStart<0 + disp('Warning: this particular sample consider is out of bounds of the data!!!') + return +end +% +xdgel=xdd(nStart+1:nData+nEnd,vlist); % gel: general term for selected xdd +xdata=xdd(nStart+1:nData,vlist); + +[Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... + idmat0,idmatpp] = szasbvar(idfile,q_m,lags,nSample,nhp,xdgel); + +% * the largest matrix in this file <<>> +yforew = zeros(ndraws,forep*nvar); % preallocating +yforeqgw = zeros(ndraws,forepq*nvar); % preallocating +yforeCalygw = zeros(ndraws,forepy*nvar); % preallocating +% * the largest matrix in this file <<>> +%%imfcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count + +load idenml % xhat ghat fhat, etc. +%load outiden % xhat ghat fhat + +%================== +% Impulse responses first +%================== +%A0 = zeros(nvar); +%A0(a0indx)=xhat; +%A0(4,2) = -xhat(7); % output in MD +%A0(5,2)=-xhat(7); % price in MD +A0in = inv(A0); +swish = A0in'; % each row corresponds to an equation +%Bh = Hm1t; % no longer have Hm1t in this new szasbvar + +% ** impulse responses +nn = [nvar lags imstp]; +imf = zimpulse(Bh,swish,nn); % in the form that is congenial to RATS +%[vd,str,imf] = errors(Bh,swish,nn); + +scaleout = imcgraph(imf,nvar,imstp,xlab,ylab) + + +%%%% +%$$$ Out-of-sample forecasts. Note: Hm1t does not change with A0. +%%%% +% +% ** out-of-sample forecast, from 82:4 to 84:3 (flp+1:flp+forep) +% * updating the last row of X (phi) with the current (last row of) y. +phil = phi(size(phi,1),:); +phil(nvar+1:ncoef-1) = phil(1:ncoef-1-nvar); +phil(1:nvar) = y(size(y,1),:); +ylast = y(size(y,1),:); +indx12 = size(y,1)-q_m+1:size(y,1); +ylast12 = y(indx12,:); % last 12 months data +nn = [nvar lags forep]; +% +yfore = forecast(Bh,phil,nn); % forep-by-nvar + + +%>>>>>>>>>>>>>>> +yforel=yfore; +yforel(:,vlistlog) = exp(yfore(:,vlistlog)); +figure; +t2=1:forep; +for i = 1:nvar + subplot(nvar/2,2,i) + plot(t2,yforel(:,i),'--') + %title('solid-actual, dotted-forecast'); + %title(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) +end +%<<<<<<<<<<<<<<< + +%%%%%%%% +% +%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r. +% +%%%%%%%% + +nconstr=4; % q: 4 years -- 4*12 months +eq_ms = 2; % location of MS equation +%eq_ms = []; % all shocks +%*** initializing +stepcon=cell(nconstr,1); % initializing, value y conditioned +valuecon=zeros(nconstr,1); % initializing, value y conditioned +varcon=zeros(nconstr,1); % initializing, endogous variables conditioned +% +stepcon{1}=[1:12]'; % average over 12 months. +stepcon{2}=[13:24]'; % average over 12 months. +stepcon{3}=[25:36]'; % average over 12 months. +stepcon{4}=[37:48]'; % average over 12 months. +% +%for i=1:nconstr +% stepcon{i}=i; +%end +% +chk1 = mean(yfore(stepcon{1},3)) +chk2 = mean(yfore(stepcon{2},3)) +chk3 = mean(yfore(stepcon{3},3)) +chk4 = mean(yfore(stepcon{4},3)) +Ro=[chk1 chk2 chk3 chk4]; +% +chk1 = exp( (sum(yfore(stepcon{1},5))-sum(ylast12(:,5))) ./ q_m ) +chk2 = exp( (sum(yfore(stepcon{2},5))-sum(yfore(stepcon{1},5))) ./ q_m ) +chk3 = exp( (sum(yfore(stepcon{3},5))-sum(yfore(stepcon{2},5))) ./ q_m ) +chk4 = exp( (sum(yfore(stepcon{4},5))-sum(yfore(stepcon{3},5))) ./ q_m ) +% +%valuecon(:)=0.055; +% +%>>>>>>>>>>>>>>>>> E: Condition on funds rate path >>>>>>>>>>>>> Toggle +%delta=0.0010; +%valuecon(1) = mean(yfore(stepcon{1},3))+2*delta; +%valuecon(2) = mean(yfore(stepcon{2},3))+2*delta; +%valuecon(3) = mean(yfore(stepcon{3},3))-2*delta; +%valuecon(4) = mean(yfore(stepcon{4},3))-2*delta; +%valuecon(1) = 0.055; +%valuecon(2) = 0.050; +%valuecon(3) = 0.0475; +%valuecon(4) = 0.045; +%>>>>>>>>>>>>>>>>> E: Condition on funds rate path >>>>>>>>>>>>> +% +%<<<<<<<<<<<<<<<< B: Condition on inflation path <<<<<<<<<< Toggle +%delta=0.0010; +%valuecon(1)=mean(ylast12(:,5))+log(chk1-0*delta); +%valuecon(2)=valuecon(1)+log(chk2-2*delta); +%valuecon(3)=valuecon(2)+log(chk3-6*delta); +%valuecon(4)=valuecon(3)+log(chk4-12*delta); +% % 5: CPI; 2.5%: annual inflation over 12 months, geometric means +%$$$ very good results -- following +valuecon(1)=mean(ylast12(:,5))+log(chk1); +valuecon(2)=valuecon(1)+log(1.020); +valuecon(3)=valuecon(2)+log(1.02); +valuecon(4)=valuecon(3)+log(1.02); +% % 5: CPI; 2.5%: annual inflation over 12 months, geometric means +%<<<<<<<<<<<<<<<< E: Condition on inflation path <<<<<<<<<< + +nstepsm = 0; % initializing, the maximum step in all constraints +for i=1:nconstr + nstepsm = max([nstepsm max(stepcon{i})]); +end +varcon(:)=5; % 3: FFR; 5: CPI +% +imf3=reshape(imf,size(imf,1),nvar,nvar); + % imf3: row-steps, column-nvar responses, 3rd dimension-nvar shocks +imf3s=permute(imf3,[1 3 2]); + % imf3s: permuted so that row-steps, column-nvar shocks, + % 3rd dimension-nvar responses + +[yhat,Estr] = fidencond(valuecon,stepcon,varcon,nconstr,nstepsm,nvar,lags,... + yfore,imf3s,phil,Bh,eq_ms); + +chk1 = mean(yhat(stepcon{1},3)) +chk2 = mean(yhat(stepcon{2},3)) +chk3 = mean(yhat(stepcon{3},3)) +chk4 = mean(yhat(stepcon{4},3)) +Rh=[chk1 chk2 chk3 chk4]; + +chk1 = exp( (sum(yhat(stepcon{1},5))-sum(ylast12(:,5))) ./ q_m ) +chk2 = exp( (sum(yhat(stepcon{2},5))-sum(yhat(stepcon{1},5))) ./ q_m ) +chk3 = exp( (sum(yhat(stepcon{3},5))-sum(yhat(stepcon{2},5))) ./ q_m ) +chk4 = exp( (sum(yhat(stepcon{4},5))-sum(yhat(stepcon{3},5))) ./ q_m ) + +%chk1 = mean(yhat(1:12,3)) +%chk2 = mean(yhat(13:24,3)) +%chk3 = mean(yhat(25:36,3)) +%chk4 = mean(yhat(36:48,3)) +%Rh=[chk1 chk2 chk3 chk4]; + +%chk1 = exp( (sum(yhat(1:12,5))-sum(ylast12(:,5))) ./ q_m ) +%chk2 = exp( (sum(yhat(13:24,5))-sum(yhat(1:12,5))) ./ q_m ) +%chk3 = exp( (sum(yhat(25:36,5))-sum(yhat(13:24,5))) ./ q_m ) +%chk4 = exp( (sum(yhat(37:48,5))-sum(yhat(25:36,5))) ./ q_m ) + + +idiff=mean(yfore(:,3))-mean(yhat(:,3)) +mean(yfore(:,3)) +mean(yhat(:,3)) +figure +plot(1:48,yfore(:,3),1:48,yhat(:,3),':') +figure +plot(1:4,Ro,1:4,Rh,':') + +%>>>>>>>>>>>>>>> +yhatl=yhat; +yhatl(:,vlistlog) = exp(yhat(:,vlistlog)); +figure; +t2=1:forep; +for i = 1:nvar + subplot(nvar/2,2,i) + plot(t2,yhatl(:,i),'--') + %title('solid-actual, dotted-forecast'); + %title(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) +end +%<<<<<<<<<<<<<<< + + +% inputs needed. +%yfore=yhat; + +%=================================================== +%%% Converting to calendar years and all at level +%=================================================== +[yforeml,yforeqgml,yforeCalygml] = fore_cal(yhat,xdata,nvar,nSample,... + nSampleCal,forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog); + +%================== +% Note +%================= +% ? 1--median; l--lower bound; h--upper bound: between the bound: 2/3 probability +% yfore? % monthly, level +% yforeqg? % quarterly, growth rate +% yforeCalyg? % calendar year, growth rate + +%save outw ndraws yfore1 yforeqg1 yforeCalyg1 yforel yforeqgl yforeh yforeqgh ... +% yforeCalygl yforeCalygh IUbeta + +yforeCalygml + + +%---------------------------------------------------------------------- +%================= Graphics ===================== +%---------------------------------------------------------------------- +% + +%[yactCalyg,yforeCalygml,yAg,yFg] = fore_gh(xdata,nvar,nSample,nSampleCal,... +% yforeml,yforeqgml,yforeCalygml,actup,actupq,actupy,... +% vlist,vlistlog,vlistper,q_m,forep,ylab); + +xinput = cell(16,1); +xinput{1}=xdata; xinput{2}=nvar; xinput{3}=nSample; xinput{4}=nSampleCal; +xinput{5}=yforeml; xinput{6}=yforeqgml; xinput{7}=yforeCalygml; xinput{8}=actup; +xinput{9}=actupq; xinput{10}=actupy; xinput{11}=vlist; xinput{12}=vlistlog; +xinput{13}=vlistper; xinput{14}=q_m; xinput{15}=forep; xinput{16}=ylab; +[yactCalyg,yforeCalygml,yAg,yFg] = fore_gh(xinput); + + +% Key Macroeconomic Variables: GDP, CPI, U +%******* From Goldbook July 1-2, 1997 FOMC +yforeBlue = [ + 3.6 2.4 5.0 + 2.5 2.6 5.0 + ]; % real GDP, CPI-U, U, +yforeMacro = [ + 3.7 2.3 4.9 + 2.1 2.4 4.9 + ]; % real GDP, CPI-U, U +yforeGold = [ + 3.8 2.4 5.0 + 2.5 2.5 4.8 + 2.4 2.7 4.7 + ]; % real GDP, CPI-U, U +t3 = yAg+1:yAg+length(yforeBlue(:,1)); +t4 = yAg+1:yAg+length(yforeGold(:,1)); +% +keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 +count=0; +t1 = 1:yAg; +t2 = yAg:yAg+yFg; +for i = keyindx + count = count+1; + subplot(3,2,count) + %plot(t1,yactqg(:,i),t2,yforeqg(:,i),':') + if (i==3) | (i==2) + plot(t1,yactCalyg(:,i),t2,[yactCalyg(length(t1),i);yforeCalygml(:,i)],'--') + %title('solid-actual, dotted-forecast'); + %xlabel(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) + else + plot(t1,yactCalyg(:,i),t2,[yactCalyg(length(t1),i);yforeCalygml(:,i)],'--',... + t3,yforeBlue(:,count),'o',t3,yforeMacro(:,count),'d',... + t4,yforeGold(:,count),'^') + %title('solid-actual, dotted-forecast'); + %xlabel(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) + end +end + +actual=yactCalyg(:,keyindx) % GDP, CPI, U, M2 +mode=yforeCalygml(:,keyindx) % GDP, CPI, U, M2 +%low=yforeCalygl(:,keyindx) +%high=yforeCalygh(:,keyindx) +yforeBlue +yforeMacro +yforeGold diff --git a/MatlabFiles/chol2.m b/MatlabFiles/chol2.m index 619c829f0b00e132bd3de4a359ac10514dfee09a..e9024ec30cb2f929ee226e807cbf43dd189d80b1 100644 --- a/MatlabFiles/chol2.m +++ b/MatlabFiles/chol2.m @@ -1,30 +1,30 @@ -function R = chol2(A) -% R = chol2(A) -% -% Returns an upper triangular R such that % R * R' is a factorization of -% a symmetric, positive definite A -% -% Written by Tao Zha, July 1996 -% Copyright (C) 1996-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -%* The following two lines give another expression of the same result -%%function [R,p] = chol2(A) -%%[R,p] = chol(fliplr(flipud(A))); - -R = chol(fliplr(flipud(A))); -R = fliplr(flipud(R))'; +function R = chol2(A) +% R = chol2(A) +% +% Returns an upper triangular R such that % R * R' is a factorization of +% a symmetric, positive definite A +% +% Written by Tao Zha, July 1996 +% +% Copyright (C) 1996-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +%* The following two lines give another expression of the same result +%%function [R,p] = chol2(A) +%%[R,p] = chol(fliplr(flipud(A))); + +R = chol(fliplr(flipud(A))); +R = fliplr(flipud(R))'; diff --git a/MatlabFiles/clgls.m b/MatlabFiles/clgls.m index b6bf9c63db99d157af3529185aa802660e3ab185..9435297ecee38791402a755680e1626760b98111 100644 --- a/MatlabFiles/clgls.m +++ b/MatlabFiles/clgls.m @@ -1,66 +1,66 @@ -function [bhat,Vq,ACt,uqhat,q2] = clgls(a,yq,Xq,C,qm,mT,qT) -%function [bhat,Vq,ACt,uqhat,q2] = clgls(a,yq,Xq,C,qm,mT,qT) -% bhat = inv[Xq' * inv(Vq) * Xq] * Xq' * inv(Vq) * yq -% Vq = C*A*C' -% ACt = A*C' -% uqhat = yq - Xq * bhat -% -% Written by E.M. Leeper -% Modified by T. Zha, 5/6/97 -% Copyright (C) 1997-2012 Eric Leeper and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%*** The following creation of Ahat may be inefficient, T.Z., 5/7/97 -Ahat = eye(mT,mT); -i = 1; -arow = zeros(1,mT-1); -while i <= mT-1 - arow(1,i) = a^i; - i = i + 1; -end -i = 1; -while i <= mT-1 - Ahat(i,i+1:mT) = arow(1,1:mT-i); - i = i + 1; -end -Ahat = Ahat + Ahat' - eye(mT,mT); - - - -%*** GLS to estimate bhat -ACt = Ahat*C'; -Vq = C*ACt; -Xqt = Xq'; -%CACinv = inv(CAhatC); commented out by T.Z., not necessary -%XqCACinv = Xq' * CACinv; commented out by T.Z., not necessary -bhat = ((Xqt/Vq)*Xq)\(Xqt*(Vq\yq)); -uqhat = yq - Xq * bhat; - -%*** compute the new quarterly coefficeint "q2" -uqlag = zeros(qT-1,1); -uqlag = uqhat(1:qT-1,1); -uqc = uqhat(2:qT,1); -[u d v]=svd(uqlag,0); %trial -dinv = 1./diag(d); % inv(diag(d)) -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -vdinv=v.*(ones(size(v,2),1)*dinv'); %trial -xtxinv = vdinv*vdinv'; -uy = u'*uqc; %trial -xty = vd*uy; %trial -%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). -q2 = xtxinv*xty; % initial q \ No newline at end of file +function [bhat,Vq,ACt,uqhat,q2] = clgls(a,yq,Xq,C,qm,mT,qT) +%function [bhat,Vq,ACt,uqhat,q2] = clgls(a,yq,Xq,C,qm,mT,qT) +% bhat = inv[Xq' * inv(Vq) * Xq] * Xq' * inv(Vq) * yq +% Vq = C*A*C' +% ACt = A*C' +% uqhat = yq - Xq * bhat +% +% Written by E.M. Leeper +% Modified by T. Zha, 5/6/97 +% +% Copyright (C) 1997-2012 Eric Leeper and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%*** The following creation of Ahat may be inefficient, T.Z., 5/7/97 +Ahat = eye(mT,mT); +i = 1; +arow = zeros(1,mT-1); +while i <= mT-1 + arow(1,i) = a^i; + i = i + 1; +end +i = 1; +while i <= mT-1 + Ahat(i,i+1:mT) = arow(1,1:mT-i); + i = i + 1; +end +Ahat = Ahat + Ahat' - eye(mT,mT); + + + +%*** GLS to estimate bhat +ACt = Ahat*C'; +Vq = C*ACt; +Xqt = Xq'; +%CACinv = inv(CAhatC); commented out by T.Z., not necessary +%XqCACinv = Xq' * CACinv; commented out by T.Z., not necessary +bhat = ((Xqt/Vq)*Xq)\(Xqt*(Vq\yq)); +uqhat = yq - Xq * bhat; + +%*** compute the new quarterly coefficeint "q2" +uqlag = zeros(qT-1,1); +uqlag = uqhat(1:qT-1,1); +uqc = uqhat(2:qT,1); +[u d v]=svd(uqlag,0); %trial +dinv = 1./diag(d); % inv(diag(d)) +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +vdinv=v.*(ones(size(v,2),1)*dinv'); %trial +xtxinv = vdinv*vdinv'; +uy = u'*uqc; %trial +xty = vd*uy; %trial +%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). +q2 = xtxinv*xty; % initial q diff --git a/MatlabFiles/clmonq.m b/MatlabFiles/clmonq.m index a0d86c98d196ade7c1dab65d6c5d6a524bdd46f7..93c9e11dfffaecc9f0f8eeaf7922947b8a127dbe 100644 --- a/MatlabFiles/clmonq.m +++ b/MatlabFiles/clmonq.m @@ -1,41 +1,41 @@ -function a = clmonq(q) -% function a = monq(q) -% Find the monthly AR coefficient for interpolated data given -% an estimate of the quarterly AR coefficient -% Written by E.M. Leeper -% -% Copyright (C) 1997-2012 E. M. Leeper and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. -% First take the quarterly AR coefficient, q, and then -% seek the root, a, that solves -% q = (a^5 + 2 a^4 + 3 a^3 + 2 a^2 + a) / (2 a^2 + 4 a + 3) (1) - -% if n = numerator poly and d = denominator poly in (1) -n = [1 2 3 2 1 0]; -d = [2 4 3]; -ln = length(n); -ld = length(d); -pad = ln - ld; -dd = [zeros(1,pad) d]; -qdd = q.*dd; -newpol = n - qdd; -r = roots(newpol); -for i = 1:length(r) - if imag(r(i)) == 0 - a = r(i); - end -end +function a = clmonq(q) +% function a = monq(q) +% Find the monthly AR coefficient for interpolated data given +% an estimate of the quarterly AR coefficient +% Written by E.M. Leeper +% +% +% Copyright (C) 1997-2012 E. M. Leeper and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% +% First take the quarterly AR coefficient, q, and then +% seek the root, a, that solves +% q = (a^5 + 2 a^4 + 3 a^3 + 2 a^2 + a) / (2 a^2 + 4 a + 3) (1) + +% if n = numerator poly and d = denominator poly in (1) +n = [1 2 3 2 1 0]; +d = [2 4 3]; +ln = length(n); +ld = length(d); +pad = ln - ld; +dd = [zeros(1,pad) d]; +qdd = q.*dd; +newpol = n - qdd; +r = roots(newpol); +for i = 1:length(r) + if imag(r(i)) == 0 + a = r(i); + end +end diff --git a/MatlabFiles/contents.m b/MatlabFiles/contents.m deleted file mode 100644 index ae8be2ca59647a3a224bd1887d43173b3d77cd41..0000000000000000000000000000000000000000 --- a/MatlabFiles/contents.m +++ /dev/null @@ -1,21 +0,0 @@ -% Chris Sims and Tao Zha's .m files. -% Vertion 1.1 March 1998 -% optimization, impulse, forecast, hessian, gradient -% -% Copyright (c) by Sims and Zha -% Copyright (C) 1997-2012 Christopher Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. \ No newline at end of file diff --git a/MatlabFiles/csminit.m b/MatlabFiles/csminit.m index 6f790c17b0dd1c04381be456e83e481e351b5de6..ec75890c1447193a88034f132f54d477e019c78a 100644 --- a/MatlabFiles/csminit.m +++ b/MatlabFiles/csminit.m @@ -1,215 +1,215 @@ -function [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,varargin) -% [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,... -% P1,P2,P3,P4,P5,P6,P7,P8) -% retcodes: 0, normal step. 5, largest step still improves too fast. -% 4,2 back and forth adjustment of stepsize didn't finish. 3, smallest -% stepsize still improves too slow. 6, no improvement found. 1, zero -% gradient. -%--------------------- -% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation. -% Places where the number of P's need to be altered or the code could be returned to -% its old form are marked with ARGLIST comments. -% -% Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs -% update. -% -% Fixed 7/19/93 to flip eigenvalues of H to get better performance when -% it's not psd. -% -% Fixed 02/19/05 to correct for low angle problems. -% -%tailstr = ')'; -%for i=nargin-6:-1:1 -% tailstr=[ ',P' num2str(i) tailstr]; -%end -% Copyright (C) 1997-2012 Christopher A. Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -dispIndx = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) - - -%ANGLE = .03; % when output of this variable becomes negative, we have wrong analytical graident -ANGLE = .005; % works for identified VARs and OLS -%THETA = .03; -THETA = .3; %(0<THETA<.5) THETA near .5 makes long line searches, possibly fewer iterations. -FCHANGE = 1000; -MINLAMB = 1e-9; -% fixed 7/15/94 -% MINDX = .0001; -% MINDX = 1e-6; -MINDFAC = .01; -fcount=0; -lambda=1; -xhat=x0; -f=f0; -fhat=f0; -g = g0; -gnorm = norm(g); -% -if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94 - retcode =1; - dxnorm=0; - % gradient convergence -else - % with badg true, we don't try to match rate of improvement to directional - % derivative. We're satisfied just to get some improvement in f. - % - %if(badg) - % dx = -g*FCHANGE/(gnorm*gnorm); - % dxnorm = norm(dx); - % if dxnorm > 1e12 - % disp('Bad, small gradient problem.') - % dx = dx*FCHANGE/dxnorm; - % end - %else - % Gauss-Newton step; - %---------- Start of 7/19/93 mod --------------- - %[v d] = eig(H0); - %toc - %d=max(1e-10,abs(diag(d))); - %d=abs(diag(d)); - %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g); -% toc - dx = -H0*g; -% toc - dxnorm = norm(dx); - if dxnorm > 1e12 - if dispIndx, disp('Near-singular H problem.'), end - dx = dx*FCHANGE/dxnorm; - end - dfhat = dx'*g0; - %end - % - % - if ~badg - % test for alignment of dx with gradient and fix if necessary - a = -dfhat/(gnorm*dxnorm); - if a<ANGLE - dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g; - % suggested alternate code: --------------------- - dx = dx*dxnorm/norm(dx); % Added 02/19/05 by CAS. This keeps scale invariant to the angle correction - % ------------------------------------------------ - dfhat = dx'*g; - % dxnorm = norm(dx); % Removed 02/19/05 by CAS. This line unnecessary with modification that keeps scale invariant - if dispIndx, disp(sprintf('Correct for low angle: %g',a)), end - end - end - if dispIndx, disp(sprintf('Predicted improvement: %18.9f',-dfhat/2)), end - % - % Have OK dx, now adjust length of step (lambda) until min and - % max improvement rate criteria are met. - done=0; - factor=3; - shrink=1; - lambdaMin=0; - lambdaMax=inf; - lambdaPeak=0; - fPeak=f0; - lambdahat=0; - while ~done - if size(x0,2)>1 - dxtest=x0+dx'*lambda; - else - dxtest=x0+dx*lambda; - end - % home - f = feval(fcn,dxtest,varargin{:}); - %ARGLIST - %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); - % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8); - if dispIndx, disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f )), end - %debug - %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) - if f<fhat - fhat=f; - xhat=dxtest; - lambdahat = lambda; - end - fcount=fcount+1; - shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ; - growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) ); - if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) ) - if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak)) - shrink=1; - factor=factor^.6; - while lambda/factor <= lambdaPeak - factor=factor^.6; - end - %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB) - if abs(factor-1)<MINDFAC - if abs(lambda)<4 - retcode=2; - else - retcode=7; - end - done=1; - end - end - if (lambda<lambdaMax) & (lambda>lambdaPeak) - lambdaMax=lambda; - end - lambda=lambda/factor; - if abs(lambda) < MINLAMB - if (lambda > 0) & (f0 <= fhat) - % try going against gradient, which may be inaccurate - if dispIndx, lambda = -lambda*factor^6, end - else - if lambda < 0 - retcode = 6; - else - retcode = 3; - end - done = 1; - end - end - elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0))) - if shrink - shrink=0; - factor = factor^.6; - %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB) - if abs(factor-1)<MINDFAC - if abs(lambda)<4 - retcode=4; - else - retcode=7; - end - done=1; - end - end - if ( f<fPeak ) & (lambda>0) - fPeak=f; - lambdaPeak=lambda; - if lambdaMax<=lambdaPeak - lambdaMax=lambdaPeak*factor*factor; - end - end - lambda=lambda*factor; - if abs(lambda) > 1e20; - retcode = 5; - done =1; - end - else - done=1; - if factor < 1.2 - retcode=7; - else - retcode=0; - end - end - end -end -if dispIndx, disp(sprintf('Norm of dx %10.5g', dxnorm)), end +function [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,varargin) +% [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,... +% P1,P2,P3,P4,P5,P6,P7,P8) +% retcodes: 0, normal step. 5, largest step still improves too fast. +% 4,2 back and forth adjustment of stepsize didn't finish. 3, smallest +% stepsize still improves too slow. 6, no improvement found. 1, zero +% gradient. +%--------------------- +% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation. +% Places where the number of P's need to be altered or the code could be returned to +% its old form are marked with ARGLIST comments. +% +% Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs +% update. +% +% Fixed 7/19/93 to flip eigenvalues of H to get better performance when +% it's not psd. +% +% Fixed 02/19/05 to correct for low angle problems. +% +%tailstr = ')'; +%for i=nargin-6:-1:1 +% tailstr=[ ',P' num2str(i) tailstr]; +%end +% +% Copyright (C) 1997-2012 Christopher A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +dispIndx = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) + + +%ANGLE = .03; % when output of this variable becomes negative, we have wrong analytical graident +ANGLE = .005; % works for identified VARs and OLS +%THETA = .03; +THETA = .3; %(0<THETA<.5) THETA near .5 makes long line searches, possibly fewer iterations. +FCHANGE = 1000; +MINLAMB = 1e-9; +% fixed 7/15/94 +% MINDX = .0001; +% MINDX = 1e-6; +MINDFAC = .01; +fcount=0; +lambda=1; +xhat=x0; +f=f0; +fhat=f0; +g = g0; +gnorm = norm(g); +% +if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94 + retcode =1; + dxnorm=0; + % gradient convergence +else + % with badg true, we don't try to match rate of improvement to directional + % derivative. We're satisfied just to get some improvement in f. + % + %if(badg) + % dx = -g*FCHANGE/(gnorm*gnorm); + % dxnorm = norm(dx); + % if dxnorm > 1e12 + % disp('Bad, small gradient problem.') + % dx = dx*FCHANGE/dxnorm; + % end + %else + % Gauss-Newton step; + %---------- Start of 7/19/93 mod --------------- + %[v d] = eig(H0); + %toc + %d=max(1e-10,abs(diag(d))); + %d=abs(diag(d)); + %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g); +% toc + dx = -H0*g; +% toc + dxnorm = norm(dx); + if dxnorm > 1e12 + if dispIndx, disp('Near-singular H problem.'), end + dx = dx*FCHANGE/dxnorm; + end + dfhat = dx'*g0; + %end + % + % + if ~badg + % test for alignment of dx with gradient and fix if necessary + a = -dfhat/(gnorm*dxnorm); + if a<ANGLE + dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g; + % suggested alternate code: --------------------- + dx = dx*dxnorm/norm(dx); % Added 02/19/05 by CAS. This keeps scale invariant to the angle correction + % ------------------------------------------------ + dfhat = dx'*g; + % dxnorm = norm(dx); % Removed 02/19/05 by CAS. This line unnecessary with modification that keeps scale invariant + if dispIndx, disp(sprintf('Correct for low angle: %g',a)), end + end + end + if dispIndx, disp(sprintf('Predicted improvement: %18.9f',-dfhat/2)), end + % + % Have OK dx, now adjust length of step (lambda) until min and + % max improvement rate criteria are met. + done=0; + factor=3; + shrink=1; + lambdaMin=0; + lambdaMax=inf; + lambdaPeak=0; + fPeak=f0; + lambdahat=0; + while ~done + if size(x0,2)>1 + dxtest=x0+dx'*lambda; + else + dxtest=x0+dx*lambda; + end + % home + f = feval(fcn,dxtest,varargin{:}); + %ARGLIST + %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); + % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8); + if dispIndx, disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f )), end + %debug + %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) + if f<fhat + fhat=f; + xhat=dxtest; + lambdahat = lambda; + end + fcount=fcount+1; + shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ; + growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) ); + if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) ) + if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak)) + shrink=1; + factor=factor^.6; + while lambda/factor <= lambdaPeak + factor=factor^.6; + end + %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB) + if abs(factor-1)<MINDFAC + if abs(lambda)<4 + retcode=2; + else + retcode=7; + end + done=1; + end + end + if (lambda<lambdaMax) & (lambda>lambdaPeak) + lambdaMax=lambda; + end + lambda=lambda/factor; + if abs(lambda) < MINLAMB + if (lambda > 0) & (f0 <= fhat) + % try going against gradient, which may be inaccurate + if dispIndx, lambda = -lambda*factor^6, end + else + if lambda < 0 + retcode = 6; + else + retcode = 3; + end + done = 1; + end + end + elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0))) + if shrink + shrink=0; + factor = factor^.6; + %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB) + if abs(factor-1)<MINDFAC + if abs(lambda)<4 + retcode=4; + else + retcode=7; + end + done=1; + end + end + if ( f<fPeak ) & (lambda>0) + fPeak=f; + lambdaPeak=lambda; + if lambdaMax<=lambdaPeak + lambdaMax=lambdaPeak*factor*factor; + end + end + lambda=lambda*factor; + if abs(lambda) > 1e20; + retcode = 5; + done =1; + end + else + done=1; + if factor < 1.2 + retcode=7; + else + retcode=0; + end + end + end +end +if dispIndx, disp(sprintf('Norm of dx %10.5g', dxnorm)), end diff --git a/MatlabFiles/csminitworksuntiil0205.m b/MatlabFiles/csminitworksuntiil0205.m index 6e1e2805bcc9998db727d9f916b957034736d570..52b1b5c67fb3583d4f41b5c934ef7c33cfed0687 100644 --- a/MatlabFiles/csminitworksuntiil0205.m +++ b/MatlabFiles/csminitworksuntiil0205.m @@ -1,214 +1,214 @@ -function [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,varargin) -% [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,... -% P1,P2,P3,P4,P5,P6,P7,P8) -% retcodes: 0, normal step. 5, largest step still improves too fast. -% 4,2 back and forth adjustment of stepsize didn't finish. 3, smallest -% stepsize still improves too slow. 6, no improvement found. 1, zero -% gradient. -%--------------------- -% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation. -% Places where the number of P's need to be altered or the code could be returned to -% its old form are marked with ARGLIST comments. -% -% Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs -% update. -% -% Fixed 7/19/93 to flip eigenvalues of H to get better performance when -% it's not psd. -% NOTE: The display on screen can be turned off by seeting dispIndx=0 in this -% function. This option is used for the loop operation. T. Zha, 2 May 2000 - -% Copyright (C) 1997-2012 C. A. Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -dispIndx = 0; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) - -% -%tailstr = ')'; -%for i=nargin-6:-1:1 -% tailstr=[ ',P' num2str(i) tailstr]; -%end - -%ANGLE = .01; % when output of this variable becomes negative, we have wrong analytical graident -ANGLE = .005; % works for identified VARs and OLS -%THETA = .1; % works for OLS or other nonlinear functions -THETA = .3; %(0<THETA<.5) THETA near .5 makes long line searches, possibly fewer iterations. - % workds for identified VARs -FCHANGE = 1000; -MINLAMB = 1e-9; -% fixed 7/15/94 -% MINDX = .0001; -% MINDX = 1e-6; -MINDFAC = .01; -fcount=0; -lambda=1; -xhat=x0; -f=f0; -fhat=f0; -g = g0; -gnorm = norm(g); -% -if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94 - retcode =1; - dxnorm=0; - % gradient convergence -else - % with badg true, we don't try to match rate of improvement to directional - % derivative. We're satisfied just to get some improvement in f. - % - %if(badg) - % dx = -g*FCHANGE/(gnorm*gnorm); - % dxnorm = norm(dx); - % if dxnorm > 1e12 - % disp('Bad, small gradient problem.') - % dx = dx*FCHANGE/dxnorm; - % end - %else - % Gauss-Newton step; - %---------- Start of 7/19/93 mod --------------- - %[v d] = eig(H0); - %toc - %d=max(1e-10,abs(diag(d))); - %d=abs(diag(d)); - %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g); -% toc - dx = -H0*g; -% toc - dxnorm = norm(dx); - if dxnorm > 1e12 - if dispIndx, disp('Near-singular H problem.'), end - dx = dx*FCHANGE/dxnorm; - end - dfhat = dx'*g0; - %end - % - % - if ~badg - % test for alignment of dx with gradient and fix if necessary - a = -dfhat/(gnorm*dxnorm); - if a<ANGLE - dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g; - dfhat = dx'*g; - dxnorm = norm(dx); - if dispIndx, disp(sprintf('Correct for low angle: %g',a)), end - end - end - if dispIndx, disp(sprintf('Predicted improvement: %18.9f',-dfhat/2)), end - % - % Have OK dx, now adjust length of step (lambda) until min and - % max improvement rate criteria are met. - done=0; - factor=3; - shrink=1; - lambdaMin=0; - lambdaMax=inf; - lambdaPeak=0; - fPeak=f0; - lambdahat=0; - while ~done - if size(x0,2)>1 - dxtest=x0+dx'*lambda; - else - dxtest=x0+dx*lambda; - end - % home - f = eval([fcn '(dxtest,varargin{:})']); - %ARGLIST - %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); - % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8); - if dispIndx, disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f )), end - %debug - %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) - if f<fhat - fhat=f; - xhat=dxtest; - lambdahat = lambda; - end - fcount=fcount+1; - shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ; - growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) ); - if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) ) - if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak)) - shrink=1; - factor=factor^.6; - while lambda/factor <= lambdaPeak - factor=factor^.6; - end - %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB) - if abs(factor-1) < MINDFAC - if abs(lambda)<4 - retcode = 2; - else - retcode=7; - end - done=1; - end - end - if (lambda<lambdaMax) & (lambda>lambdaPeak) - lambdaMax=lambda; - end - lambda=lambda/factor; - if abs(lambda) < MINLAMB - if (lambda > 0) & (f0 <= fhat) - % try going against gradient, which may be inaccurate - lambda = -lambda*factor^6 - else - if lambda < 0 - retcode = 6; - else - retcode = 3; - end - done = 1; - end - end - elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0))) - if shrink - shrink=0; - factor = factor^.6; - %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB) - if abs(factor-1) < MINDFAC - if abs(lambda)<4 - retcode = 4; - else - retcode=7; - end - done=1; - end - end - if ( f<fPeak ) & (lambda>0) - fPeak=f; - lambdaPeak=lambda; - if lambdaMax<=lambdaPeak - lambdaMax=lambdaPeak*factor*factor; - end - end - lambda=lambda*factor; - if abs(lambda) > 1e20; - retcode = 5; - done =1; - end - else - done=1; - if factor < 1.2 - retcode=7; - else - retcode=0; - end - end - end -end -if dispIndx, disp(sprintf('Norm of dx %10.5g', dxnorm)), end +function [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,varargin) +% [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,... +% P1,P2,P3,P4,P5,P6,P7,P8) +% retcodes: 0, normal step. 5, largest step still improves too fast. +% 4,2 back and forth adjustment of stepsize didn't finish. 3, smallest +% stepsize still improves too slow. 6, no improvement found. 1, zero +% gradient. +%--------------------- +% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation. +% Places where the number of P's need to be altered or the code could be returned to +% its old form are marked with ARGLIST comments. +% +% Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs +% update. +% +% Fixed 7/19/93 to flip eigenvalues of H to get better performance when +% it's not psd. +% NOTE: The display on screen can be turned off by seeting dispIndx=0 in this +% function. This option is used for the loop operation. T. Zha, 2 May 2000 + +% +% Copyright (C) 1997-2012 C. A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +dispIndx = 0; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) + +% +%tailstr = ')'; +%for i=nargin-6:-1:1 +% tailstr=[ ',P' num2str(i) tailstr]; +%end + +%ANGLE = .01; % when output of this variable becomes negative, we have wrong analytical graident +ANGLE = .005; % works for identified VARs and OLS +%THETA = .1; % works for OLS or other nonlinear functions +THETA = .3; %(0<THETA<.5) THETA near .5 makes long line searches, possibly fewer iterations. + % workds for identified VARs +FCHANGE = 1000; +MINLAMB = 1e-9; +% fixed 7/15/94 +% MINDX = .0001; +% MINDX = 1e-6; +MINDFAC = .01; +fcount=0; +lambda=1; +xhat=x0; +f=f0; +fhat=f0; +g = g0; +gnorm = norm(g); +% +if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94 + retcode =1; + dxnorm=0; + % gradient convergence +else + % with badg true, we don't try to match rate of improvement to directional + % derivative. We're satisfied just to get some improvement in f. + % + %if(badg) + % dx = -g*FCHANGE/(gnorm*gnorm); + % dxnorm = norm(dx); + % if dxnorm > 1e12 + % disp('Bad, small gradient problem.') + % dx = dx*FCHANGE/dxnorm; + % end + %else + % Gauss-Newton step; + %---------- Start of 7/19/93 mod --------------- + %[v d] = eig(H0); + %toc + %d=max(1e-10,abs(diag(d))); + %d=abs(diag(d)); + %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g); +% toc + dx = -H0*g; +% toc + dxnorm = norm(dx); + if dxnorm > 1e12 + if dispIndx, disp('Near-singular H problem.'), end + dx = dx*FCHANGE/dxnorm; + end + dfhat = dx'*g0; + %end + % + % + if ~badg + % test for alignment of dx with gradient and fix if necessary + a = -dfhat/(gnorm*dxnorm); + if a<ANGLE + dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g; + dfhat = dx'*g; + dxnorm = norm(dx); + if dispIndx, disp(sprintf('Correct for low angle: %g',a)), end + end + end + if dispIndx, disp(sprintf('Predicted improvement: %18.9f',-dfhat/2)), end + % + % Have OK dx, now adjust length of step (lambda) until min and + % max improvement rate criteria are met. + done=0; + factor=3; + shrink=1; + lambdaMin=0; + lambdaMax=inf; + lambdaPeak=0; + fPeak=f0; + lambdahat=0; + while ~done + if size(x0,2)>1 + dxtest=x0+dx'*lambda; + else + dxtest=x0+dx*lambda; + end + % home + f = eval([fcn '(dxtest,varargin{:})']); + %ARGLIST + %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); + % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8); + if dispIndx, disp(sprintf('lambda = %10.5g; f = %20.7f',lambda,f )), end + %debug + %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda)) + if f<fhat + fhat=f; + xhat=dxtest; + lambdahat = lambda; + end + fcount=fcount+1; + shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ; + growSignal = ~badg & ( (lambda > 0) & (f0-f > -(1-THETA)*dfhat*lambda) ); + if shrinkSignal & ( (lambda>lambdaPeak) | (lambda<0) ) + if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak)) + shrink=1; + factor=factor^.6; + while lambda/factor <= lambdaPeak + factor=factor^.6; + end + %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB) + if abs(factor-1) < MINDFAC + if abs(lambda)<4 + retcode = 2; + else + retcode=7; + end + done=1; + end + end + if (lambda<lambdaMax) & (lambda>lambdaPeak) + lambdaMax=lambda; + end + lambda=lambda/factor; + if abs(lambda) < MINLAMB + if (lambda > 0) & (f0 <= fhat) + % try going against gradient, which may be inaccurate + lambda = -lambda*factor^6 + else + if lambda < 0 + retcode = 6; + else + retcode = 3; + end + done = 1; + end + end + elseif (growSignal & lambda>0) | (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0))) + if shrink + shrink=0; + factor = factor^.6; + %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB) + if abs(factor-1) < MINDFAC + if abs(lambda)<4 + retcode = 4; + else + retcode=7; + end + done=1; + end + end + if ( f<fPeak ) & (lambda>0) + fPeak=f; + lambdaPeak=lambda; + if lambdaMax<=lambdaPeak + lambdaMax=lambdaPeak*factor*factor; + end + end + lambda=lambda*factor; + if abs(lambda) > 1e20; + retcode = 5; + done =1; + end + else + done=1; + if factor < 1.2 + retcode=7; + else + retcode=0; + end + end + end +end +if dispIndx, disp(sprintf('Norm of dx %10.5g', dxnorm)), end diff --git a/MatlabFiles/csminwel.m b/MatlabFiles/csminwel.m index 04485eef2300d5f637314c98100d7a1b580e452e..e5a6ee61599509a586191e31cba87533607b6768 100644 --- a/MatlabFiles/csminwel.m +++ b/MatlabFiles/csminwel.m @@ -1,311 +1,311 @@ -function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel(fcn,x0,H0,grad,crit,nit,varargin) -%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel(fcn,x0,H0,grad,crit,nit,varargin) -% fcn: string naming the objective function to be minimized -% x0: initial value of the parameter vector -% H0: initial value for the inverse Hessian. Must be positive definite. -% grad: Either a string naming a function that calculates the gradient, or the null matrix. -% If it's null, the program calculates a numerical gradient. In this case fcn must -% be written so that it can take a matrix argument and produce a row vector of values. -% crit: Convergence criterion. Iteration will cease when it proves impossible to improve the -% function value by more than crit. -% nit: Maximum number of iterations. -% varargin: A list of optional length of additional parameters that get handed off to fcn each -% time it is called. -% Note that if the program ends abnormally, it is possible to retrieve the current x, -% f, and H from the files g1.mat and H.mat that are written at each iteration and at each -% hessian update, respectively. (When the routine hits certain kinds of difficulty, it -% write g2.mat and g3.mat as well. If all were written at about the same time, any of them -% may be a decent starting point. One can also start from the one with best function value.) -% NOTE: The display on screen can be turned off by seeting dispIndx=0 in this -% function. This option is used for the loop operation. T. Zha, 2 May 2000 -% NOTE: You may want to change stps to 1.0e-02 or 1.0e-03 to get a better convergence. August, 2006 -% Copyright (C) 1997-2012 Christopher Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -Verbose = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) -dispIndx = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) - -[nx,no]=size(x0); -nx=max(nx,no); -NumGrad= ( ~isstr(grad) | length(grad)==0); -done=0; -itct=0; -fcount=0; -snit=100; -%tailstr = ')'; -%stailstr = []; -% Lines below make the number of Pi's optional. This is inefficient, though, and precludes -% use of the matlab compiler. Without them, we use feval and the number of Pi's must be -% changed with the editor for each application. Places where this is required are marked -% with ARGLIST comments -%for i=nargin-6:-1:1 -% tailstr=[ ',P' num2str(i) tailstr]; -% stailstr=[' P' num2str(i) stailstr]; -%end -if ischar(fcn) - f0 = eval([fcn '(x0,varargin{:})']); -else - f0 = fcn(x0,varargin{:}); -end -%ARGLIST -%f0 = feval(fcn,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); -% disp('first fcn in csminwel.m ----------------') % Jinill on 9/5/95 -if f0 > 1e50, disp('Bad initial parameter.'), return, end -if NumGrad - if length(grad)==0 - [g badg] = numgradcd(fcn,x0, varargin{:}); - %ARGLIST - %[g badg] = numgradcd(fcn,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); - else - badg=any(find(grad==0)); - g=grad; - end - %numgradcd(fcn,x0,P1,P2,P3,P4); -else - [g badg] = eval([grad '(x0,varargin{:})']); - %ARGLIST - %[g badg] = feval(grad,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); -end -retcode3=101; -x=x0; -f=f0; -H=H0; -cliff=0; -while ~done - g1=[]; g2=[]; g3=[]; - %addition fj. 7/6/94 for control - if dispIndx - disp('-----------------') - disp('-----------------') - %disp('f and x at the beginning of new iteration') - disp(sprintf('f at the beginning of new iteration, %20.10f',f)) - %-----------Comment out this line if the x vector is long---------------- - disp([sprintf('x = ') sprintf('%15.8g%15.8g%15.8g%15.8g%15.8g\n',x)]); - end - %------------------------- - itct=itct+1; - [f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:}); - %ARGLIST - %[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,... - % P8,P9,P10,P11,P12,P13); - % itct=itct+1; - fcount = fcount+fc; - % erased on 8/4/94 - % if (retcode == 1) | (abs(f1-f) < crit) - % done=1; - % end - % if itct > nit - % done = 1; - % retcode = -retcode; - % end - if retcode1 ~= 1 - if retcode1==2 | retcode1==4 - wall1=1; badg1=1; - else - if NumGrad - [g1 badg1] = numgradcd(fcn, x1,varargin{:}); - %ARGLIST - %[g1 badg1] = numgradcd(fcn, x1,P1,P2,P3,P4,P5,P6,P7,P8,P9,... - % P10,P11,P12,P13); - else - [g1 badg1] = eval([grad '(x1,varargin{:})']); - %ARGLIST - %[g1 badg1] = feval(grad, x1,P1,P2,P3,P4,P5,P6,P7,P8,P9,... - % P10,P11,P12,P13); - end - wall1=badg1; - % g1 - save g1 g1 x1 f1 varargin; - %ARGLIST - %save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; - end - if wall1 % & (~done) by Jinill - % Bad gradient or back and forth on step length. Possibly at - % cliff edge. Try perturbing search direction. - % - %fcliff=fh;xcliff=xh; - if dispIndx - disp(' ') - disp('************************* Random search. *****************************************') - disp('************************* Random search. *****************************************') - disp(' ') - pause(1.0) - end - Hcliff=H+diag(diag(H).*rand(nx,1)); - if dispIndx, disp('Cliff. Perturbing search direction.'), end - [f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:}); - %ARGLIST - %[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,... - % P5,P6,P7,P8,P9,P10,P11,P12,P13); - fcount = fcount+fc; % put by Jinill - if f2 < f - if retcode2==2 | retcode2==4 - wall2=1; badg2=1; - else - if NumGrad - [g2 badg2] = numgradcd(fcn, x2,varargin{:}); - %ARGLIST - %[g2 badg2] = numgradcd(fcn, x2,P1,P2,P3,P4,P5,P6,P7,P8,... - % P9,P10,P11,P12,P13); - else - [g2 badg2] = eval([grad '(x2,varargin{:})']); - %ARGLIST - %[g2 badg2] = feval(grad,x2,P1,P2,P3,P4,P5,P6,P7,P8,... - % P9,P10,P11,P12,P13); - end - wall2=badg2; - % g2 - if dispIndx, badg2, end - save g2 g2 x2 f2 varargin - %ARGLIST - %save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; - end - if wall2 - if dispIndx, disp('Cliff again. Try traversing'), end - if norm(x2-x1) < 1e-13 - f3=f; x3=x; badg3=1;retcode3=101; - else - gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1); - [f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:}); - %ARGLIST - %[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,... - % P4,P5,P6,P7,P8,... - % P9,P10,P11,P12,P13); - fcount = fcount+fc; % put by Jinill - if retcode3==2 | retcode3==4 - wall3=1; badg3=1; - else - if NumGrad - [g3 badg3] = numgradcd(fcn, x3,varargin{:}); - %ARGLIST - %[g3 badg3] = numgradcd(fcn, x3,P1,P2,P3,P4,P5,P6,P7,P8,... - % P9,P10,P11,P12,P13); - else - [g3 badg3] = eval([grad '(x3,varargin{:})']); - %ARGLIST - %[g3 badg3] = feval(grad,x3,P1,P2,P3,P4,P5,P6,P7,P8,... - % P9,P10,P11,P12,P13); - end - wall3=badg3; - % g3 - if dispIndx, badg3, end - save g3 g3 x3 f3 varargin; - %ARGLIST - %save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; - end - end - else - f3=f; x3=x; badg3=1; retcode3=101; - end - else - f3=f; x3=x; badg3=1;retcode3=101; - end - else - % normal iteration, no walls, or else we're finished here. - f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101; - end - else - f1=f; f2=f; f3=f; retcode2=retcode1; retcode3=retcode1; - end - %how to pick gh and xh - if f3<f & badg3==0 - if dispIndx, ih=3, end - fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3; - elseif f2<f & badg2==0 - if dispIndx, ih=2, end - fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2; - elseif f1<f & badg1==0 - if dispIndx, ih=1, end - fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1; - else - [fh,ih] = min([f1,f2,f3]); - if dispIndx, disp(sprintf('ih = %d',ih)), end - %eval(['xh=x' num2str(ih) ';']) - switch ih - case 1 - xh=x1; - case 2 - xh=x2; - case 3 - xh=x3; - end %case - %eval(['gh=g' num2str(ih) ';']) - %eval(['retcodeh=retcode' num2str(ih) ';']) - retcodei=[retcode1,retcode2,retcode3]; - retcodeh=retcodei(ih); - if exist('gh') - nogh=isempty(gh); - else - nogh=1; - end - if nogh - if NumGrad - [gh badgh] = numgradcd(fcn, xh,varargin{:}); %Pointed out by Junior Maih. - %[gh badgh] = feval('numgrad',fcn,xh,varargin{:}); - else - [gh badgh] = numgradcd(fcn, xh,varargin{:}); %Pointed out by Junior Maih. - %[gh badgh] = feval('grad', xh,varargin{:}); - end - end - badgh=1; - end - %end of picking - %ih - %fh - %xh - %gh - %badgh - stuck = (abs(fh-f) < crit); - if (~badg)&(~badgh)&(~stuck) - H = bfgsi(H,gh-g,xh-x); - end - if Verbose - if dispIndx - disp('----') - disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh)) - end - end - - if itct > nit - if dispIndx, disp('iteration count termination'), end - done = 1; - elseif stuck - if dispIndx, disp('improvement < crit termination'), end - done = 1; - end - rc=retcodeh; - if rc == 1 - if dispIndx, disp('zero gradient'), end - elseif rc == 6 - if dispIndx, disp('smallest step still improving too slow, reversed gradient'), end - elseif rc == 5 - if dispIndx, disp('largest step still improving too fast'), end - elseif (rc == 4) | (rc==2) - if dispIndx, disp('back and forth on step length never finished'), end - elseif rc == 3 - if dispIndx, disp('smallest step still improving too slow'), end - elseif rc == 7 - if dispIndx, disp('warning: possible inaccuracy in H matrix'), end - end - - f=fh; - x=xh; - g=gh; - badg=badgh; -end -% what about making an m-file of 10 lines including numgrad.m -% since it appears three times in csminwel.m +function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel(fcn,x0,H0,grad,crit,nit,varargin) +%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel(fcn,x0,H0,grad,crit,nit,varargin) +% fcn: string naming the objective function to be minimized +% x0: initial value of the parameter vector +% H0: initial value for the inverse Hessian. Must be positive definite. +% grad: Either a string naming a function that calculates the gradient, or the null matrix. +% If it's null, the program calculates a numerical gradient. In this case fcn must +% be written so that it can take a matrix argument and produce a row vector of values. +% crit: Convergence criterion. Iteration will cease when it proves impossible to improve the +% function value by more than crit. +% nit: Maximum number of iterations. +% varargin: A list of optional length of additional parameters that get handed off to fcn each +% time it is called. +% Note that if the program ends abnormally, it is possible to retrieve the current x, +% f, and H from the files g1.mat and H.mat that are written at each iteration and at each +% hessian update, respectively. (When the routine hits certain kinds of difficulty, it +% write g2.mat and g3.mat as well. If all were written at about the same time, any of them +% may be a decent starting point. One can also start from the one with best function value.) +% NOTE: The display on screen can be turned off by seeting dispIndx=0 in this +% function. This option is used for the loop operation. T. Zha, 2 May 2000 +% NOTE: You may want to change stps to 1.0e-02 or 1.0e-03 to get a better convergence. August, 2006 +% +% Copyright (C) 1997-2012 Christopher Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +Verbose = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) +dispIndx = 1; % 1: turn on all the diplays on the screen; 0: turn off (Added by T. Zha) + +[nx,no]=size(x0); +nx=max(nx,no); +NumGrad= ( ~isstr(grad) | length(grad)==0); +done=0; +itct=0; +fcount=0; +snit=100; +%tailstr = ')'; +%stailstr = []; +% Lines below make the number of Pi's optional. This is inefficient, though, and precludes +% use of the matlab compiler. Without them, we use feval and the number of Pi's must be +% changed with the editor for each application. Places where this is required are marked +% with ARGLIST comments +%for i=nargin-6:-1:1 +% tailstr=[ ',P' num2str(i) tailstr]; +% stailstr=[' P' num2str(i) stailstr]; +%end +if ischar(fcn) + f0 = eval([fcn '(x0,varargin{:})']); +else + f0 = fcn(x0,varargin{:}); +end +%ARGLIST +%f0 = feval(fcn,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); +% disp('first fcn in csminwel.m ----------------') % Jinill on 9/5/95 +if f0 > 1e50, disp('Bad initial parameter.'), return, end +if NumGrad + if length(grad)==0 + [g badg] = numgradcd(fcn,x0, varargin{:}); + %ARGLIST + %[g badg] = numgradcd(fcn,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); + else + badg=any(find(grad==0)); + g=grad; + end + %numgradcd(fcn,x0,P1,P2,P3,P4); +else + [g badg] = eval([grad '(x0,varargin{:})']); + %ARGLIST + %[g badg] = feval(grad,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13); +end +retcode3=101; +x=x0; +f=f0; +H=H0; +cliff=0; +while ~done + g1=[]; g2=[]; g3=[]; + %addition fj. 7/6/94 for control + if dispIndx + disp('-----------------') + disp('-----------------') + %disp('f and x at the beginning of new iteration') + disp(sprintf('f at the beginning of new iteration, %20.10f',f)) + %-----------Comment out this line if the x vector is long---------------- + disp([sprintf('x = ') sprintf('%15.8g%15.8g%15.8g%15.8g%15.8g\n',x)]); + end + %------------------------- + itct=itct+1; + [f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:}); + %ARGLIST + %[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,... + % P8,P9,P10,P11,P12,P13); + % itct=itct+1; + fcount = fcount+fc; + % erased on 8/4/94 + % if (retcode == 1) | (abs(f1-f) < crit) + % done=1; + % end + % if itct > nit + % done = 1; + % retcode = -retcode; + % end + if retcode1 ~= 1 + if retcode1==2 | retcode1==4 + wall1=1; badg1=1; + else + if NumGrad + [g1 badg1] = numgradcd(fcn, x1,varargin{:}); + %ARGLIST + %[g1 badg1] = numgradcd(fcn, x1,P1,P2,P3,P4,P5,P6,P7,P8,P9,... + % P10,P11,P12,P13); + else + [g1 badg1] = eval([grad '(x1,varargin{:})']); + %ARGLIST + %[g1 badg1] = feval(grad, x1,P1,P2,P3,P4,P5,P6,P7,P8,P9,... + % P10,P11,P12,P13); + end + wall1=badg1; + % g1 + save g1 g1 x1 f1 varargin; + %ARGLIST + %save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; + end + if wall1 % & (~done) by Jinill + % Bad gradient or back and forth on step length. Possibly at + % cliff edge. Try perturbing search direction. + % + %fcliff=fh;xcliff=xh; + if dispIndx + disp(' ') + disp('************************* Random search. *****************************************') + disp('************************* Random search. *****************************************') + disp(' ') + pause(1.0) + end + Hcliff=H+diag(diag(H).*rand(nx,1)); + if dispIndx, disp('Cliff. Perturbing search direction.'), end + [f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:}); + %ARGLIST + %[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,... + % P5,P6,P7,P8,P9,P10,P11,P12,P13); + fcount = fcount+fc; % put by Jinill + if f2 < f + if retcode2==2 | retcode2==4 + wall2=1; badg2=1; + else + if NumGrad + [g2 badg2] = numgradcd(fcn, x2,varargin{:}); + %ARGLIST + %[g2 badg2] = numgradcd(fcn, x2,P1,P2,P3,P4,P5,P6,P7,P8,... + % P9,P10,P11,P12,P13); + else + [g2 badg2] = eval([grad '(x2,varargin{:})']); + %ARGLIST + %[g2 badg2] = feval(grad,x2,P1,P2,P3,P4,P5,P6,P7,P8,... + % P9,P10,P11,P12,P13); + end + wall2=badg2; + % g2 + if dispIndx, badg2, end + save g2 g2 x2 f2 varargin + %ARGLIST + %save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; + end + if wall2 + if dispIndx, disp('Cliff again. Try traversing'), end + if norm(x2-x1) < 1e-13 + f3=f; x3=x; badg3=1;retcode3=101; + else + gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1); + [f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:}); + %ARGLIST + %[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,... + % P4,P5,P6,P7,P8,... + % P9,P10,P11,P12,P13); + fcount = fcount+fc; % put by Jinill + if retcode3==2 | retcode3==4 + wall3=1; badg3=1; + else + if NumGrad + [g3 badg3] = numgradcd(fcn, x3,varargin{:}); + %ARGLIST + %[g3 badg3] = numgradcd(fcn, x3,P1,P2,P3,P4,P5,P6,P7,P8,... + % P9,P10,P11,P12,P13); + else + [g3 badg3] = eval([grad '(x3,varargin{:})']); + %ARGLIST + %[g3 badg3] = feval(grad,x3,P1,P2,P3,P4,P5,P6,P7,P8,... + % P9,P10,P11,P12,P13); + end + wall3=badg3; + % g3 + if dispIndx, badg3, end + save g3 g3 x3 f3 varargin; + %ARGLIST + %save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13; + end + end + else + f3=f; x3=x; badg3=1; retcode3=101; + end + else + f3=f; x3=x; badg3=1;retcode3=101; + end + else + % normal iteration, no walls, or else we're finished here. + f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101; + end + else + f1=f; f2=f; f3=f; retcode2=retcode1; retcode3=retcode1; + end + %how to pick gh and xh + if f3<f & badg3==0 + if dispIndx, ih=3, end + fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3; + elseif f2<f & badg2==0 + if dispIndx, ih=2, end + fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2; + elseif f1<f & badg1==0 + if dispIndx, ih=1, end + fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1; + else + [fh,ih] = min([f1,f2,f3]); + if dispIndx, disp(sprintf('ih = %d',ih)), end + %eval(['xh=x' num2str(ih) ';']) + switch ih + case 1 + xh=x1; + case 2 + xh=x2; + case 3 + xh=x3; + end %case + %eval(['gh=g' num2str(ih) ';']) + %eval(['retcodeh=retcode' num2str(ih) ';']) + retcodei=[retcode1,retcode2,retcode3]; + retcodeh=retcodei(ih); + if exist('gh') + nogh=isempty(gh); + else + nogh=1; + end + if nogh + if NumGrad + [gh badgh] = numgradcd(fcn, xh,varargin{:}); %Pointed out by Junior Maih. + %[gh badgh] = feval('numgrad',fcn,xh,varargin{:}); + else + [gh badgh] = numgradcd(fcn, xh,varargin{:}); %Pointed out by Junior Maih. + %[gh badgh] = feval('grad', xh,varargin{:}); + end + end + badgh=1; + end + %end of picking + %ih + %fh + %xh + %gh + %badgh + stuck = (abs(fh-f) < crit); + if (~badg)&(~badgh)&(~stuck) + H = bfgsi(H,gh-g,xh-x); + end + if Verbose + if dispIndx + disp('----') + disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh)) + end + end + + if itct > nit + if dispIndx, disp('iteration count termination'), end + done = 1; + elseif stuck + if dispIndx, disp('improvement < crit termination'), end + done = 1; + end + rc=retcodeh; + if rc == 1 + if dispIndx, disp('zero gradient'), end + elseif rc == 6 + if dispIndx, disp('smallest step still improving too slow, reversed gradient'), end + elseif rc == 5 + if dispIndx, disp('largest step still improving too fast'), end + elseif (rc == 4) | (rc==2) + if dispIndx, disp('back and forth on step length never finished'), end + elseif rc == 3 + if dispIndx, disp('smallest step still improving too slow'), end + elseif rc == 7 + if dispIndx, disp('warning: possible inaccuracy in H matrix'), end + end + + f=fh; + x=xh; + g=gh; + badg=badgh; +end +% what about making an m-file of 10 lines including numgrad.m +% since it appears three times in csminwel.m diff --git a/MatlabFiles/datactcon.m b/MatlabFiles/datactcon.m index fcc9b6492c9c31019ef407e2ef86526ecf290be3..85d48bbb0db422d2295d84f53340618a2f842d06 100644 --- a/MatlabFiles/datactcon.m +++ b/MatlabFiles/datactcon.m @@ -1,133 +1,133 @@ -function [yact,yactmg,yactqg,yactCalyg,yactCal] = datactcon(xinput) -% [yact,yactmg,yactqg,yactCalyg,yactCal] = datactcon(xinput) -% Data-actual-conditions. Take the raw data xdata to mlog, mg, qg, and yg. -% Note yact(mlog), yactqg, and yactCalyg corr. to myears, qyears, and yearsCal -% -% xdata=xinput{1}: data, all logged except R, U, etc. -% nSample=xinput{2}: sample size (including lags or initial periods) -% nSampleCal=xinput{3}: converting nSample to sample marked by calendar years; -% actup=xinput{4}: periods for actual data (monthly) -% actupq=xinput{5}: periods for actual data (quarterly) -% actupy=xinput{6}: periods for actual data (calendar yearly) -% vlist=xinput{7}: list of variables -% vlistlog=xinput{8}: sub list of variables that are in log -% vlistper=xinput{9}: sub list of variables that are in percent -% q_m=xinput{10}: month or quarter in the model -% forep=xinput{11}: forecast periods (monthly) -% forepq=xinput{12}: quarters in the forecast period -% forepy=xinput{13}: calendar years in the forecast period -% Psuedo=xinput{14}: 1: Psuedo out-of-sample; 0: real time out-of-sample -% qmEnd=xinput{15}: last month (or quarter) of the sample -%------------- -% yact: (actup+forep*Psuedo)-by-nvar; log(y) except R, ect. (monthly). -% Begin: nSample-actup+1; End: nSample+forep*Psuedo. Match dates myears -% yactmg: (size(yact,1)-1)-by-nvar; month-to-month annualized growth for actual data. -% Begin: nSample-actup+2; End: nSample+forep*Psuedo. Match dates "myears(2:end)" -% yactqg: prior-quarter annualized growth for actual data -% Match dates "qyears." -% yactCalyg: annual growth for actual data -% Match dates "yearsCal." -% yactCal: weirdo -- seldom used. Same as yact but ends at the end of the -% last calendar year. If Psuedo, it includes some actual data in -% the 1st forecast calendar year. I haven't found the use of this weirdo. -% -% Copyright (c) March 1998 by Tao Zha -% Revised, October 1998 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -xdata=xinput{1}; nSample=xinput{2}; nSampleCal=xinput{3}; -actup=xinput{4}; actupq=xinput{5}; actupy=xinput{6}; vlist=xinput{7}; -vlistlog=xinput{8}; vlistper=xinput{9}; q_m=xinput{10}; forep=xinput{11}; -forepq=xinput{12}; forepy=xinput{13}; Psuedo=xinput{14}; qmEnd=xinput{15}; - -%-------------------------------------- -% Monthly log, acutal data -% yact the way it is and yactCal ends at the end of calendar year -%---------------------------------------- -yact = xdata(nSample-actup+1:nSample+forep*Psuedo,:); - % actup (not calendar) months + forep -yactCal = xdata(nSampleCal-actupy*q_m+1:nSampleCal+forepy*q_m*Psuedo,:); - % calendar years - - - - -%--------------------------------------------------------------- -% Actual monthly growth rate, Prior quarter, and calendar yearly change -%--------------------------------------------------------------- -% -%@@@ Monthly change (annaluized rate) -% -yactm = yact; -mT1 = length(yact(:,1)); -% -yactmg = yactm(2:mT1,:); % start at second month to get growth rate -yactmg(:,vlistlog) = (yactm(2:mT1,vlistlog) - yactm(1:mT1-1,vlistlog)) .* q_m; - % monthly, 12*log(1+growth rate), annualized growth rate -yactmg(:,vlistlog) = 100*(exp(yactmg(:,vlistlog))-1); -yactmg(:,vlistper) = 100*yactmg(:,vlistper); - -% -%@@@ Prior Quarter change (annaluized rate) -% -yactQ = xdata(nSample-mod(qmEnd,3)-actupq*3+1:nSample-mod(qmEnd,3)+forepq*3*Psuedo,:); -yactq = zeros(actupq+forepq*Psuedo,length(vlist)); -% -qT1 = length(yactQ(:,1))/3; -qT1a = length(yactq(:,1)); -if qT1 ~= qT1a - warning('line #') - error('qT1: Beginings or ends of monthly and quarterly series do not match!') -end -% -for i = 1:qT1 - i1 = 1+3*(i-1); - i2 = 3*i; - yactq(i,:) = sum(yactQ(i1:i2,:)) ./ 3; -end -% -yactqg = yactq(5:qT1,:); % 4+1=5 where 4 means 4 quarters -yactqg(:,vlistlog) = (yactq(5:qT1,vlistlog) - yactq(4:qT1-1,vlistlog)) .* 4; - % quarterly, 4*log(1+growth rate), annualized growth rate -yactqg(:,vlistlog) = 100*(exp(yactqg(:,vlistlog))-1); -yactqg(:,vlistper) = 100*yactqg(:,vlistper); - -% -%@@@ Calendar year-over-year change -% -yactCaly = zeros(actupy+forepy*Psuedo,length(vlist)); - % past "actupy" calendar years + forepy*Psuedo -yT1 = length(yactCal(:,1))/q_m; -yT1a = length(yactCaly(:,1)); -if yT1 ~= yT1a - warning('Line #') - error('yT1: Beginings or ends of monthly and quarterly series are not the same!') -end -% -for i = 1:yT1 - i1 = 1+q_m*(i-1); - i2 = q_m*i; - yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; -end -% -yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year -yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); - % annual rate: log(1+growth rate) -yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); -yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); +function [yact,yactmg,yactqg,yactCalyg,yactCal] = datactcon(xinput) +% [yact,yactmg,yactqg,yactCalyg,yactCal] = datactcon(xinput) +% Data-actual-conditions. Take the raw data xdata to mlog, mg, qg, and yg. +% Note yact(mlog), yactqg, and yactCalyg corr. to myears, qyears, and yearsCal +% +% xdata=xinput{1}: data, all logged except R, U, etc. +% nSample=xinput{2}: sample size (including lags or initial periods) +% nSampleCal=xinput{3}: converting nSample to sample marked by calendar years; +% actup=xinput{4}: periods for actual data (monthly) +% actupq=xinput{5}: periods for actual data (quarterly) +% actupy=xinput{6}: periods for actual data (calendar yearly) +% vlist=xinput{7}: list of variables +% vlistlog=xinput{8}: sub list of variables that are in log +% vlistper=xinput{9}: sub list of variables that are in percent +% q_m=xinput{10}: month or quarter in the model +% forep=xinput{11}: forecast periods (monthly) +% forepq=xinput{12}: quarters in the forecast period +% forepy=xinput{13}: calendar years in the forecast period +% Psuedo=xinput{14}: 1: Psuedo out-of-sample; 0: real time out-of-sample +% qmEnd=xinput{15}: last month (or quarter) of the sample +%------------- +% yact: (actup+forep*Psuedo)-by-nvar; log(y) except R, ect. (monthly). +% Begin: nSample-actup+1; End: nSample+forep*Psuedo. Match dates myears +% yactmg: (size(yact,1)-1)-by-nvar; month-to-month annualized growth for actual data. +% Begin: nSample-actup+2; End: nSample+forep*Psuedo. Match dates "myears(2:end)" +% yactqg: prior-quarter annualized growth for actual data +% Match dates "qyears." +% yactCalyg: annual growth for actual data +% Match dates "yearsCal." +% yactCal: weirdo -- seldom used. Same as yact but ends at the end of the +% last calendar year. If Psuedo, it includes some actual data in +% the 1st forecast calendar year. I haven't found the use of this weirdo. +% +% Written by Tao Zha March 1998 +% Revised, October 1998 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +xdata=xinput{1}; nSample=xinput{2}; nSampleCal=xinput{3}; +actup=xinput{4}; actupq=xinput{5}; actupy=xinput{6}; vlist=xinput{7}; +vlistlog=xinput{8}; vlistper=xinput{9}; q_m=xinput{10}; forep=xinput{11}; +forepq=xinput{12}; forepy=xinput{13}; Psuedo=xinput{14}; qmEnd=xinput{15}; + +%-------------------------------------- +% Monthly log, acutal data +% yact the way it is and yactCal ends at the end of calendar year +%---------------------------------------- +yact = xdata(nSample-actup+1:nSample+forep*Psuedo,:); + % actup (not calendar) months + forep +yactCal = xdata(nSampleCal-actupy*q_m+1:nSampleCal+forepy*q_m*Psuedo,:); + % calendar years + + + + +%--------------------------------------------------------------- +% Actual monthly growth rate, Prior quarter, and calendar yearly change +%--------------------------------------------------------------- +% +%@@@ Monthly change (annaluized rate) +% +yactm = yact; +mT1 = length(yact(:,1)); +% +yactmg = yactm(2:mT1,:); % start at second month to get growth rate +yactmg(:,vlistlog) = (yactm(2:mT1,vlistlog) - yactm(1:mT1-1,vlistlog)) .* q_m; + % monthly, 12*log(1+growth rate), annualized growth rate +yactmg(:,vlistlog) = 100*(exp(yactmg(:,vlistlog))-1); +yactmg(:,vlistper) = 100*yactmg(:,vlistper); + +% +%@@@ Prior Quarter change (annaluized rate) +% +yactQ = xdata(nSample-mod(qmEnd,3)-actupq*3+1:nSample-mod(qmEnd,3)+forepq*3*Psuedo,:); +yactq = zeros(actupq+forepq*Psuedo,length(vlist)); +% +qT1 = length(yactQ(:,1))/3; +qT1a = length(yactq(:,1)); +if qT1 ~= qT1a + warning('line #') + error('qT1: Beginings or ends of monthly and quarterly series do not match!') +end +% +for i = 1:qT1 + i1 = 1+3*(i-1); + i2 = 3*i; + yactq(i,:) = sum(yactQ(i1:i2,:)) ./ 3; +end +% +yactqg = yactq(5:qT1,:); % 4+1=5 where 4 means 4 quarters +yactqg(:,vlistlog) = (yactq(5:qT1,vlistlog) - yactq(4:qT1-1,vlistlog)) .* 4; + % quarterly, 4*log(1+growth rate), annualized growth rate +yactqg(:,vlistlog) = 100*(exp(yactqg(:,vlistlog))-1); +yactqg(:,vlistper) = 100*yactqg(:,vlistper); + +% +%@@@ Calendar year-over-year change +% +yactCaly = zeros(actupy+forepy*Psuedo,length(vlist)); + % past "actupy" calendar years + forepy*Psuedo +yT1 = length(yactCal(:,1))/q_m; +yT1a = length(yactCaly(:,1)); +if yT1 ~= yT1a + warning('Line #') + error('yT1: Beginings or ends of monthly and quarterly series are not the same!') +end +% +for i = 1:yT1 + i1 = 1+q_m*(i-1); + i2 = q_m*i; + yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; +end +% +yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year +yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); + % annual rate: log(1+growth rate) +yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); +yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); diff --git a/MatlabFiles/dataext.m b/MatlabFiles/dataext.m index 1301c1c9b45f45683536407bc7228cbb111336d5..d6d56a251d473ba7ea7ffeaa94514425824deac2 100644 --- a/MatlabFiles/dataext.m +++ b/MatlabFiles/dataext.m @@ -1,61 +1,61 @@ -function [xdsube,Brow,Erow] = dataext(Byrqm,Eyrqm,xdatae) -% xdsube = dataext(Byrqm,Eyrqm,xdatae) -% -% Extract subset of xdatae, given Byrqm and Eyrqm -% -% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)=0, we get annual data. -% Eyrqm: [year period]: end year and period. If Byrqm(2)=0, it must be Eyrqm(2)=0. -% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. -%---------- -% xdsube: subset of xdatae. -% Brow: the row number in xdatee that marks the first row of xdsube. -% Erow: the row number in xdatee that marks the last row of xdsube. -% -% Tao Zha, April 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if (Byrqm(2)==0) & (Eyrqm(2)~=0) - error('If annual data, make sure both Byrqm(2) and Eyrqm(2) are zero') -end - -Brow = min(find(xdatae(:,1)==Byrqm(1))); -if isempty(Brow) - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') -end -if Byrqm(2)>0 - nadt=Byrqm(2)-xdatae(Brow,2); - if nadt<0 - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Brow=Brow+nadt; -end -% -Erow = min(find(xdatae(:,1)==Eyrqm(1))); -if isempty(Erow) - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') -end -if Eyrqm(2)>0 - nadt2=Eyrqm(2)-xdatae(Erow,2); - if nadt<0 - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Erow=Erow+nadt2; -end -% -xdsube = xdatae(Brow:Erow,:); % with dates \ No newline at end of file +function [xdsube,Brow,Erow] = dataext(Byrqm,Eyrqm,xdatae) +% xdsube = dataext(Byrqm,Eyrqm,xdatae) +% +% Extract subset of xdatae, given Byrqm and Eyrqm +% +% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)=0, we get annual data. +% Eyrqm: [year period]: end year and period. If Byrqm(2)=0, it must be Eyrqm(2)=0. +% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. +%---------- +% xdsube: subset of xdatae. +% Brow: the row number in xdatee that marks the first row of xdsube. +% Erow: the row number in xdatee that marks the last row of xdsube. +% +% Tao Zha, April 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if (Byrqm(2)==0) & (Eyrqm(2)~=0) + error('If annual data, make sure both Byrqm(2) and Eyrqm(2) are zero') +end + +Brow = min(find(xdatae(:,1)==Byrqm(1))); +if isempty(Brow) + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') +end +if Byrqm(2)>0 + nadt=Byrqm(2)-xdatae(Brow,2); + if nadt<0 + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Brow=Brow+nadt; +end +% +Erow = min(find(xdatae(:,1)==Eyrqm(1))); +if isempty(Erow) + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') +end +if Eyrqm(2)>0 + nadt2=Eyrqm(2)-xdatae(Erow,2); + if nadt<0 + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Erow=Erow+nadt2; +end +% +xdsube = xdatae(Brow:Erow,:); % with dates diff --git a/MatlabFiles/datana.m b/MatlabFiles/datana.m index 3d7052e3faaa9b655fb15b1de4921a3b5aae5e0a..d7658c5a0122b4ed8f6101d1db31e217b33f8d9c 100644 --- a/MatlabFiles/datana.m +++ b/MatlabFiles/datana.m @@ -1,113 +1,113 @@ -function [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = datana(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) -% [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = datana(Byrqm,Eyrqm,xdatae,q_m,vlistlog,vlistper) -% -% Generate prior period, period-to-period-in-last-year, and annual growth rates -% For annual rates, works for both calendar and any annual years, depending on Byrqm and Eyrqm -% If monthly data, we haven't got time to get quarterly growth rates yet. -% -% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. -% q_m: quarter or month period -% vlistlog: sublist for logged variables -% vlistper: sublists for percent variables -% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)~=1, we don't get -% calendar annual rates. In other words, the first column of yactyge (which -% indicates years) does not mean calendar years -% Eyrqm: [year period]: end year and period -% NOTE: if no inputs Byrqm and Eyrqm are specified, all growth rates begin at xdatae(1,1:2). -%---------- -% yactyrge: annual growth rates with dates in the first 2 columns. -% yactyre: annual average logged level with dates in the 1st 2 columns. -% yactqmyge: period-to-period-in-last-year annual growth rates with dates in the first 2 columns. -% yactqmge: prior-period annualized growth rates with dates in the first 2 columns. -% yactqme: logged data with dates in the first 2 columns. -% -% Tao Zha, April 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if size(xdatae,1)<2*q_m - error('We need at least two years of xdatae to get annual rates. Check xdatae!!') -end - -if nargin==4 - Brow=1; Erow=length(xdatae(:,1)); - nyr = floor((Erow-Brow+1)/q_m); - yrsg = [xdatae(q_m+1,1):xdatae(q_m+1,1)+nyr-2]'; % for annual growth later on -else - if Byrqm(2)<1 | Eyrqm(2)<1 - error('This function requires both years and months (quarters) in Byrqm and Eyrqm') - end - - Brow = min(find(xdatae(:,1)==Byrqm(1))); - if isempty(Brow) - error('Byrqm is outside the date range of xdatae(:,1:2)!') - end - nadt=Byrqm(2)-xdatae(Brow,2); - if nadt<0 - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Brow=Brow+nadt; - % - Erow = min(find(xdatae(:,1)==Eyrqm(1))); - if isempty(Brow) - error('Eyrqm is outside the date range of xdatae(:,1:2)!') - end - nadt2=Eyrqm(2)-xdatae(Erow,2); - if nadt<0 - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Erow=Erow+nadt2; - - nyr = floor((Erow-Brow+1)/q_m); - yrsg = [Byrqm(1)+1:Byrqm(1)+nyr-1]'; % for annual growth later on, which will - % start at Byrqm(1) instead of Byrqm(1)+1 -end -% -yactqme = xdatae(Brow:Erow,:); % with dates -yactqm = yactqme(:,3:end); % only data - -%======== prior period change (annaluized rate) -yactqmg = yactqm(2:end,:); % start at second period to get growth rate -yactqmg(:,vlistlog) = (yactqm(2:end,vlistlog) - yactqm(1:end-1,vlistlog)) .* q_m; - % monthly, 12*log(1+growth rate), annualized growth rate -yactqmg(:,vlistlog) = 100*(exp(yactqmg(:,vlistlog))-1); -yactqmg(:,vlistper) = 100*yactqmg(:,vlistper); -yactqmge = [yactqme(2:end,1:2) yactqmg]; - -%======== change from the last year -yactqmyg = yactqm(q_m+1:end,:); % start at the last-year period to get growth rate -yactqmyg(:,vlistlog) = (yactqm(q_m+1:end,vlistlog) - yactqm(1:end-q_m,vlistlog)); -yactqmyg(:,vlistlog) = 100*(exp(yactqmyg(:,vlistlog))-1); -yactqmyg(:,vlistper) = 100*yactqmyg(:,vlistper); -yactqmyge = [yactqme(q_m+1:end,1:2) yactqmyg]; - -%======== annual growth rates -nvar = length(xdatae(1,3:end)); -ygmts = yactqm(1:nyr*q_m,:); % converted to the multiplication of q_m -ygmts1 = reshape(ygmts,q_m,nyr,nvar); -ygmts2 = sum(ygmts1,1) ./ q_m; -ygmts3 = reshape(ygmts2,nyr,nvar); % converted to annual average series -% -yactyrg = ygmts3(2:end,:); % start at the last-year period to get growth rate -yactyrg(:,vlistlog) = ygmts3(2:end,vlistlog) - ygmts3(1:end-1,vlistlog); - % annual rate: log(1+growth rate) -yactyrg(:,vlistlog) = 100*(exp(yactyrg(:,vlistlog))-1); -yactyrg(:,vlistper) = 100*yactyrg(:,vlistper); -yactyrge = [yrsg zeros(nyr-1,1) yactyrg]; -yrsg1=[yrsg(1)-1:yrsg(end)]'; -yactyre = [yrsg1 zeros(nyr,1) ygmts3]; \ No newline at end of file +function [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = datana(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) +% [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = datana(Byrqm,Eyrqm,xdatae,q_m,vlistlog,vlistper) +% +% Generate prior period, period-to-period-in-last-year, and annual growth rates +% For annual rates, works for both calendar and any annual years, depending on Byrqm and Eyrqm +% If monthly data, we haven't got time to get quarterly growth rates yet. +% +% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. +% q_m: quarter or month period +% vlistlog: sublist for logged variables +% vlistper: sublists for percent variables +% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)~=1, we don't get +% calendar annual rates. In other words, the first column of yactyge (which +% indicates years) does not mean calendar years +% Eyrqm: [year period]: end year and period +% NOTE: if no inputs Byrqm and Eyrqm are specified, all growth rates begin at xdatae(1,1:2). +%---------- +% yactyrge: annual growth rates with dates in the first 2 columns. +% yactyre: annual average logged level with dates in the 1st 2 columns. +% yactqmyge: period-to-period-in-last-year annual growth rates with dates in the first 2 columns. +% yactqmge: prior-period annualized growth rates with dates in the first 2 columns. +% yactqme: logged data with dates in the first 2 columns. +% +% Tao Zha, April 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if size(xdatae,1)<2*q_m + error('We need at least two years of xdatae to get annual rates. Check xdatae!!') +end + +if nargin==4 + Brow=1; Erow=length(xdatae(:,1)); + nyr = floor((Erow-Brow+1)/q_m); + yrsg = [xdatae(q_m+1,1):xdatae(q_m+1,1)+nyr-2]'; % for annual growth later on +else + if Byrqm(2)<1 | Eyrqm(2)<1 + error('This function requires both years and months (quarters) in Byrqm and Eyrqm') + end + + Brow = min(find(xdatae(:,1)==Byrqm(1))); + if isempty(Brow) + error('Byrqm is outside the date range of xdatae(:,1:2)!') + end + nadt=Byrqm(2)-xdatae(Brow,2); + if nadt<0 + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Brow=Brow+nadt; + % + Erow = min(find(xdatae(:,1)==Eyrqm(1))); + if isempty(Brow) + error('Eyrqm is outside the date range of xdatae(:,1:2)!') + end + nadt2=Eyrqm(2)-xdatae(Erow,2); + if nadt<0 + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Erow=Erow+nadt2; + + nyr = floor((Erow-Brow+1)/q_m); + yrsg = [Byrqm(1)+1:Byrqm(1)+nyr-1]'; % for annual growth later on, which will + % start at Byrqm(1) instead of Byrqm(1)+1 +end +% +yactqme = xdatae(Brow:Erow,:); % with dates +yactqm = yactqme(:,3:end); % only data + +%======== prior period change (annaluized rate) +yactqmg = yactqm(2:end,:); % start at second period to get growth rate +yactqmg(:,vlistlog) = (yactqm(2:end,vlistlog) - yactqm(1:end-1,vlistlog)) .* q_m; + % monthly, 12*log(1+growth rate), annualized growth rate +yactqmg(:,vlistlog) = 100*(exp(yactqmg(:,vlistlog))-1); +yactqmg(:,vlistper) = 100*yactqmg(:,vlistper); +yactqmge = [yactqme(2:end,1:2) yactqmg]; + +%======== change from the last year +yactqmyg = yactqm(q_m+1:end,:); % start at the last-year period to get growth rate +yactqmyg(:,vlistlog) = (yactqm(q_m+1:end,vlistlog) - yactqm(1:end-q_m,vlistlog)); +yactqmyg(:,vlistlog) = 100*(exp(yactqmyg(:,vlistlog))-1); +yactqmyg(:,vlistper) = 100*yactqmyg(:,vlistper); +yactqmyge = [yactqme(q_m+1:end,1:2) yactqmyg]; + +%======== annual growth rates +nvar = length(xdatae(1,3:end)); +ygmts = yactqm(1:nyr*q_m,:); % converted to the multiplication of q_m +ygmts1 = reshape(ygmts,q_m,nyr,nvar); +ygmts2 = sum(ygmts1,1) ./ q_m; +ygmts3 = reshape(ygmts2,nyr,nvar); % converted to annual average series +% +yactyrg = ygmts3(2:end,:); % start at the last-year period to get growth rate +yactyrg(:,vlistlog) = ygmts3(2:end,vlistlog) - ygmts3(1:end-1,vlistlog); + % annual rate: log(1+growth rate) +yactyrg(:,vlistlog) = 100*(exp(yactyrg(:,vlistlog))-1); +yactyrg(:,vlistper) = 100*yactyrg(:,vlistper); +yactyrge = [yrsg zeros(nyr-1,1) yactyrg]; +yrsg1=[yrsg(1)-1:yrsg(end)]'; +yactyre = [yrsg1 zeros(nyr,1) ygmts3]; diff --git a/MatlabFiles/dataxy.m b/MatlabFiles/dataxy.m index 639e78d49f16ff4538e491e385738d2ec4f9f426..25abb6cefd01b41655252ed34269881eaaf5c2c2 100644 --- a/MatlabFiles/dataxy.m +++ b/MatlabFiles/dataxy.m @@ -1,160 +1,160 @@ -function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = dataxy(nvar,lags,z,mu,indxDummy,nexo) -% [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = dataxy(nvar,lags,z,mu,indxDummy,nexo) -% -% Export arranged data matrices for future estimation for DM models. -% See Wagonner and Zha's Gibbs sampling paper. -% -% nvar: number of endogenous variables. -% lags: the maximum length of lag -% nhp: number of haperparameters -% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) -% with sample size including lags. -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1) -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% Here, only mu(5) and mu(6) are used for dummy observations -% indxDummy = 1; % 1: add dummy observations to the data; 0: no dummy added. -% nexo: number of exogenous variables. Besides constant terms, we have nexo-1 exogenous variables. -% ------------------- -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. -% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, const] -% y: Y: T-by-nvar where T=fss -% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+ncoef -% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X -% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; -% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, exogenous variables, const] -% e: estimated residual e = y -x*Bh, T-by-nvar -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin == 5 - nexo=1; % default for constant term -elseif nexo<1 - error('We need at least one exogenous term so nexo must >= 1') -end - -%*** original sample dimension without dummy prior -nSample = size(z,1); % the sample size (including lags, of course) -sb = lags+1; % original beginning without dummies -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -if indxDummy % prior dummy prior - - %*** expanded sample dimension by dummy prior - ndobs=nvar+1; % number of dummy observations - fss = nSample+ndobs-lags; - - % - % **** nvar prior dummy observations with the sum of coefficients - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % ** Now, T=T+ndobs -- added with "ndobs" dummy observations - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - const(1:nvar) = zeros(nvar,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - exox = zeros(ndobs,nexo); - phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %* Dummies - for k=1:nvar - for m=1:lags - phi(ndobs,nvar*(m-1)+k) = xdgelint(k); - phi(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - %* True data - for k=1:lags - phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - % ** Y with "ndobs" dummies added - y = zeros(fss,nvar); - %* Dummies - for k=1:nvar - y(ndobs,k) = xdgelint(k); - y(k,k) = xdgelint(k); - % multiply hyperparameter later - end - %* True data - y(ndobs+1:fss,:) = xdgel(sb:nSample,:); - - phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior - y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior - phi(nvar+1,:) = mu(6)*phi(nvar+1,:); - y(nvar+1,:) = mu(6)*y(nvar+1,:); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -else - fss = nSample-lags; - % - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - %* True data - for k=1:lags - phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - y = xdgel(sb:nSample,:); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -end +function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = dataxy(nvar,lags,z,mu,indxDummy,nexo) +% [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = dataxy(nvar,lags,z,mu,indxDummy,nexo) +% +% Export arranged data matrices for future estimation for DM models. +% See Wagonner and Zha's Gibbs sampling paper. +% +% nvar: number of endogenous variables. +% lags: the maximum length of lag +% nhp: number of haperparameters +% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) +% with sample size including lags. +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1) +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% Here, only mu(5) and mu(6) are used for dummy observations +% indxDummy = 1; % 1: add dummy observations to the data; 0: no dummy added. +% nexo: number of exogenous variables. Besides constant terms, we have nexo-1 exogenous variables. +% ------------------- +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. +% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, const] +% y: Y: T-by-nvar where T=fss +% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+ncoef +% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X +% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; +% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, exogenous variables, const] +% e: estimated residual e = y -x*Bh, T-by-nvar +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin == 5 + nexo=1; % default for constant term +elseif nexo<1 + error('We need at least one exogenous term so nexo must >= 1') +end + +%*** original sample dimension without dummy prior +nSample = size(z,1); % the sample size (including lags, of course) +sb = lags+1; % original beginning without dummies +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +if indxDummy % prior dummy prior + + %*** expanded sample dimension by dummy prior + ndobs=nvar+1; % number of dummy observations + fss = nSample+ndobs-lags; + + % + % **** nvar prior dummy observations with the sum of coefficients + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % ** Now, T=T+ndobs -- added with "ndobs" dummy observations + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + const(1:nvar) = zeros(nvar,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + exox = zeros(ndobs,nexo); + phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %* Dummies + for k=1:nvar + for m=1:lags + phi(ndobs,nvar*(m-1)+k) = xdgelint(k); + phi(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + %* True data + for k=1:lags + phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + % ** Y with "ndobs" dummies added + y = zeros(fss,nvar); + %* Dummies + for k=1:nvar + y(ndobs,k) = xdgelint(k); + y(k,k) = xdgelint(k); + % multiply hyperparameter later + end + %* True data + y(ndobs+1:fss,:) = xdgel(sb:nSample,:); + + phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior + y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior + phi(nvar+1,:) = mu(6)*phi(nvar+1,:); + y(nvar+1,:) = mu(6)*y(nvar+1,:); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +else + fss = nSample-lags; + % + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + %* True data + for k=1:lags + phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + y = xdgel(sb:nSample,:); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +end diff --git a/MatlabFiles/demarcate.m b/MatlabFiles/demarcate.m index c83940772b9976fee9329b7a1c58e3e5eed200ab..d3b030a8aeed7e8e2b86109fa6198b417e19c0bc 100644 --- a/MatlabFiles/demarcate.m +++ b/MatlabFiles/demarcate.m @@ -1,115 +1,114 @@ -function [imfl,imfh,imfl1,imfh1] = demarcate(imfcnt,imndraws,forep,nvar,... - ninv,invc,Am) -% [imfl,imfh,imfl1,imfh1] = demarcate(imfcnt,imndraws,forep,nvar,... -% ninv,invc,Am) -% imfcnt: 2+ninv-by-forep*nvar. Counted logcnt, yhatqgcnt, or yhatCalygcnt. -% In the case of impulse responses, forep=imstp and nvar=nvar^2 -% imndraws: total number of draws allocated to "imfcnt" -% forep: the number of forecast periods (for both impulse responses and forecasting) -% nvar: the number of variables. -% ninv: the number of small interior intervals for sorting. -% invc: 1-by-forep*nvar. Whole inverval lenghth from min to max for one of -% (yhat, yhatqg, or yhatCalyg) -% Am: 1-by-forep*nvar. Range5{i}(:,:,1) is lowest range for for one of -% (yhat, yhatqg, or yhatCalyg) -%----------------- -% imfl: lower .95 bound, forep-by-nvar -% imfh: higher .95 bound, forep-by-nvar -% imfl1: lower .68 bound, forep-by-nvar -% imfh1: higher .68 bound, forep-by-nvar -% -% Copyright (c) March 1998 Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - - -%$$$ .68 and .95 probability bands -imfl = zeros(forep*nvar,1); % preallocating -imfh = zeros(forep*nvar,1); % preallocating -imfl1 = zeros(forep*nvar,1); % preallocating -imfh1 = zeros(forep*nvar,1); % preallocating -imfpo = zeros(4,forep*nvar); % 4 positions: l,h,l1,h1. -% -%tic -tem = cumsum(imfcnt) ./ imndraws; % cumulative probability -tem = tem .* 100; -clear imfcnt - -uptail1=5; % 2.5, interval -lowtail1=95; % 97.5 - -%t_cum = toc -% -%tic -% -%@@@ the following operations are valid only because tem are increasing! -for k = 1:forep*nvar - % - %@@@ the following operations are valid only because tem are increasing! - %** 2.5% low tail - if isempty(max(find(tem(:,k)<uptail1))) - imfpo(1,k) = 1; - else - imfpo(1,k) = max(find(tem(:,k)<uptail1)); - end - %** 16% low tail - if isempty(max(find(tem(:,k)<16))) - imfpo(2,k) = 1; - else - imfpo(2,k) = max(find(tem(:,k)<16)); - end - %** 2.5% high tail - imfpo(3,k) = min(find(tem(:,k)>lowtail1)); - %** 16% low tail - imfpo(4,k) = min(find(tem(:,k)>84)); -end - -tem = imfpo'; -%save outprob.txt tem -ascii -% - -imfpo = imfpo - 2; % the first step to put back to original form -% * 2.5% low tail -imfs = ((imfpo(1,:) .* invc) ./ ninv) + Am; - % the final step to put back to original form of impulse responses -imfl = imfs'; -% * 16% low tail -imfs = ((imfpo(2,:) .* invc) ./ ninv) + Am; - % the final step to put back to original form of impulse responses -imfl1 = imfs'; -% * 2.5% high tail -imfs = ((imfpo(3,:) .* invc) ./ ninv) + Am; - % the final step to put back to original form of impulse responses -imfh = imfs'; -% * 16% high tail -imfs = ((imfpo(4,:) .* invc) ./ ninv) + Am; - % the final step to put back to original form of impulse responses -imfh1 = imfs'; -% -%e_t = toc - - -% *** write out final results -clear tem -imfl = reshape(imfl,forep,nvar); -imfh = reshape(imfh,forep,nvar); -imfl1 = reshape(imfl1,forep,nvar); -imfh1 = reshape(imfh1,forep,nvar); -% -% \ No newline at end of file +function [imfl,imfh,imfl1,imfh1] = demarcate(imfcnt,imndraws,forep,nvar,... + ninv,invc,Am) +% [imfl,imfh,imfl1,imfh1] = demarcate(imfcnt,imndraws,forep,nvar,... +% ninv,invc,Am) +% imfcnt: 2+ninv-by-forep*nvar. Counted logcnt, yhatqgcnt, or yhatCalygcnt. +% In the case of impulse responses, forep=imstp and nvar=nvar^2 +% imndraws: total number of draws allocated to "imfcnt" +% forep: the number of forecast periods (for both impulse responses and forecasting) +% nvar: the number of variables. +% ninv: the number of small interior intervals for sorting. +% invc: 1-by-forep*nvar. Whole inverval lenghth from min to max for one of +% (yhat, yhatqg, or yhatCalyg) +% Am: 1-by-forep*nvar. Range5{i}(:,:,1) is lowest range for for one of +% (yhat, yhatqg, or yhatCalyg) +%----------------- +% imfl: lower .95 bound, forep-by-nvar +% imfh: higher .95 bound, forep-by-nvar +% imfl1: lower .68 bound, forep-by-nvar +% imfh1: higher .68 bound, forep-by-nvar +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + + +%$$$ .68 and .95 probability bands +imfl = zeros(forep*nvar,1); % preallocating +imfh = zeros(forep*nvar,1); % preallocating +imfl1 = zeros(forep*nvar,1); % preallocating +imfh1 = zeros(forep*nvar,1); % preallocating +imfpo = zeros(4,forep*nvar); % 4 positions: l,h,l1,h1. +% +%tic +tem = cumsum(imfcnt) ./ imndraws; % cumulative probability +tem = tem .* 100; +clear imfcnt + +uptail1=5; % 2.5, interval +lowtail1=95; % 97.5 + +%t_cum = toc +% +%tic +% +%@@@ the following operations are valid only because tem are increasing! +for k = 1:forep*nvar + % + %@@@ the following operations are valid only because tem are increasing! + %** 2.5% low tail + if isempty(max(find(tem(:,k)<uptail1))) + imfpo(1,k) = 1; + else + imfpo(1,k) = max(find(tem(:,k)<uptail1)); + end + %** 16% low tail + if isempty(max(find(tem(:,k)<16))) + imfpo(2,k) = 1; + else + imfpo(2,k) = max(find(tem(:,k)<16)); + end + %** 2.5% high tail + imfpo(3,k) = min(find(tem(:,k)>lowtail1)); + %** 16% low tail + imfpo(4,k) = min(find(tem(:,k)>84)); +end + +tem = imfpo'; +%save outprob.txt tem -ascii +% + +imfpo = imfpo - 2; % the first step to put back to original form +% * 2.5% low tail +imfs = ((imfpo(1,:) .* invc) ./ ninv) + Am; + % the final step to put back to original form of impulse responses +imfl = imfs'; +% * 16% low tail +imfs = ((imfpo(2,:) .* invc) ./ ninv) + Am; + % the final step to put back to original form of impulse responses +imfl1 = imfs'; +% * 2.5% high tail +imfs = ((imfpo(3,:) .* invc) ./ ninv) + Am; + % the final step to put back to original form of impulse responses +imfh = imfs'; +% * 16% high tail +imfs = ((imfpo(4,:) .* invc) ./ ninv) + Am; + % the final step to put back to original form of impulse responses +imfh1 = imfs'; +% +%e_t = toc + + +% *** write out final results +clear tem +imfl = reshape(imfl,forep,nvar); +imfh = reshape(imfh,forep,nvar); +imfl1 = reshape(imfl1,forep,nvar); +imfh1 = reshape(imfh1,forep,nvar); +% +% diff --git a/MatlabFiles/demarw.m b/MatlabFiles/demarw.m index f354059495b1273ae92563101200bf39452a93d6..ac28a39cc646570a822b5ab819bda65d1057c193 100644 --- a/MatlabFiles/demarw.m +++ b/MatlabFiles/demarw.m @@ -1,65 +1,64 @@ -function [imfl,imfh,imfl1,imfh1] = demarw(xpo,xprob) -% [imfl,imfh,imfl1,imfh1] = demarw(xpo,xprob) -% Demarcate the .68 and .95 error bands given prob. (weights) and positions -% -% xpo: ndraws-by-nvar. Centered position -% xprob: ndraws-by-nvar. Properly scaled probabilities corresponding to xpo. -%----------------- -% imfl: lower .95 bound, nvar-by-1 -% imfh: higher .95 bound, nvar-by-1 -% imfl1: lower .68 bound, nvar-by-1 -% imfh1: higher .68 bound, nvar-by-1 -% -% Copyright (c) August 1999 Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[ndraws,nvar]=size(xpo); - -%$$$ .68 and .95 probability bands -imfl = zeros(nvar,1); % preallocating -imfh = zeros(nvar,1); % preallocating -imfl1 = zeros(nvar,1); % preallocating -imfh1 = zeros(nvar,1); % preallocating -imfpo = zeros(4,nvar); % 4 positions: l,h,l1,h1. -% -%tic -tem = cumsum(xprob); % cumulative probability -tem = tem .* 100; -% -%@@@ the following operations are valid only because tem are increasing! -for k = 1:nvar - % - %@@@ the following operations are valid only because tem are increasing! - %** 2.5% low tail - if isempty(max(find(tem(:,k)<2.5))) - imfl(k) = xpo(1,k); - else - imfl(k) = xpo(max(find(tem(:,k)<2.5)),k); - end - %** 16% low tail - if isempty(max(find(tem(:,k)<16))) - imfl1(k) = xpo(1,k); - else - imfl1(k) = xpo(max(find(tem(:,k)<16)),k); - end - %** 2.5% high tail - imfh(k) = xpo(min(find(tem(:,k)>97.5)),k); - %** 16% low tail - imfh1(k) = xpo(min(find(tem(:,k)>84)),k); -end +function [imfl,imfh,imfl1,imfh1] = demarw(xpo,xprob) +% [imfl,imfh,imfl1,imfh1] = demarw(xpo,xprob) +% Demarcate the .68 and .95 error bands given prob. (weights) and positions +% +% xpo: ndraws-by-nvar. Centered position +% xprob: ndraws-by-nvar. Properly scaled probabilities corresponding to xpo. +%----------------- +% imfl: lower .95 bound, nvar-by-1 +% imfh: higher .95 bound, nvar-by-1 +% imfl1: lower .68 bound, nvar-by-1 +% imfh1: higher .68 bound, nvar-by-1 +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[ndraws,nvar]=size(xpo); + +%$$$ .68 and .95 probability bands +imfl = zeros(nvar,1); % preallocating +imfh = zeros(nvar,1); % preallocating +imfl1 = zeros(nvar,1); % preallocating +imfh1 = zeros(nvar,1); % preallocating +imfpo = zeros(4,nvar); % 4 positions: l,h,l1,h1. +% +%tic +tem = cumsum(xprob); % cumulative probability +tem = tem .* 100; +% +%@@@ the following operations are valid only because tem are increasing! +for k = 1:nvar + % + %@@@ the following operations are valid only because tem are increasing! + %** 2.5% low tail + if isempty(max(find(tem(:,k)<2.5))) + imfl(k) = xpo(1,k); + else + imfl(k) = xpo(max(find(tem(:,k)<2.5)),k); + end + %** 16% low tail + if isempty(max(find(tem(:,k)<16))) + imfl1(k) = xpo(1,k); + else + imfl1(k) = xpo(max(find(tem(:,k)<16)),k); + end + %** 2.5% high tail + imfh(k) = xpo(min(find(tem(:,k)>97.5)),k); + %** 16% low tail + imfh1(k) = xpo(min(find(tem(:,k)>84)),k); +end diff --git a/MatlabFiles/dlrpostr.m b/MatlabFiles/dlrpostr.m index 52b7ba54cbbd0f6e22ba2d7d67de77a9cf0a9c8d..b462f8dae5a1384524ae55e6b506ba5bd6727e48 100644 --- a/MatlabFiles/dlrpostr.m +++ b/MatlabFiles/dlrpostr.m @@ -1,59 +1,59 @@ -function [P,H0inv,Hpinv] = dlrpostr(xtx,xty,yty,Ui,Vi) -% [P,H0inv,Hpinv] = dlrpostr(xtx,xty,yty,Ui,Vi) -% -% Exporting deterministic (hard restrictions) Bayesian posterior matrices with linear restrictions -% See Waggoner and Zha's Gibbs sampling paper -% -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. Imported from dnrprior.m. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. Imported from dnrprior.m. -%----------------- -% P: cell(nvar,1). In each cell, posterior linear transformation for random walk prior for the ith equation % tld: tilda -% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, -% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. -% Hpinv: cell(nvar,1). In each cell, posterior inv(Hp) for the ith equation. -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -nvar = size(yty,1); - -P = cell(nvar,1); % tld: tilda -H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. -Hpinv = cell(nvar,1); % posterior inv(Hp). - -for n=1:nvar % one for each equation - Hpinv{n} = Vi{n}'*xtx*Vi{n}; - P1 = Vi{n}'*xty*Ui{n}; - P{n} = Hpinv{n}\P1; - H0inv{n} = Ui{n}'*yty*Ui{n} - P1'*(Hpinv{n}\P1); -end - +function [P,H0inv,Hpinv] = dlrpostr(xtx,xty,yty,Ui,Vi) +% [P,H0inv,Hpinv] = dlrpostr(xtx,xty,yty,Ui,Vi) +% +% Exporting deterministic (hard restrictions) Bayesian posterior matrices with linear restrictions +% See Waggoner and Zha's Gibbs sampling paper +% +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. Imported from dnrprior.m. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. Imported from dnrprior.m. +%----------------- +% P: cell(nvar,1). In each cell, posterior linear transformation for random walk prior for the ith equation % tld: tilda +% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, +% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. +% Hpinv: cell(nvar,1). In each cell, posterior inv(Hp) for the ith equation. +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +nvar = size(yty,1); + +P = cell(nvar,1); % tld: tilda +H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. +Hpinv = cell(nvar,1); % posterior inv(Hp). + +for n=1:nvar % one for each equation + Hpinv{n} = Vi{n}'*xtx*Vi{n}; + P1 = Vi{n}'*xty*Ui{n}; + P{n} = Hpinv{n}\P1; + H0inv{n} = Ui{n}'*yty*Ui{n} - P1'*(Hpinv{n}\P1); +end + diff --git a/MatlabFiles/eigsort.m b/MatlabFiles/eigsort.m index 771d7b0d7018be1fee38611648d575a4e99ffdbb..43877703176968bc1436d166460debdc24bccaba 100644 --- a/MatlabFiles/eigsort.m +++ b/MatlabFiles/eigsort.m @@ -1,46 +1,46 @@ -function [vU2,dU2] = eigsort(U,desI) -% E = EIGSORT(X,desI) is a vector containing the eigenvalues of a square -% matrix X, where E is sorted descendingly if desI=1 or ascendingly otherwise -% -% [V,D] = EIG(X) produces a diagonal matrix D of eigenvalues and a -% full matrix V whose columns are the corresponding eigenvectors so -% that X*V = V*D. -% -% Written 9/6/98 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -[vU,dU]=eig(U); -dUvec = diag(dU); % If dU is SPD, use "abs" in front of diag. This is because, - % even though dU is supposed to be positive, the numerical solution - % for a near-zero eigenvalue can be negative. - % ******************* - % Second thought: "abs" is not necessary, I think. If negative, it - % implies zero already -- thus the smallest number -[dUvec2,dUI2] = sort(dUvec); % ascending -if desI==1 % if descending is required - dUvec2 = flipud(dUvec2); - dUI2 = flipud(dUI2); -end - -if nargout==1 - vU2 = dUvec2; - dU2 = NaN; -else - vU2 = vU(:,dUI2); - dU2 = diag(dUvec2); % put it back to matrix form -end \ No newline at end of file +function [vU2,dU2] = eigsort(U,desI) +% E = EIGSORT(X,desI) is a vector containing the eigenvalues of a square +% matrix X, where E is sorted descendingly if desI=1 or ascendingly otherwise +% +% [V,D] = EIG(X) produces a diagonal matrix D of eigenvalues and a +% full matrix V whose columns are the corresponding eigenvectors so +% that X*V = V*D. +% +% Written 9/6/98 by Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +[vU,dU]=eig(U); +dUvec = diag(dU); % If dU is SPD, use "abs" in front of diag. This is because, + % even though dU is supposed to be positive, the numerical solution + % for a near-zero eigenvalue can be negative. + % ******************* + % Second thought: "abs" is not necessary, I think. If negative, it + % implies zero already -- thus the smallest number +[dUvec2,dUI2] = sort(dUvec); % ascending +if desI==1 % if descending is required + dUvec2 = flipud(dUvec2); + dUI2 = flipud(dUI2); +end + +if nargout==1 + vU2 = dUvec2; + dU2 = NaN; +else + vU2 = vU(:,dUI2); + dU2 = diag(dUvec2); % put it back to matrix form +end diff --git a/MatlabFiles/ellipse.m b/MatlabFiles/ellipse.m index 5ef3f6b56a3fd0c5d7d3ff9b025afca3210c4a1d..d80b6865a7dc930b0f98bb94533f4be1b851c862 100644 --- a/MatlabFiles/ellipse.m +++ b/MatlabFiles/ellipse.m @@ -1,86 +1,86 @@ -function [x,y,z] = ellipse(sigma,mu,k) -%ELLIPSE Creates an ellipsoid -%[X,Y,Z] = ELLIPSE(SIGMA,MU,K) Creates an arbitrary -%ellipsoid in 2 or 3 dimensions. The ellipsoid represents -%the solutions to the quadratic equation: -% -% (x-MU)'*SIGMA*(x-MU) = K -% -%SIGMA is a positive definate matrix of size 2x2 or 3x3. -%SIGMA determines the shape of the ellipsoid. -%MU is a vector conformable with SIGMA; either 2x1 or 3x1. -%MU determines the location of the ellipsoid. -%K is a real constant. -%K determines the size of the ellipsoid. -%The vector x=[X;Y] in 2D or x=[X,Y,Z] in 3D. -% -%If no output aruments are specified, the resulting -%ellipsoid is plotted. One can create these plots manually -%using PLOT(X,Y) in the 2 dimensional case and -%using MESH(X,Y,Z) in the 3 dimensional case. - -% QPLOT was written by Clark A. Burdick of the research -% department of the Federal Reserve Bank of Atlanta. -% Original: August 19, 1997 -% Last Modified: August 19, 1997 -% Copyright (C) 1997-2012 Clark A. Burdick -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% TO BE DONE: -% I'm open to suggestions. - -n=50; % <<>> -theta=pi*(-n:2:n)/n; -phi=(pi/2)*(-n:2:n)'/n; - -R=chol(sigma); -rho=sqrt(k); - -if length(mu) == 2 - X = rho*cos(theta); - Y = rho*sin(theta); - - for i = 1:length(theta) - circlevec = [X(i);Y(i)]; - ellipsevec = R\circlevec; % T.A. Zha, 8/16/98 - x(i) = mu(1) + ellipsevec(1); - y(i) = mu(2) + ellipsevec(2); - end - if nargout == 0 - plot(x,y) - end - z='This was only a 2 dimensional ellipse'; -end - -if length(mu) == 3 - X = rho*cos(phi)*cos(theta); - Y = rho*cos(phi)*sin(theta); - Z = rho*sin(phi)*ones(size(theta)); - - for i = 1:length(phi) - for j = 1:length(theta) - spherevec = [X(i,j); Y(i,j); Z(i,j)]; - ellipsevec = R\spherevec; % T.A. Zha, 8/16/98 - x(i,j) = mu(1) + ellipsevec(1); - y(i,j) = mu(2) + ellipsevec(2); - z(i,j) = mu(3) + ellipsevec(3); - end - end - if nargout == 0 - mesh(x,y,z) - end -end \ No newline at end of file +function [x,y,z] = ellipse(sigma,mu,k) +%ELLIPSE Creates an ellipsoid +%[X,Y,Z] = ELLIPSE(SIGMA,MU,K) Creates an arbitrary +%ellipsoid in 2 or 3 dimensions. The ellipsoid represents +%the solutions to the quadratic equation: +% +% (x-MU)'*SIGMA*(x-MU) = K +% +%SIGMA is a positive definate matrix of size 2x2 or 3x3. +%SIGMA determines the shape of the ellipsoid. +%MU is a vector conformable with SIGMA; either 2x1 or 3x1. +%MU determines the location of the ellipsoid. +%K is a real constant. +%K determines the size of the ellipsoid. +%The vector x=[X;Y] in 2D or x=[X,Y,Z] in 3D. +% +%If no output aruments are specified, the resulting +%ellipsoid is plotted. One can create these plots manually +%using PLOT(X,Y) in the 2 dimensional case and +%using MESH(X,Y,Z) in the 3 dimensional case. + +% QPLOT was written by Clark A. Burdick of the research +% department of the Federal Reserve Bank of Atlanta. +% Original: August 19, 1997 +% Last Modified: August 19, 1997 +% +% Copyright (C) 1997-2012 Clark A. Burdick +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% TO BE DONE: +% I'm open to suggestions. + +n=50; % <<>> +theta=pi*(-n:2:n)/n; +phi=(pi/2)*(-n:2:n)'/n; + +R=chol(sigma); +rho=sqrt(k); + +if length(mu) == 2 + X = rho*cos(theta); + Y = rho*sin(theta); + + for i = 1:length(theta) + circlevec = [X(i);Y(i)]; + ellipsevec = R\circlevec; % T.A. Zha, 8/16/98 + x(i) = mu(1) + ellipsevec(1); + y(i) = mu(2) + ellipsevec(2); + end + if nargout == 0 + plot(x,y) + end + z='This was only a 2 dimensional ellipse'; +end + +if length(mu) == 3 + X = rho*cos(phi)*cos(theta); + Y = rho*cos(phi)*sin(theta); + Z = rho*sin(phi)*ones(size(theta)); + + for i = 1:length(phi) + for j = 1:length(theta) + spherevec = [X(i,j); Y(i,j); Z(i,j)]; + ellipsevec = R\spherevec; % T.A. Zha, 8/16/98 + x(i,j) = mu(1) + ellipsevec(1); + y(i,j) = mu(2) + ellipsevec(2); + z(i,j) = mu(3) + ellipsevec(3); + end + end + if nargout == 0 + mesh(x,y,z) + end +end diff --git a/MatlabFiles/empdfsort.m b/MatlabFiles/empdfsort.m index c9f36273705aaa75b878d7babdd694f1fa27daa5..68282b7df68b8e2b0a592abc301b17b2bee29b06 100644 --- a/MatlabFiles/empdfsort.m +++ b/MatlabFiles/empdfsort.m @@ -1,47 +1,47 @@ -function imfcnt = empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) -% imfcnt = empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) -% Variablewise (but multivariate) empirical probability distribution with counts -% sorted into bins variablewise -% Note that since a particular draw (imf_h) can be below "imfloor" and above "imceiling" -% (=(imceiling-imfloor)*hbin), this function allows ninv+2 bins for each variable -% -% imfcnt: initial ninv+2-by-k matrix that records counts in each bin given a column in imfcnt -% if k==1, then only one variable is considered. -% imf_h: particular draw, needed not to be a 1-by-k row vector -% imfloor: the low value of imf but imf_h can be below "imfloor" and above "imceiling" -% hbin: bin size = (imceilling-imfloor)/ninv -% ninv: number of bins between "imfloor" and "imceiling" -%------------------ -% imfcnt: updated ninv+2-by-k matrix of counts (probability) -% -% January 1999 TAZ -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%** find the bin locations and arrange them to the order of 1, 2, ... -countInt = floor( (imf_h-imfloor) ./ hbin ); % imstp-by-nvar^2 - % bin locations from <0, 0, 1,..., ninv-1, >=ninv, a total of ninv+2 bins -countInt = 2+countInt(:)'; % row vector, 1-by-imstp*nvar^2, see my shock (1), pp.1 - % move everyting by 2 so as to take account of <0 - -countInt(find(countInt<2)) = 1; % set <0 or -infinity at 1 to start -countInt(find(countInt>=ninv+2)) = ninv+2; % set >=ninv+2 or +infinity at ninv+2 to end -countInt = countInt + (0:length(countInt)-1)*(ninv+2); % index to fill the matrix with prob. (counts) - % The term after "+": with every count, skip ninv+2 to keep - % each column in "imfcnt" with only one element (which is probability) -imfcnt(countInt) = imfcnt(countInt) + 1; +function imfcnt = empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) +% imfcnt = empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) +% Variablewise (but multivariate) empirical probability distribution with counts +% sorted into bins variablewise +% Note that since a particular draw (imf_h) can be below "imfloor" and above "imceiling" +% (=(imceiling-imfloor)*hbin), this function allows ninv+2 bins for each variable +% +% imfcnt: initial ninv+2-by-k matrix that records counts in each bin given a column in imfcnt +% if k==1, then only one variable is considered. +% imf_h: particular draw, needed not to be a 1-by-k row vector +% imfloor: the low value of imf but imf_h can be below "imfloor" and above "imceiling" +% hbin: bin size = (imceilling-imfloor)/ninv +% ninv: number of bins between "imfloor" and "imceiling" +%------------------ +% imfcnt: updated ninv+2-by-k matrix of counts (probability) +% +% January 1999 TAZ +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%** find the bin locations and arrange them to the order of 1, 2, ... +countInt = floor( (imf_h-imfloor) ./ hbin ); % imstp-by-nvar^2 + % bin locations from <0, 0, 1,..., ninv-1, >=ninv, a total of ninv+2 bins +countInt = 2+countInt(:)'; % row vector, 1-by-imstp*nvar^2, see my shock (1), pp.1 + % move everyting by 2 so as to take account of <0 + +countInt(find(countInt<2)) = 1; % set <0 or -infinity at 1 to start +countInt(find(countInt>=ninv+2)) = ninv+2; % set >=ninv+2 or +infinity at ninv+2 to end +countInt = countInt + (0:length(countInt)-1)*(ninv+2); % index to fill the matrix with prob. (counts) + % The term after "+": with every count, skip ninv+2 to keep + % each column in "imfcnt" with only one element (which is probability) +imfcnt(countInt) = imfcnt(countInt) + 1; diff --git a/MatlabFiles/errors.m b/MatlabFiles/errors.m index 09a5dd6f076aef483c335117d1bc8b0201c2635c..bcbd57b7c4185f3988125cf28805c51a2c1e3a29 100644 --- a/MatlabFiles/errors.m +++ b/MatlabFiles/errors.m @@ -1,102 +1,102 @@ -function [vd,str,imf] = errors(Bh,swish,nn) -% Computing variance decompositions and impulse functions with -% [vd,str,imf] = errors(Bh,swish,nn) -% where imf and vd is of the same format as in RATS, that is to say: -% Column: nvar responses to 1st shock, -% nvar responses to 2nd shock, and so on. -% Row: steps of impulse responses. -% vd: variance decompositions -% str: standard errors of each variable, steps-by-nvar -% imf: impulse response functions -% Bh is the estimated reduced form coefficient in the form -% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix -% form or dimension is the same as "Bh" from the function "sye"; -% swish is the inv(A0) in the structural model A(L)y(t) = e(t). -% nn is the numbers of inputs [nvar,lags,# of impulse responses]. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nvar = nn(1); -lags = nn(2); -imstep = nn(3); % number of steps for impulse responses - -Ah = Bh'; -% Row: nvar equations -% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. - -imf = zeros(imstep,nvar*nvar); -vd = imf; -% Column: nvar responses to 1st shock, nvar responses to 2nd shock, and so on. -% Row: steps of impulse responses. -str = zeros(imstep,nvar); % initializing standard errors of each equation -M = zeros(nvar*(lags+1),nvar); -% Stack lags M's in the order of, e.g., [Mlags, ..., M2,M1;M0] -M(1:nvar,:) = swish'; -Mtem = M(1:nvar,:); % temporary M -- impulse responses. -% -Mvd = Mtem.^2; % saved for the cumulative sum later -Mvds = (sum(Mvd'))'; -str(1,:) = sqrt(Mvds'); % standard errors of each equation -Mvds = Mvds(:,ones(size(Mvds,1),1)); -Mvdtem = (100.0*Mvd) ./ Mvds; % tempoary Mvd -- variance decompositions -% first or initial responses to -% one standard deviation shock (or forecast errors). -% Row: responses; Column: shocks -% -% * put in the form of "imf" -imf(1,:) = Mtem(:)'; -vd(1,:) = Mvdtem(:)'; - -t = 1; -ims1 = min([imstep-1 lags]); -while t <= ims1 - Mtem = Ah(:,1:nvar*t)*M(1:nvar*t,:); - % Row: nvar equations, each for the nvar variables at tth lag - M(nvar+1:nvar*(t+1),:)=M(1:nvar*t,:); - M(1:nvar,:) = Mtem; - % ** impulse response functions - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. - % ** variance decompositions - Mvd = Mvd + Mtem.^2; % saved for the cumulative sum later - Mvds = (sum(Mvd'))'; - str(t+1,:) = sqrt(Mvds'); % standard errors of each equation - Mvds = Mvds(:,ones(size(Mvds,1),1)); - Mvdtem = (100.0*Mvd) ./ Mvds; % tempoary Mvd -- variance decompositions - vd(t+1,:) = Mvdtem(:)'; - % stack vd with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. - t= t+1; -end - -for t = lags+1:imstep-1 - Mtem = Ah(:,1:nvar*lags)*M(1:nvar*lags,:); - % Row: nvar equations, each for the nvar variables at tth lag - M(nvar+1:nvar*(t+1),:) = M(1:nvar*t,:); - M(1:nvar,:)=Mtem; - % ** impulse response functions - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. - % ** variance decompositions - Mvd = Mvd + Mtem.^2; % saved for the cumulative sum later - Mvds = (sum(Mvd'))'; - str(t+1,:) = sqrt(Mvds'); % standard errors of each equation - Mvds = Mvds(:,ones(size(Mvds,1),1)); - Mvdtem = (100.0*Mvd) ./ Mvds; % tempoary Mvd -- variance decompositions - vd(t+1,:) = Mvdtem(:)'; - % stack vd with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. -end - +function [vd,str,imf] = errors(Bh,swish,nn) +% Computing variance decompositions and impulse functions with +% [vd,str,imf] = errors(Bh,swish,nn) +% where imf and vd is of the same format as in RATS, that is to say: +% Column: nvar responses to 1st shock, +% nvar responses to 2nd shock, and so on. +% Row: steps of impulse responses. +% vd: variance decompositions +% str: standard errors of each variable, steps-by-nvar +% imf: impulse response functions +% Bh is the estimated reduced form coefficient in the form +% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix +% form or dimension is the same as "Bh" from the function "sye"; +% swish is the inv(A0) in the structural model A(L)y(t) = e(t). +% nn is the numbers of inputs [nvar,lags,# of impulse responses]. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nvar = nn(1); +lags = nn(2); +imstep = nn(3); % number of steps for impulse responses + +Ah = Bh'; +% Row: nvar equations +% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. + +imf = zeros(imstep,nvar*nvar); +vd = imf; +% Column: nvar responses to 1st shock, nvar responses to 2nd shock, and so on. +% Row: steps of impulse responses. +str = zeros(imstep,nvar); % initializing standard errors of each equation +M = zeros(nvar*(lags+1),nvar); +% Stack lags M's in the order of, e.g., [Mlags, ..., M2,M1;M0] +M(1:nvar,:) = swish'; +Mtem = M(1:nvar,:); % temporary M -- impulse responses. +% +Mvd = Mtem.^2; % saved for the cumulative sum later +Mvds = (sum(Mvd'))'; +str(1,:) = sqrt(Mvds'); % standard errors of each equation +Mvds = Mvds(:,ones(size(Mvds,1),1)); +Mvdtem = (100.0*Mvd) ./ Mvds; % tempoary Mvd -- variance decompositions +% first or initial responses to +% one standard deviation shock (or forecast errors). +% Row: responses; Column: shocks +% +% * put in the form of "imf" +imf(1,:) = Mtem(:)'; +vd(1,:) = Mvdtem(:)'; + +t = 1; +ims1 = min([imstep-1 lags]); +while t <= ims1 + Mtem = Ah(:,1:nvar*t)*M(1:nvar*t,:); + % Row: nvar equations, each for the nvar variables at tth lag + M(nvar+1:nvar*(t+1),:)=M(1:nvar*t,:); + M(1:nvar,:) = Mtem; + % ** impulse response functions + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. + % ** variance decompositions + Mvd = Mvd + Mtem.^2; % saved for the cumulative sum later + Mvds = (sum(Mvd'))'; + str(t+1,:) = sqrt(Mvds'); % standard errors of each equation + Mvds = Mvds(:,ones(size(Mvds,1),1)); + Mvdtem = (100.0*Mvd) ./ Mvds; % tempoary Mvd -- variance decompositions + vd(t+1,:) = Mvdtem(:)'; + % stack vd with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. + t= t+1; +end + +for t = lags+1:imstep-1 + Mtem = Ah(:,1:nvar*lags)*M(1:nvar*lags,:); + % Row: nvar equations, each for the nvar variables at tth lag + M(nvar+1:nvar*(t+1),:) = M(1:nvar*t,:); + M(1:nvar,:)=Mtem; + % ** impulse response functions + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. + % ** variance decompositions + Mvd = Mvd + Mtem.^2; % saved for the cumulative sum later + Mvds = (sum(Mvd'))'; + str(t+1,:) = sqrt(Mvds'); % standard errors of each equation + Mvds = Mvds(:,ones(size(Mvds,1),1)); + Mvdtem = (100.0*Mvd) ./ Mvds; % tempoary Mvd -- variance decompositions + vd(t+1,:) = Mvdtem(:)'; + % stack vd with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. +end + diff --git a/MatlabFiles/fcstidcnd.m b/MatlabFiles/fcstidcnd.m index edce12ff627fafc1876e8773ffaf91b52c4ab303..e2bc7898746551c51f95177fd88726e47c305271 100644 --- a/MatlabFiles/fcstidcnd.m +++ b/MatlabFiles/fcstidcnd.m @@ -1,321 +1,322 @@ -function [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd(valuecon,stepcon,varcon,nstepsm,... - nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... - forep,TLindx,TLnumber,nCms,eq_Cms) -% [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd(valuecon,stepcon,varcon,nstepsm,... -% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... -% forep,TLindx,TLnumber,nCms,eq_Cms) -% -% Conditional forecasting in the identified model with or without error bands -% It handles conditions on average values as well, so "valuecon" must be -% expressed at average (NOT sum) level. -% Aband is used only once when nconstr>0 and Bband=1 where Gibbs sampler may be used -% Unconditional forecast when imf3s_h, etc is fixed and nconstr=0. -% -% valuecon: vector of values conditioned -% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition -% is then an arithmetic average of log(y) over the stepcon{i} period. -% varcon: vector of variables conditioned -% nconstr: number of DLS constraints -% nstepsm: maximum number of steps in all DLS constraints -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% Aband: 1: draws from A0 and Bh; 0: no draws -% Sband: 1: draws from random shocks E; 0: no random shocks -% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. -% In this case, set it to []; -% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses -% Never used when nconstr=0. In this case, set it to []; -% A0_h: A0 contemporaneous parameter matrix -% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% forep: # of forecast periods (e.g., monthly for a monthly model) -% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser -% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. -% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose -% nCms: # of LZ conditions -% eq_Cms: equation location of MS shocks -% ------ -% yhat: conditional forecasts: forep-by-nvar -% Estr: backed-out structural shocks (from N(0,1)) -% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) -% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that -% Rcon'*e = rcon where e is k-by-1 -% [u,d,v]: svd(Rcon,0) -% -%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r and k>=q -% -% Copyright (c) March 1998 by Tao Zha. Revised November 1998; -% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part -% 3/20/99 Added A0_h and forep and deleted Cms as input argument. Previous -% programs may not be compatible. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS - -impsteps=size(imf3s_h,1); -if (forep<nstepsm) | (impsteps<nstepsm) - disp('Increase # of forecast or impulse steps!!') - disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') - error('Maximum of conditional steps > # of forecast or impulse steps!!') -end -kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others - % are free. -%*** initializing -Rcon = zeros(kts,nconstr); % R: k-by-q -Econ = zeros(kts,1); % E: k-by-1 -rcon = zeros(nconstr,1); % r: q-by-1 -%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. -tcwc = nvar*lags; % total coefficients without constant -phi=phil; - - - -%---------------------------------------------------- -% Form rcon, Rcon, and Econ (the mean of structural shocks) -%---------------------------------------------------- -if nconstr - A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses - for i=1:nconstr - rcon(i)=length(stepcon{i})*valuecon(i) - ... - sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> - Rmat = zeros(nstepsm,nvar); - r2mat = zeros(nstepsm,1); % simply one identified equation - % Must be here inside the loop because it's matrix of one column of Rcon - for j=1:length(stepcon{i}) - if DLSIdShock % Assuming the Fed can't see all other shocks within a month - Rmat(1:stepcon{i}(j),eq_ms) = Rmat(1:stepcon{i}(j),eq_ms) + ... - imf3s_h(stepcon{i}(j):-1:1,eq_ms,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks except - % the identified one are set to zero) for a particular - % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - else % Rcon random with (A0,A+) - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks are - % *not* set to zero) for a particular endogenous - % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - end - end - Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error - % i.e. "OVERR" is not transposed when overlaid to "CAPR" - Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr - end - - [u d v]=svd(Rcon,0); %trial - %???? Can we reduce the time by computing inv(R'*R) directly? - % rtr = Rcon'*Rcon; %trial - % rtrinv = inv(Rcon'*Rcon); %trial - vd=v.*(ones(size(v,2),1)*diag(d)'); %trial - dinv = 1./diag(d); % inv(diag(d)) - vdinv=v.*(ones(size(v,2),1)*dinv'); %trial - rtr=vd*vd'; % R'*R - rtrinv = vdinv*vdinv'; % inv(R'*R) - - Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks -else - Econ = zeros(kts,1); % the mean of shocks is zero under no variable condition - Rcon = NaN; - rcon = NaN; - u = NaN; - d = NaN; - v = NaN; -end - - - -%--------------------------------------- -% No uncertainty at all or only random (A0,A+) -% In other words, no future shocks -%--------------------------------------- -if (~Sband) %| (nconstr & (length(eq_ms)==1)) - % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR - % if nstepsm==nconstr. If this condition does not hold, this procedure - % is incorrect. I don't have time to fix it now (3/20/99). So I use - % this as a proximation - Estr = reshape(Econ,nvar,nstepsm); - Estr = Estr'; % transpose so that - % Estr: structural shocks. Row--steps, Column--n shocks - Estr = [Estr;zeros(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - % - end - -%--------------------------------------- -% With random future shocks and possibly (A0,A+) depending -% on if imf3s_h is random -%--------------------------------------- -else - %-------------- - % Condition on variables and A random - %-------------- - if nconstr & Aband - warning(' ') - disp('This situation (both E and A random) is still under construction') - disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') - disp('Please press ctrl-c to abort') - pause - elseif nconstr - %-------------- - % Condition on variables and DLS MS shock, no A random but S random - %-------------- - if DLSIdShock % other shocks are indepedent of the eq_ms shock - % 3/20/99 The following may be problematic because Osk should depend - % on u (A0_h and Bh_h) in general. I haven't worked out any good version - %/* - % Osk = randn(kts,1); % other shocks - % for j=1:nstepsm - % Osk(nvar*(j-1)+eq_ms)=0; % no shock to the MS or identified equation - % end - % Estr = Econ + Osk; % Econ is non zero only at position - % % eq_ms*j where j=1:nstepsm - % Estr = reshape(Estr,nvar,nstepsm); - % Estr = Estr'; % transpose so that - % % Estr: structural shocks. Row--steps, Column--n shocks - % Estr = [Estr;randn(forep-nstepsm,nvar)]; - % % Now, forep-by-nvar -- ready for forecasts - % - disp('DLS') - Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - %[u1 d1 v1] = svd(Ome); % too slow - [u1 d1] = eig(Ome); - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % see Zha's forecast (1), p.17 - tmp1=zeros(nvar,nstepsm); - tmp1(eq_ms,:)=randn(1,nstepsm); - tmp2=tmp1(:); - %Estr1 = Econ + Stdcon*randn(kts,1); - %jnk = reshape(Stdcon*tmp2,nvar,nstepsm) - Estr1 = Econ + Stdcon*tmp2; - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - else - Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - %[u1 d1 v1] = svd(Ome); % too slow - [u1 d1] = eig(Ome); - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % see Zha's forecast (1), p.17 - %-------------- - % Condition on variables and LZ MS shock, no A random but S random - % This section has not be tested yet, 10/14/98 - %-------------- - if nCms - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - %-------------- - % Condition on variables only, no A random but S random - %-------------- - else - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - end - end - %-------------- - % Condition on LZ MS shocks only, S random and possibly A random depending on - % if A0_h and Bh_h are random - %-------------- - else - if nCms - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - else - Estr = randn(forep,nvar); % Unconditional forecast - % Now, forep-by-nvar -- ready for forecasts - end - end - % - - - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -end +function [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd(valuecon,stepcon,varcon,nstepsm,... + nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... + forep,TLindx,TLnumber,nCms,eq_Cms) +% [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd(valuecon,stepcon,varcon,nstepsm,... +% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... +% forep,TLindx,TLnumber,nCms,eq_Cms) +% +% Conditional forecasting in the identified model with or without error bands +% It handles conditions on average values as well, so "valuecon" must be +% expressed at average (NOT sum) level. +% Aband is used only once when nconstr>0 and Bband=1 where Gibbs sampler may be used +% Unconditional forecast when imf3s_h, etc is fixed and nconstr=0. +% +% valuecon: vector of values conditioned +% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition +% is then an arithmetic average of log(y) over the stepcon{i} period. +% varcon: vector of variables conditioned +% nconstr: number of DLS constraints +% nstepsm: maximum number of steps in all DLS constraints +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% Aband: 1: draws from A0 and Bh; 0: no draws +% Sband: 1: draws from random shocks E; 0: no random shocks +% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. +% In this case, set it to []; +% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses +% Never used when nconstr=0. In this case, set it to []; +% A0_h: A0 contemporaneous parameter matrix +% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% forep: # of forecast periods (e.g., monthly for a monthly model) +% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser +% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. +% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose +% nCms: # of LZ conditions +% eq_Cms: equation location of MS shocks +% ------ +% yhat: conditional forecasts: forep-by-nvar +% Estr: backed-out structural shocks (from N(0,1)) +% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) +% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that +% Rcon'*e = rcon where e is k-by-1 +% [u,d,v]: svd(Rcon,0) +% +%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r and k>=q +% +% Written by Tao Zha. Revised November 1998; +% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part +% 3/20/99 Added A0_h and forep and deleted Cms as input argument. Previous +% programs may not be compatible. +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS + +impsteps=size(imf3s_h,1); +if (forep<nstepsm) | (impsteps<nstepsm) + disp('Increase # of forecast or impulse steps!!') + disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') + error('Maximum of conditional steps > # of forecast or impulse steps!!') +end +kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others + % are free. +%*** initializing +Rcon = zeros(kts,nconstr); % R: k-by-q +Econ = zeros(kts,1); % E: k-by-1 +rcon = zeros(nconstr,1); % r: q-by-1 +%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. +tcwc = nvar*lags; % total coefficients without constant +phi=phil; + + + +%---------------------------------------------------- +% Form rcon, Rcon, and Econ (the mean of structural shocks) +%---------------------------------------------------- +if nconstr + A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses + for i=1:nconstr + rcon(i)=length(stepcon{i})*valuecon(i) - ... + sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> + Rmat = zeros(nstepsm,nvar); + r2mat = zeros(nstepsm,1); % simply one identified equation + % Must be here inside the loop because it's matrix of one column of Rcon + for j=1:length(stepcon{i}) + if DLSIdShock % Assuming the Fed can't see all other shocks within a month + Rmat(1:stepcon{i}(j),eq_ms) = Rmat(1:stepcon{i}(j),eq_ms) + ... + imf3s_h(stepcon{i}(j):-1:1,eq_ms,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks except + % the identified one are set to zero) for a particular + % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + else % Rcon random with (A0,A+) + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks are + % *not* set to zero) for a particular endogenous + % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + end + end + Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error + % i.e. "OVERR" is not transposed when overlaid to "CAPR" + Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr + end + + [u d v]=svd(Rcon,0); %trial + %???? Can we reduce the time by computing inv(R'*R) directly? + % rtr = Rcon'*Rcon; %trial + % rtrinv = inv(Rcon'*Rcon); %trial + vd=v.*(ones(size(v,2),1)*diag(d)'); %trial + dinv = 1./diag(d); % inv(diag(d)) + vdinv=v.*(ones(size(v,2),1)*dinv'); %trial + rtr=vd*vd'; % R'*R + rtrinv = vdinv*vdinv'; % inv(R'*R) + + Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks +else + Econ = zeros(kts,1); % the mean of shocks is zero under no variable condition + Rcon = NaN; + rcon = NaN; + u = NaN; + d = NaN; + v = NaN; +end + + + +%--------------------------------------- +% No uncertainty at all or only random (A0,A+) +% In other words, no future shocks +%--------------------------------------- +if (~Sband) %| (nconstr & (length(eq_ms)==1)) + % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR + % if nstepsm==nconstr. If this condition does not hold, this procedure + % is incorrect. I don't have time to fix it now (3/20/99). So I use + % this as a proximation + Estr = reshape(Econ,nvar,nstepsm); + Estr = Estr'; % transpose so that + % Estr: structural shocks. Row--steps, Column--n shocks + Estr = [Estr;zeros(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + % + end + +%--------------------------------------- +% With random future shocks and possibly (A0,A+) depending +% on if imf3s_h is random +%--------------------------------------- +else + %-------------- + % Condition on variables and A random + %-------------- + if nconstr & Aband + warning(' ') + disp('This situation (both E and A random) is still under construction') + disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') + disp('Please press ctrl-c to abort') + pause + elseif nconstr + %-------------- + % Condition on variables and DLS MS shock, no A random but S random + %-------------- + if DLSIdShock % other shocks are indepedent of the eq_ms shock + % 3/20/99 The following may be problematic because Osk should depend + % on u (A0_h and Bh_h) in general. I haven't worked out any good version + %/* + % Osk = randn(kts,1); % other shocks + % for j=1:nstepsm + % Osk(nvar*(j-1)+eq_ms)=0; % no shock to the MS or identified equation + % end + % Estr = Econ + Osk; % Econ is non zero only at position + % % eq_ms*j where j=1:nstepsm + % Estr = reshape(Estr,nvar,nstepsm); + % Estr = Estr'; % transpose so that + % % Estr: structural shocks. Row--steps, Column--n shocks + % Estr = [Estr;randn(forep-nstepsm,nvar)]; + % % Now, forep-by-nvar -- ready for forecasts + % + disp('DLS') + Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + %[u1 d1 v1] = svd(Ome); % too slow + [u1 d1] = eig(Ome); + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % see Zha's forecast (1), p.17 + tmp1=zeros(nvar,nstepsm); + tmp1(eq_ms,:)=randn(1,nstepsm); + tmp2=tmp1(:); + %Estr1 = Econ + Stdcon*randn(kts,1); + %jnk = reshape(Stdcon*tmp2,nvar,nstepsm) + Estr1 = Econ + Stdcon*tmp2; + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + else + Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + %[u1 d1 v1] = svd(Ome); % too slow + [u1 d1] = eig(Ome); + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % see Zha's forecast (1), p.17 + %-------------- + % Condition on variables and LZ MS shock, no A random but S random + % This section has not be tested yet, 10/14/98 + %-------------- + if nCms + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + %-------------- + % Condition on variables only, no A random but S random + %-------------- + else + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + end + end + %-------------- + % Condition on LZ MS shocks only, S random and possibly A random depending on + % if A0_h and Bh_h are random + %-------------- + else + if nCms + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + else + Estr = randn(forep,nvar); % Unconditional forecast + % Now, forep-by-nvar -- ready for forecasts + end + end + % + + + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +end diff --git a/MatlabFiles/fcstidcnd2.m b/MatlabFiles/fcstidcnd2.m index 081c52049838c6f557a29143efe4fa4e0f62a2d6..aa21a74156a801ffd6f9e293dc13371f941f89e8 100644 --- a/MatlabFiles/fcstidcnd2.m +++ b/MatlabFiles/fcstidcnd2.m @@ -1,358 +1,358 @@ -function [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... - nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... - forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) -% [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... -% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... -% forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) -% -% 5/2/99: This one is much, much slower than fidcnderr.m when eq_ms=[] and -% nconstr>0 and length(eq_ms)*nstepsm>nconstr. Seems to me that fcstidcnd2.m -% is designed for the situation which eq_ms=2. The slow speed is due to -% "Radd" added. When I have time, I need to check to see if I can speed up -% this M file. -% -% Conditional forecasting in the identified model with or without error bands -% It handles conditions on average values as well, so "valuecon" must be -% expressed at average (NOT sum) level. Including unconditional forecasts -% when nconstr=nCms=0. Maybe slower than "fcstidcnd.m" when length(eq_ms)*nstepsm=nconstr -% because of Radd added. But "fsctidcnd.m" is incorrect when length(eq_ms) -% *nstepsm>nconstr (situations like the average annual FFR constraint). 3/22/99 -% Ref.: Zha Forecast (I), pp. 17-17c. -% -% valuecon: vector of values conditioned -% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition -% is then an arithmetic average of log(y) over the stepcon{i} period. -% varcon: vector of variables conditioned -% nconstr: number of DLS constraints -% nstepsm: maximum number of steps in all DLS constraints -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% eq_ms: identified equation or shock (in terms of number). If equ_ms=[], then "fidencond" or -% 'fcstidcond' is, similar to RATS, to compute forecasts with *all* shocks. -% Aband: 1: draws from A0 and Bh; 0: no draws -% Sband: 1: draws from random shocks E; 0: no random shocks -% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. -% In this case, set it to []; -% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses -% Never used when nconstr=0. In this case, set it to []; -% A0_h: A0 contemporaneous parameter matrix -% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% forep: # of forecast periods (e.g., monthly for a monthly model) -% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser -% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. -% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose -% nCms: # of LZ conditions -% eq_Cms: equation location of MS shocks -% nconadd: number of DLS added constraints DIRECTLY on structural shocks -% for identified version where eq_ms is not empty. Note -% nconadd=0 when eq_ms is empty. -% eq_oth: index for other structural shocks than those in eq_ms. -% If eq_ms=[], eq_oth=[]. Note length(eq_oth)+length(eq_ms)=nvar -% radd: sparse nconadd-by-1; nconadd values added to rcon in the text later -% Radd: sparce nvar*nstepsm-by-nconadd; added to Rcon in the text later -% ------ -% yhat: conditional forecasts: forep-by-nvar -% Estr: backed-out structural shocks (from N(0,1)) -% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) -% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that -% Rcon'*e = rcon where e is k-by-1 -% [u,d,v]: svd(Rcon,0) -% -% Copyright (c) March 1998 by Tao Zha. Revised November 1998; -% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part -% 3/20/99 Added A0_h and forep and deleted Cms as input argument. -% 3/21/99 Added nconadd and eq_oth. -% Previous programs may not be compatible. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -% -%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. -%% See also Zha Forecast (I), pp. 17-17c. -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r and k>=q -% - - -DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS - -impsteps=size(imf3s_h,1); -if (forep<nstepsm) | (impsteps<nstepsm) - disp('Increase # of forecast or impulse steps!!') - disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') - error('Maximum of conditional steps > # of forecast or impulse steps!!') -end -kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others - % are free. -%*** initializing -Rcon = zeros(kts,nconstr); % R: k-by-q where q include possible additional - % constraints directly on structural shocks for identified models. - % These addtional constraints will be added later. -Econ = sparse(zeros(kts,1)); % E: k-by-1 -rcon = zeros(nconstr,1); % r: q-by-1 -%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. -tcwc = nvar*lags; % total coefficients without constant -phi=phil; - - - -%---------------------------------------------------- -% Form rcon, Rcon, and Econ (the mean of structural shocks) -%---------------------------------------------------- -if nconstr - A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses - for i=1:nconstr - rcon(i)=length(stepcon{i})*valuecon(i) - ... - sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> - Rmat = zeros(nstepsm,nvar); - % Must be here inside the loop because it's matrix of one column of Rcon - for j=1:length(stepcon{i}) - if DLSIdShock % Assuming the Fed can't see all other shocks within a month - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks except - % the identified one are set to zero) for a particular - % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - else % Rcon random with (A0,A+) - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks are - % *not* set to zero) for a particular endogenous - % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - end - end - Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error - % i.e. "OVERR" is not transposed when overlaid to "CAPR" - Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr - end - - rcon = [rcon;radd]; % added nconadd constrained values for identified model - % sparse because radd is sparse - Rcon = [Rcon Radd]; % added constraints on shocks for identified version - % sparse because Radd is sparse - Rcont=Rcon'; - rinvrtr=Rcon/(Rcont*Rcon); - Econ = rinvrtr*rcon; - - - %/* Too slow, I believe, when q is large. 3/21/99 - % [u d v]=svd(Rcon,0); %trial - % %???? Can we reduce the time by computing inv(R'*R) directly? - % % rtr = Rcon'*Rcon; %trial - % % rtrinv = inv(Rcon'*Rcon); %trial - % vd=v.*(ones(size(v,2),1)*diag(d)'); %trial - % dinv = 1./diag(d); % inv(diag(d)) - % vdinv=v.*(ones(size(v,2),1)*dinv'); %trial - % rtr=vd*vd'; % R'*R - % rtrinv = vdinv*vdinv'; % inv(R'*R) - % - % Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks -else - Econ = sparse(zeros(kts,1)); % the mean of shocks is zero under no variable condition - Rcon = NaN; - rcon = NaN; - u = NaN; - d = NaN; - v = NaN; -end - - - -%--------------------------------------- -% No uncertainty at all or only random (A0,A+) -% In other words, no future shocks -%--------------------------------------- -if (~Sband) | (nconstr & length(eq_ms)*nstepsm==nconstr) - % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR - % if nstepsm==nconstr. If this condition does not hold, this procedure - % is incorrect. I don't have time to fix it now (3/20/99). So I use - % this as a proximation - Estr = reshape(Econ,nvar,nstepsm); - Estr = Estr'; % transpose so that - % Estr: structural shocks. Row--steps, Column--n shocks - Estr = [Estr;zeros(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - % - end - -%--------------------------------------- -% With random future shocks and possibly (A0,A+) depending -% on if imf3s_h is random -%--------------------------------------- -else - %-------------- - % Condition on variables and A random - %-------------- - if nconstr & Aband - warning(' ') - disp('This situation (both E and A random) is still under construction') - disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') - disp('and related to "if DLSIdShock" in the following') - disp('Please press ctrl-c to abort') - pause - elseif nconstr - %-------------- - % Condition on variables and DLS MS shock, no A random but S random - %-------------- - if DLSIdShock % other shocks are indepedent of the eq_ms shock - Ome=speye(kts)-rinvrtr*Rcont; - Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it - % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very - % tight. After all, when the number in Ome is very small relative to - % 1 (which is the variance of structural shocks Estr), we can treat it - % as zero. - [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); - % We have exactly nconstr+nconadd zero singular values - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome - % see Zha's forecast (1), p.17 - Stdcon = [Stdcon sparse(zeros(kts,kts-size(d1,1)))]; - Estr1 = Econ + Stdcon*randn(kts,1); % We must have rand(kts,1). Assigning - % some of randn(kts,1) to be zero according to Radd is WRONG. - % For this argument, see Zha Forecast (I) p.17a - Estr2 = reshape(Estr1,nvar,nstepsm); - % nvar-by-nstepsm; Needed to be transposed later - Estr = [Estr2';randn(forep-nstepsm,nvar)]; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - % Now, forep-by-nvar -- ready for forecasts - else - Ome=speye(kts)-rinvrtr*Rcont; - Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it - % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very - % tight. After all, when the number in Ome is very small relative to - % 1 (which is the variance of structural shocks Estr), we can treat it - % as zero. - [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); - % We have exactly nconstr+nconadd zero singular values - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome - % see Zha's forecast (1), p.17 - Stdcon = [Stdcon sparse(zeros(kts,nconstr+nconadd))]; - - %*** The following very inefficient - % Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - % %[u1 d1 v1] = svd(Ome); % too slow - % [u1 d1] = eig(Ome); - % Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % % see Zha's forecast (1), p.17 - - %-------------- - % Condition on variables and LZ MS shock, no A random but S random - % This section has not be tested yet, 10/14/98 - %-------------- - if nCms - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - %-------------- - % Condition on variables only, no A random but S random - %-------------- - else - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - end - end - %-------------- - % Condition on LZ MS shocks only, S random and possibly A random depending on - % if A0_h and Bh_h are random - %-------------- - else - if nCms - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Estr(:,eq_Cms)=0; - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - else - Estr = randn(forep,nvar); % Unconditional forecast - % Now, forep-by-nvar -- ready for forecasts - end - end - % - - - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -end \ No newline at end of file +function [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... + nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... + forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) +% [yhat,Estr,rcon,Rcon,u,v,d] = fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... +% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... +% forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) +% +% 5/2/99: This one is much, much slower than fidcnderr.m when eq_ms=[] and +% nconstr>0 and length(eq_ms)*nstepsm>nconstr. Seems to me that fcstidcnd2.m +% is designed for the situation which eq_ms=2. The slow speed is due to +% "Radd" added. When I have time, I need to check to see if I can speed up +% this M file. +% +% Conditional forecasting in the identified model with or without error bands +% It handles conditions on average values as well, so "valuecon" must be +% expressed at average (NOT sum) level. Including unconditional forecasts +% when nconstr=nCms=0. Maybe slower than "fcstidcnd.m" when length(eq_ms)*nstepsm=nconstr +% because of Radd added. But "fsctidcnd.m" is incorrect when length(eq_ms) +% *nstepsm>nconstr (situations like the average annual FFR constraint). 3/22/99 +% Ref.: Zha Forecast (I), pp. 17-17c. +% +% valuecon: vector of values conditioned +% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition +% is then an arithmetic average of log(y) over the stepcon{i} period. +% varcon: vector of variables conditioned +% nconstr: number of DLS constraints +% nstepsm: maximum number of steps in all DLS constraints +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% eq_ms: identified equation or shock (in terms of number). If equ_ms=[], then "fidencond" or +% 'fcstidcond' is, similar to RATS, to compute forecasts with *all* shocks. +% Aband: 1: draws from A0 and Bh; 0: no draws +% Sband: 1: draws from random shocks E; 0: no random shocks +% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. +% In this case, set it to []; +% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses +% Never used when nconstr=0. In this case, set it to []; +% A0_h: A0 contemporaneous parameter matrix +% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% forep: # of forecast periods (e.g., monthly for a monthly model) +% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser +% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. +% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose +% nCms: # of LZ conditions +% eq_Cms: equation location of MS shocks +% nconadd: number of DLS added constraints DIRECTLY on structural shocks +% for identified version where eq_ms is not empty. Note +% nconadd=0 when eq_ms is empty. +% eq_oth: index for other structural shocks than those in eq_ms. +% If eq_ms=[], eq_oth=[]. Note length(eq_oth)+length(eq_ms)=nvar +% radd: sparse nconadd-by-1; nconadd values added to rcon in the text later +% Radd: sparce nvar*nstepsm-by-nconadd; added to Rcon in the text later +% ------ +% yhat: conditional forecasts: forep-by-nvar +% Estr: backed-out structural shocks (from N(0,1)) +% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) +% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that +% Rcon'*e = rcon where e is k-by-1 +% [u,d,v]: svd(Rcon,0) +% +% Written by Tao Zha March 1998. Revised November 1998; +% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part +% 3/20/99 Added A0_h and forep and deleted Cms as input argument. +% 3/21/99 Added nconadd and eq_oth. +% Previous programs may not be compatible. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +% +%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. +%% See also Zha Forecast (I), pp. 17-17c. +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r and k>=q +% + + +DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS + +impsteps=size(imf3s_h,1); +if (forep<nstepsm) | (impsteps<nstepsm) + disp('Increase # of forecast or impulse steps!!') + disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') + error('Maximum of conditional steps > # of forecast or impulse steps!!') +end +kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others + % are free. +%*** initializing +Rcon = zeros(kts,nconstr); % R: k-by-q where q include possible additional + % constraints directly on structural shocks for identified models. + % These addtional constraints will be added later. +Econ = sparse(zeros(kts,1)); % E: k-by-1 +rcon = zeros(nconstr,1); % r: q-by-1 +%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. +tcwc = nvar*lags; % total coefficients without constant +phi=phil; + + + +%---------------------------------------------------- +% Form rcon, Rcon, and Econ (the mean of structural shocks) +%---------------------------------------------------- +if nconstr + A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses + for i=1:nconstr + rcon(i)=length(stepcon{i})*valuecon(i) - ... + sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> + Rmat = zeros(nstepsm,nvar); + % Must be here inside the loop because it's matrix of one column of Rcon + for j=1:length(stepcon{i}) + if DLSIdShock % Assuming the Fed can't see all other shocks within a month + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks except + % the identified one are set to zero) for a particular + % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + else % Rcon random with (A0,A+) + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks are + % *not* set to zero) for a particular endogenous + % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + end + end + Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error + % i.e. "OVERR" is not transposed when overlaid to "CAPR" + Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr + end + + rcon = [rcon;radd]; % added nconadd constrained values for identified model + % sparse because radd is sparse + Rcon = [Rcon Radd]; % added constraints on shocks for identified version + % sparse because Radd is sparse + Rcont=Rcon'; + rinvrtr=Rcon/(Rcont*Rcon); + Econ = rinvrtr*rcon; + + + %/* Too slow, I believe, when q is large. 3/21/99 + % [u d v]=svd(Rcon,0); %trial + % %???? Can we reduce the time by computing inv(R'*R) directly? + % % rtr = Rcon'*Rcon; %trial + % % rtrinv = inv(Rcon'*Rcon); %trial + % vd=v.*(ones(size(v,2),1)*diag(d)'); %trial + % dinv = 1./diag(d); % inv(diag(d)) + % vdinv=v.*(ones(size(v,2),1)*dinv'); %trial + % rtr=vd*vd'; % R'*R + % rtrinv = vdinv*vdinv'; % inv(R'*R) + % + % Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks +else + Econ = sparse(zeros(kts,1)); % the mean of shocks is zero under no variable condition + Rcon = NaN; + rcon = NaN; + u = NaN; + d = NaN; + v = NaN; +end + + + +%--------------------------------------- +% No uncertainty at all or only random (A0,A+) +% In other words, no future shocks +%--------------------------------------- +if (~Sband) | (nconstr & length(eq_ms)*nstepsm==nconstr) + % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR + % if nstepsm==nconstr. If this condition does not hold, this procedure + % is incorrect. I don't have time to fix it now (3/20/99). So I use + % this as a proximation + Estr = reshape(Econ,nvar,nstepsm); + Estr = Estr'; % transpose so that + % Estr: structural shocks. Row--steps, Column--n shocks + Estr = [Estr;zeros(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + % + end + +%--------------------------------------- +% With random future shocks and possibly (A0,A+) depending +% on if imf3s_h is random +%--------------------------------------- +else + %-------------- + % Condition on variables and A random + %-------------- + if nconstr & Aband + warning(' ') + disp('This situation (both E and A random) is still under construction') + disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') + disp('and related to "if DLSIdShock" in the following') + disp('Please press ctrl-c to abort') + pause + elseif nconstr + %-------------- + % Condition on variables and DLS MS shock, no A random but S random + %-------------- + if DLSIdShock % other shocks are indepedent of the eq_ms shock + Ome=speye(kts)-rinvrtr*Rcont; + Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it + % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very + % tight. After all, when the number in Ome is very small relative to + % 1 (which is the variance of structural shocks Estr), we can treat it + % as zero. + [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); + % We have exactly nconstr+nconadd zero singular values + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome + % see Zha's forecast (1), p.17 + Stdcon = [Stdcon sparse(zeros(kts,kts-size(d1,1)))]; + Estr1 = Econ + Stdcon*randn(kts,1); % We must have rand(kts,1). Assigning + % some of randn(kts,1) to be zero according to Radd is WRONG. + % For this argument, see Zha Forecast (I) p.17a + Estr2 = reshape(Estr1,nvar,nstepsm); + % nvar-by-nstepsm; Needed to be transposed later + Estr = [Estr2';randn(forep-nstepsm,nvar)]; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + % Now, forep-by-nvar -- ready for forecasts + else + Ome=speye(kts)-rinvrtr*Rcont; + Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it + % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very + % tight. After all, when the number in Ome is very small relative to + % 1 (which is the variance of structural shocks Estr), we can treat it + % as zero. + [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); + % We have exactly nconstr+nconadd zero singular values + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome + % see Zha's forecast (1), p.17 + Stdcon = [Stdcon sparse(zeros(kts,nconstr+nconadd))]; + + %*** The following very inefficient + % Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + % %[u1 d1 v1] = svd(Ome); % too slow + % [u1 d1] = eig(Ome); + % Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % % see Zha's forecast (1), p.17 + + %-------------- + % Condition on variables and LZ MS shock, no A random but S random + % This section has not be tested yet, 10/14/98 + %-------------- + if nCms + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + %-------------- + % Condition on variables only, no A random but S random + %-------------- + else + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + end + end + %-------------- + % Condition on LZ MS shocks only, S random and possibly A random depending on + % if A0_h and Bh_h are random + %-------------- + else + if nCms + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Estr(:,eq_Cms)=0; + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + else + Estr = randn(forep,nvar); % Unconditional forecast + % Now, forep-by-nvar -- ready for forecasts + end + end + % + + + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +end diff --git a/MatlabFiles/fidcnderr.m b/MatlabFiles/fidcnderr.m index 979ae4e3a39cb348d158df4f777c9ea6e5db8b8a..5587dbf1ad5ba50ab571fefdb1368ee3917538fb 100644 --- a/MatlabFiles/fidcnderr.m +++ b/MatlabFiles/fidcnderr.m @@ -1,266 +1,265 @@ -function [yhat,Estr,rcon,Rcon,u,v,d] = fidcnderr(valuecon,stepcon,varcon,nconstr,... - nstepsm,nvar,lags,phil,eq_iden,Aband,Sband,yforeml,imf3sml,Bhml,... - yfore_h,imf3s_h,Bh_h,Cms,TLindx,TLnumber,nCms,eq_Cms) -%function [yhat,Estr,rcon,Rcon,u,v,d] = fidcnderr(valuecon,stepcon,varcon,nconstr,... -% nstepsm,nvar,lags,phil,eq_iden,Aband,Sband,yforeml,imf3sml,Bhml,... -% yfore_h,imf3s_h,Bh_h,Cms,TLindx,TLnumber,nCms,eq_Cms) -% To be done (8/25/98): (1) yforeml, imf3sml, and Bhml should not be there. -% (2) MS stuff need to be generalized. -% (3) perhaps, imf3s_h needs to be re-examined. -% Conditional forecasting in the identified model with one draw for error bands -% -% valuecon: vector of values conditioned -% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition -% is then an arithmetic average of log(y) over the stepcon{i} period. -% varcon: vector of variables conditioned -% nconstr: number of constraints -% nstepsm: maximum number of steps in all constraints -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% eq_iden: identified equation or shock (in terms of number). If equ_iden=[], then -% 'fidencond' is, similar to RATS, to compute forecasts with *all* shocks. -% Sband: 1: generate error bands from random shocks E; 0: no random shocks -% yfore: uncondtional forecasts: forep-by-nvar -% imf3s: 3-dimensional impulse responses matrix: -% impsteps-by-nvar shocks-by-nvar responses -% Bh: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% ------ -% yhat: conditional forecasts: forep-by-nvar -% Estr: backed-out structural shocks (from N(0,1)) -% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) -% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that -% Rcon'*e = rcon where e is k-by-1 -% [u,d,v]: svd(Rcon,0) -% -%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r. -% -% Copyright (c) March 1998 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -IdenShock = ~isempty(eq_iden); % if not empty, the shock is identified - -forep=size(yfore_h,1); -impsteps=size(imf3s_h,1); -if (forep<nstepsm) | (impsteps<nstepsm) - disp('Increase # of forecast or impulse steps!!') - disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') - error('Maximum of conditional steps > # of forecast or impulse steps!!') -end -kfs = nvar*nstepsm; % k -- fs: free shocks -%*** initializing -Rcon = zeros(kfs,nconstr); % R: k-by-q -Econ = zeros(kfs,1); % E: k-by-1 -rcon = zeros(nconstr,1); % r: q-by-1 -%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. -A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses - - -for i=1:nconstr - if IdenShock - rcon(i)=length(stepcon{i})*valuecon(i) - ... - sum(yforeml(stepcon{i},varcon(i)),1); % <<>> - else - rcon(i)=length(stepcon{i})*valuecon(i) - ... - sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> - end - Rmat = zeros(nstepsm,nvar); - r2mat = zeros(nstepsm,1); % simply one identified equation - % Must be here inside the loop because it's matrix of one column of Rcon - for j=1:length(stepcon{i}) - if IdenShock % Rcon only at ML; assuming the Fed can't see all other shocks - Rmat(1:stepcon{i}(j),eq_iden) = Rmat(1:stepcon{i}(j),eq_iden) + ... - imf3sml(stepcon{i}(j):-1:1,eq_iden,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks except - % the identified one are set to zero) for a particular - % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - else % Rcon random with (A0,A+) - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks are - % *not* set to zero) for a particular endogenous - % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - end - end - Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error - % i.e. "OVERR" is not transposed when overlaid to "CAPR" - Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr -end - -if nconstr - [u d v]=svd(Rcon,0); %trial - % rtr = Rcon'*Rcon; %trial - % rtrinv = inv(Rcon'*Rcon); %trial - vd=v.*(ones(size(v,2),1)*diag(d)'); %trial - dinv = 1./diag(d); % inv(diag(d)) - vdinv=v.*(ones(size(v,2),1)*dinv'); %trial - rtr=vd*vd'; % R'*R - rtrinv = vdinv*vdinv'; % inv(R'*R) - - Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; mean -else - Econ = zeros(kfs,1); - Rcon = NaN; - rcon = NaN; - u = NaN; - d = NaN; - v = NaN; -end - - -tcwc = nvar*lags; % total coefficients without constant -phi=phil; -phis=phil; % for exact backed out shocks -% -if (Sband==0) % no random or random only from (A0,A+) - Estr = reshape(Econ,nvar,nstepsm); - Estr = Estr'; % transpose so that - % Estr: structural shocks. Row--steps, Column--n shocks - Estr = [Estr;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Ures = Estr*A0in; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - % - end -else % random from shocks E and possibly (A0,A+) depending on if imf3s is random - if nconstr - if IdenShock % other shocks are indepedent of the eq_iden shock - Osk = randn(kfs,1); % other shocks - for j=1:nstepsm - Osk(nvar*(j-1)+eq_iden)=0; % no shock to the MS or identified equation - end - Estr = Econ + Osk; % Econ is non zero only at position - % eq_iden*j where j=1:nstepsm - else - Ome = eye(kfs) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - %[u1 d1 v1] = svd(Ome); % too slow - [u1 d1] = eig(Ome); - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % see Zha's forecast (1), p.17 - if Cms - if TLindx % tight - Estr1 = Econ + Stdcon*randn(kfs,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); - while ~isempty(Sindx) - Estr1 = Econ + Stdcon*randn(kfs,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); - end - else % loose - Estr1 = Econ + Stdcon*randn(kfs,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); - while ~isempty(Sindx) - Estr1 = Econ + Stdcon*randn(kfs,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); - end - end - else - Estr1 = Econ + Stdcon*randn(kfs,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - end - end - else - if Cms - if TLindx % tight - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); - while ~isempty(Sindx) - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); - end - else % loose - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); - while ~isempty(Sindx) - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); - end - end - else - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - end - end - % - %disp('HERE') - - Ures = Estr*A0in; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -end \ No newline at end of file +function [yhat,Estr,rcon,Rcon,u,v,d] = fidcnderr(valuecon,stepcon,varcon,nconstr,... + nstepsm,nvar,lags,phil,eq_iden,Aband,Sband,yforeml,imf3sml,Bhml,... + yfore_h,imf3s_h,Bh_h,Cms,TLindx,TLnumber,nCms,eq_Cms) +%function [yhat,Estr,rcon,Rcon,u,v,d] = fidcnderr(valuecon,stepcon,varcon,nconstr,... +% nstepsm,nvar,lags,phil,eq_iden,Aband,Sband,yforeml,imf3sml,Bhml,... +% yfore_h,imf3s_h,Bh_h,Cms,TLindx,TLnumber,nCms,eq_Cms) +% To be done (8/25/98): (1) yforeml, imf3sml, and Bhml should not be there. +% (2) MS stuff need to be generalized. +% (3) perhaps, imf3s_h needs to be re-examined. +% Conditional forecasting in the identified model with one draw for error bands +% +% valuecon: vector of values conditioned +% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition +% is then an arithmetic average of log(y) over the stepcon{i} period. +% varcon: vector of variables conditioned +% nconstr: number of constraints +% nstepsm: maximum number of steps in all constraints +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% eq_iden: identified equation or shock (in terms of number). If equ_iden=[], then +% 'fidencond' is, similar to RATS, to compute forecasts with *all* shocks. +% Sband: 1: generate error bands from random shocks E; 0: no random shocks +% yfore: uncondtional forecasts: forep-by-nvar +% imf3s: 3-dimensional impulse responses matrix: +% impsteps-by-nvar shocks-by-nvar responses +% Bh: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% ------ +% yhat: conditional forecasts: forep-by-nvar +% Estr: backed-out structural shocks (from N(0,1)) +% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) +% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that +% Rcon'*e = rcon where e is k-by-1 +% [u,d,v]: svd(Rcon,0) +% +%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r. +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +IdenShock = ~isempty(eq_iden); % if not empty, the shock is identified + +forep=size(yfore_h,1); +impsteps=size(imf3s_h,1); +if (forep<nstepsm) | (impsteps<nstepsm) + disp('Increase # of forecast or impulse steps!!') + disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') + error('Maximum of conditional steps > # of forecast or impulse steps!!') +end +kfs = nvar*nstepsm; % k -- fs: free shocks +%*** initializing +Rcon = zeros(kfs,nconstr); % R: k-by-q +Econ = zeros(kfs,1); % E: k-by-1 +rcon = zeros(nconstr,1); % r: q-by-1 +%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. +A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses + + +for i=1:nconstr + if IdenShock + rcon(i)=length(stepcon{i})*valuecon(i) - ... + sum(yforeml(stepcon{i},varcon(i)),1); % <<>> + else + rcon(i)=length(stepcon{i})*valuecon(i) - ... + sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> + end + Rmat = zeros(nstepsm,nvar); + r2mat = zeros(nstepsm,1); % simply one identified equation + % Must be here inside the loop because it's matrix of one column of Rcon + for j=1:length(stepcon{i}) + if IdenShock % Rcon only at ML; assuming the Fed can't see all other shocks + Rmat(1:stepcon{i}(j),eq_iden) = Rmat(1:stepcon{i}(j),eq_iden) + ... + imf3sml(stepcon{i}(j):-1:1,eq_iden,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks except + % the identified one are set to zero) for a particular + % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + else % Rcon random with (A0,A+) + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks are + % *not* set to zero) for a particular endogenous + % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + end + end + Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error + % i.e. "OVERR" is not transposed when overlaid to "CAPR" + Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr +end + +if nconstr + [u d v]=svd(Rcon,0); %trial + % rtr = Rcon'*Rcon; %trial + % rtrinv = inv(Rcon'*Rcon); %trial + vd=v.*(ones(size(v,2),1)*diag(d)'); %trial + dinv = 1./diag(d); % inv(diag(d)) + vdinv=v.*(ones(size(v,2),1)*dinv'); %trial + rtr=vd*vd'; % R'*R + rtrinv = vdinv*vdinv'; % inv(R'*R) + + Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; mean +else + Econ = zeros(kfs,1); + Rcon = NaN; + rcon = NaN; + u = NaN; + d = NaN; + v = NaN; +end + + +tcwc = nvar*lags; % total coefficients without constant +phi=phil; +phis=phil; % for exact backed out shocks +% +if (Sband==0) % no random or random only from (A0,A+) + Estr = reshape(Econ,nvar,nstepsm); + Estr = Estr'; % transpose so that + % Estr: structural shocks. Row--steps, Column--n shocks + Estr = [Estr;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Ures = Estr*A0in; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + % + end +else % random from shocks E and possibly (A0,A+) depending on if imf3s is random + if nconstr + if IdenShock % other shocks are indepedent of the eq_iden shock + Osk = randn(kfs,1); % other shocks + for j=1:nstepsm + Osk(nvar*(j-1)+eq_iden)=0; % no shock to the MS or identified equation + end + Estr = Econ + Osk; % Econ is non zero only at position + % eq_iden*j where j=1:nstepsm + else + Ome = eye(kfs) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + %[u1 d1 v1] = svd(Ome); % too slow + [u1 d1] = eig(Ome); + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % see Zha's forecast (1), p.17 + if Cms + if TLindx % tight + Estr1 = Econ + Stdcon*randn(kfs,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); + while ~isempty(Sindx) + Estr1 = Econ + Stdcon*randn(kfs,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); + end + else % loose + Estr1 = Econ + Stdcon*randn(kfs,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); + while ~isempty(Sindx) + Estr1 = Econ + Stdcon*randn(kfs,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); + end + end + else + Estr1 = Econ + Stdcon*randn(kfs,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + end + end + else + if Cms + if TLindx % tight + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); + while ~isempty(Sindx) + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)<TLnumber); + end + else % loose + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); + while ~isempty(Sindx) + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Sindx = find(Estr(1:nCms,eq_Cms)>TLnumber); + end + end + else + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + end + end + % + %disp('HERE') + + Ures = Estr*A0in; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +end diff --git a/MatlabFiles/fidcndexa.m b/MatlabFiles/fidcndexa.m index 1e4e478b93939ac1fd3e250c8f8ced30d8b04353..681a8365195800fdc4243ee422403aff93230c89 100644 --- a/MatlabFiles/fidcndexa.m +++ b/MatlabFiles/fidcndexa.m @@ -1,62 +1,62 @@ -function Estrexa = fidcndexa(yexa,phil,A0_h,Bh_h,nvar,lags) -% Estrexa = fidcndexa(yexa,phil,A0_h,Bh_h,nvar,lags) -% Exact structural shocks e(t) (backed out by conditioning on the path "yexa") -% -% yexa: actup-by-nvar. Actual data (all log except R, U, etc.) begin -% at nSample-actup+1 and ends at nSample, where nSample is the period -% for actual data (excluding dummy observations) -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags, prior to nSample-actup+1) -% A0_h: A0, column-equation; in the form of y(t)A0=X(t)A+ + e(t) -% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+u(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% ------ -% Estrexa: actup-by-nvar -- backed out exact shocks given parameter values -% where actup = length(yexa(:,1)). -% -%% See Zha's note "Forecast (2)" p.11 -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r. -% -% Copyright (c) April 1998 by Tao Zha -% Change the input arguments so that old programs may not be compatible, 03/19/98. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -tcwc = nvar*lags; % total coefficients without constant -actup = length(yexa(:,1)); % periods considered for structural shocks. -phis=phil; % for exact backed out shocks - -Estrsexa=zeros(actup,nvar); % backed out exact shocks - -for k=1:actup - Estrexa(k,:) = (yexa(k,:)-phis*Bh_h) * A0_h; - phis(nvar+1:tcwc) = phis(1:tcwc-nvar); - phis(1:nvar) = yexa(k,:); -end +function Estrexa = fidcndexa(yexa,phil,A0_h,Bh_h,nvar,lags) +% Estrexa = fidcndexa(yexa,phil,A0_h,Bh_h,nvar,lags) +% Exact structural shocks e(t) (backed out by conditioning on the path "yexa") +% +% yexa: actup-by-nvar. Actual data (all log except R, U, etc.) begin +% at nSample-actup+1 and ends at nSample, where nSample is the period +% for actual data (excluding dummy observations) +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags, prior to nSample-actup+1) +% A0_h: A0, column-equation; in the form of y(t)A0=X(t)A+ + e(t) +% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+u(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% ------ +% Estrexa: actup-by-nvar -- backed out exact shocks given parameter values +% where actup = length(yexa(:,1)). +% +%% See Zha's note "Forecast (2)" p.11 +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r. +% +% Written by Tao Zha April 1998 +% Change the input arguments so that old programs may not be compatible, 03/19/98. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +tcwc = nvar*lags; % total coefficients without constant +actup = length(yexa(:,1)); % periods considered for structural shocks. +phis=phil; % for exact backed out shocks + +Estrsexa=zeros(actup,nvar); % backed out exact shocks + +for k=1:actup + Estrexa(k,:) = (yexa(k,:)-phis*Bh_h) * A0_h; + phis(nvar+1:tcwc) = phis(1:tcwc-nvar); + phis(1:nvar) = yexa(k,:); +end diff --git a/MatlabFiles/fidencond.m b/MatlabFiles/fidencond.m index 4a5cb95fa4a1e619308513f7f44c8346341cd65d..5aa2c57d03a08356c29a547682c60a1ec6405847 100644 --- a/MatlabFiles/fidencond.m +++ b/MatlabFiles/fidencond.m @@ -1,192 +1,192 @@ -function [yhat,Estr,rcon,Ome,Rmat,u,v,d] = fidencond(valuecon,stepcon,varcon,nconstr,... - nstepsm,nvar,lags,yfore,imf3s,phil,Bh,eq_iden,steps_iden) -% Estimating conditional forecasting in the identified model -%function [yhat,Estr,rcon,Ome,Rmat,u,v,d] = fidencond(valuecon,stepcon,varcon,nconstr,... -% nstepsm,nvar,lags,yfore,imf3s,phil,Bh,eq_iden,steps_iden) -% -% valuecon: vector of values conditioned -% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition -% is then an arithmetic average of log(y) over the stepcon{i} period. -% varcon: vector of variables conditioned -% nconstr: number of constraints -% nstepsm: maximum number of steps in all constraints -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% yfore: uncondtional forecasts: forep-by-nvar -% imf3s: 3-dimensional impulse responses matrix: -% impsteps-by-nvar shocks-by-nvar responses -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% Bh: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% eq_iden: identified equation or shock (in terms of number). -% If eq_iden=[], then'fidencond' is, similar to RATS, to compute -% forecasts with *all* shocks. -% If length(eq_iden)=1, compute forecasts with only "MS" shocks. -% If eq_iden = [a b c], a is # of constraints for all shocks (<=nconstr), -% b is location of MS, and c is max steps for all shocks. -% My recall is that this option has never been tested 9/18/98 -% steps_iden: a vector (set) of steps for identified shocks. Valid only -% if length(eq_iden)=1. Note, length(steps_iden) must nconstr. -% ------ -% yhat: conditional forecasts: forep-by-nvar -% Estr: backed-out structural shocks (from N(0,1)) -% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) -% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that -% Rcon'*e = rcon where e is k-by-1, where k=nvar*nstepm -% Rmat: nstepsm-by-nvar (shocks), for only one constraint at a time. See Zha's -% Forecast (1), pp.5-6 -% Ome: k-by-k: covariance matrix of vectorized structural shocks vec(Estr) -% -% [u,d,v]: svd(Rcon,0) -% -%% See Zha's note "Forecast (1)" pp.5-7, RATS manual (some errors in RATS), etc. -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r. -% -% Copyright (c) February 1998 by Tao Zha -% NOTE: the code needs to be improved, 10/19/98 (use lzpaper/fcstidcnd.m for the time being). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%IdenShock = ~isempty(eq_iden); % if not empty, the shock is identified -forep=size(yfore,1); -impsteps=size(imf3s,1); -if (forep<nstepsm) | (impsteps<nstepsm) - disp('Increase # of forecast or impulse steps!!') - disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') - error('Maximum of conditional steps > # of forecast or impulse steps!!') - %warning - %return -end -if max(steps_iden) < nconstr - disp('Increase # of identified steps or decrease # of constraints') - error('length(steps_iden) > nconstr') -end - -kfs = nvar*nstepsm; % k -- fs: free shocks -%*** initializing -Rcon = zeros(kfs,nconstr); % R: k-by-q -Econ = zeros(kfs,1); % E: k-by-1 -rcon = zeros(nconstr,1); % r: q-by-1 -%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. -A0in = reshape(imf3s(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses - - -for i=1:nconstr - rcon(i)=valuecon(i)-mean(yfore(stepcon{i},varcon(i))); - %rcon(i)=valuecon(i)-sum(yfore(stepcon{i},varcon(i))); - Rmat = zeros(nstepsm,nvar); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks except - % the identified one are set to zero) for a particular - % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - r2mat = zeros(nstepsm,1); % simply one identified equation - % Must be here inside the loop because it's matrix of one column of Rcon - for j=1:length(stepcon{i}) - if (length(eq_iden)==1) - r2mat(1:stepcon{i}(j)) = r2mat(1:stepcon{i}(j)) + ... - imf3s(stepcon{i}(j):-1:1,eq_iden,varcon(i)); - elseif (length(eq_iden)>1) - if (i<=eq_iden(1)) - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s(stepcon{i}(j):-1:1,:,varcon(i)); - else - Rmat(1:eq_iden(3),:) = Rmat(1:eq_iden(3),:) + ... - imf3s(stepcon{i}(j):-1:stepcon{i}(j)-eq_iden(3)+1,:,varcon(i)); - - Rmat(eq_iden(3)+1:stepcon{i}(j),eq_iden(2)) = ... - Rmat(eq_iden(3)+1:stepcon{i}(j),eq_iden(2)) + ... - imf3s(stepcon{i}(j)-eq_iden(3):-1:1,eq_iden(2),varcon(i)); - end - else - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks are - % *not* set to zero) for a particular endogenous - % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - end - end - % - if (length(eq_iden)==1) - Rmat(steps_iden,eq_iden) = r2mat(steps_iden); % for only one constraint at a time - end - Rmat=Rmat/length(stepcon{i}); % <<>> - Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error - % i.e. "OVERR" is not transposed when overlaid to "CAPR" - Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr -end - -if nconstr - [u d v]=svd(Rcon,0); %trial. Rcon: k-by-q; u: k-by-q - % rtr = Rcon'*Rcon; %trial - % rtrinv = inv(Rcon'*Rcon); %trial - vd=v.*(ones(size(v,2),1)*diag(d)'); %trial - dinv = 1./diag(d); % inv(diag(d)) - vdinv=v.*(ones(size(v,2),1)*dinv'); %trial - rtr=vd*vd'; % R'*R - rtrinv = vdinv*vdinv'; % inv(R'*R) - Ome = eye(kfs) - u*u'; % note: I-u*u' = I - R*inv(R'*R)*R'; k-by-k - - Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; mean -else - Econ = zeros(kfs,1); - Rcon = NaN; - rcon = NaN; - u = NaN; - d = NaN; - v = NaN; -end - - -Estr = reshape(Econ,nvar,nstepsm); -Estr = Estr'; % transpose so that - % Estr: structural shocks. Row--steps, Column--n shocks -Ures = Estr*A0in; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks -%Ures = Estr*A0in; - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -% -tcwc = nvar*lags; % total coefficients without constant -phi=phil; -% -yhat = zeros(forep,nvar); -for k=1:forep - if (k<=nstepsm) - epsl = Ures(k,:); - yhat(k,:) = phi*Bh + epsl; - %yhat(k,:) = phi*Bh; - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - else - yhat(k,:) = phi*Bh; - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -end +function [yhat,Estr,rcon,Ome,Rmat,u,v,d] = fidencond(valuecon,stepcon,varcon,nconstr,... + nstepsm,nvar,lags,yfore,imf3s,phil,Bh,eq_iden,steps_iden) +% Estimating conditional forecasting in the identified model +%function [yhat,Estr,rcon,Ome,Rmat,u,v,d] = fidencond(valuecon,stepcon,varcon,nconstr,... +% nstepsm,nvar,lags,yfore,imf3s,phil,Bh,eq_iden,steps_iden) +% +% valuecon: vector of values conditioned +% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition +% is then an arithmetic average of log(y) over the stepcon{i} period. +% varcon: vector of variables conditioned +% nconstr: number of constraints +% nstepsm: maximum number of steps in all constraints +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% yfore: uncondtional forecasts: forep-by-nvar +% imf3s: 3-dimensional impulse responses matrix: +% impsteps-by-nvar shocks-by-nvar responses +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% Bh: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% eq_iden: identified equation or shock (in terms of number). +% If eq_iden=[], then'fidencond' is, similar to RATS, to compute +% forecasts with *all* shocks. +% If length(eq_iden)=1, compute forecasts with only "MS" shocks. +% If eq_iden = [a b c], a is # of constraints for all shocks (<=nconstr), +% b is location of MS, and c is max steps for all shocks. +% My recall is that this option has never been tested 9/18/98 +% steps_iden: a vector (set) of steps for identified shocks. Valid only +% if length(eq_iden)=1. Note, length(steps_iden) must nconstr. +% ------ +% yhat: conditional forecasts: forep-by-nvar +% Estr: backed-out structural shocks (from N(0,1)) +% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) +% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that +% Rcon'*e = rcon where e is k-by-1, where k=nvar*nstepm +% Rmat: nstepsm-by-nvar (shocks), for only one constraint at a time. See Zha's +% Forecast (1), pp.5-6 +% Ome: k-by-k: covariance matrix of vectorized structural shocks vec(Estr) +% +% [u,d,v]: svd(Rcon,0) +% +%% See Zha's note "Forecast (1)" pp.5-7, RATS manual (some errors in RATS), etc. +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r. +% +% NOTE: the code needs to be improved, 10/19/98 (use lzpaper/fcstidcnd.m for the time being). +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%IdenShock = ~isempty(eq_iden); % if not empty, the shock is identified +forep=size(yfore,1); +impsteps=size(imf3s,1); +if (forep<nstepsm) | (impsteps<nstepsm) + disp('Increase # of forecast or impulse steps!!') + disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') + error('Maximum of conditional steps > # of forecast or impulse steps!!') + %warning + %return +end +if max(steps_iden) < nconstr + disp('Increase # of identified steps or decrease # of constraints') + error('length(steps_iden) > nconstr') +end + +kfs = nvar*nstepsm; % k -- fs: free shocks +%*** initializing +Rcon = zeros(kfs,nconstr); % R: k-by-q +Econ = zeros(kfs,1); % E: k-by-1 +rcon = zeros(nconstr,1); % r: q-by-1 +%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. +A0in = reshape(imf3s(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses + + +for i=1:nconstr + rcon(i)=valuecon(i)-mean(yfore(stepcon{i},varcon(i))); + %rcon(i)=valuecon(i)-sum(yfore(stepcon{i},varcon(i))); + Rmat = zeros(nstepsm,nvar); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks except + % the identified one are set to zero) for a particular + % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + r2mat = zeros(nstepsm,1); % simply one identified equation + % Must be here inside the loop because it's matrix of one column of Rcon + for j=1:length(stepcon{i}) + if (length(eq_iden)==1) + r2mat(1:stepcon{i}(j)) = r2mat(1:stepcon{i}(j)) + ... + imf3s(stepcon{i}(j):-1:1,eq_iden,varcon(i)); + elseif (length(eq_iden)>1) + if (i<=eq_iden(1)) + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s(stepcon{i}(j):-1:1,:,varcon(i)); + else + Rmat(1:eq_iden(3),:) = Rmat(1:eq_iden(3),:) + ... + imf3s(stepcon{i}(j):-1:stepcon{i}(j)-eq_iden(3)+1,:,varcon(i)); + + Rmat(eq_iden(3)+1:stepcon{i}(j),eq_iden(2)) = ... + Rmat(eq_iden(3)+1:stepcon{i}(j),eq_iden(2)) + ... + imf3s(stepcon{i}(j)-eq_iden(3):-1:1,eq_iden(2),varcon(i)); + end + else + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks are + % *not* set to zero) for a particular endogenous + % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + end + end + % + if (length(eq_iden)==1) + Rmat(steps_iden,eq_iden) = r2mat(steps_iden); % for only one constraint at a time + end + Rmat=Rmat/length(stepcon{i}); % <<>> + Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error + % i.e. "OVERR" is not transposed when overlaid to "CAPR" + Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr +end + +if nconstr + [u d v]=svd(Rcon,0); %trial. Rcon: k-by-q; u: k-by-q + % rtr = Rcon'*Rcon; %trial + % rtrinv = inv(Rcon'*Rcon); %trial + vd=v.*(ones(size(v,2),1)*diag(d)'); %trial + dinv = 1./diag(d); % inv(diag(d)) + vdinv=v.*(ones(size(v,2),1)*dinv'); %trial + rtr=vd*vd'; % R'*R + rtrinv = vdinv*vdinv'; % inv(R'*R) + Ome = eye(kfs) - u*u'; % note: I-u*u' = I - R*inv(R'*R)*R'; k-by-k + + Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; mean +else + Econ = zeros(kfs,1); + Rcon = NaN; + rcon = NaN; + u = NaN; + d = NaN; + v = NaN; +end + + +Estr = reshape(Econ,nvar,nstepsm); +Estr = Estr'; % transpose so that + % Estr: structural shocks. Row--steps, Column--n shocks +Ures = Estr*A0in; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks +%Ures = Estr*A0in; + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +% +tcwc = nvar*lags; % total coefficients without constant +phi=phil; +% +yhat = zeros(forep,nvar); +for k=1:forep + if (k<=nstepsm) + epsl = Ures(k,:); + yhat(k,:) = phi*Bh + epsl; + %yhat(k,:) = phi*Bh; + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + else + yhat(k,:) = phi*Bh; + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +end diff --git a/MatlabFiles/find_betapar.m b/MatlabFiles/find_betapar.m index 7345cc4b7e8539118cc75879d36e1e4c65f959cd..bad7d275c66afdebeda366cde6fcc7dd8f1a0e76 100644 --- a/MatlabFiles/find_betapar.m +++ b/MatlabFiles/find_betapar.m @@ -1,59 +1,59 @@ -function [a, b, XLO, XUP] = find_betapar(XLO, XUP, PLO, PUP, a0, b0); - -% This function takes as inputs the bounds [XLO, XUP] in the support of the -% Beta distribution (with unknown parameters a and b), the -% probabilities of the bounds [PLO, PUP], and the initial values for ab=[a0, b0] -% and returns the estimates of a and b (as well as XLO and XUP) -% by solving the non-linear functions in betapar(ab, XLO, XUP, PLO, PUP). - -%----------------------------------------------------------------------------------- -%------------------------------- Beta distribution --------------------------------% -%--- p(x) = ( Gamma(a+b)/(Gamma(a)*Gamma(b)) ) x^(a-1) (1-x)^(b-1) -% = (1/Beta(a, b))x^(a-1) (1-x)^(b-1) for a>0 and b>0, and -% 0<=x<=1. -%--- E(x) = a/(a+b); var(x) = a*b/( (a+b)^2*(a+b+1) ); -%--- The density is finite if a,b>=1. -%--- Noninformative density: (1) a=b=1; (2) a=b=0.5; or (3) a=b=0. -%----------------------------------------------------------------------------------- -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if XLO >= XUP; - error('the lower bound needs to be smaller than the upper bound') -elseif XLO<=0 or XUP >=1; - error('the support for Beta distribution needs to be between 0 and 1'); -end; - -if a0 <= 0 || b0 <= 0; - error('the values for a and b need to be positive'); -end; - -disp(' ') -disp('*************** Convergence results for beta density ***************') -options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); -ab_values = fsolve('betapar', [a0, b0], options, XLO, XUP, PLO, PUP); -a = ab_values(1); b = ab_values(2); - -% Alternatively, it is possible to constrain the search for the values of a -% and b in the positive range (with 0 being the explicit lower bound) by -% using the lsqnonlin function (see below) instead of the fsolve. The -% tradeoff is that lsqnonlin is typically slower than fsolve. -% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; -% ab_values = lsqnonlin('betapar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... -% options, XLO, XUP, PLO, PUP); -% a = ab_values(1); b = ab_values(2); +function [a, b, XLO, XUP] = find_betapar(XLO, XUP, PLO, PUP, a0, b0); + +% This function takes as inputs the bounds [XLO, XUP] in the support of the +% Beta distribution (with unknown parameters a and b), the +% probabilities of the bounds [PLO, PUP], and the initial values for ab=[a0, b0] +% and returns the estimates of a and b (as well as XLO and XUP) +% by solving the non-linear functions in betapar(ab, XLO, XUP, PLO, PUP). + +%----------------------------------------------------------------------------------- +%------------------------------- Beta distribution --------------------------------% +%--- p(x) = ( Gamma(a+b)/(Gamma(a)*Gamma(b)) ) x^(a-1) (1-x)^(b-1) +% = (1/Beta(a, b))x^(a-1) (1-x)^(b-1) for a>0 and b>0, and +% 0<=x<=1. +%--- E(x) = a/(a+b); var(x) = a*b/( (a+b)^2*(a+b+1) ); +%--- The density is finite if a,b>=1. +%--- Noninformative density: (1) a=b=1; (2) a=b=0.5; or (3) a=b=0. +%----------------------------------------------------------------------------------- +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if XLO >= XUP; + error('the lower bound needs to be smaller than the upper bound') +elseif XLO<=0 or XUP >=1; + error('the support for Beta distribution needs to be between 0 and 1'); +end; + +if a0 <= 0 || b0 <= 0; + error('the values for a and b need to be positive'); +end; + +disp(' ') +disp('*************** Convergence results for beta density ***************') +options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); +ab_values = fsolve('betapar', [a0, b0], options, XLO, XUP, PLO, PUP); +a = ab_values(1); b = ab_values(2); + +% Alternatively, it is possible to constrain the search for the values of a +% and b in the positive range (with 0 being the explicit lower bound) by +% using the lsqnonlin function (see below) instead of the fsolve. The +% tradeoff is that lsqnonlin is typically slower than fsolve. +% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; +% ab_values = lsqnonlin('betapar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... +% options, XLO, XUP, PLO, PUP); +% a = ab_values(1); b = ab_values(2); diff --git a/MatlabFiles/find_gampar.m b/MatlabFiles/find_gampar.m index e008085db2b8843296fd4100a5740ef9ed657dcd..2659681ac68c73dd74c0c566dedcfb3a745dbac7 100644 --- a/MatlabFiles/find_gampar.m +++ b/MatlabFiles/find_gampar.m @@ -1,56 +1,56 @@ -function [a, b, XLO, XUP] = find_gampar(XLO, XUP, PLO, PUP, a0, b0); - -% This function takes as inputs the bounds [XLO, XUP] in the support of the -% gamma distribution (with parameters a and b), the probabilities of the -% bounds [PLO, PUP], and the initial values for ab=[a0, b0] -% and returns the estimates of a and b (as well as XLO and XUP) -% by solving the non-linear functions in gampar(ab, XLO, XUP, PLO, PUP).\ - -%---------------------------- Gamma distribution ----------------------------------% -%--- p(x) = ( 1/(b^a Gamma(a) ) x^(a-1) exp(-x/b) for a>0, b>0, and x>=0. -%--- where a is the shape and b is the scale parameter. -%--- E(x) = a b; var(x) = a b^2; -%--- Noninformative distribution: a,b -> 0. -%--- The density function is finite if a >= 1. -%----------------------------------------------------------------------------------- -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if XLO >= XUP; - error('the lower bound needs to be smaller than the upper bound') -elseif XLO<= 0; - error('the support for Gamma distribution needs to be non-negative'); -end; - -if a0 <= 0 || b0 <= 0; - error('the values for a0 and b0 need to be positive'); -end; - -disp(' ') -disp('*************** Convergence results for gamma density ***************') -options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); -ab_values = fsolve('gampar', [a0, b0], options, XLO, XUP, PLO, PUP); -a = ab_values(1); b = ab_values(2); - -% Alternatively, it is possible to constrain the search for the values of a -% and b in the positive range (with 0 being the explicit lower bound) by -% using the lsqnonlin function (see below) instead of the fsolve. The -% tradeoff is that lsqnonlin is typically slower than fsolve. -% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; -% ab_values = lsqnonlin('gampar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... -% options, XLO, XUP, PLO, PUP); -% a = ab_values(1); b = ab_values(2); +function [a, b, XLO, XUP] = find_gampar(XLO, XUP, PLO, PUP, a0, b0); + +% This function takes as inputs the bounds [XLO, XUP] in the support of the +% gamma distribution (with parameters a and b), the probabilities of the +% bounds [PLO, PUP], and the initial values for ab=[a0, b0] +% and returns the estimates of a and b (as well as XLO and XUP) +% by solving the non-linear functions in gampar(ab, XLO, XUP, PLO, PUP).\ + +%---------------------------- Gamma distribution ----------------------------------% +%--- p(x) = ( 1/(b^a Gamma(a) ) x^(a-1) exp(-x/b) for a>0, b>0, and x>=0. +%--- where a is the shape and b is the scale parameter. +%--- E(x) = a b; var(x) = a b^2; +%--- Noninformative distribution: a,b -> 0. +%--- The density function is finite if a >= 1. +%----------------------------------------------------------------------------------- +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if XLO >= XUP; + error('the lower bound needs to be smaller than the upper bound') +elseif XLO<= 0; + error('the support for Gamma distribution needs to be non-negative'); +end; + +if a0 <= 0 || b0 <= 0; + error('the values for a0 and b0 need to be positive'); +end; + +disp(' ') +disp('*************** Convergence results for gamma density ***************') +options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); +ab_values = fsolve('gampar', [a0, b0], options, XLO, XUP, PLO, PUP); +a = ab_values(1); b = ab_values(2); + +% Alternatively, it is possible to constrain the search for the values of a +% and b in the positive range (with 0 being the explicit lower bound) by +% using the lsqnonlin function (see below) instead of the fsolve. The +% tradeoff is that lsqnonlin is typically slower than fsolve. +% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; +% ab_values = lsqnonlin('gampar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... +% options, XLO, XUP, PLO, PUP); +% a = ab_values(1); b = ab_values(2); diff --git a/MatlabFiles/find_invgampar.m b/MatlabFiles/find_invgampar.m index 56e27a872714396db7663f7ee35310532e11e2ad..30b3338609f36c989cdff94a6d90a5306254a0da 100644 --- a/MatlabFiles/find_invgampar.m +++ b/MatlabFiles/find_invgampar.m @@ -1,57 +1,57 @@ -function [a, b, XLO, XUP] = find_invgampar(XLO, XUP, PLO, PUP, a0, b0); - -% This function takes as inputs the bounds [XLO, XUP] in the support of the -% Inverse Gamma distribution (with parameters a and b), the probabilities of the -% bounds [PLO, PUP], and the initial values for ab=[a0, b0] -% and returns the estimates of a and b (as well as XLO and XUP) -% by solving the non-linear functions in invgampar(ab, XLO, XUP, PLO, PUP).\ - -%----------------------------------------------------------------------------------- -%------------------------ Inverse-Gamma distribution ------------------------------% -%--- p(x) = ( b^a/Gamma(a) ) x^(-a-1) exp(-b/x) for a>0 and b>0. -%--- where a is shape and b is scale parameter. -%--- E(x) = b/(a-1) for a>1; var(x) = b^2/( (a-1)^2*(a-2) ) for a>2; -%--- Noninformative distribution: a,b -> 0. -%--- How to draw: (1) draw z from Gamma(a,b); (2) let x=1/z. -%----------------------------------------------------------------------------------- -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if XLO >= XUP; - error('the lower bound needs to be smaller than the upper bound') -elseif XLO<= 0; - error('the support for Gamma distribution needs to be non-negative'); -end; - -if a0 <= 0 || b0 <= 0; - error('the values for a and b need to be positive'); -end; - -disp(' ') -disp('*************** Convergence results for inverse gamma density ***************') -options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); -ab_values = fsolve('invgampar', [a0, b0], options, XLO, XUP, PLO, PUP); -a = ab_values(1); b = ab_values(2); - -% Alternatively, it is possible to constrain the search for the values of a -% and b in the positive range (with 0 being the explicit lower bound) by -% using the lsqnonlin function (see below) instead of the fsolve. The -% tradeoff is that lsqnonlin is typically slower than fsolve. -% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; -% ab_values = lsqnonlin('invgampar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... -% options, XLO, XUP, PLO, PUP); -% a = ab_values(1); b = ab_values(2); +function [a, b, XLO, XUP] = find_invgampar(XLO, XUP, PLO, PUP, a0, b0); + +% This function takes as inputs the bounds [XLO, XUP] in the support of the +% Inverse Gamma distribution (with parameters a and b), the probabilities of the +% bounds [PLO, PUP], and the initial values for ab=[a0, b0] +% and returns the estimates of a and b (as well as XLO and XUP) +% by solving the non-linear functions in invgampar(ab, XLO, XUP, PLO, PUP).\ + +%----------------------------------------------------------------------------------- +%------------------------ Inverse-Gamma distribution ------------------------------% +%--- p(x) = ( b^a/Gamma(a) ) x^(-a-1) exp(-b/x) for a>0 and b>0. +%--- where a is shape and b is scale parameter. +%--- E(x) = b/(a-1) for a>1; var(x) = b^2/( (a-1)^2*(a-2) ) for a>2; +%--- Noninformative distribution: a,b -> 0. +%--- How to draw: (1) draw z from Gamma(a,b); (2) let x=1/z. +%----------------------------------------------------------------------------------- +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if XLO >= XUP; + error('the lower bound needs to be smaller than the upper bound') +elseif XLO<= 0; + error('the support for Gamma distribution needs to be non-negative'); +end; + +if a0 <= 0 || b0 <= 0; + error('the values for a and b need to be positive'); +end; + +disp(' ') +disp('*************** Convergence results for inverse gamma density ***************') +options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); +ab_values = fsolve('invgampar', [a0, b0], options, XLO, XUP, PLO, PUP); +a = ab_values(1); b = ab_values(2); + +% Alternatively, it is possible to constrain the search for the values of a +% and b in the positive range (with 0 being the explicit lower bound) by +% using the lsqnonlin function (see below) instead of the fsolve. The +% tradeoff is that lsqnonlin is typically slower than fsolve. +% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; +% ab_values = lsqnonlin('invgampar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... +% options, XLO, XUP, PLO, PUP); +% a = ab_values(1); b = ab_values(2); diff --git a/MatlabFiles/find_normpar.m b/MatlabFiles/find_normpar.m index c39b7432102df739618a03814fe9bd73be8f3c81..b5ce545ac6d54b980a882bf88594bb6e00a7c182 100644 --- a/MatlabFiles/find_normpar.m +++ b/MatlabFiles/find_normpar.m @@ -1,47 +1,47 @@ -function [a, b, XLO, XUP] = find_normpar(XLO, XUP, PLO, PUP, a0, b0); - -% This function takes as inputs the bounds [XLO, XUP] in the support of the -% Normal distribution (with unknown parameters a = mean and b=standard deviation), the -% probabilities of the bounds [PLO, PUP], and the initial values for ab=[a0, b0] -% and returns the estimates of a and b (as well as XLO and XUP) -% by solving the non-linear functions in normpar(ab, XLO, XUP, PLO, PUP). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if XLO >= XUP; - error('the lower bound needs to be smaller than the upper bound') -end; - -if b0 <= 0; - error('the values for the standard deviation needs to be positive'); -end; - - -disp(' ') -disp('*************** Convergence results for normal density ***************') -options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); -ab_values = fsolve('normpar', [a0, b0], options, XLO, XUP, PLO, PUP); -a = ab_values(1); b = ab_values(2); - -% Alternatively, it is possible to constrain the search for the values of a -% and b in the positive range (with 0 being the explicit lower bound) by -% using the lsqnonlin function (see below) instead of the fsolve. The -% tradeoff is that lsqnonlin is typically slower than fsolve. -% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; -% ab_values = lsqnonlin('normpar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... -% options, XLO, XUP, PLO, PUP); -% a = ab_values(1); b = ab_values(2); +function [a, b, XLO, XUP] = find_normpar(XLO, XUP, PLO, PUP, a0, b0); + +% This function takes as inputs the bounds [XLO, XUP] in the support of the +% Normal distribution (with unknown parameters a = mean and b=standard deviation), the +% probabilities of the bounds [PLO, PUP], and the initial values for ab=[a0, b0] +% and returns the estimates of a and b (as well as XLO and XUP) +% by solving the non-linear functions in normpar(ab, XLO, XUP, PLO, PUP). +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if XLO >= XUP; + error('the lower bound needs to be smaller than the upper bound') +end; + +if b0 <= 0; + error('the values for the standard deviation needs to be positive'); +end; + + +disp(' ') +disp('*************** Convergence results for normal density ***************') +options = optimset('Display', 'on','TolFun', 1.0e-10, 'TolX', 1.0e-10); +ab_values = fsolve('normpar', [a0, b0], options, XLO, XUP, PLO, PUP); +a = ab_values(1); b = ab_values(2); + +% Alternatively, it is possible to constrain the search for the values of a +% and b in the positive range (with 0 being the explicit lower bound) by +% using the lsqnonlin function (see below) instead of the fsolve. The +% tradeoff is that lsqnonlin is typically slower than fsolve. +% LB_a = 0; LB_b = 0; UB_a = Inf; UB_b = Inf; +% ab_values = lsqnonlin('normpar', [a0, b0], [LB_a, LB_b], [UB_a, UB_b],... +% options, XLO, XUP, PLO, PUP); +% a = ab_values(1); b = ab_values(2); diff --git a/MatlabFiles/fn_a0cfreefun_tv.m b/MatlabFiles/fn_a0cfreefun_tv.m index d4a189ecf510b900b0214fb7d12d415929eaa19b..79feb2e01fdc2a4cb598ba1c7a756cc11b966a35 100644 --- a/MatlabFiles/fn_a0cfreefun_tv.m +++ b/MatlabFiles/fn_a0cfreefun_tv.m @@ -1,77 +1,77 @@ -function of = fn_a0cfreefun_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) -% of = fn_a0cfreefun_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) -% Negative logPosterior function for squeesed free A0 parameters (bar tv structural variances) in -% a new SZ time-varying model, which are vectorized as b's in the WZ notation. In other words, -% A0 parameters can be fully time varying, but the time varying structural variances will be -% excluded. It differs from fn_a0sfreefun*.m in several aspects: -% (a) can deal with equations with only structural variances time varying; -% (b) take care of lag restrictions; -% (c) conditional on the values of all other parameters including A+. -% Note: (1) columns correspond to equations; (2) c stands for constant or for an exclusion of -% time varying structural variances. -% See TBVAR NOTE p. 61. -% -% b: n0cumsum(end)-by-1 vector of free constant A0 parameters, vectorized from b_ihatcell. -% nvar: Number of endogeous variables. -% nStates: Number of states. -% n0cumsum: [0;cumsum(n0)] where n0 is nvar-by-1 and its ith element represents the number of -% free constant A0 parameters in ith equation for *all states*. -% Ui: nvar-by-1 cell. In each cell, nvar*nStates-by-(qi+si) orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters -% within the state and si is the number of free parameters across the states. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, -% averaged (ave) over E-step draws. For T_k. See p.61. In the Gibbs-Metropolis step, there is -% no need to make Tk the same as Tkave (See Chib and Jeliazkov 2001). -% Del00invcell_ave: Quardratic term for b0_j in each cell. See p.61. When fn_a0cfreegrad_tv.m is used, -% always make this systemetric by using (Del00invcell_ave'+Del00invcell_ave)/2. -% Also note that in the Gibbs-Metropolis step, there is no need to make Del00invcell the same -% as Del00invcell_ave (See Chib and Jeliazkov 2001). -% dpDelp0cell_ave: Cross d+_j and b0_j term in each cell. See p.61. In the Gibbs-Metropolis step, there is no need -% to make dpDelp0cell the same as dpDelp0cell_ave (See Chib and Jeliazkov 2001). -%---------------- -% of: Objective function (negative logPosterior). -% -% This function is called by szeml*.m which is a bettern program than tveml*.m. Thus, -% use this function in place of fn_a0sfreefun2.m if possible. -% See fn_a0cfreegrad_tv.m for analytical gradient for this function. -% -% Tao Zha, September 2001 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -A0_shat=zeros(nvar,nvar,nStates); % Arranged A0 matrix across states. - -tra = 0.0; -for kj = 1:nvar - bj = b(n0cumsum(kj)+1:n0cumsum(kj+1)); - A0_shat(:,kj,:) = reshape(Ui{kj}*bj,nvar,nStates); - tra = tra+0.5*( (bj'*Del00invcell_ave{kj})*bj - 2*dpDelp0cell_ave{kj}*bj ); % Negative exponential term -end - -ada=0.0; -for si=1:nStates % See p.34a. - [A0l,A0u] = lu(A0_shat(:,:,si)); - ada = ada - Tkave(si)*sum(log(abs(diag(A0u)))); % Negative log determinant of A0 raised to power T -end - -of = ada + tra; +function of = fn_a0cfreefun_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) +% of = fn_a0cfreefun_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) +% Negative logPosterior function for squeesed free A0 parameters (bar tv structural variances) in +% a new SZ time-varying model, which are vectorized as b's in the WZ notation. In other words, +% A0 parameters can be fully time varying, but the time varying structural variances will be +% excluded. It differs from fn_a0sfreefun*.m in several aspects: +% (a) can deal with equations with only structural variances time varying; +% (b) take care of lag restrictions; +% (c) conditional on the values of all other parameters including A+. +% Note: (1) columns correspond to equations; (2) c stands for constant or for an exclusion of +% time varying structural variances. +% See TBVAR NOTE p. 61. +% +% b: n0cumsum(end)-by-1 vector of free constant A0 parameters, vectorized from b_ihatcell. +% nvar: Number of endogeous variables. +% nStates: Number of states. +% n0cumsum: [0;cumsum(n0)] where n0 is nvar-by-1 and its ith element represents the number of +% free constant A0 parameters in ith equation for *all states*. +% Ui: nvar-by-1 cell. In each cell, nvar*nStates-by-(qi+si) orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters +% within the state and si is the number of free parameters across the states. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, +% averaged (ave) over E-step draws. For T_k. See p.61. In the Gibbs-Metropolis step, there is +% no need to make Tk the same as Tkave (See Chib and Jeliazkov 2001). +% Del00invcell_ave: Quardratic term for b0_j in each cell. See p.61. When fn_a0cfreegrad_tv.m is used, +% always make this systemetric by using (Del00invcell_ave'+Del00invcell_ave)/2. +% Also note that in the Gibbs-Metropolis step, there is no need to make Del00invcell the same +% as Del00invcell_ave (See Chib and Jeliazkov 2001). +% dpDelp0cell_ave: Cross d+_j and b0_j term in each cell. See p.61. In the Gibbs-Metropolis step, there is no need +% to make dpDelp0cell the same as dpDelp0cell_ave (See Chib and Jeliazkov 2001). +%---------------- +% of: Objective function (negative logPosterior). +% +% This function is called by szeml*.m which is a bettern program than tveml*.m. Thus, +% use this function in place of fn_a0sfreefun2.m if possible. +% See fn_a0cfreegrad_tv.m for analytical gradient for this function. +% +% Tao Zha, September 2001 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +A0_shat=zeros(nvar,nvar,nStates); % Arranged A0 matrix across states. + +tra = 0.0; +for kj = 1:nvar + bj = b(n0cumsum(kj)+1:n0cumsum(kj+1)); + A0_shat(:,kj,:) = reshape(Ui{kj}*bj,nvar,nStates); + tra = tra+0.5*( (bj'*Del00invcell_ave{kj})*bj - 2*dpDelp0cell_ave{kj}*bj ); % Negative exponential term +end + +ada=0.0; +for si=1:nStates % See p.34a. + [A0l,A0u] = lu(A0_shat(:,:,si)); + ada = ada - Tkave(si)*sum(log(abs(diag(A0u)))); % Negative log determinant of A0 raised to power T +end + +of = ada + tra; diff --git a/MatlabFiles/fn_a0cfreegrad_tv.m b/MatlabFiles/fn_a0cfreegrad_tv.m index 5bea42ff1ca68995303776cbef069195614ea673..29b0493a52abd58db424efdc4ad2549ce3e401cc 100644 --- a/MatlabFiles/fn_a0cfreegrad_tv.m +++ b/MatlabFiles/fn_a0cfreegrad_tv.m @@ -1,72 +1,72 @@ -function [g,badg] = fn_a0cfreegrad_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) -% [g,badg] = fn_a0cfreegrad_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) -% Analytical gradient for fn_a0cfreegrad_tv.m when using csminwel.m. -% Note: (1) columns correspond to equations; (2) c stands for constant. -% See TBVAR NOTE pp. 61-62, 34a-34c. -% -% b: n0cumsum(end)-by-1 vector of free constant A0 parameters, vectorized from b_ihatcell. -% nvar: Number of endogeous variables. -% nStates: Number of states. -% n0cumsum: [0;cumsum(n0)] where n0 is nvar-by-1 and its ith element represents the number of -% free constant A0 parameters in ith equation for *all states*. -% Ui: nvar-by-1 cell. In each cell, nvar*nStates-by-(qi+si) orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters -% within the state and si is the number of free parameters across the states. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, -% averaged (ave) over E-step draws. For T_k. See p.61. -% Del00invcell_ave: Quardratic term for b0_j in each cell. See p.61. -% dpDelp0cell_ave: Cross d+_j and b0_j term in each cell. See p.61. -%---------------- -% g: n0cumsum(end)-by-1 analytical gradient for fn_a0cfreegrad_tv.m. -% badg: 0, the value that is used in csminwel.m. -% -% Tao Zha, September 2001 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -A0_shat=zeros(nvar,nvar,nStates); % Arranged A0 matrix across states. -B_shat=zeros(nvar,nvar,nStates); % inv(A0_shat); - -badg = 0; -g = zeros(size(b(:))); - -%**** The derivative of the exponential term w.r.t. each free constanta A0 paramater. See pp. 34a and 62. -for kj = 1:nvar - indxn0j = [n0cumsum(kj)+1:n0cumsum(kj+1)]; % Index for the parameters in the ith equation. - bj = b(indxn0j); - g(indxn0j) = Del00invcell_ave{kj}*bj - dpDelp0cell_ave{kj}'; - A0_shat(:,kj,:) = reshape(Ui{kj}*bj,nvar,nStates); -end - - -%for si=1:nStates % See p.34a. - -%end -%**** Add the derivative of -Tk_ave*log|A0(k)| w.r.t. each free constanta A0 paramater. See pp. 62 and 34a. -for kj = 1:nvar - indxn0j = [n0cumsum(kj)+1:n0cumsum(kj+1)]; % Index for the parameters in the ith equation. - for si=1:nStates % See p.34a. - B_shat(:,:,si)=inv(A0_shat(:,:,si)); % See p.62. - g(indxn0j) = g(indxn0j) - Tkave(si)*( B_shat(kj,:,si)*Ui{kj}((si-1)*nvar+1:si*nvar,:) )'; % See p.62. - end -end - +function [g,badg] = fn_a0cfreegrad_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) +% [g,badg] = fn_a0cfreegrad_tv(b,nvar,nStates,n0cumsum,Ui,Tkave,Del00invcell_ave,dpDelp0cell_ave) +% Analytical gradient for fn_a0cfreegrad_tv.m when using csminwel.m. +% Note: (1) columns correspond to equations; (2) c stands for constant. +% See TBVAR NOTE pp. 61-62, 34a-34c. +% +% b: n0cumsum(end)-by-1 vector of free constant A0 parameters, vectorized from b_ihatcell. +% nvar: Number of endogeous variables. +% nStates: Number of states. +% n0cumsum: [0;cumsum(n0)] where n0 is nvar-by-1 and its ith element represents the number of +% free constant A0 parameters in ith equation for *all states*. +% Ui: nvar-by-1 cell. In each cell, nvar*nStates-by-(qi+si) orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters +% within the state and si is the number of free parameters across the states. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, +% averaged (ave) over E-step draws. For T_k. See p.61. +% Del00invcell_ave: Quardratic term for b0_j in each cell. See p.61. +% dpDelp0cell_ave: Cross d+_j and b0_j term in each cell. See p.61. +%---------------- +% g: n0cumsum(end)-by-1 analytical gradient for fn_a0cfreegrad_tv.m. +% badg: 0, the value that is used in csminwel.m. +% +% Tao Zha, September 2001 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +A0_shat=zeros(nvar,nvar,nStates); % Arranged A0 matrix across states. +B_shat=zeros(nvar,nvar,nStates); % inv(A0_shat); + +badg = 0; +g = zeros(size(b(:))); + +%**** The derivative of the exponential term w.r.t. each free constanta A0 paramater. See pp. 34a and 62. +for kj = 1:nvar + indxn0j = [n0cumsum(kj)+1:n0cumsum(kj+1)]; % Index for the parameters in the ith equation. + bj = b(indxn0j); + g(indxn0j) = Del00invcell_ave{kj}*bj - dpDelp0cell_ave{kj}'; + A0_shat(:,kj,:) = reshape(Ui{kj}*bj,nvar,nStates); +end + + +%for si=1:nStates % See p.34a. + +%end +%**** Add the derivative of -Tk_ave*log|A0(k)| w.r.t. each free constanta A0 paramater. See pp. 62 and 34a. +for kj = 1:nvar + indxn0j = [n0cumsum(kj)+1:n0cumsum(kj+1)]; % Index for the parameters in the ith equation. + for si=1:nStates % See p.34a. + B_shat(:,:,si)=inv(A0_shat(:,:,si)); % See p.62. + g(indxn0j) = g(indxn0j) - Tkave(si)*( B_shat(kj,:,si)*Ui{kj}((si-1)*nvar+1:si*nvar,:) )'; % See p.62. + end +end + diff --git a/MatlabFiles/fn_a0freefun.m b/MatlabFiles/fn_a0freefun.m index 9c1cbb415fb6e99a9ddff3599304767e9054ad01..0e776e420a9965f3470028ab5232aea9288e3dc1 100644 --- a/MatlabFiles/fn_a0freefun.m +++ b/MatlabFiles/fn_a0freefun.m @@ -1,55 +1,55 @@ -function of = fn_a0freefun(b,Ui,nvar,n0,fss,H0inv) -% of = fn_a0freefun(b,Ui,nvar,n0,fss,H0inv) -% -% Negative logPosterior function for squeesed A0 free parameters, which are b's in the WZ notation -% Note: columns correspond to equations -% -% b: sum(n0)-by-1 vector of A0 free parameters -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -% fss: nSample-lags (plus ndobs if dummies are included) -% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, -% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. -%---------------- -% of: objective function (negative logPosterior) -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -b=b(:); n0=n0(:); - -A0 = zeros(nvar); -n0cum = [0;cumsum(n0)]; -tra = 0.0; -for kj = 1:nvar - bj = b(n0cum(kj)+1:n0cum(kj+1)); - A0(:,kj) = Ui{kj}*bj; - tra = tra + 0.5*bj'*H0inv{kj}*bj; % negative exponential term -end - -[A0l,A0u] = lu(A0); - -ada = -fss*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T - -of = ada + tra; +function of = fn_a0freefun(b,Ui,nvar,n0,fss,H0inv) +% of = fn_a0freefun(b,Ui,nvar,n0,fss,H0inv) +% +% Negative logPosterior function for squeesed A0 free parameters, which are b's in the WZ notation +% Note: columns correspond to equations +% +% b: sum(n0)-by-1 vector of A0 free parameters +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +% fss: nSample-lags (plus ndobs if dummies are included) +% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, +% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. +%---------------- +% of: objective function (negative logPosterior) +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +b=b(:); n0=n0(:); + +A0 = zeros(nvar); +n0cum = [0;cumsum(n0)]; +tra = 0.0; +for kj = 1:nvar + bj = b(n0cum(kj)+1:n0cum(kj+1)); + A0(:,kj) = Ui{kj}*bj; + tra = tra + 0.5*bj'*H0inv{kj}*bj; % negative exponential term +end + +[A0l,A0u] = lu(A0); + +ada = -fss*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T + +of = ada + tra; diff --git a/MatlabFiles/fn_a0freegrad.m b/MatlabFiles/fn_a0freegrad.m index 638db31417d89aef616c41d15f75f9532b05e4bd..ea3d1a05d2f995e3a8b895ae9e724c5ab5f9addb 100644 --- a/MatlabFiles/fn_a0freegrad.m +++ b/MatlabFiles/fn_a0freegrad.m @@ -1,59 +1,59 @@ -function [g,badg] = fn_a0freegrad(b,Ui,nvar,n0,fss,H0inv) -% [g,badg] = a0freegrad(b,Ui,nvar,n0,fss,H0inv) -% Analytical gradient for a0freefun.m in use of csminwel.m. See Dhrymes's book. -% -% b: sum(n0)-by-1 vector of A0 free parameters -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -% fss: nSample-lags (plus ndobs if dummies are included) -% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, -% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. -%--------------- -% g: sum(n0)-by-1 analytical gradient for a0freefun.m -% badg: 0, the value that is used in csminwel.m -% -% Tao Zha, February 2000. Revised, August 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -b=b(:); n0 = n0(:); - -A0 = zeros(nvar); -n0cum = [0;cumsum(n0)]; -g = zeros(n0cum(end),1); -badg = 0; - -%*** The derivative of the exponential term w.r.t. each free paramater -for kj = 1:nvar - bj = b(n0cum(kj)+1:n0cum(kj+1)); - g(n0cum(kj)+1:n0cum(kj+1)) = H0inv{kj}*bj; - A0(:,kj) = Ui{kj}*bj; -end -B=inv(A0'); - -%*** Add the derivative of -Tlog|A0| w.r.t. each free paramater -for ki = 1:sum(n0) - n = max(find( (ki-n0cum)>0 )); % note, 1<=n<=nvar - g(ki) = g(ki) - fss*B(:,n)'*Ui{n}(:,ki-n0cum(n)); -end +function [g,badg] = fn_a0freegrad(b,Ui,nvar,n0,fss,H0inv) +% [g,badg] = a0freegrad(b,Ui,nvar,n0,fss,H0inv) +% Analytical gradient for a0freefun.m in use of csminwel.m. See Dhrymes's book. +% +% b: sum(n0)-by-1 vector of A0 free parameters +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +% fss: nSample-lags (plus ndobs if dummies are included) +% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, +% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. +%--------------- +% g: sum(n0)-by-1 analytical gradient for a0freefun.m +% badg: 0, the value that is used in csminwel.m +% +% Tao Zha, February 2000. Revised, August 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +b=b(:); n0 = n0(:); + +A0 = zeros(nvar); +n0cum = [0;cumsum(n0)]; +g = zeros(n0cum(end),1); +badg = 0; + +%*** The derivative of the exponential term w.r.t. each free paramater +for kj = 1:nvar + bj = b(n0cum(kj)+1:n0cum(kj+1)); + g(n0cum(kj)+1:n0cum(kj+1)) = H0inv{kj}*bj; + A0(:,kj) = Ui{kj}*bj; +end +B=inv(A0'); + +%*** Add the derivative of -Tlog|A0| w.r.t. each free paramater +for ki = 1:sum(n0) + n = max(find( (ki-n0cum)>0 )); % note, 1<=n<=nvar + g(ki) = g(ki) - fss*B(:,n)'*Ui{n}(:,ki-n0cum(n)); +end diff --git a/MatlabFiles/fn_a0sfreefun.m b/MatlabFiles/fn_a0sfreefun.m index 3f5144f65da3f762ea146faba7a501d35f342622..1f75812a620b82f98780e66baa9f0e0d178e9648 100644 --- a/MatlabFiles/fn_a0sfreefun.m +++ b/MatlabFiles/fn_a0sfreefun.m @@ -1,76 +1,76 @@ -function of = fn_a0sfreefun(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) -% of = fn_a0sfreefun(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) -% Negative logPosterior function for regime-switching squeesed free A0 parameters, -% which are b's in the WZ notation. The case of no asymmetric prior and no lag restrictions. -% Note: (1) columns correspond to equations; s stands for state. -% See TBVAR NOTE pp.34-34a,38. -% -% b: sum(n0)*nStates-by-1 vector of free A0 parameters, vectorized from the sum(n0)-by-nStates matrix. -% Uistar: cell(nvar,1). In each cell, nvar*nSates-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. See p.33. -% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged -% from Uistar or Ui. See p.33. This is NOT used for this function, but serves as an argument -% to keep it compatible with fn_a0sfreegrad.m which uses it. -% nvar: Number of endogeous variables. -% nStates: NUmber of states. -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation for each state. -% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, -% averaged (ave) over E-step draws. For T_k. See p.38. -% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) -% over E-step draws. Same for all equations because of no asymmetric prior and no lag -% restrictions. Resembles old SpH in the exponent term in posterior of A0, -% but NOT divided by fss (T) yet. See p.38. -%---------------- -% of: Objective function (negative logPosterior). -% -% This function is a special case of fn_a0sfreefun2.m. -% Tao Zha, March 2001 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -n0=n0(:); -A0=zeros(nvar,nvar,nStates); -n0cum = [0;cumsum(n0)]; -b=reshape(b,n0cum(end),nStates); - -tra = 0.0; -for kj = 1:nvar - lenbjs=length(n0cum(kj)+1:n0cum(kj+1)); - bj = zeros(nStates*lenbjs,1); - a0j = zeros(nStates*nvar,1); % See p.33. - for si=1:nStates - bj((si-1)*lenbjs+1:si*lenbjs) = b(n0cum(kj)+1:n0cum(kj+1),si); % bj(si). See p.34a. - A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b(n0cum(kj)+1:n0cum(kj+1),si); - a0j((si-1)*nvar+1:si*nvar) = A0(:,kj,si); % a0j(si). See p.33. - end - %tra = tra + 0.5*a0j'*Sgm0tldinvave*a0j; % negative exponential term - tra = tra+0.5*bj'*(Uibar{kj}'*Sgm0tldinvave*Uibar{kj})*bj; -end - -ada=0.0; -for si=1:nStates % See p.34a. - [A0l,A0u] = lu(A0(:,:,si)); - ada = ada - Tkave(si)*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T -end - -of = ada + tra; +function of = fn_a0sfreefun(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) +% of = fn_a0sfreefun(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) +% Negative logPosterior function for regime-switching squeesed free A0 parameters, +% which are b's in the WZ notation. The case of no asymmetric prior and no lag restrictions. +% Note: (1) columns correspond to equations; s stands for state. +% See TBVAR NOTE pp.34-34a,38. +% +% b: sum(n0)*nStates-by-1 vector of free A0 parameters, vectorized from the sum(n0)-by-nStates matrix. +% Uistar: cell(nvar,1). In each cell, nvar*nSates-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. See p.33. +% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged +% from Uistar or Ui. See p.33. This is NOT used for this function, but serves as an argument +% to keep it compatible with fn_a0sfreegrad.m which uses it. +% nvar: Number of endogeous variables. +% nStates: NUmber of states. +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation for each state. +% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, +% averaged (ave) over E-step draws. For T_k. See p.38. +% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) +% over E-step draws. Same for all equations because of no asymmetric prior and no lag +% restrictions. Resembles old SpH in the exponent term in posterior of A0, +% but NOT divided by fss (T) yet. See p.38. +%---------------- +% of: Objective function (negative logPosterior). +% +% This function is a special case of fn_a0sfreefun2.m. +% Tao Zha, March 2001 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +n0=n0(:); +A0=zeros(nvar,nvar,nStates); +n0cum = [0;cumsum(n0)]; +b=reshape(b,n0cum(end),nStates); + +tra = 0.0; +for kj = 1:nvar + lenbjs=length(n0cum(kj)+1:n0cum(kj+1)); + bj = zeros(nStates*lenbjs,1); + a0j = zeros(nStates*nvar,1); % See p.33. + for si=1:nStates + bj((si-1)*lenbjs+1:si*lenbjs) = b(n0cum(kj)+1:n0cum(kj+1),si); % bj(si). See p.34a. + A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b(n0cum(kj)+1:n0cum(kj+1),si); + a0j((si-1)*nvar+1:si*nvar) = A0(:,kj,si); % a0j(si). See p.33. + end + %tra = tra + 0.5*a0j'*Sgm0tldinvave*a0j; % negative exponential term + tra = tra+0.5*bj'*(Uibar{kj}'*Sgm0tldinvave*Uibar{kj})*bj; +end + +ada=0.0; +for si=1:nStates % See p.34a. + [A0l,A0u] = lu(A0(:,:,si)); + ada = ada - Tkave(si)*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T +end + +of = ada + tra; diff --git a/MatlabFiles/fn_a0sfreefun2.m b/MatlabFiles/fn_a0sfreefun2.m index ffc2f441ecd76456bbf78df22740b5d50498d759..e6ce14645f32e24d4c08043c4229dc8d803c73cf 100644 --- a/MatlabFiles/fn_a0sfreefun2.m +++ b/MatlabFiles/fn_a0sfreefun2.m @@ -1,97 +1,97 @@ -function of = fn_a0sfreefun2(b,Uistar,Uibar,nvar,nStates,n0,n0cumsum,tvstate,tvtot,constot,... - tvinx,constinx,indxTV,indxConst,Tkave,Sgm0tldinvaveConst,Sgm0tldinvaveTV) -% Negative logPosterior function for regime-switching vectorized free A0 parameters, -% which are b's in the WZ notation. The case of no asymmetric prior and no lag restrictions. -% It improves fn_a0sfreefun2.m in several aspects: -% (a) allows some equations to have constant parameters. -% It differs from fn_a0cfreefun_tv.m in several aspects: -% (a) does not deal with equations with only structural variances time varying; -% (b) cannot deal with lag restrictions; -% (c) only deal with the marginal distribution of A0_s. -% Note: (1) columns correspond to equations; (2) s stands for state. -% See Time-Varying BVAR NOTE pp.34-34c,40. -% -% b: sum(n0)*nStates-by-1 vector of free A0 parameters, vectorized from the sum(n0)-by-nStates matrix. -% Uistar: cell(nvar,1). In each cell, nvar*nSates-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. See p.33. -% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged -% from Uistar or Ui. See p.33. -% nvar: Number of endogeous variables. -% nStates: NUmber of states. -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation for each state. -% n0cumsum: Equal to [0;cumsum(n0)]; -% tvstate: Number of time-varying parameters for all equations for each state. -% tvtot: Total number of time-varying parameters. -% constot: Total number of constant parameters. -% tvinx: Vectorized index to include time-varying parameters for all equations under *each* state. -% constinx: Vectorized index to include constant parameters for all equations. -% indxTV: Index of acending order for equations with time-varying parameters. -% indxConst: Index of ascending order for equations with constant parameters. When [], all equations -% are time varying; when [1:nvar], all equations have constant parameters. -% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, -% averaged (ave) over E-step draws. For T_k. See p.40. -% Sgm0tldinvaveConst -% Sgm0tldinvaveTV -% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) -% over E-step draws. Same for all equations because of no asymmetric prior and no lag -% restrictions. Resembles old SpH in the exponent term in posterior of A0, -% but NOT divided by fss (T) yet. See p.40. -%---------------- -% of: Objective function (negative logPosterior). -% -% This function is called by tveml*.m which is an old program compared with szeml*.m. Thus, -% use fn_a0cfreefun_tv.m if possible. -% Tao Zha, August 2001. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -n0=n0(:); -A0=zeros(nvar,nvar,nStates); -b_shat = zeros(n0cumsum(end),nStates); -b_shat(tvinx,:) = reshape(b(1:tvtot),tvstate,nStates); % Time-varying parameter matrix. -b_shat(constinx,:) = repmat(b(tvtot+1:end), [1 nStates]); % Constant parameter matrix. - -tra = 0.0; -for kj = 1:nvar - lenbjs=length(n0cumsum(kj)+1:n0cumsum(kj+1)); - bj = zeros(nStates*lenbjs,1); - a0j = zeros(nStates*nvar,1); % See p.33. - for si=1:nStates - bj((si-1)*lenbjs+1:si*lenbjs) = b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); % bj(si). See p.34a. - A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); - a0j((si-1)*nvar+1:si*nvar) = A0(:,kj,si); % a0j(si). See p.33. - end - %tra = tra + 0.5*a0j'*Sgm0tldinvave*a0j; % negative exponential term - if find(kj==indxTV) % For time-varying equations. - tra = tra+0.5*bj'*(Uibar{kj}'*Sgm0tldinvaveTV*Uibar{kj})*bj; - else % % For constant parameter equations. - tra = tra+0.5*bj'*(Uibar{kj}'*Sgm0tldinvaveConst*Uibar{kj})*bj; - end -end - -ada=0.0; -for si=1:nStates % See p.34a. - [A0l,A0u] = lu(A0(:,:,si)); - ada = ada - Tkave(si)*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T -end - -of = ada + tra; +function of = fn_a0sfreefun2(b,Uistar,Uibar,nvar,nStates,n0,n0cumsum,tvstate,tvtot,constot,... + tvinx,constinx,indxTV,indxConst,Tkave,Sgm0tldinvaveConst,Sgm0tldinvaveTV) +% Negative logPosterior function for regime-switching vectorized free A0 parameters, +% which are b's in the WZ notation. The case of no asymmetric prior and no lag restrictions. +% It improves fn_a0sfreefun2.m in several aspects: +% (a) allows some equations to have constant parameters. +% It differs from fn_a0cfreefun_tv.m in several aspects: +% (a) does not deal with equations with only structural variances time varying; +% (b) cannot deal with lag restrictions; +% (c) only deal with the marginal distribution of A0_s. +% Note: (1) columns correspond to equations; (2) s stands for state. +% See Time-Varying BVAR NOTE pp.34-34c,40. +% +% b: sum(n0)*nStates-by-1 vector of free A0 parameters, vectorized from the sum(n0)-by-nStates matrix. +% Uistar: cell(nvar,1). In each cell, nvar*nSates-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. See p.33. +% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged +% from Uistar or Ui. See p.33. +% nvar: Number of endogeous variables. +% nStates: NUmber of states. +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation for each state. +% n0cumsum: Equal to [0;cumsum(n0)]; +% tvstate: Number of time-varying parameters for all equations for each state. +% tvtot: Total number of time-varying parameters. +% constot: Total number of constant parameters. +% tvinx: Vectorized index to include time-varying parameters for all equations under *each* state. +% constinx: Vectorized index to include constant parameters for all equations. +% indxTV: Index of acending order for equations with time-varying parameters. +% indxConst: Index of ascending order for equations with constant parameters. When [], all equations +% are time varying; when [1:nvar], all equations have constant parameters. +% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, +% averaged (ave) over E-step draws. For T_k. See p.40. +% Sgm0tldinvaveConst +% Sgm0tldinvaveTV +% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) +% over E-step draws. Same for all equations because of no asymmetric prior and no lag +% restrictions. Resembles old SpH in the exponent term in posterior of A0, +% but NOT divided by fss (T) yet. See p.40. +%---------------- +% of: Objective function (negative logPosterior). +% +% This function is called by tveml*.m which is an old program compared with szeml*.m. Thus, +% use fn_a0cfreefun_tv.m if possible. +% Tao Zha, August 2001. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +n0=n0(:); +A0=zeros(nvar,nvar,nStates); +b_shat = zeros(n0cumsum(end),nStates); +b_shat(tvinx,:) = reshape(b(1:tvtot),tvstate,nStates); % Time-varying parameter matrix. +b_shat(constinx,:) = repmat(b(tvtot+1:end), [1 nStates]); % Constant parameter matrix. + +tra = 0.0; +for kj = 1:nvar + lenbjs=length(n0cumsum(kj)+1:n0cumsum(kj+1)); + bj = zeros(nStates*lenbjs,1); + a0j = zeros(nStates*nvar,1); % See p.33. + for si=1:nStates + bj((si-1)*lenbjs+1:si*lenbjs) = b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); % bj(si). See p.34a. + A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); + a0j((si-1)*nvar+1:si*nvar) = A0(:,kj,si); % a0j(si). See p.33. + end + %tra = tra + 0.5*a0j'*Sgm0tldinvave*a0j; % negative exponential term + if find(kj==indxTV) % For time-varying equations. + tra = tra+0.5*bj'*(Uibar{kj}'*Sgm0tldinvaveTV*Uibar{kj})*bj; + else % % For constant parameter equations. + tra = tra+0.5*bj'*(Uibar{kj}'*Sgm0tldinvaveConst*Uibar{kj})*bj; + end +end + +ada=0.0; +for si=1:nStates % See p.34a. + [A0l,A0u] = lu(A0(:,:,si)); + ada = ada - Tkave(si)*sum(log(abs(diag(A0u)))); % negative log determinant of A0 raised to power T +end + +of = ada + tra; diff --git a/MatlabFiles/fn_a0sfreegrad.m b/MatlabFiles/fn_a0sfreegrad.m index 4d09f2396db5c9fdaee12eed43fa0e86d37e95c8..9f4b272b0d2ef7eb4493c43c4b121bcee44e05cf 100644 --- a/MatlabFiles/fn_a0sfreegrad.m +++ b/MatlabFiles/fn_a0sfreegrad.m @@ -1,82 +1,82 @@ -function [g,badg] = fn_a0sfreegrad(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) -% [g,badg] = fn_a0sfreegrad(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) -% Analytical gradient for fn_a0sfreefun.m when using csminwel.m. -% The case of no asymmetric prior and no lag restrictions. -% Note: (1) columns correspond to equations; s stands for state. -% See TBVAR NOTE p.34a. -% -% b: sum(n0)*nStates-by-1 vector of free A0 parameters, vectorized from the sum(n0)-by-nStates matrix. -% Uistar: cell(nvar,1). In each cell, nvar*nStates-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. See p.33. -% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged -% from Uistar or Ui. See p.33. -% nvar: Number of endogeous variables. -% nStates: NUmber of states. -% n0: nvar-by-1. n0(i)=qi where ith element represents the number of free A0 parameters in ith equation for each state. -% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, -% averaged (ave) over E-step draws. For T_k. See p.38. -% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) -% over E-step draws. Same for all equations because of no asymmetric prior and no lag -% restrictions. Resembles old SpH in the exponent term in posterior of A0, -% but NOT divided by fss (T) yet. See p.38. -%---------------- -% g: sum(n0)*nStates-by-1 analytical gradient for fn_a0sfreefun.m. -% Vectorized frmo the sum(n0)-by-nStates matrix. -% badg: 0, the value that is used in csminwel.m. -% -% Tao Zha, March 2001 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -n0=n0(:); -A0=zeros(nvar,nvar,nStates); -n0cum = [0;cumsum(n0)]; -b=reshape(b,n0cum(end),nStates); - -g = zeros(n0cum(end),nStates); % which will be vectorized later. -badg = 0; - - -%*** The derivative of the exponential term w.r.t. each free paramater -for kj = 1:nvar - lenbjs=length(n0cum(kj)+1:n0cum(kj+1)); - bj = zeros(nStates*lenbjs,1); - for si=1:nStates - bj((si-1)*lenbjs+1:si*lenbjs) = b(n0cum(kj)+1:n0cum(kj+1),si); % bj(si). See p.34a. - A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b(n0cum(kj)+1:n0cum(kj+1),si); - end - gj = (Uibar{kj}'*Sgm0tldinvave*Uibar{kj})*bj; - for si=1:nStates - g(n0cum(kj)+1:n0cum(kj+1),si) = gj((si-1)*lenbjs+1:si*lenbjs); - end -end - -%*** Add the derivative of -T_klog|A0(k)| w.r.t. each free paramater -for si=1:nStates % See p.34a. - B=inv(A0(:,:,si)'); - for ki = 1:n0cum(end) % from 1 to sum(q_i) - n = max(find( (ki-n0cum)>0 )); % note, 1<=n<=nvar equations. - g(ki,si) = g(ki,si) - Tkave(si)*B(:,n)'*Uistar{n}((si-1)*nvar+1:si*nvar,ki-n0cum(n)); % See p.34a. - end -end -g = g(:); % vectorized the same way as b is vectorized. +function [g,badg] = fn_a0sfreegrad(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) +% [g,badg] = fn_a0sfreegrad(b,Uistar,Uibar,nvar,nStates,n0,Tkave,Sgm0tldinvave) +% Analytical gradient for fn_a0sfreefun.m when using csminwel.m. +% The case of no asymmetric prior and no lag restrictions. +% Note: (1) columns correspond to equations; s stands for state. +% See TBVAR NOTE p.34a. +% +% b: sum(n0)*nStates-by-1 vector of free A0 parameters, vectorized from the sum(n0)-by-nStates matrix. +% Uistar: cell(nvar,1). In each cell, nvar*nStates-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. See p.33. +% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged +% from Uistar or Ui. See p.33. +% nvar: Number of endogeous variables. +% nStates: NUmber of states. +% n0: nvar-by-1. n0(i)=qi where ith element represents the number of free A0 parameters in ith equation for each state. +% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, +% averaged (ave) over E-step draws. For T_k. See p.38. +% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) +% over E-step draws. Same for all equations because of no asymmetric prior and no lag +% restrictions. Resembles old SpH in the exponent term in posterior of A0, +% but NOT divided by fss (T) yet. See p.38. +%---------------- +% g: sum(n0)*nStates-by-1 analytical gradient for fn_a0sfreefun.m. +% Vectorized frmo the sum(n0)-by-nStates matrix. +% badg: 0, the value that is used in csminwel.m. +% +% Tao Zha, March 2001 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +n0=n0(:); +A0=zeros(nvar,nvar,nStates); +n0cum = [0;cumsum(n0)]; +b=reshape(b,n0cum(end),nStates); + +g = zeros(n0cum(end),nStates); % which will be vectorized later. +badg = 0; + + +%*** The derivative of the exponential term w.r.t. each free paramater +for kj = 1:nvar + lenbjs=length(n0cum(kj)+1:n0cum(kj+1)); + bj = zeros(nStates*lenbjs,1); + for si=1:nStates + bj((si-1)*lenbjs+1:si*lenbjs) = b(n0cum(kj)+1:n0cum(kj+1),si); % bj(si). See p.34a. + A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b(n0cum(kj)+1:n0cum(kj+1),si); + end + gj = (Uibar{kj}'*Sgm0tldinvave*Uibar{kj})*bj; + for si=1:nStates + g(n0cum(kj)+1:n0cum(kj+1),si) = gj((si-1)*lenbjs+1:si*lenbjs); + end +end + +%*** Add the derivative of -T_klog|A0(k)| w.r.t. each free paramater +for si=1:nStates % See p.34a. + B=inv(A0(:,:,si)'); + for ki = 1:n0cum(end) % from 1 to sum(q_i) + n = max(find( (ki-n0cum)>0 )); % note, 1<=n<=nvar equations. + g(ki,si) = g(ki,si) - Tkave(si)*B(:,n)'*Uistar{n}((si-1)*nvar+1:si*nvar,ki-n0cum(n)); % See p.34a. + end +end +g = g(:); % vectorized the same way as b is vectorized. diff --git a/MatlabFiles/fn_a0sfreegrad2.m b/MatlabFiles/fn_a0sfreegrad2.m index bc7eb939a3026265a53c009dcd3dab44182db193..a88760bede55065b31a0e10e798292ab11b3d055 100644 --- a/MatlabFiles/fn_a0sfreegrad2.m +++ b/MatlabFiles/fn_a0sfreegrad2.m @@ -1,141 +1,141 @@ -function [g,badg] = fn_a0sfreegrad2(b,Uistar,Uibar,nvar,nStates,n0,n0cumsum,tvstate,tvtot,constot,... - tvinx,constinx,indxTV,indxConst,Tkave,Sgm0tldinvaveConst,Sgm0tldinvaveTV) -% Analytical gradient for both time-varying and constant parameters for fn_a0sfreefun2.m when using csminwel.m. -% The case of no asymmetric prior and no lag restrictions. -% Note: (1) columns correspond to equations; s stands for state. -% See Time-Varying BVAR NOTE pp.34a-34c. -% -% b: tvtot+constot-by-1 vector of free A0 parameters, vectorized from b_shat for both time-varying and constant parameter matrices. -% Uistar: cell(nvar,1). In each cell, nvar*nStates-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters -% where in each state, nvar-by-qi is the same. With this transformation, we have -% ai = Ui*bi or Ui'*ai = bi where ai is a vector of total original parameters and -% bi is a vector of free parameters. When no restrictions are imposed, we have Ui = I. -% There must be at least one free parameter left for the ith equation. See p.33. -% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged -% from Uistar or Ui. See p.33. -% nvar: Number of endogenous variables. -% nStates: NUmber of states. -% n0: nvar-by-1. n0(i)=qi where ith element represents the number of free A0 parameters in ith equation for each state. -% n0cumsum=[0;cumsum(n0)]: nvar+1-by-1. Cumulative sums of n0 with zero added. -% tvstate=length(tvinx): Number of time-varying parameters for all equations under *each* state. -% constot=length(constinx): Total number of constant parameters for all equations. -% tvtot = tvstate*nStates: Total number of time-varying parameters for all equations under all states. -% tvinx: Vectorized index to include time-varying parameters for all equations under *each* state. -% constinx: Vectorized index to include constant parameters for all equations. -% indxTV: Index vector of ascending order for equations with time-varying parameters. -% indxConst: Index vector of ascending order for equations with constant parameters. When [], all equations -% are time varying; when [1:nvar], all equations have constant parameters. -% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, -% averaged (ave) over E-step draws. For T_k. See p.40. -% Sgm0tldinvaveConst -% Sgm0tldinvaveTV -% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) -% over E-step draws. Same for all equations because of no asymmetric prior and no lag -% restrictions. Resembles old SpH in the exponent term in posterior of A0, -% but NOT divided by fss (T) yet. See p.40. -%---------------- -% g: tvtot+constot-by-1 analytical gradient for fn_a0sfreefun2.m. Vectorized first from the -% time-varying parameter matrix and then from constant parameter and constant parameter matrix. -% badg: Always 0 --- the value that is used in csminwel.m. -% -% Tao Zha, August 2001. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -n0=n0(:); -A0=zeros(nvar,nvar,nStates); -B0=A0; -b_shat = zeros(n0cumsum(end),nStates); -b_shat(tvinx,:) = reshape(b(1:tvtot),tvstate,nStates); % Time-varying parameter matrix. -b_shat(constinx,:) = repmat(b(tvtot+1:end), [1 nStates]); % Constant parameter matrix. -% -gmix = zeros(n0cumsum(end),nStates); - % Gradient matrix mixing time-varying and constant parameters. - % Rows of gmix, indexed by constinx, will not be used but instead treated - % different under "for kj=indxConst." -gtv = zeros(tvstate,nStates); % Gradient wrt time-varying parameters, which will be vectorized later. -gconst1 = zeros(constot,1); % The first gradient wrt constant parameters for the exponetial term. -gconst2=zeros(constot,1); % The second gradient wrt constant parameters for -T_klog|A0(k)|. - - -%--------------------------------------------------- -% Time-varying situation. See p. 34a. -%--------------------------------------------------- -%*** The derivative of the exponential term w.r.t. each free time-varying paramater. -for kj = 1:nvar % For all equations - lenbjs=length(n0cumsum(kj)+1:n0cumsum(kj+1)); - bj = zeros(nStates*lenbjs,1); - for si=1:nStates - bj((si-1)*lenbjs+1:si*lenbjs) = b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); % bj(si). See p.34a. - A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); - end - gj = (Uibar{kj}'*Sgm0tldinvaveTV*Uibar{kj})*bj; - if find(kj==indxTV) % For time-varying equations. - for si=1:nStates - gmix(n0cumsum(kj)+1:n0cumsum(kj+1),si) = gj((si-1)*lenbjs+1:si*lenbjs); - end - end -end - -%*** Add the derivative of -T_klog|A0(k)| w.r.t. each free time-varying paramater. -for si=1:nStates % See p.34a. - B0(:,:,si)=inv(A0(:,:,si)'); - for ki = tvinx % Those from 1 to sum(q_i) that pertain to time-varying parameters. - n = max(find( (ki-n0cumsum)>0 )); % note, 1<=n<=nvar equations. - gmix(ki,si) = gmix(ki,si) - Tkave(si)*B0(:,n,si)'*Uistar{n}((si-1)*nvar+1:si*nvar,ki-n0cumsum(n)); % See p.34a. - end -end - -%--------------------------------------------------- -% Constant-parameter situation. See pp. 34b-34c. -%--------------------------------------------------- -kcount = 0; % Counts. -for kj = indxConst % Equations - klocat=kcount+n0(kj); % Losition for the last constant element in the jth equation. - Bbar = repmat(eye(n0(kj)),[1 nStates]); % See p.34b. - lenbjs=length(n0cumsum(kj)+1:n0cumsum(kj+1)); - bj = zeros(nStates*lenbjs,1); - for si=1:nStates - bj((si-1)*lenbjs+1:si*lenbjs) = b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); % bj(si). See p.34a. - A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); - end - gconst1(kcount+1:klocat) = Bbar*( (Uibar{kj}'*Sgm0tldinvaveConst*Uibar{kj})*bj ); - kcount=klocat; -end -%*** Add the derivative of -T_klog|A0(k)| w.r.t. each free time-varying paramater. -kcount = 0; % Counts. -for ki = constinx % Those from 1 to sum(q_i) that pertain to constant parameters. - kcount=kcount+1; - n = max(find( (ki-n0cumsum)>0 )); % note, 1<=n<=nvar equations. - gi=0; % Initializes a gradient summed across the states. See p. 34c. - for si=1:nStates % See p.34c. - gi = gi - Tkave(si)*B0(:,n,si)'*Uistar{n}((si-1)*nvar+1:si*nvar,ki-n0cumsum(n)); % See p. 34a. - end - gconst2(kcount)=gi; -end - - -%--------------------------------------------------- -% Conclusion. -%--------------------------------------------------- -gtv = gmix(tvinx,:); % Extract the gradient wrt time-varying parameters. -gconst = gconst1+gconst2; % Gradient wrt to constant parameters. -% -g = [gtv(:);gconst]; % Vectorized the same way as b is vectorized. -badg = 0; % This term is used for Sims's csminwel program. +function [g,badg] = fn_a0sfreegrad2(b,Uistar,Uibar,nvar,nStates,n0,n0cumsum,tvstate,tvtot,constot,... + tvinx,constinx,indxTV,indxConst,Tkave,Sgm0tldinvaveConst,Sgm0tldinvaveTV) +% Analytical gradient for both time-varying and constant parameters for fn_a0sfreefun2.m when using csminwel.m. +% The case of no asymmetric prior and no lag restrictions. +% Note: (1) columns correspond to equations; s stands for state. +% See Time-Varying BVAR NOTE pp.34a-34c. +% +% b: tvtot+constot-by-1 vector of free A0 parameters, vectorized from b_shat for both time-varying and constant parameter matrices. +% Uistar: cell(nvar,1). In each cell, nvar*nStates-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters +% where in each state, nvar-by-qi is the same. With this transformation, we have +% ai = Ui*bi or Ui'*ai = bi where ai is a vector of total original parameters and +% bi is a vector of free parameters. When no restrictions are imposed, we have Ui = I. +% There must be at least one free parameter left for the ith equation. See p.33. +% Uibar: cell(nvar,1). In each cell, we have nvar*nStates-by-qi*nStates, rearranged +% from Uistar or Ui. See p.33. +% nvar: Number of endogenous variables. +% nStates: NUmber of states. +% n0: nvar-by-1. n0(i)=qi where ith element represents the number of free A0 parameters in ith equation for each state. +% n0cumsum=[0;cumsum(n0)]: nvar+1-by-1. Cumulative sums of n0 with zero added. +% tvstate=length(tvinx): Number of time-varying parameters for all equations under *each* state. +% constot=length(constinx): Total number of constant parameters for all equations. +% tvtot = tvstate*nStates: Total number of time-varying parameters for all equations under all states. +% tvinx: Vectorized index to include time-varying parameters for all equations under *each* state. +% constinx: Vectorized index to include constant parameters for all equations. +% indxTV: Index vector of ascending order for equations with time-varying parameters. +% indxConst: Index vector of ascending order for equations with constant parameters. When [], all equations +% are time varying; when [1:nvar], all equations have constant parameters. +% Tkave: nStates-by-1 of sample sizes (excluding lags but including dummies if provided) for different states k, +% averaged (ave) over E-step draws. For T_k. See p.40. +% Sgm0tldinvaveConst +% Sgm0tldinvaveTV +% Sgm0tldinvave: nvar*nStates-by-nvar*nStates. The matrix inv(\Sigma~_0) averaged (ave) +% over E-step draws. Same for all equations because of no asymmetric prior and no lag +% restrictions. Resembles old SpH in the exponent term in posterior of A0, +% but NOT divided by fss (T) yet. See p.40. +%---------------- +% g: tvtot+constot-by-1 analytical gradient for fn_a0sfreefun2.m. Vectorized first from the +% time-varying parameter matrix and then from constant parameter and constant parameter matrix. +% badg: Always 0 --- the value that is used in csminwel.m. +% +% Tao Zha, August 2001. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +n0=n0(:); +A0=zeros(nvar,nvar,nStates); +B0=A0; +b_shat = zeros(n0cumsum(end),nStates); +b_shat(tvinx,:) = reshape(b(1:tvtot),tvstate,nStates); % Time-varying parameter matrix. +b_shat(constinx,:) = repmat(b(tvtot+1:end), [1 nStates]); % Constant parameter matrix. +% +gmix = zeros(n0cumsum(end),nStates); + % Gradient matrix mixing time-varying and constant parameters. + % Rows of gmix, indexed by constinx, will not be used but instead treated + % different under "for kj=indxConst." +gtv = zeros(tvstate,nStates); % Gradient wrt time-varying parameters, which will be vectorized later. +gconst1 = zeros(constot,1); % The first gradient wrt constant parameters for the exponetial term. +gconst2=zeros(constot,1); % The second gradient wrt constant parameters for -T_klog|A0(k)|. + + +%--------------------------------------------------- +% Time-varying situation. See p. 34a. +%--------------------------------------------------- +%*** The derivative of the exponential term w.r.t. each free time-varying paramater. +for kj = 1:nvar % For all equations + lenbjs=length(n0cumsum(kj)+1:n0cumsum(kj+1)); + bj = zeros(nStates*lenbjs,1); + for si=1:nStates + bj((si-1)*lenbjs+1:si*lenbjs) = b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); % bj(si). See p.34a. + A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); + end + gj = (Uibar{kj}'*Sgm0tldinvaveTV*Uibar{kj})*bj; + if find(kj==indxTV) % For time-varying equations. + for si=1:nStates + gmix(n0cumsum(kj)+1:n0cumsum(kj+1),si) = gj((si-1)*lenbjs+1:si*lenbjs); + end + end +end + +%*** Add the derivative of -T_klog|A0(k)| w.r.t. each free time-varying paramater. +for si=1:nStates % See p.34a. + B0(:,:,si)=inv(A0(:,:,si)'); + for ki = tvinx % Those from 1 to sum(q_i) that pertain to time-varying parameters. + n = max(find( (ki-n0cumsum)>0 )); % note, 1<=n<=nvar equations. + gmix(ki,si) = gmix(ki,si) - Tkave(si)*B0(:,n,si)'*Uistar{n}((si-1)*nvar+1:si*nvar,ki-n0cumsum(n)); % See p.34a. + end +end + +%--------------------------------------------------- +% Constant-parameter situation. See pp. 34b-34c. +%--------------------------------------------------- +kcount = 0; % Counts. +for kj = indxConst % Equations + klocat=kcount+n0(kj); % Losition for the last constant element in the jth equation. + Bbar = repmat(eye(n0(kj)),[1 nStates]); % See p.34b. + lenbjs=length(n0cumsum(kj)+1:n0cumsum(kj+1)); + bj = zeros(nStates*lenbjs,1); + for si=1:nStates + bj((si-1)*lenbjs+1:si*lenbjs) = b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); % bj(si). See p.34a. + A0(:,kj,si) = Uistar{kj}((si-1)*nvar+1:si*nvar,:)*b_shat(n0cumsum(kj)+1:n0cumsum(kj+1),si); + end + gconst1(kcount+1:klocat) = Bbar*( (Uibar{kj}'*Sgm0tldinvaveConst*Uibar{kj})*bj ); + kcount=klocat; +end +%*** Add the derivative of -T_klog|A0(k)| w.r.t. each free time-varying paramater. +kcount = 0; % Counts. +for ki = constinx % Those from 1 to sum(q_i) that pertain to constant parameters. + kcount=kcount+1; + n = max(find( (ki-n0cumsum)>0 )); % note, 1<=n<=nvar equations. + gi=0; % Initializes a gradient summed across the states. See p. 34c. + for si=1:nStates % See p.34c. + gi = gi - Tkave(si)*B0(:,n,si)'*Uistar{n}((si-1)*nvar+1:si*nvar,ki-n0cumsum(n)); % See p. 34a. + end + gconst2(kcount)=gi; +end + + +%--------------------------------------------------- +% Conclusion. +%--------------------------------------------------- +gtv = gmix(tvinx,:); % Extract the gradient wrt time-varying parameters. +gconst = gconst1+gconst2; % Gradient wrt to constant parameters. +% +g = [gtv(:);gconst]; % Vectorized the same way as b is vectorized. +badg = 0; % This term is used for Sims's csminwel program. diff --git a/MatlabFiles/fn_calyrqm.m b/MatlabFiles/fn_calyrqm.m index 5025449e9797c9dc12995b8fb59310558b6cd7a1..65b7b5ac5efe628f8df1e1e2d0371958c3adc0e7 100644 --- a/MatlabFiles/fn_calyrqm.m +++ b/MatlabFiles/fn_calyrqm.m @@ -1,75 +1,75 @@ -function [Myrqm,nMyrqm] = fn_calyrqm(q_m,Byrqm,Eyrqm) -% [Myrqm,nMyrqm] = fn_calyrqm(q_m,Byrqm,Eyrqm) -% -% Given the beginning and end years and quarters (months), export a matrix of all years and -% quarters (months) for these years and in between -% -% q_m: 4 if quarterly and 12 if monthly -% Byrqm: [year quarter(month)] -- all integers, the begining year and quarter (month) -% Eyrqm: [year quarter(month)] -- all integers, the end year and quarter (month) -%------------------- -% Myrqm: matrix of all years and quarters (months) between and incl. Byrqm and Eyrqm -% nMyrqm: number of data points incl. Byrqm and Eyrqm -% -% Tao Zha, April 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if ~isempty(find(Byrqm-round(Byrqm))) | (q_m-round(q_m)) | ~isempty(find(Byrqm-round(Byrqm))) - error('argin qm, Byrqm, or Eyrqm must of integer') -elseif Byrqm(1)>Eyrqm(1) - error('Eyrqm(1) must be equal to or greater than Byrqm(1)') -elseif Byrqm(1)==Eyrqm(1) - if Byrqm(2)>Eyrqm(2) - error('Eyrqm(2) must be equal to or greater than Byrqm(2) because of the same year') - end -end - - -Yr = Byrqm(1)+[0:Eyrqm(1)-Byrqm(1)]'; - -if length(Yr)>=2 % there are years and quarters (months) between Byrqm and Eyrqm - n=length(Yr)-2; - C=zeros(n*q_m,2); - C(:,1) = kron(Yr(2:end-1),ones(q_m,1)); - C(:,2) = kron(ones(n,1),[1:q_m]'); - - %* initialize a matrix of years and quarters (months) including Byrqm and Eyrqm - Myrqm = zeros((q_m-Byrqm(2)+1)+Eyrqm(2)+n*q_m,2); - - %* Years in between - n1=q_m-Byrqm(2)+1; - n2=Eyrqm(2); - Myrqm(n1+1:end-n2,:) = C; - %* Beginning year - for k=1:n1 - Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; - end - %* End year - for k=1:n2 - Myrqm(end-Eyrqm(2)+k,:) = [Eyrqm(1) k]; - end -else %* all the data are in the same calendar year - n1=Eyrqm(2)-Byrqm(2)+1; - Myrqm = zeros(n1,2); - for k=1:n1 - Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; - end -end - -nMyrqm = size(Myrqm,1); +function [Myrqm,nMyrqm] = fn_calyrqm(q_m,Byrqm,Eyrqm) +% [Myrqm,nMyrqm] = fn_calyrqm(q_m,Byrqm,Eyrqm) +% +% Given the beginning and end years and quarters (months), export a matrix of all years and +% quarters (months) for these years and in between +% +% q_m: 4 if quarterly and 12 if monthly +% Byrqm: [year quarter(month)] -- all integers, the begining year and quarter (month) +% Eyrqm: [year quarter(month)] -- all integers, the end year and quarter (month) +%------------------- +% Myrqm: matrix of all years and quarters (months) between and incl. Byrqm and Eyrqm +% nMyrqm: number of data points incl. Byrqm and Eyrqm +% +% Tao Zha, April 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if ~isempty(find(Byrqm-round(Byrqm))) | (q_m-round(q_m)) | ~isempty(find(Byrqm-round(Byrqm))) + error('argin qm, Byrqm, or Eyrqm must of integer') +elseif Byrqm(1)>Eyrqm(1) + error('Eyrqm(1) must be equal to or greater than Byrqm(1)') +elseif Byrqm(1)==Eyrqm(1) + if Byrqm(2)>Eyrqm(2) + error('Eyrqm(2) must be equal to or greater than Byrqm(2) because of the same year') + end +end + + +Yr = Byrqm(1)+[0:Eyrqm(1)-Byrqm(1)]'; + +if length(Yr)>=2 % there are years and quarters (months) between Byrqm and Eyrqm + n=length(Yr)-2; + C=zeros(n*q_m,2); + C(:,1) = kron(Yr(2:end-1),ones(q_m,1)); + C(:,2) = kron(ones(n,1),[1:q_m]'); + + %* initialize a matrix of years and quarters (months) including Byrqm and Eyrqm + Myrqm = zeros((q_m-Byrqm(2)+1)+Eyrqm(2)+n*q_m,2); + + %* Years in between + n1=q_m-Byrqm(2)+1; + n2=Eyrqm(2); + Myrqm(n1+1:end-n2,:) = C; + %* Beginning year + for k=1:n1 + Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; + end + %* End year + for k=1:n2 + Myrqm(end-Eyrqm(2)+k,:) = [Eyrqm(1) k]; + end +else %* all the data are in the same calendar year + n1=Eyrqm(2)-Byrqm(2)+1; + Myrqm = zeros(n1,2); + for k=1:n1 + Myrqm(k,:) = [Byrqm(1) Byrqm(2)+k-1]; + end +end + +nMyrqm = size(Myrqm,1); diff --git a/MatlabFiles/fn_construct_cov.m b/MatlabFiles/fn_construct_cov.m index 47f58887a60aebbbe8ccdc9ca5a715b3af1cb6a9..76bd1b5e5c68554e8fac39b6bf50d5da9c33c80d 100644 --- a/MatlabFiles/fn_construct_cov.m +++ b/MatlabFiles/fn_construct_cov.m @@ -1,36 +1,36 @@ -function covM = fn_construct_cov(diagcovM, corM) -% function corM = corr(covM) -% diagcovM: diag of covariance matrix (input) -% corM: correlation matrix (input) -% covM: covariance matrix (output) -% 9 May 2008 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[nvar,jnk]=size(corM); -if nvar~=jnk - error('The input matrix must be square!!') -end -covM=zeros(nvar); - -for i=1:nvar - for j=1:nvar - covM(i,j)= corM(i,j) * sqrt( diagcovM(i) * diagcovM(j) ); - end -end - +function covM = fn_construct_cov(diagcovM, corM) +% function corM = corr(covM) +% diagcovM: diag of covariance matrix (input) +% corM: correlation matrix (input) +% covM: covariance matrix (output) +% 9 May 2008 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[nvar,jnk]=size(corM); +if nvar~=jnk + error('The input matrix must be square!!') +end +covM=zeros(nvar); + +for i=1:nvar + for j=1:nvar + covM(i,j)= corM(i,j) * sqrt( diagcovM(i) * diagcovM(j) ); + end +end + diff --git a/MatlabFiles/fn_corr.m b/MatlabFiles/fn_corr.m index 165f329143b19094774bb129d94522f6f86440c0..581a1cd5cfa6384c7d94bbc9068b030807e71f63 100644 --- a/MatlabFiles/fn_corr.m +++ b/MatlabFiles/fn_corr.m @@ -1,35 +1,35 @@ -function corM = fn_corr(covM) -% function corM = fn_corr(covM) -% -% covM: covariance matrix (input) -% corM: correlation matrix (output) -% 6 September 1998 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[nvar,jnk]=size(covM); -if nvar~=jnk - error('The input matrix must be square!!') -end -corM=zeros(nvar); -for i=1:nvar - for j=1:nvar - corM(i,j)=covM(i,j) / sqrt( covM(i,i) * covM(j,j)); - end -end - +function corM = fn_corr(covM) +% function corM = fn_corr(covM) +% +% covM: covariance matrix (input) +% corM: correlation matrix (output) +% 6 September 1998 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[nvar,jnk]=size(covM); +if nvar~=jnk + error('The input matrix must be square!!') +end +corM=zeros(nvar); +for i=1:nvar + for j=1:nvar + corM(i,j)=covM(i,j) / sqrt( covM(i,i) * covM(j,j)); + end +end + diff --git a/MatlabFiles/fn_dataext.m b/MatlabFiles/fn_dataext.m index 0366fdf0fbb1530927b7dbe426cde78865e956d6..0069eff4bda69b0eeec9da31b2963d24b4a28960 100644 --- a/MatlabFiles/fn_dataext.m +++ b/MatlabFiles/fn_dataext.m @@ -1,60 +1,60 @@ -function [xdsube,Brow,Erow] = fn_dataext(Byrqm,Eyrqm,xdatae) -% xdsube = dataext(Byrqm,Eyrqm,xdatae) -% Extract subset of xdatae, given Byrqm and Eyrqm -% -% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)=0, we get annual data. -% Eyrqm: [year period]: end year and period. If Byrqm(2)=0, it must be Eyrqm(2)=0. -% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. -%---------- -% xdsube: subset of xdatae. -% Brow: the row number in xdatee that marks the first row of xdsube. -% Erow: the row number in xdatee that marks the last row of xdsube. -% -% Tao Zha, April 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if (Byrqm(2)==0) & (Eyrqm(2)~=0) - error('If annual data, make sure both Byrqm(2) and Eyrqm(2) are zero') -end - -Brow = min(find(xdatae(:,1)==Byrqm(1))); -if isempty(Brow) - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') -end -if Byrqm(2)>0 - nadt=Byrqm(2)-xdatae(Brow,2); - if nadt<0 - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Brow=Brow+nadt; -end -% -Erow = min(find(xdatae(:,1)==Eyrqm(1))); -if isempty(Erow) - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') -end -if Eyrqm(2)>0 - nadt2=Eyrqm(2)-xdatae(Erow,2); - if nadt<0 - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Erow=Erow+nadt2; -end -% -xdsube = xdatae(Brow:Erow,:); % with dates +function [xdsube,Brow,Erow] = fn_dataext(Byrqm,Eyrqm,xdatae) +% xdsube = dataext(Byrqm,Eyrqm,xdatae) +% Extract subset of xdatae, given Byrqm and Eyrqm +% +% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)=0, we get annual data. +% Eyrqm: [year period]: end year and period. If Byrqm(2)=0, it must be Eyrqm(2)=0. +% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. +%---------- +% xdsube: subset of xdatae. +% Brow: the row number in xdatee that marks the first row of xdsube. +% Erow: the row number in xdatee that marks the last row of xdsube. +% +% Tao Zha, April 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if (Byrqm(2)==0) & (Eyrqm(2)~=0) + error('If annual data, make sure both Byrqm(2) and Eyrqm(2) are zero') +end + +Brow = min(find(xdatae(:,1)==Byrqm(1))); +if isempty(Brow) + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') +end +if Byrqm(2)>0 + nadt=Byrqm(2)-xdatae(Brow,2); + if nadt<0 + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Brow=Brow+nadt; +end +% +Erow = min(find(xdatae(:,1)==Eyrqm(1))); +if isempty(Erow) + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') +end +if Eyrqm(2)>0 + nadt2=Eyrqm(2)-xdatae(Erow,2); + if nadt<0 + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Erow=Erow+nadt2; +end +% +xdsube = xdatae(Brow:Erow,:); % with dates diff --git a/MatlabFiles/fn_dataext2.m b/MatlabFiles/fn_dataext2.m index dc9abb99af9550462ce9395c118be242ea4bdc4a..09ce79b201503311f12fb8781c596b2b889952a5 100644 --- a/MatlabFiles/fn_dataext2.m +++ b/MatlabFiles/fn_dataext2.m @@ -1,73 +1,73 @@ -function [xdsube,Brow,Erow] = fn_dataext2(Byrqm,Eyrqm,xdatae) -% xdsube = dataext(Byrqm,Eyrqm,xdatae) -% Extract subset of xdatae, given Byrqm and Eyrqm -% -% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)=0, we get annual data. -% Eyrqm: [year period]: end year and period. If Byrqm(2)=0, it must be Eyrqm(2)=0. -% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. -%---------- -% xdsube: subset of xdatae. -% Brow: the row number in xdatee that marks the first row of xdsube. -% Erow: the row number in xdatee that marks the last row of xdsube. -% -% Tao Zha, April 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if (Byrqm(2)==0) - Eyrqm(2)=0; - q_m1=find(xdatae(:,2)==xdatae(1,2)); % Locating quarter or month - if length(q_m1)<2 - error('The matrix xdatae must at least have a cycle of q_m periods for possibly one calendar year') - end - q_m=q_m1(2)-1; -end - -Brow = min(find(xdatae(:,1)==Byrqm(1))); -if isempty(Brow) - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') -end -if Byrqm(2)>0 - nadt=Byrqm(2)-xdatae(Brow,2); - if nadt<0 - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Brow=Brow+nadt; -end -% -Erow = min(find(xdatae(:,1)==Eyrqm(1))); -if isempty(Erow) - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') -end -if Eyrqm(2)>0 - nadt2=Eyrqm(2)-xdatae(Erow,2); - if nadt<0 - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Erow=Erow+nadt2; -end -% - -if (Byrqm(2)==0) % By calendar years. - if (xdatae(Brow,2)~=1) | (xdatae(Erow,2)~=1) - error('Calendar years extracted here must have q_m periods') - end - Erow=Erow+q_m-1; -end - -xdsube = xdatae(Brow:Erow,:); % with dates +function [xdsube,Brow,Erow] = fn_dataext2(Byrqm,Eyrqm,xdatae) +% xdsube = dataext(Byrqm,Eyrqm,xdatae) +% Extract subset of xdatae, given Byrqm and Eyrqm +% +% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)=0, we get annual data. +% Eyrqm: [year period]: end year and period. If Byrqm(2)=0, it must be Eyrqm(2)=0. +% xdatae: all data (some of which may be NaN) with the first 2 columns indicating years and periods. +%---------- +% xdsube: subset of xdatae. +% Brow: the row number in xdatee that marks the first row of xdsube. +% Erow: the row number in xdatee that marks the last row of xdsube. +% +% Tao Zha, April 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if (Byrqm(2)==0) + Eyrqm(2)=0; + q_m1=find(xdatae(:,2)==xdatae(1,2)); % Locating quarter or month + if length(q_m1)<2 + error('The matrix xdatae must at least have a cycle of q_m periods for possibly one calendar year') + end + q_m=q_m1(2)-1; +end + +Brow = min(find(xdatae(:,1)==Byrqm(1))); +if isempty(Brow) + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') +end +if Byrqm(2)>0 + nadt=Byrqm(2)-xdatae(Brow,2); + if nadt<0 + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Brow=Brow+nadt; +end +% +Erow = min(find(xdatae(:,1)==Eyrqm(1))); +if isempty(Erow) + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') +end +if Eyrqm(2)>0 + nadt2=Eyrqm(2)-xdatae(Erow,2); + if nadt<0 + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Erow=Erow+nadt2; +end +% + +if (Byrqm(2)==0) % By calendar years. + if (xdatae(Brow,2)~=1) | (xdatae(Erow,2)~=1) + error('Calendar years extracted here must have q_m periods') + end + Erow=Erow+q_m-1; +end + +xdsube = xdatae(Brow:Erow,:); % with dates diff --git a/MatlabFiles/fn_datana.m b/MatlabFiles/fn_datana.m index 64c6e4baf50aa42d56dd9bc6ccbfc4007cdd8e65..cf4f8d5d17d70926b170867d0236aa08ed3715d7 100644 --- a/MatlabFiles/fn_datana.m +++ b/MatlabFiles/fn_datana.m @@ -1,117 +1,117 @@ -function [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = fn_datana(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) -% [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = fn_datana(Byrqm,Eyrqm,xdatae,q_m,vlistlog,vlistper) -% -% Generate prior period, period-to-period-in-last-year, and annual growth rates -% For annual rates, works for both calendar and any annual years, depending on Byrqm and Eyrqm -% If monthly data, we haven't got time to get quarterly growth rates yet. -% -% xdatae: all data (logged levels or interest rates/100, some of which may be NaN) with the first -% 2 columns indicating years and periods. -% q_m: quarter or month period -% vlistlog: sublist for logged variables -% vlistper: sublists for percent variables -% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)~=1, we don't get -% calendar annual rates. In other words, the first column of yactyge (which -% indicates years) does not mean calendar years. Byqm(2) must be specified; in other -% words, it must be not set to 0 as in, say, fn_dataext. -% Eyrqm: [year period]: end year and period. Eyqm(2) must be specified; in other words, it -% must be not set to 0 as in, say, fn_dataext. -% NOTE: if no inputs Byrqm and Eyrqm are specified, all growth rates begin at xdatae(1,1:2). -%---------- -% yactyrge: annual growth rates with dates in the first 2 columns. -% yactyre: annual average logged level with dates in the 1st 2 columns. -% yactqmyge: period-to-period-in-last-year annual growth rates with dates in the first 2 columns. -% yactqmge: prior-period annualized growth rates with dates in the first 2 columns. -% yactqme: data (logged levels or interest rates/100) with dates in the first 2 columns. -% Same as xdatae but with Brow:Erow. -% -% Tao Zha, April 2000. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if size(xdatae,1)<2*q_m - error('We need at least two years of xdatae to get annual rates. Check xdatae!!') -end - -if nargin==4 - Brow=1; Erow=length(xdatae(:,1)); - nyr = floor((Erow-Brow+1)/q_m); - yrsg = [xdatae(q_m+1,1):xdatae(q_m+1,1)+nyr-2]'; % for annual growth later on -else - if Byrqm(2)<1 | Eyrqm(2)<1 - error('This function requires specifying both years and months (quarters) in Byrqm and Eyrqm') - end - - Brow = min(find(xdatae(:,1)==Byrqm(1))); - if isempty(Brow) - error('Byrqm is outside the date range of xdatae(:,1:2)!') - end - nadt=Byrqm(2)-xdatae(Brow,2); - if nadt<0 - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Brow=Brow+nadt; - % - Erow = min(find(xdatae(:,1)==Eyrqm(1))); - if isempty(Brow) - error('Eyrqm is outside the date range of xdatae(:,1:2)!') - end - nadt2=Eyrqm(2)-xdatae(Erow,2); - if nadt<0 - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Erow=Erow+nadt2; - - nyr = floor((Erow-Brow+1)/q_m); - yrsg = [Byrqm(1)+1:Byrqm(1)+nyr-1]'; % for annual growth later on, which will - % start at Byrqm(1) instead of Byrqm(1)+1 -end -% -yactqme = xdatae(Brow:Erow,:); % with dates -yactqm = yactqme(:,3:end); % only data - -%======== prior period change (annaluized rate) -yactqmg = yactqm(2:end,:); % start at second period to get growth rate -yactqmg(:,vlistlog) = (yactqm(2:end,vlistlog) - yactqm(1:end-1,vlistlog)) .* q_m; - % monthly, 12*log(1+growth rate), annualized growth rate -yactqmg(:,vlistlog) = 100*(exp(yactqmg(:,vlistlog))-1); -yactqmg(:,vlistper) = 100*yactqmg(:,vlistper); -yactqmge = [yactqme(2:end,1:2) yactqmg]; - -%======== change from the last year -yactqmyg = yactqm(q_m+1:end,:); % start at the last-year period to get growth rate -yactqmyg(:,vlistlog) = (yactqm(q_m+1:end,vlistlog) - yactqm(1:end-q_m,vlistlog)); -yactqmyg(:,vlistlog) = 100*(exp(yactqmyg(:,vlistlog))-1); -yactqmyg(:,vlistper) = 100*yactqmyg(:,vlistper); -yactqmyge = [yactqme(q_m+1:end,1:2) yactqmyg]; - -%======== annual growth rates -nvar = length(xdatae(1,3:end)); -ygmts = yactqm(1:nyr*q_m,:); % converted to the multiplication of q_m -ygmts1 = reshape(ygmts,q_m,nyr,nvar); -ygmts2 = sum(ygmts1,1) ./ q_m; -ygmts3 = reshape(ygmts2,nyr,nvar); % converted to annual average series -% -yactyrg = ygmts3(2:end,:); % start at the last-year period to get growth rate -yactyrg(:,vlistlog) = ygmts3(2:end,vlistlog) - ygmts3(1:end-1,vlistlog); - % annual rate: log(1+growth rate) -yactyrg(:,vlistlog) = 100*(exp(yactyrg(:,vlistlog))-1); -yactyrg(:,vlistper) = 100*yactyrg(:,vlistper); -yactyrge = [yrsg zeros(nyr-1,1) yactyrg]; -yrsg1=[yrsg(1)-1:yrsg(end)]'; -yactyre = [yrsg1 zeros(nyr,1) ygmts3]; +function [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = fn_datana(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) +% [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = fn_datana(Byrqm,Eyrqm,xdatae,q_m,vlistlog,vlistper) +% +% Generate prior period, period-to-period-in-last-year, and annual growth rates +% For annual rates, works for both calendar and any annual years, depending on Byrqm and Eyrqm +% If monthly data, we haven't got time to get quarterly growth rates yet. +% +% xdatae: all data (logged levels or interest rates/100, some of which may be NaN) with the first +% 2 columns indicating years and periods. +% q_m: quarter or month period +% vlistlog: sublist for logged variables +% vlistper: sublists for percent variables +% Byrqm: [year quarter(month)]: beginning year and period. If Byqm(2)~=1, we don't get +% calendar annual rates. In other words, the first column of yactyge (which +% indicates years) does not mean calendar years. Byqm(2) must be specified; in other +% words, it must be not set to 0 as in, say, fn_dataext. +% Eyrqm: [year period]: end year and period. Eyqm(2) must be specified; in other words, it +% must be not set to 0 as in, say, fn_dataext. +% NOTE: if no inputs Byrqm and Eyrqm are specified, all growth rates begin at xdatae(1,1:2). +%---------- +% yactyrge: annual growth rates with dates in the first 2 columns. +% yactyre: annual average logged level with dates in the 1st 2 columns. +% yactqmyge: period-to-period-in-last-year annual growth rates with dates in the first 2 columns. +% yactqmge: prior-period annualized growth rates with dates in the first 2 columns. +% yactqme: data (logged levels or interest rates/100) with dates in the first 2 columns. +% Same as xdatae but with Brow:Erow. +% +% Tao Zha, April 2000. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if size(xdatae,1)<2*q_m + error('We need at least two years of xdatae to get annual rates. Check xdatae!!') +end + +if nargin==4 + Brow=1; Erow=length(xdatae(:,1)); + nyr = floor((Erow-Brow+1)/q_m); + yrsg = [xdatae(q_m+1,1):xdatae(q_m+1,1)+nyr-2]'; % for annual growth later on +else + if Byrqm(2)<1 | Eyrqm(2)<1 + error('This function requires specifying both years and months (quarters) in Byrqm and Eyrqm') + end + + Brow = min(find(xdatae(:,1)==Byrqm(1))); + if isempty(Brow) + error('Byrqm is outside the date range of xdatae(:,1:2)!') + end + nadt=Byrqm(2)-xdatae(Brow,2); + if nadt<0 + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Brow=Brow+nadt; + % + Erow = min(find(xdatae(:,1)==Eyrqm(1))); + if isempty(Brow) + error('Eyrqm is outside the date range of xdatae(:,1:2)!') + end + nadt2=Eyrqm(2)-xdatae(Erow,2); + if nadt<0 + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Erow=Erow+nadt2; + + nyr = floor((Erow-Brow+1)/q_m); + yrsg = [Byrqm(1)+1:Byrqm(1)+nyr-1]'; % for annual growth later on, which will + % start at Byrqm(1) instead of Byrqm(1)+1 +end +% +yactqme = xdatae(Brow:Erow,:); % with dates +yactqm = yactqme(:,3:end); % only data + +%======== prior period change (annaluized rate) +yactqmg = yactqm(2:end,:); % start at second period to get growth rate +yactqmg(:,vlistlog) = (yactqm(2:end,vlistlog) - yactqm(1:end-1,vlistlog)) .* q_m; + % monthly, 12*log(1+growth rate), annualized growth rate +yactqmg(:,vlistlog) = 100*(exp(yactqmg(:,vlistlog))-1); +yactqmg(:,vlistper) = 100*yactqmg(:,vlistper); +yactqmge = [yactqme(2:end,1:2) yactqmg]; + +%======== change from the last year +yactqmyg = yactqm(q_m+1:end,:); % start at the last-year period to get growth rate +yactqmyg(:,vlistlog) = (yactqm(q_m+1:end,vlistlog) - yactqm(1:end-q_m,vlistlog)); +yactqmyg(:,vlistlog) = 100*(exp(yactqmyg(:,vlistlog))-1); +yactqmyg(:,vlistper) = 100*yactqmyg(:,vlistper); +yactqmyge = [yactqme(q_m+1:end,1:2) yactqmyg]; + +%======== annual growth rates +nvar = length(xdatae(1,3:end)); +ygmts = yactqm(1:nyr*q_m,:); % converted to the multiplication of q_m +ygmts1 = reshape(ygmts,q_m,nyr,nvar); +ygmts2 = sum(ygmts1,1) ./ q_m; +ygmts3 = reshape(ygmts2,nyr,nvar); % converted to annual average series +% +yactyrg = ygmts3(2:end,:); % start at the last-year period to get growth rate +yactyrg(:,vlistlog) = ygmts3(2:end,vlistlog) - ygmts3(1:end-1,vlistlog); + % annual rate: log(1+growth rate) +yactyrg(:,vlistlog) = 100*(exp(yactyrg(:,vlistlog))-1); +yactyrg(:,vlistper) = 100*yactyrg(:,vlistper); +yactyrge = [yrsg zeros(nyr-1,1) yactyrg]; +yrsg1=[yrsg(1)-1:yrsg(end)]'; +yactyre = [yrsg1 zeros(nyr,1) ygmts3]; diff --git a/MatlabFiles/fn_datana2.m b/MatlabFiles/fn_datana2.m index 6a78d07537764973aad225318be1ff0904f47299..c67531e06b7496d0e0f814960a1e36f164db4279 100644 --- a/MatlabFiles/fn_datana2.m +++ b/MatlabFiles/fn_datana2.m @@ -1,193 +1,193 @@ -function [yactyrge,yactyre,yactqmyge,yactqmge,yactqge,yacteoqyge,yactqme] = fn_datana2(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) -% [yactyrge,yactyre,yactqmyge,yactqmge,yactqge,yacteoqyge,yactqme] = fn_datana2(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) -% -% Generate prior period, period-this-year-to-period-last-year, and other growth rates. -% For annual rates, works for both calendar and any annual years, depending on Byrqm and Eyrqm -% -% xdatae: all data (logged levels or interest rates/100, some of which may be NaN) with the first -% 2 columns indicating years and periods. -% q_m: quarter or month period -% vlistlog: sublist for logged variables -% vlistper: sublists for percent variables -% Byrqm: [year quarter(month)] -- beginning year and period. Optional. If Byqm(2)~=1, we don't get -% calendar annual rates. In other words, the first column of yactyge (which -% indicates years) does not mean calendar years. Byqm(2) must be specified; in other -% words, it must be not set to 0 as in, say, fn_dataext. -% Eyrqm: [year period] -- end year and period. Optional. Eyqm(2) must be specified; in other words, it -% must be not set to 0 as in, say, fn_dataext. -% NOTE: if no inputs Byrqm and Eyrqm are specified, all growth rates begin at xdatae(1,1:2). -%---------- -% yactyrge: annual growth rates with dates in the first 2 columns. -% yactyre: annual average logged level with dates in the 1st 2 columns. -% yactqmyge: period-this-year-to-period-last-year annual growth rates with dates in the first 2 columns. -% yactqmge: prior-period annualized growth rates with dates in the first 2 columns. -% yactqge: if monthly data, prior-quarter annualized growth rate with dates in the first 2 columns; -% if not, yactqge = NaN. -% yacteoqyge: if monthly data, EOQ is last month of quarter. EOQ-this-year-to-EOQ-last-year annual growth rates with dates in first 2 columns. -% If not monthly data, yacteoqyge = NaN. -% Note that yacteoqyge(:,1:2) = yactqge(4:end,1:2). -% yactqme: data (logged levels or interest rates/100) with dates in the first 2 columns. -% Same as xdatae but with Brow:Erow. -% -% Tao Zha, April 2000. -% See the old but useful function fore_mqy.m. -% Added yactqge in February 2004. -% Added yacteoqyge in March 2004. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if size(xdatae,1)<2*q_m - error('We need at least two years of xdatae to get annual rates. Check xdatae!!') -end - -if nargin==4 - Brow=1; Erow=length(xdatae(:,1)); - nyr = floor((Erow-Brow+1)/q_m); - yrsg = [xdatae(q_m+1,1):xdatae(q_m+1,1)+nyr-2]'; % for annual growth later on -else - if Byrqm(2)<1 | Eyrqm(2)<1 - error('This function requires specifying both years and months (quarters) in Byrqm and Eyrqm') - end - - Brow = min(find(xdatae(:,1)==Byrqm(1))); - if isempty(Brow) - error('Byrqm is outside the date range of xdatae(:,1:2)!') - end - nadt=Byrqm(2)-xdatae(Brow,2); - if nadt<0 - error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Brow=Brow+nadt; - % - Erow = min(find(xdatae(:,1)==Eyrqm(1))); - if isempty(Brow) - error('Eyrqm is outside the date range of xdatae(:,1:2)!') - end - nadt2=Eyrqm(2)-xdatae(Erow,2); - if nadt<0 - error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') - end - Erow=Erow+nadt2; - - nyr = floor((Erow-Brow+1)/q_m); - yrsg = [Byrqm(1)+1:Byrqm(1)+nyr-1]'; % for annual growth later on, which will - % start at Byrqm(1) instead of Byrqm(1)+1 -end -% -yactqme = xdatae(Brow:Erow,:); % with dates -yactqm = yactqme(:,3:end); % only data - -%======== prior period change (annaluized rate) -yactqmg = yactqm(2:end,:); % start at second period to get growth rate -yactqmg(:,vlistlog) = (yactqm(2:end,vlistlog) - yactqm(1:end-1,vlistlog)) .* q_m; - % monthly, 12*log(1+growth rate), annualized growth rate -yactqmg(:,vlistlog) = 100*(exp(yactqmg(:,vlistlog))-1); -yactqmg(:,vlistper) = 100*yactqmg(:,vlistper); -yactqmge = [yactqme(2:end,1:2) yactqmg]; - -%======== change from the last year -yactqmyg = yactqm(q_m+1:end,:); % start at the last-year period to get growth rate -yactqmyg(:,vlistlog) = (yactqm(q_m+1:end,vlistlog) - yactqm(1:end-q_m,vlistlog)); -yactqmyg(:,vlistlog) = 100*(exp(yactqmyg(:,vlistlog))-1); -yactqmyg(:,vlistper) = 100*yactqmyg(:,vlistper); -yactqmyge = [yactqme(q_m+1:end,1:2) yactqmyg]; - -%======== annual growth rates -nvar = length(xdatae(1,3:end)); -ygmts = yactqm(1:nyr*q_m,:); % converted to the multiplication of q_m -ygmts1 = reshape(ygmts,q_m,nyr,nvar); -ygmts2 = sum(ygmts1,1) ./ q_m; -ygmts3 = reshape(ygmts2,nyr,nvar); % converted to annual average series -% -yactyrg = ygmts3(2:end,:); % start at the last-year period to get growth rate -yactyrg(:,vlistlog) = ygmts3(2:end,vlistlog) - ygmts3(1:end-1,vlistlog); - % annual rate: log(1+growth rate) -yactyrg(:,vlistlog) = 100*(exp(yactyrg(:,vlistlog))-1); -yactyrg(:,vlistper) = 100*yactyrg(:,vlistper); -yactyrge = [yrsg zeros(nyr-1,1) yactyrg]; -yrsg1=[yrsg(1)-1:yrsg(end)]'; -yactyre = [yrsg1 zeros(nyr,1) ygmts3]; - - -%======== Quarter-to-last quarter annualized growth rates. -if (q_m==12) - %=== Beginning row. - mcnt = mod(xdatae(1,2),3); %Begining month. - if (mcnt==0) - QrowBin = 2; % Reset the beginning month to match a quarter. - elseif (mcnt==1) - QrowBin = 1; % Reset the beginning month to match a quarter. - elseif (mcnt==2) - QrowBin = 3; % Reset the beginning month to match a quarter. - else - error('.../fn_datana2.m: Number for months in the dates must be between 1 and 12 inclusive'); - end - Qcnt = (xdatae(QrowBin,2)+2)/3; - if (xdatae(1,2)<11) % Up to October. - QyearBin = xdatae(1,1); - else % November and December. - QyearBin = xdatae(1,1) + 1; - end;%if - %=== Ending row. - QrowEnd = size(xdatae, 1) - mod(xdatae(end,2),3); % Reset the ending month to match a quarter. - nqs = (QrowEnd - QrowBin + 1)/3; - - - %=== Getting last month of the quarter (end of quarter: eoq). - yacteoq = xdatae(QrowBin:QrowEnd,3:end); % Without dates. - yacteoq1 = reshape(yacteoq, 3, nqs, nvar); - yacteoq2 = zeros(1, nqs, nvar); - yacteoq2(:,:,vlistper) = yacteoq1(3,:,vlistper); - yacteoq2(:,:,vlistlog) = yacteoq1(3,:,vlistlog); - yacteoq3 = reshape(yacteoq2, nqs, nvar); - %=== EOQ-this-year-to-EOQ-last-year annual growth rates. - yacteoqyg = yacteoq3(5:end,:); - yacteoqyg(:,vlistlog) = 100*(exp(yacteoq3(5:end, vlistlog) - yacteoq3(1:end-4, vlistlog))-1); - yacteoqyg(:,vlistper) = 100*yacteoqyg(:,vlistper); - - - %=== Getting quarterly averages. - yactq = xdatae(QrowBin:QrowEnd,3:end); % Without dates. - nqs = (QrowEnd - QrowBin + 1)/3; - yactq1 = reshape(yactq, 3, nqs, nvar); - yactq2 = zeros(1, nqs, nvar); - yactq2(:,:,vlistper) = sum(yactq1(:,:,vlistper), 1) ./ 3; - yactq2(:,:,vlistlog) = sum(exp(yactq1(:,:,vlistlog)), 1) ./ 3; - yactq3 = reshape(yactq2, nqs, nvar); - %=== Quarterly (to prior-quarter) annualized growth rates. - yactqg = yactq3(2:end,:); - yactqg(:,vlistlog) = 100*((yactq3(2:end, vlistlog) ./ yactq3(1:end-1, vlistlog)).^4-1); - yactqg(:,vlistper) = 100*yactqg(:,vlistper); - - - %======= Adding quarterly dates. ======= - qdates = zeros(nqs,2); - for k=1:nqs - qdates(k,1) = floor(QyearBin + (k+Qcnt-2)/4); - tmpi = mod(k+Qcnt-1, 4); - if (tmpi==0) - qdates(k,2) = 4; - else - qdates(k,2) = tmpi; - end - end - yacteoqyge = [qdates(5:end,:) yacteoqyg]; - yactqge = [qdates(2:end,:) yactqg]; -else - yacteoqyge = NaN; - yactqge = NaN; -end +function [yactyrge,yactyre,yactqmyge,yactqmge,yactqge,yacteoqyge,yactqme] = fn_datana2(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) +% [yactyrge,yactyre,yactqmyge,yactqmge,yactqge,yacteoqyge,yactqme] = fn_datana2(xdatae,q_m,vlistlog,vlistper,Byrqm,Eyrqm) +% +% Generate prior period, period-this-year-to-period-last-year, and other growth rates. +% For annual rates, works for both calendar and any annual years, depending on Byrqm and Eyrqm +% +% xdatae: all data (logged levels or interest rates/100, some of which may be NaN) with the first +% 2 columns indicating years and periods. +% q_m: quarter or month period +% vlistlog: sublist for logged variables +% vlistper: sublists for percent variables +% Byrqm: [year quarter(month)] -- beginning year and period. Optional. If Byqm(2)~=1, we don't get +% calendar annual rates. In other words, the first column of yactyge (which +% indicates years) does not mean calendar years. Byqm(2) must be specified; in other +% words, it must be not set to 0 as in, say, fn_dataext. +% Eyrqm: [year period] -- end year and period. Optional. Eyqm(2) must be specified; in other words, it +% must be not set to 0 as in, say, fn_dataext. +% NOTE: if no inputs Byrqm and Eyrqm are specified, all growth rates begin at xdatae(1,1:2). +%---------- +% yactyrge: annual growth rates with dates in the first 2 columns. +% yactyre: annual average logged level with dates in the 1st 2 columns. +% yactqmyge: period-this-year-to-period-last-year annual growth rates with dates in the first 2 columns. +% yactqmge: prior-period annualized growth rates with dates in the first 2 columns. +% yactqge: if monthly data, prior-quarter annualized growth rate with dates in the first 2 columns; +% if not, yactqge = NaN. +% yacteoqyge: if monthly data, EOQ is last month of quarter. EOQ-this-year-to-EOQ-last-year annual growth rates with dates in first 2 columns. +% If not monthly data, yacteoqyge = NaN. +% Note that yacteoqyge(:,1:2) = yactqge(4:end,1:2). +% yactqme: data (logged levels or interest rates/100) with dates in the first 2 columns. +% Same as xdatae but with Brow:Erow. +% +% Tao Zha, April 2000. +% See the old but useful function fore_mqy.m. +% Added yactqge in February 2004. +% Added yacteoqyge in March 2004. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if size(xdatae,1)<2*q_m + error('We need at least two years of xdatae to get annual rates. Check xdatae!!') +end + +if nargin==4 + Brow=1; Erow=length(xdatae(:,1)); + nyr = floor((Erow-Brow+1)/q_m); + yrsg = [xdatae(q_m+1,1):xdatae(q_m+1,1)+nyr-2]'; % for annual growth later on +else + if Byrqm(2)<1 | Eyrqm(2)<1 + error('This function requires specifying both years and months (quarters) in Byrqm and Eyrqm') + end + + Brow = min(find(xdatae(:,1)==Byrqm(1))); + if isempty(Brow) + error('Byrqm is outside the date range of xdatae(:,1:2)!') + end + nadt=Byrqm(2)-xdatae(Brow,2); + if nadt<0 + error('Byrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Brow=Brow+nadt; + % + Erow = min(find(xdatae(:,1)==Eyrqm(1))); + if isempty(Brow) + error('Eyrqm is outside the date range of xdatae(:,1:2)!') + end + nadt2=Eyrqm(2)-xdatae(Erow,2); + if nadt<0 + error('Eyrqm is outside the date range indicated by xdatae(:,1:2)!') + end + Erow=Erow+nadt2; + + nyr = floor((Erow-Brow+1)/q_m); + yrsg = [Byrqm(1)+1:Byrqm(1)+nyr-1]'; % for annual growth later on, which will + % start at Byrqm(1) instead of Byrqm(1)+1 +end +% +yactqme = xdatae(Brow:Erow,:); % with dates +yactqm = yactqme(:,3:end); % only data + +%======== prior period change (annaluized rate) +yactqmg = yactqm(2:end,:); % start at second period to get growth rate +yactqmg(:,vlistlog) = (yactqm(2:end,vlistlog) - yactqm(1:end-1,vlistlog)) .* q_m; + % monthly, 12*log(1+growth rate), annualized growth rate +yactqmg(:,vlistlog) = 100*(exp(yactqmg(:,vlistlog))-1); +yactqmg(:,vlistper) = 100*yactqmg(:,vlistper); +yactqmge = [yactqme(2:end,1:2) yactqmg]; + +%======== change from the last year +yactqmyg = yactqm(q_m+1:end,:); % start at the last-year period to get growth rate +yactqmyg(:,vlistlog) = (yactqm(q_m+1:end,vlistlog) - yactqm(1:end-q_m,vlistlog)); +yactqmyg(:,vlistlog) = 100*(exp(yactqmyg(:,vlistlog))-1); +yactqmyg(:,vlistper) = 100*yactqmyg(:,vlistper); +yactqmyge = [yactqme(q_m+1:end,1:2) yactqmyg]; + +%======== annual growth rates +nvar = length(xdatae(1,3:end)); +ygmts = yactqm(1:nyr*q_m,:); % converted to the multiplication of q_m +ygmts1 = reshape(ygmts,q_m,nyr,nvar); +ygmts2 = sum(ygmts1,1) ./ q_m; +ygmts3 = reshape(ygmts2,nyr,nvar); % converted to annual average series +% +yactyrg = ygmts3(2:end,:); % start at the last-year period to get growth rate +yactyrg(:,vlistlog) = ygmts3(2:end,vlistlog) - ygmts3(1:end-1,vlistlog); + % annual rate: log(1+growth rate) +yactyrg(:,vlistlog) = 100*(exp(yactyrg(:,vlistlog))-1); +yactyrg(:,vlistper) = 100*yactyrg(:,vlistper); +yactyrge = [yrsg zeros(nyr-1,1) yactyrg]; +yrsg1=[yrsg(1)-1:yrsg(end)]'; +yactyre = [yrsg1 zeros(nyr,1) ygmts3]; + + +%======== Quarter-to-last quarter annualized growth rates. +if (q_m==12) + %=== Beginning row. + mcnt = mod(xdatae(1,2),3); %Begining month. + if (mcnt==0) + QrowBin = 2; % Reset the beginning month to match a quarter. + elseif (mcnt==1) + QrowBin = 1; % Reset the beginning month to match a quarter. + elseif (mcnt==2) + QrowBin = 3; % Reset the beginning month to match a quarter. + else + error('.../fn_datana2.m: Number for months in the dates must be between 1 and 12 inclusive'); + end + Qcnt = (xdatae(QrowBin,2)+2)/3; + if (xdatae(1,2)<11) % Up to October. + QyearBin = xdatae(1,1); + else % November and December. + QyearBin = xdatae(1,1) + 1; + end;%if + %=== Ending row. + QrowEnd = size(xdatae, 1) - mod(xdatae(end,2),3); % Reset the ending month to match a quarter. + nqs = (QrowEnd - QrowBin + 1)/3; + + + %=== Getting last month of the quarter (end of quarter: eoq). + yacteoq = xdatae(QrowBin:QrowEnd,3:end); % Without dates. + yacteoq1 = reshape(yacteoq, 3, nqs, nvar); + yacteoq2 = zeros(1, nqs, nvar); + yacteoq2(:,:,vlistper) = yacteoq1(3,:,vlistper); + yacteoq2(:,:,vlistlog) = yacteoq1(3,:,vlistlog); + yacteoq3 = reshape(yacteoq2, nqs, nvar); + %=== EOQ-this-year-to-EOQ-last-year annual growth rates. + yacteoqyg = yacteoq3(5:end,:); + yacteoqyg(:,vlistlog) = 100*(exp(yacteoq3(5:end, vlistlog) - yacteoq3(1:end-4, vlistlog))-1); + yacteoqyg(:,vlistper) = 100*yacteoqyg(:,vlistper); + + + %=== Getting quarterly averages. + yactq = xdatae(QrowBin:QrowEnd,3:end); % Without dates. + nqs = (QrowEnd - QrowBin + 1)/3; + yactq1 = reshape(yactq, 3, nqs, nvar); + yactq2 = zeros(1, nqs, nvar); + yactq2(:,:,vlistper) = sum(yactq1(:,:,vlistper), 1) ./ 3; + yactq2(:,:,vlistlog) = sum(exp(yactq1(:,:,vlistlog)), 1) ./ 3; + yactq3 = reshape(yactq2, nqs, nvar); + %=== Quarterly (to prior-quarter) annualized growth rates. + yactqg = yactq3(2:end,:); + yactqg(:,vlistlog) = 100*((yactq3(2:end, vlistlog) ./ yactq3(1:end-1, vlistlog)).^4-1); + yactqg(:,vlistper) = 100*yactqg(:,vlistper); + + + %======= Adding quarterly dates. ======= + qdates = zeros(nqs,2); + for k=1:nqs + qdates(k,1) = floor(QyearBin + (k+Qcnt-2)/4); + tmpi = mod(k+Qcnt-1, 4); + if (tmpi==0) + qdates(k,2) = 4; + else + qdates(k,2) = tmpi; + end + end + yacteoqyge = [qdates(5:end,:) yacteoqyg]; + yactqge = [qdates(2:end,:) yactqg]; +else + yacteoqyge = NaN; + yactqge = NaN; +end diff --git a/MatlabFiles/fn_dataxy.m b/MatlabFiles/fn_dataxy.m index 128038a58ec47c7fcd1dcd6c112e7d6451da138b..e8bce7e7d85a9668052a213cddcd07f7e3e9c346 100644 --- a/MatlabFiles/fn_dataxy.m +++ b/MatlabFiles/fn_dataxy.m @@ -1,164 +1,164 @@ -function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy(nvar,lags,z,mu,indxDummy,nexo) -% [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy(nvar,lags,z,mu,indxDummy,nexo) -% -% Export arranged data matrices for future estimation of the VAR. -% If indxDummy=0, no mu's are used at all and Bh is the OLS estimate. -% If indxDummy=1, only mu(5) and mu(6) as dummy observations. See fn_rnrprior*.m for using mu(1)-mu(4). -% See Wagonner and Zha's Gibbs sampling paper. -% -% nvar: number of endogenous variables. -% lags: the maximum length of lag -% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) -% with sample size including lags and with exogenous variables other than a constant. -% Order of columns: (1) nvar endogenous variables; (2) (nexo-1) exogenous variables; -% (3) constants will be automatically put in the last column. -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% only mu(5) and mu(6) are used for dummy observations in this function (i.e., -% mu(1)-mu(4) are irrelevant here). See fn_rnrprior*.m for using mu(1)-mu(4). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1) -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% indxDummy: 1: add dummy observations to the data; 0: no dummy added. -% nexo: number of exogenous variables. The constant term is the default setting. Besides this term, -% we have nexo-1 exogenous variables. Optional. If left blank, nexo is set to 1. -% ------------------- -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. -% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] -% y: Y: T-by-nvar where T=fss -% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+nexo -% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X -% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; -% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] -% e: estimated residual e = y -x*Bh, T-by-nvar -% -% Tao Zha, February 2000. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin == 5 - nexo=1; % default for constant term -elseif nexo<1 - error('We need at least one exogenous term so nexo must >= 1') -end - -%*** original sample dimension without dummy prior -nSample = size(z,1); % the sample size (including lags, of course) -sb = lags+1; % original beginning without dummies -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -if indxDummy % prior dummy prior - %*** expanded sample dimension by dummy prior - ndobs=nvar+1; % number of dummy observations - fss = nSample+ndobs-lags; - - % - % **** nvar prior dummy observations with the sum of coefficients - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % ** Now, T=T+ndobs -- added with "ndobs" dummy observations - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - const(1:nvar) = zeros(nvar,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - exox = zeros(ndobs,nexo); - phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %* Dummies - for k=1:nvar - for m=1:lags - phi(ndobs,nvar*(m-1)+k) = xdgelint(k); - phi(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - %* True data - for k=1:lags - phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - % ** Y with "ndobs" dummies added - y = zeros(fss,nvar); - %* Dummies - for k=1:nvar - y(ndobs,k) = xdgelint(k); - y(k,k) = xdgelint(k); - % multiply hyperparameter later - end - %* True data - y(ndobs+1:fss,:) = xdgel(sb:nSample,:); - - phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior - y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior - phi(nvar+1,:) = mu(6)*phi(nvar+1,:); - y(nvar+1,:) = mu(6)*y(nvar+1,:); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -else - fss = nSample-lags; - % - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - %* True data - for k=1:lags - phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - y = xdgel(sb:nSample,:); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -end +function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy(nvar,lags,z,mu,indxDummy,nexo) +% [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy(nvar,lags,z,mu,indxDummy,nexo) +% +% Export arranged data matrices for future estimation of the VAR. +% If indxDummy=0, no mu's are used at all and Bh is the OLS estimate. +% If indxDummy=1, only mu(5) and mu(6) as dummy observations. See fn_rnrprior*.m for using mu(1)-mu(4). +% See Wagonner and Zha's Gibbs sampling paper. +% +% nvar: number of endogenous variables. +% lags: the maximum length of lag +% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) +% with sample size including lags and with exogenous variables other than a constant. +% Order of columns: (1) nvar endogenous variables; (2) (nexo-1) exogenous variables; +% (3) constants will be automatically put in the last column. +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% only mu(5) and mu(6) are used for dummy observations in this function (i.e., +% mu(1)-mu(4) are irrelevant here). See fn_rnrprior*.m for using mu(1)-mu(4). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1) +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% indxDummy: 1: add dummy observations to the data; 0: no dummy added. +% nexo: number of exogenous variables. The constant term is the default setting. Besides this term, +% we have nexo-1 exogenous variables. Optional. If left blank, nexo is set to 1. +% ------------------- +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. +% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] +% y: Y: T-by-nvar where T=fss +% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+nexo +% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X +% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; +% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] +% e: estimated residual e = y -x*Bh, T-by-nvar +% +% Tao Zha, February 2000. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin == 5 + nexo=1; % default for constant term +elseif nexo<1 + error('We need at least one exogenous term so nexo must >= 1') +end + +%*** original sample dimension without dummy prior +nSample = size(z,1); % the sample size (including lags, of course) +sb = lags+1; % original beginning without dummies +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +if indxDummy % prior dummy prior + %*** expanded sample dimension by dummy prior + ndobs=nvar+1; % number of dummy observations + fss = nSample+ndobs-lags; + + % + % **** nvar prior dummy observations with the sum of coefficients + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % ** Now, T=T+ndobs -- added with "ndobs" dummy observations + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + const(1:nvar) = zeros(nvar,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + exox = zeros(ndobs,nexo); + phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %* Dummies + for k=1:nvar + for m=1:lags + phi(ndobs,nvar*(m-1)+k) = xdgelint(k); + phi(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + %* True data + for k=1:lags + phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + % ** Y with "ndobs" dummies added + y = zeros(fss,nvar); + %* Dummies + for k=1:nvar + y(ndobs,k) = xdgelint(k); + y(k,k) = xdgelint(k); + % multiply hyperparameter later + end + %* True data + y(ndobs+1:fss,:) = xdgel(sb:nSample,:); + + phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior + y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior + phi(nvar+1,:) = mu(6)*phi(nvar+1,:); + y(nvar+1,:) = mu(6)*y(nvar+1,:); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +else + fss = nSample-lags; + % + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + %* True data + for k=1:lags + phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + y = xdgel(sb:nSample,:); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +end diff --git a/MatlabFiles/fn_dataxy7982.m b/MatlabFiles/fn_dataxy7982.m index c08e79cbb39313a65516845d46e47f8b2607f355..334b4186ca38d43c246c9e4efd9154956539d7f7 100644 --- a/MatlabFiles/fn_dataxy7982.m +++ b/MatlabFiles/fn_dataxy7982.m @@ -1,183 +1,183 @@ -function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy7982(nvar,lags,z,mu,indxDummy,... - q_m,SpBin,SkipBin,SkipFin,nexo) -% [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy7982(nvar,lags,z,mu,indxDummy,... -% q_m,SpBin,SkipBin,SkipFin,nexo) -% Export arranged data matrices for future estimation for DM models with the period from -% SkipBin to SkipFin to be skiped. -% See Wagonner and Zha's Gibbs sampling paper. -% -% nvar: number of endogenous variables. -% lags: the maximum length of lag -% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) -% with sample size including lags and with exogenous variables other than a constant. -% Order of columns: (1) nvar endogenous variables; (2) (nexo-1) exogenous variables; -% (3) constants are automatically put in the last column. -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1) -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% Here, only mu(5) and mu(6) are used for dummy observations -% indxDummy = 1; % 1: add dummy observations to the data; 0: no dummy added. -% q_m: 12 (monthly) or 4 (quarterly). -% SpBin: [year month] at the begining of the sample (including lags). -% SkipBin: [year month] at the begining of the skipped period. -% SkipFin: [year month] at the end of the skipped period. -% nexo: number of exogenous variables. The constant term is the default setting. Besides this term, -% we have nexo-1 exogenous variables. -% ------------------- -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. -% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] -% y: Y: T-by-nvar where T=fss -% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+nexo -% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X -% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; -% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] -% e: estimated residual e = y -x*Bh, T-by-nvar -% -% Tao Zha, February 2000. Revised, May 2001. -% See fn_dataxy.m. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin == 9 - nexo=1; % default for constant term -elseif nexo<1 - error('We need at least one exogenous term so nexo must >= 1') -end - -%*** original sample dimension without dummy prior -nSample = size(z,1); % the sample size (including lags, of course) -sb = lags+1; % original beginning without dummies -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -if indxDummy % prior dummy prior - - %*** expanded sample dimension by dummy prior - ndobs=nvar+1; % number of dummy observations - fss = nSample+ndobs-lags; - - % - % **** nvar prior dummy observations with the sum of coefficients - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % ** Now, T=T+ndobs -- added with "ndobs" dummy observations - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - const(1:nvar) = zeros(nvar,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - exox = zeros(ndobs,nexo); - phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %* Dummies - for k=1:nvar - for m=1:lags - phi(ndobs,nvar*(m-1)+k) = xdgelint(k); - phi(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - %* True data - for k=1:lags - phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - % ** Y with "ndobs" dummies added - y = zeros(fss,nvar); - %* Dummies - for k=1:nvar - y(ndobs,k) = xdgelint(k); - y(k,k) = xdgelint(k); - % multiply hyperparameter later - end - %* True data - y(ndobs+1:fss,:) = xdgel(sb:nSample,:); - - phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior - y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior - phi(nvar+1,:) = mu(6)*phi(nvar+1,:); - y(nvar+1,:) = mu(6)*y(nvar+1,:); - - %-------------- Taking the 79:10-83:12 period out ---------------------- - outper1=(SkipBin(1)-SpBin(1))*q_m+(SkipBin(2)-SpBin(2)+1) + ndobs-lags; - outper2=(SkipFin(1)-SpBin(1))*q_m+(SkipFin(2)-SpBin(2)+1) + ndobs-lags; - phi(outper1:outper2,:)=[]; - y(outper1:outper2,:)=[]; - fss=size(phi,1); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -else - fss = nSample-lags; - % - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - %* True data - for k=1:lags - phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - y = xdgel(sb:nSample,:); - - %-------------- Taking the 79:10-83:12 period out ---------------------- - outper1=(SkipBin(1)-SpBin(1))*q_m+(SkipBin(2)-SpBin(2)+1) - lags; - outper2=(SkipFin(1)-SpBin(1))*q_m+(SkipFin(2)-SpBin(2)+1) - lags; - phi(outper1:outper2,:)=[]; - y(outper1:outper2,:)=[]; - fss=size(phi,1); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -end +function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy7982(nvar,lags,z,mu,indxDummy,... + q_m,SpBin,SkipBin,SkipFin,nexo) +% [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxy7982(nvar,lags,z,mu,indxDummy,... +% q_m,SpBin,SkipBin,SkipFin,nexo) +% Export arranged data matrices for future estimation for DM models with the period from +% SkipBin to SkipFin to be skiped. +% See Wagonner and Zha's Gibbs sampling paper. +% +% nvar: number of endogenous variables. +% lags: the maximum length of lag +% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) +% with sample size including lags and with exogenous variables other than a constant. +% Order of columns: (1) nvar endogenous variables; (2) (nexo-1) exogenous variables; +% (3) constants are automatically put in the last column. +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1) +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% Here, only mu(5) and mu(6) are used for dummy observations +% indxDummy = 1; % 1: add dummy observations to the data; 0: no dummy added. +% q_m: 12 (monthly) or 4 (quarterly). +% SpBin: [year month] at the begining of the sample (including lags). +% SkipBin: [year month] at the begining of the skipped period. +% SkipFin: [year month] at the end of the skipped period. +% nexo: number of exogenous variables. The constant term is the default setting. Besides this term, +% we have nexo-1 exogenous variables. +% ------------------- +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. +% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] +% y: Y: T-by-nvar where T=fss +% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+nexo +% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X +% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; +% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] +% e: estimated residual e = y -x*Bh, T-by-nvar +% +% Tao Zha, February 2000. Revised, May 2001. +% See fn_dataxy.m. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin == 9 + nexo=1; % default for constant term +elseif nexo<1 + error('We need at least one exogenous term so nexo must >= 1') +end + +%*** original sample dimension without dummy prior +nSample = size(z,1); % the sample size (including lags, of course) +sb = lags+1; % original beginning without dummies +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +if indxDummy % prior dummy prior + + %*** expanded sample dimension by dummy prior + ndobs=nvar+1; % number of dummy observations + fss = nSample+ndobs-lags; + + % + % **** nvar prior dummy observations with the sum of coefficients + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % ** Now, T=T+ndobs -- added with "ndobs" dummy observations + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + const(1:nvar) = zeros(nvar,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + exox = zeros(ndobs,nexo); + phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %* Dummies + for k=1:nvar + for m=1:lags + phi(ndobs,nvar*(m-1)+k) = xdgelint(k); + phi(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + %* True data + for k=1:lags + phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + % ** Y with "ndobs" dummies added + y = zeros(fss,nvar); + %* Dummies + for k=1:nvar + y(ndobs,k) = xdgelint(k); + y(k,k) = xdgelint(k); + % multiply hyperparameter later + end + %* True data + y(ndobs+1:fss,:) = xdgel(sb:nSample,:); + + phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior + y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior + phi(nvar+1,:) = mu(6)*phi(nvar+1,:); + y(nvar+1,:) = mu(6)*y(nvar+1,:); + + %-------------- Taking the 79:10-83:12 period out ---------------------- + outper1=(SkipBin(1)-SpBin(1))*q_m+(SkipBin(2)-SpBin(2)+1) + ndobs-lags; + outper2=(SkipFin(1)-SpBin(1))*q_m+(SkipFin(2)-SpBin(2)+1) + ndobs-lags; + phi(outper1:outper2,:)=[]; + y(outper1:outper2,:)=[]; + fss=size(phi,1); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +else + fss = nSample-lags; + % + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + %* True data + for k=1:lags + phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + y = xdgel(sb:nSample,:); + + %-------------- Taking the 79:10-83:12 period out ---------------------- + outper1=(SkipBin(1)-SpBin(1))*q_m+(SkipBin(2)-SpBin(2)+1) - lags; + outper2=(SkipFin(1)-SpBin(1))*q_m+(SkipFin(2)-SpBin(2)+1) - lags; + phi(outper1:outper2,:)=[]; + y(outper1:outper2,:)=[]; + fss=size(phi,1); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +end diff --git a/MatlabFiles/fn_dataxyoldver.m b/MatlabFiles/fn_dataxyoldver.m index d7056fe8dff3a4b1d40b85579e3d8458914a15a4..5621eb2608778f01556020f7ee69759369e0264e 100644 --- a/MatlabFiles/fn_dataxyoldver.m +++ b/MatlabFiles/fn_dataxyoldver.m @@ -1,157 +1,157 @@ -function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxyOldVer(nvar,lags,z,mu5,mu6,indxDummy,nexo) -% Export arranged data matrices (including dummy obs priors) for estimation for DM models. -% See Wagonner and Zha's Gibbs sampling paper. -% -% nvar: number of endogenous variables. -% lags: the maximum length of lag -% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) -% with sample size including lags and with exogenous variables other than a constant. -% Order of columns: (1) nvar endogenous variables; (2) (nexo-1) exogenous variables; -% (3) constants are automatically put in the last column. -% mu5: nvar-by-1 weights on nvar sums of coeffs dummy observations (unit roots); (all equal 5--Atlanta model setting) -% mu6: weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5--Atlanta model number) -% indxDummy = 1; % 1: add dummy observations to the data; 0: no dummy added. -% nexo: number of exogenous variables. The constant term is the default setting. Besides this term, -% we have nexo-1 exogenous variables. -% ------------------- -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. -% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] -% y: Y: T-by-nvar where T=fss -% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+nexo -% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X -% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; -% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] -% e: estimated residual e = y -x*Bh, T-by-nvar -% -% Tao Zha, February 2000 -% See fn_rnrprior2.m for the base prior. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin == 6 - nexo=1; % default for constant term -elseif nexo<1 - error('We need at least one exogenous term so nexo must >= 1') -end - -%*** original sample dimension without dummy prior -nSample = size(z,1); % the sample size (including lags, of course) -sb = lags+1; % original beginning without dummies -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -if indxDummy % prior dummy prior - - %*** expanded sample dimension by dummy prior - ndobs=nvar+1; % number of dummy observations - fss = nSample+ndobs-lags; - - % - % **** nvar prior dummy observations with the sum of coefficients - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % ** Now, T=T+ndobs -- added with "ndobs" dummy observations - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - const(1:nvar) = zeros(nvar,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - exox = zeros(ndobs,nexo); - phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %* Dummies - for k=1:nvar - for m=1:lags - phi(ndobs,nvar*(m-1)+k) = xdgelint(k); - phi(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - %* True data - for k=1:lags - phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - % ** Y with "ndobs" dummies added - y = zeros(fss,nvar); - %* Dummies - for k=1:nvar - y(ndobs,k) = xdgelint(k); - y(k,k) = xdgelint(k); - % multiply hyperparameter later - end - %* True data - y(ndobs+1:fss,:) = xdgel(sb:nSample,:); - - for ki=1:nvar - phi(ki,:) = 1*mu5(ki)*phi(ki,:); % standard Sims and Zha prior - y(ki,:) = mu5(ki)*y(ki,:); % standard Sims and Zha prior - end - phi(nvar+1,:) = mu6*phi(nvar+1,:); - y(nvar+1,:) = mu6*y(nvar+1,:); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -else - fss = nSample-lags; - % - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % - phi = zeros(fss,ncoef); - %* constant term - const = ones(fss,1); - phi(:,ncoef) = const; % the first nvar periods: no or zero constant! - %* other exogenous (than) constant term - phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); - % this = [] when nexo=1 (no other exogenous than constant) - - xdgel = z(:,1:nvar); % endogenous variable matrix - %* True data - for k=1:lags - phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] - % Thus, # of columns is nvar*lags+nexo = ncoef. - end - % - y = xdgel(sb:nSample,:); - - [xq,xr]=qr(phi,0); - xtx=xr'*xr; - xty=phi'*y; - [yq,yr]=qr(y,0); - yty=yr'*yr; - Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) - e=y-phi*Bh; -end +function [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh,e] = fn_dataxyOldVer(nvar,lags,z,mu5,mu6,indxDummy,nexo) +% Export arranged data matrices (including dummy obs priors) for estimation for DM models. +% See Wagonner and Zha's Gibbs sampling paper. +% +% nvar: number of endogenous variables. +% lags: the maximum length of lag +% z: T*(nvar+(nexo-1)) matrix of raw or original data (no manipulation involved) +% with sample size including lags and with exogenous variables other than a constant. +% Order of columns: (1) nvar endogenous variables; (2) (nexo-1) exogenous variables; +% (3) constants are automatically put in the last column. +% mu5: nvar-by-1 weights on nvar sums of coeffs dummy observations (unit roots); (all equal 5--Atlanta model setting) +% mu6: weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5--Atlanta model number) +% indxDummy = 1; % 1: add dummy observations to the data; 0: no dummy added. +% nexo: number of exogenous variables. The constant term is the default setting. Besides this term, +% we have nexo-1 exogenous variables. +% ------------------- +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% fss: T: sample size excluding lags. With dummyies, fss=nSample-lags+ndobs. +% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] +% y: Y: T-by-nvar where T=fss +% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+nexo +% xr: the economy size (ncoef-by-ncoef) in qr(phi) so that xr=chol(X'*X) or xr'*xr=X'*X +% Bh: ncoef-by-nvar estimated reduced-form parameter; column: nvar; +% row: ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] +% e: estimated residual e = y -x*Bh, T-by-nvar +% +% Tao Zha, February 2000 +% See fn_rnrprior2.m for the base prior. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin == 6 + nexo=1; % default for constant term +elseif nexo<1 + error('We need at least one exogenous term so nexo must >= 1') +end + +%*** original sample dimension without dummy prior +nSample = size(z,1); % the sample size (including lags, of course) +sb = lags+1; % original beginning without dummies +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +if indxDummy % prior dummy prior + + %*** expanded sample dimension by dummy prior + ndobs=nvar+1; % number of dummy observations + fss = nSample+ndobs-lags; + + % + % **** nvar prior dummy observations with the sum of coefficients + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % ** Now, T=T+ndobs -- added with "ndobs" dummy observations + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + const(1:nvar) = zeros(nvar,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(ndobs+1:end,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + exox = zeros(ndobs,nexo); + phi(1:ndobs,ncoef-nexo+1:ncoef-1) = exox(:,1:nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %* Dummies + for k=1:nvar + for m=1:lags + phi(ndobs,nvar*(m-1)+k) = xdgelint(k); + phi(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + %* True data + for k=1:lags + phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + % ** Y with "ndobs" dummies added + y = zeros(fss,nvar); + %* Dummies + for k=1:nvar + y(ndobs,k) = xdgelint(k); + y(k,k) = xdgelint(k); + % multiply hyperparameter later + end + %* True data + y(ndobs+1:fss,:) = xdgel(sb:nSample,:); + + for ki=1:nvar + phi(ki,:) = 1*mu5(ki)*phi(ki,:); % standard Sims and Zha prior + y(ki,:) = mu5(ki)*y(ki,:); % standard Sims and Zha prior + end + phi(nvar+1,:) = mu6*phi(nvar+1,:); + y(nvar+1,:) = mu6*y(nvar+1,:); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +else + fss = nSample-lags; + % + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % + phi = zeros(fss,ncoef); + %* constant term + const = ones(fss,1); + phi(:,ncoef) = const; % the first nvar periods: no or zero constant! + %* other exogenous (than) constant term + phi(:,ncoef-nexo+1:ncoef-1) = z(lags+1:end,nvar+1:nvar+nexo-1); + % this = [] when nexo=1 (no other exogenous than constant) + + xdgel = z(:,1:nvar); % endogenous variable matrix + %* True data + for k=1:lags + phi(:,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, exo var, const] + % Thus, # of columns is nvar*lags+nexo = ncoef. + end + % + y = xdgel(sb:nSample,:); + + [xq,xr]=qr(phi,0); + xtx=xr'*xr; + xty=phi'*y; + [yq,yr]=qr(y,0); + yty=yr'*yr; + Bh = xr\(xr'\xty); % xtx\xty where inv(X'X)*(X'Y) + e=y-phi*Bh; +end diff --git a/MatlabFiles/fn_demarw.m b/MatlabFiles/fn_demarw.m index 08acf55affa27e681aaef7dfcecdaa7d0d25aa39..6530780049aa847ae07e9832ab53cab98a3f8aca 100644 --- a/MatlabFiles/fn_demarw.m +++ b/MatlabFiles/fn_demarw.m @@ -1,75 +1,75 @@ -function [imfl,imfh,imfl1,imfh1, imfmedian] = demarw(xpo,xprob) -% [imfl,imfh,imfl1,imfh1] = fn_demarw(xpo,xprob) -% Demarcate the .68 and .90 error bands given positions and properly scaled probabilities (weights). -% Calls fn_histwpdfg() first. -% -% xpo: ndraws-by-n. Centered position -% xprob: ndraws-by-n. Must be properly scaled probabilities corresponding to xpo. -%----------------- -% imfl: lower .90 bound, n-by-1 -% imfh: higher .90 bound, n-by-1 -% imfl1: lower .68 bound, n-by-1 -% imfh1: higher .68 bound, n-by-1 -% imfmedian: .50 estimate, n-by-1. -% -% Note: fn_histwpdfg() must be called first to get xpo and xprob. -% August 1999 Tao Zha; Revised, August 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[ndraws,n]=size(xpo); - -%$$$ .68 and .95 probability bands -imfl = zeros(n,1); % preallocating -imfh = zeros(n,1); % preallocating -imfl1 = zeros(n,1); % preallocating -imfh1 = zeros(n,1); % preallocating -imfmedian = zeros(n,1); % preallocating -imfpo = zeros(4,n); % 4 positions: l,h,l1,h1. -% -%tic -tem = cumsum(xprob); % cumulative probability -tem = tem .* 100; -% -%@@@ the following operations are valid only because tem are increasing! -for k = 1:n - % - %@@@ the following operations are valid only because tem are increasing! - %** 5% low tail - if isempty(max(find(tem(:,k)<5))) - imfl(k) = xpo(1,k); - else - imfl(k) = xpo(max(find(tem(:,k)<5)),k); - end - %** 16% low tail - if isempty(max(find(tem(:,k)<16))) - imfl1(k) = xpo(1,k); - else - imfl1(k) = xpo(max(find(tem(:,k)<16)),k); - end - %** 50% estimate - if isempty(max(find(tem(:,k)<50))) - imfmedian(k) = xpo(1,k); - else - imfmedian(k) = xpo(max(find(tem(:,k)<50)),k); - end - %** 5% high tail - imfh(k) = xpo(min(find(tem(:,k)>95)),k); - %** 16% low tail - imfh1(k) = xpo(min(find(tem(:,k)>84)),k); -end +function [imfl,imfh,imfl1,imfh1, imfmedian] = demarw(xpo,xprob) +% [imfl,imfh,imfl1,imfh1] = fn_demarw(xpo,xprob) +% Demarcate the .68 and .90 error bands given positions and properly scaled probabilities (weights). +% Calls fn_histwpdfg() first. +% +% xpo: ndraws-by-n. Centered position +% xprob: ndraws-by-n. Must be properly scaled probabilities corresponding to xpo. +%----------------- +% imfl: lower .90 bound, n-by-1 +% imfh: higher .90 bound, n-by-1 +% imfl1: lower .68 bound, n-by-1 +% imfh1: higher .68 bound, n-by-1 +% imfmedian: .50 estimate, n-by-1. +% +% Note: fn_histwpdfg() must be called first to get xpo and xprob. +% August 1999 Tao Zha; Revised, August 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[ndraws,n]=size(xpo); + +%$$$ .68 and .95 probability bands +imfl = zeros(n,1); % preallocating +imfh = zeros(n,1); % preallocating +imfl1 = zeros(n,1); % preallocating +imfh1 = zeros(n,1); % preallocating +imfmedian = zeros(n,1); % preallocating +imfpo = zeros(4,n); % 4 positions: l,h,l1,h1. +% +%tic +tem = cumsum(xprob); % cumulative probability +tem = tem .* 100; +% +%@@@ the following operations are valid only because tem are increasing! +for k = 1:n + % + %@@@ the following operations are valid only because tem are increasing! + %** 5% low tail + if isempty(max(find(tem(:,k)<5))) + imfl(k) = xpo(1,k); + else + imfl(k) = xpo(max(find(tem(:,k)<5)),k); + end + %** 16% low tail + if isempty(max(find(tem(:,k)<16))) + imfl1(k) = xpo(1,k); + else + imfl1(k) = xpo(max(find(tem(:,k)<16)),k); + end + %** 50% estimate + if isempty(max(find(tem(:,k)<50))) + imfmedian(k) = xpo(1,k); + else + imfmedian(k) = xpo(max(find(tem(:,k)<50)),k); + end + %** 5% high tail + imfh(k) = xpo(min(find(tem(:,k)>95)),k); + %** 16% low tail + imfh1(k) = xpo(min(find(tem(:,k)>84)),k); +end diff --git a/MatlabFiles/fn_dirichprior.m b/MatlabFiles/fn_dirichprior.m index 6c903d434e708f27faeb1cc48fa54724c91041e5..6f660c49300b47e951cc2504a30516e42397fbb6 100644 --- a/MatlabFiles/fn_dirichprior.m +++ b/MatlabFiles/fn_dirichprior.m @@ -1,95 +1,95 @@ -function [Galpha,stdthe] = fn_dirichprior(Glamda,std_maxv) -% [Galpha,stdthe] = fn_dirichprior(Glamda,std_maxv) -% Setup of the Dirichlet prior on the transition matrix P. Given the mode of each random -% variable theta_j, solve for the (hyper)parameter \alpha where one of \alpha, say, \alpha_j -% is free for controlling the overall variance of \alpha consisdent with the given modes. -% -% Glamda: h-by-1 vector of prior modes for the random variables \theta. -% For each column of P (transitional matrix), Glamda'll be different with a large weight on a diaganol. -% std_maxv: prior standard deviation for the selected random variable -% (here the one with the maximum (largest) mode). -%---------- -% Galpha: h-by-1 vector of parameters' values for the Dirichlet distribtuion. If one of the -% elements in Galpha is Inf, we mean a degenerate case where stdthe is set to zeros. -% stdthe: h-by-1 vector of standard deviations for all random variables \theta. -% -% See Gelman, et al p. 476 and TVBvar Note pp. 24-31 -% Tao Zha, March 2001 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -Glamda = Glamda(:); % Column vector! Prior modes for the random variables \theta. -[maxlam,indxlam] = max(Glamda); % index for the selected hyperparameter that is freely set to match the variance of the corresponding random variable. -ndiri = length(Glamda); % the number of random variables in the Dirichlet distribution. -Galpha=zeros(ndiri,1); % \alpha's: hyperparameters that need to be choosen. Must be all greater than 1. -stdthe = zeros(ndiri,1); % Standard deviations for each \theta -if indxlam>ndiri - warning('Make sure indxlam is less than the total number of parameters in the Dirichlet') - error(' ') -end -if (maxlam==1) % We treat this as a degenerate case for convenient coding. - Galpha(indxlam)=Inf; % Note the use of Inf, NOT NaN. Because - % 0(or any finite number)/Inf=0 while 0/NaN gives a nonsense (i.e., NaN again). - % See tveml.m and pp. 27a-27b for more information. - return % The function stops here. -end - - -%*** Given std_maxv, find the corresponding hyperparameter Galpha_j by soloving -% a polynomial of order 3. See Note (*) page 30. -vj=std_maxv^2; % variance of the selected random variable \theta. -Gsi = (1-Glamda(indxlam))/Glamda(indxlam); % unchanged value, given Glamda. -coevec = zeros(4,1); % 4 because we're going to consider a polynomial of order 3 (+ constant). -coevec(1) = vj*(1+Gsi)^3; -coevec(2) = vj*(1+Gsi)^2*(3*(ndiri-Gsi)-2) - Gsi; -coevec(3) = (ndiri-Gsi-1)*(vj*(1+Gsi)*(3*(ndiri-Gsi)-1)-1); -coevec(4) = vj*(ndiri-Gsi)*(ndiri-Gsi-1)^2; - -Galphaj = max(roots(coevec)); % j: jth element, set to match the variance. Must be greater than 1. -if (Galphaj<=1) - disp(' ') - warning('Error! Make sure std_maxv is small enough to have a large Galphaj > 1') - error(' ') -end - -%*** Solve for the rest of \alpha's. See Note page 27. -A = eye(ndiri) - repmat(Glamda,[1 ndiri]); -C = ones(ndiri,1) + (Galphaj-ndiri)*Glamda; -A1=A; C1=C; -A1(indxlam,:)=[]; A1(:,indxlam)=[]; C1(indxlam)=[]; -indxrest=1:ndiri; indxrest(indxlam)=[]; -Galpha(indxrest) = A1\C1; -Galpha(indxlam) = Galphaj; - -%========= Debugging or checking the properties ========== -%disp(' ') -%disp('2nd-to-first-or-rest ratio: it should not change with the last element of \alpha') -%(Galpha(2)-1)/(Galpha(1)-1) -%(Galpha(2)-1)/(sum(Galpha([1 3]))-2) -%disp(' ') -%disp('Solution for \alpha') -%Galpha - -for k=1:ndiri - tmp=Galpha; - tmp(k)=[]; - stdthe(k)=sqrt( Galpha(k)*sum(tmp)/(sum(Galpha)^2*(sum(Galpha)+1)) ); -end -%disp(' ') -%disp('Standard deviations for each \theta') -%stdthe +function [Galpha,stdthe] = fn_dirichprior(Glamda,std_maxv) +% [Galpha,stdthe] = fn_dirichprior(Glamda,std_maxv) +% Setup of the Dirichlet prior on the transition matrix P. Given the mode of each random +% variable theta_j, solve for the (hyper)parameter \alpha where one of \alpha, say, \alpha_j +% is free for controlling the overall variance of \alpha consisdent with the given modes. +% +% Glamda: h-by-1 vector of prior modes for the random variables \theta. +% For each column of P (transitional matrix), Glamda'll be different with a large weight on a diaganol. +% std_maxv: prior standard deviation for the selected random variable +% (here the one with the maximum (largest) mode). +%---------- +% Galpha: h-by-1 vector of parameters' values for the Dirichlet distribtuion. If one of the +% elements in Galpha is Inf, we mean a degenerate case where stdthe is set to zeros. +% stdthe: h-by-1 vector of standard deviations for all random variables \theta. +% +% See Gelman, et al p. 476 and TVBvar Note pp. 24-31 +% Tao Zha, March 2001 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +Glamda = Glamda(:); % Column vector! Prior modes for the random variables \theta. +[maxlam,indxlam] = max(Glamda); % index for the selected hyperparameter that is freely set to match the variance of the corresponding random variable. +ndiri = length(Glamda); % the number of random variables in the Dirichlet distribution. +Galpha=zeros(ndiri,1); % \alpha's: hyperparameters that need to be choosen. Must be all greater than 1. +stdthe = zeros(ndiri,1); % Standard deviations for each \theta +if indxlam>ndiri + warning('Make sure indxlam is less than the total number of parameters in the Dirichlet') + error(' ') +end +if (maxlam==1) % We treat this as a degenerate case for convenient coding. + Galpha(indxlam)=Inf; % Note the use of Inf, NOT NaN. Because + % 0(or any finite number)/Inf=0 while 0/NaN gives a nonsense (i.e., NaN again). + % See tveml.m and pp. 27a-27b for more information. + return % The function stops here. +end + + +%*** Given std_maxv, find the corresponding hyperparameter Galpha_j by soloving +% a polynomial of order 3. See Note (*) page 30. +vj=std_maxv^2; % variance of the selected random variable \theta. +Gsi = (1-Glamda(indxlam))/Glamda(indxlam); % unchanged value, given Glamda. +coevec = zeros(4,1); % 4 because we're going to consider a polynomial of order 3 (+ constant). +coevec(1) = vj*(1+Gsi)^3; +coevec(2) = vj*(1+Gsi)^2*(3*(ndiri-Gsi)-2) - Gsi; +coevec(3) = (ndiri-Gsi-1)*(vj*(1+Gsi)*(3*(ndiri-Gsi)-1)-1); +coevec(4) = vj*(ndiri-Gsi)*(ndiri-Gsi-1)^2; + +Galphaj = max(roots(coevec)); % j: jth element, set to match the variance. Must be greater than 1. +if (Galphaj<=1) + disp(' ') + warning('Error! Make sure std_maxv is small enough to have a large Galphaj > 1') + error(' ') +end + +%*** Solve for the rest of \alpha's. See Note page 27. +A = eye(ndiri) - repmat(Glamda,[1 ndiri]); +C = ones(ndiri,1) + (Galphaj-ndiri)*Glamda; +A1=A; C1=C; +A1(indxlam,:)=[]; A1(:,indxlam)=[]; C1(indxlam)=[]; +indxrest=1:ndiri; indxrest(indxlam)=[]; +Galpha(indxrest) = A1\C1; +Galpha(indxlam) = Galphaj; + +%========= Debugging or checking the properties ========== +%disp(' ') +%disp('2nd-to-first-or-rest ratio: it should not change with the last element of \alpha') +%(Galpha(2)-1)/(Galpha(1)-1) +%(Galpha(2)-1)/(sum(Galpha([1 3]))-2) +%disp(' ') +%disp('Solution for \alpha') +%Galpha + +for k=1:ndiri + tmp=Galpha; + tmp(k)=[]; + stdthe(k)=sqrt( Galpha(k)*sum(tmp)/(sum(Galpha)^2*(sum(Galpha)+1)) ); +end +%disp(' ') +%disp('Standard deviations for each \theta') +%stdthe diff --git a/MatlabFiles/fn_dlrpostr.m b/MatlabFiles/fn_dlrpostr.m index 27a8628de1811b8e3d1548e720070ce53a6d6c73..3b57e8b62b88f31aa3d81245990819cfea48651e 100644 --- a/MatlabFiles/fn_dlrpostr.m +++ b/MatlabFiles/fn_dlrpostr.m @@ -1,61 +1,61 @@ -function [P,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Ui,Vi) -% [P,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Ui,Vi) -% -% Exporting deterministic (no random prior) Bayesian posterior matrices with linear restrictions -% See Waggoner and Zha's Gibbs sampling paper -% -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. Imported from dnrprior.m. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. Imported from dnrprior.m. -%----------------- -% P: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. -% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance matrix (i.e., the exponential -% term is a_i'*H0*a_i) for the ith equation (not divided by T yet). It resembles -% old SpH in the exponent term in posterior of A0, but not divided by T yet. -% Hpinv: cell(nvar,1). In each cell, posterior inverse of covariance matrix Hp (A+) for the -% ith equation. -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -nvar = size(yty,1); - -P = cell(nvar,1); % tld: tilda -H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. -Hpinv = cell(nvar,1); % posterior inv(Hp). - -for n=1:nvar % one for each equation - Hpinv{n} = Vi{n}'*xtx*Vi{n}; - P1 = Vi{n}'*xty*Ui{n}; - P{n} = Hpinv{n}\P1; - H0inv{n} = Ui{n}'*yty*Ui{n} - P1'*(Hpinv{n}\P1); -end - +function [P,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Ui,Vi) +% [P,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Ui,Vi) +% +% Exporting deterministic (no random prior) Bayesian posterior matrices with linear restrictions +% See Waggoner and Zha's Gibbs sampling paper +% +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. Imported from dnrprior.m. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. Imported from dnrprior.m. +%----------------- +% P: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. +% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance matrix (i.e., the exponential +% term is a_i'*H0*a_i) for the ith equation (not divided by T yet). It resembles +% old SpH in the exponent term in posterior of A0, but not divided by T yet. +% Hpinv: cell(nvar,1). In each cell, posterior inverse of covariance matrix Hp (A+) for the +% ith equation. +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +nvar = size(yty,1); + +P = cell(nvar,1); % tld: tilda +H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. +Hpinv = cell(nvar,1); % posterior inv(Hp). + +for n=1:nvar % one for each equation + Hpinv{n} = Vi{n}'*xtx*Vi{n}; + P1 = Vi{n}'*xty*Ui{n}; + P{n} = Hpinv{n}\P1; + H0inv{n} = Ui{n}'*yty*Ui{n} - P1'*(Hpinv{n}\P1); +end + diff --git a/MatlabFiles/fn_empdfsort.m b/MatlabFiles/fn_empdfsort.m index ce2f41936c69c1843d96979ce2050c9625823fe8..eeca73fca4c83a3057ab23bdc7c96ef828798021 100644 --- a/MatlabFiles/fn_empdfsort.m +++ b/MatlabFiles/fn_empdfsort.m @@ -1,49 +1,49 @@ -function imfcnt = fn_empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) -% imfcnt = fn_empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) -% Variablewise (but multivariate) empirical probability distribution with counts -% sorted into bins variablewise -% Note that since a particular draw (imf_h) can be below "imfloor" and above "imceiling" -% (=(imceiling-imfloor)*hbin), this function allows ninv+2 bins for each variable -% -% imfcnt: initial ninv+2-by-k matrix that records counts in each bin given a column in imfcnt -% if k==1, then only one variable is considered. -% imf_h: k-element vector of particular draws. Need not be a 1-by-k row vector. -% imfloor: k-element vector of low values of imf but imf_h can be below "imfloor" and above "imceiling" -% hbin: k-element vector of bin lengths = (imceilling-imfloor)/ninv. -% ninv: number of bins between "imfloor" and "imceiling" -%------------------ -% imfcnt: updated ninv+2-by-k matrix of counts (probability) -% -% January 1999 TZ; Revised, August 2000. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%** find the bin locations and arrange them to the order of 1, 2, ... -imf_h=imf_h(:); imfloor=imfloor(:); hbin=hbin(:); -countInt = floor( (imf_h-imfloor) ./ hbin ); % k-by-1 - % bin locations from <0, 0, 1,..., ninv-1, >=ninv, a total of ninv+2 bins -countInt = 2+countInt'; % 1-by-k row vector, see my shock (1), pp.1 - % move everyting by 2 so as to take account of <0 - -countInt(find(countInt<2)) = 1; % set <0 or -infinity at 1 to start -countInt(find(countInt>=ninv+2)) = ninv+2; % set >=ninv+2 or +infinity at ninv+2 to end -countInt = countInt + (0:length(countInt)-1)*(ninv+2); - % 1-by-k*(ninv+2) index vector to fill the matrix with prob. (counts) - % The term after "+" implies that with every count, we skip ninv+2 to keep - % each column in "imfcnt" with only one element (which is probability) -imfcnt(countInt) = imfcnt(countInt) + 1; +function imfcnt = fn_empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) +% imfcnt = fn_empdfsort(imfcnt,imf_h,imfloor,hbin,ninv) +% Variablewise (but multivariate) empirical probability distribution with counts +% sorted into bins variablewise +% Note that since a particular draw (imf_h) can be below "imfloor" and above "imceiling" +% (=(imceiling-imfloor)*hbin), this function allows ninv+2 bins for each variable +% +% imfcnt: initial ninv+2-by-k matrix that records counts in each bin given a column in imfcnt +% if k==1, then only one variable is considered. +% imf_h: k-element vector of particular draws. Need not be a 1-by-k row vector. +% imfloor: k-element vector of low values of imf but imf_h can be below "imfloor" and above "imceiling" +% hbin: k-element vector of bin lengths = (imceilling-imfloor)/ninv. +% ninv: number of bins between "imfloor" and "imceiling" +%------------------ +% imfcnt: updated ninv+2-by-k matrix of counts (probability) +% +% January 1999 TZ; Revised, August 2000. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%** find the bin locations and arrange them to the order of 1, 2, ... +imf_h=imf_h(:); imfloor=imfloor(:); hbin=hbin(:); +countInt = floor( (imf_h-imfloor) ./ hbin ); % k-by-1 + % bin locations from <0, 0, 1,..., ninv-1, >=ninv, a total of ninv+2 bins +countInt = 2+countInt'; % 1-by-k row vector, see my shock (1), pp.1 + % move everyting by 2 so as to take account of <0 + +countInt(find(countInt<2)) = 1; % set <0 or -infinity at 1 to start +countInt(find(countInt>=ninv+2)) = ninv+2; % set >=ninv+2 or +infinity at ninv+2 to end +countInt = countInt + (0:length(countInt)-1)*(ninv+2); + % 1-by-k*(ninv+2) index vector to fill the matrix with prob. (counts) + % The term after "+" implies that with every count, we skip ninv+2 to keep + % each column in "imfcnt" with only one element (which is probability) +imfcnt(countInt) = imfcnt(countInt) + 1; diff --git a/MatlabFiles/fn_ergodp.m b/MatlabFiles/fn_ergodp.m index 93cef5da493ae5095ea3953444264cc4e37665ae..660cf1704c370b9f2c8da1bc26a8af5df64d5c7e 100644 --- a/MatlabFiles/fn_ergodp.m +++ b/MatlabFiles/fn_ergodp.m @@ -1,33 +1,33 @@ -function gpi = fn_ergodp(P) -% gpi = fn_ergodp(P) -% Compute the ergodic probabilities. See Hamilton p.681. -% -% P: n-by-n matrix of transition matrix where all elements in each column sum up to 1. -%----- -% gpi: n-by-1 vector of ergodic probabilities. -% -% Tao Zha August 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[gpim,gpid] = eig(P); % m: matrix; d: diagonal -[gpidv,gpidvinx] = sort(diag(gpid)); -gpidv = fliplr(gpidv); -gpidvinx = flipud(gpidvinx); -gpim = gpim(:,gpidvinx); -gpi = gpim(:,1)/sum(gpim(:,1)); +function gpi = fn_ergodp(P) +% gpi = fn_ergodp(P) +% Compute the ergodic probabilities. See Hamilton p.681. +% +% P: n-by-n matrix of transition matrix where all elements in each column sum up to 1. +%----- +% gpi: n-by-1 vector of ergodic probabilities. +% +% Tao Zha August 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[gpim,gpid] = eig(P); % m: matrix; d: diagonal +[gpidv,gpidvinx] = sort(diag(gpid)); +gpidv = fliplr(gpidv); +gpidvinx = flipud(gpidvinx); +gpim = gpim(:,gpidvinx); +gpi = gpim(:,1)/sum(gpim(:,1)); diff --git a/MatlabFiles/fn_fcstcnd.m b/MatlabFiles/fn_fcstcnd.m index 68a246153c48dbaced423d6af48766954f35f628..74602005e21e9bb03ad672a6b12366c7b2937588 100644 --- a/MatlabFiles/fn_fcstcnd.m +++ b/MatlabFiles/fn_fcstcnd.m @@ -1,252 +1,253 @@ -function [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstcnd(valuecon,stepcon,varcon,nstepsm,... - nconstr,eq_ms,nvar,lags,phil,Sband,yfore_h,imf3s_h,Bh_h,forep) -% ******* There are some BUG problems when calling this fucntion. ******* 3/15/2004. -% [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstcnd(valuecon,stepcon,varcon,nstepsm,... -% nconstr,eq_ms,nvar,lags,phil,Sband,yfore_h,imf3s_h,Bh_h,forep) -% -% Conditional forecasting in the identified model with or without error bands -% It handles conditions on average values as well, so "valuecon" must be -% expressed at average (NOT sum) levels (i.e., arithmetic averages of log(y) over -% the period of stepcon{i}. 5/22/01. -% Unconditional forecast when imf3s_h, etc is fixed and nconstr=0. -% Note that length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR -% if nstepsm==nconstr. If this condition does not hold, this procedure is incorrect. -% I don't have time to fix it now (3/20/99). Meantime, consult or use the old code -% fidencond.m. -% -% valuecon: vector of values conditioned -% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition -% is then an arithmetic average of log(y) over the stepcon{i} period. -% varcon: vector of variables conditioned -% nstepsm: maximum number of steps in all DLS constraints -% nconstr: number of DLS constraints -% eq_ms: Equation location of MS shocks. If [], all shocks. -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% Sband: 1: draws from random shocks E; 0: no random shocks For now (4/27/01), no option -% for Aband because I don't think it works best to do both Aband and Sband in one function. -% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. -% In this case, may set it to []; -% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses -% Never used when nconstr=0. In this case, may set it to []; -% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% forep: # of forecast periods (e.g., monthly for a monthly model) -% eq_Cms: equation location of MS shocks -% ------ -% yhat: conditional forecasts: forep-by-nvar -% Estr: backed-out structural shocks (from constrained Gaussians) -% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) -% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that -% Rcon'*e = rcon where e is k-by-1 -% [u,d,v]: svd(Rcon,0) -% -%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r and k>=q -% -% See the old code fidencond.m. I wond't use fn_fcstidcnd?.m, 5/22/01. -% Copyright (c) March 1998 by Tao Zha. Revised November 1998, May 2001 (Delete A0_h as -% input arg so that previous programs may not be compatible). - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS - -impsteps=size(imf3s_h,1); -if (forep<nstepsm) | (impsteps<nstepsm) - disp('Increase # of forecast or impulse steps!!') - disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') - error('Maximum of conditional steps > # of forecast or impulse steps!!') -end -kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others - % are free. -%*** initializing -Rcon = zeros(kts,nconstr); % R: k-by-q -Econ = zeros(kts,1); % E: k-by-1 -rcon = zeros(nconstr,1); % r: q-by-1 -%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. -tcwc = nvar*lags; % total coefficients without constant -phi=phil; - - - -%---------------------------------------------------- -% Form rcon, Rcon, and Econ (the mean of structural shocks) -%---------------------------------------------------- -A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % <<>>1 nvar shocks-by-nvar responses -if nconstr % Conditional forecasts. - for i=1:nconstr - rcon(i)=length(stepcon{i})*valuecon(i) - sum(yfore_h(stepcon{i},varcon(i)),1); - %<<>>2 Automatically taking care of average conditions. - Rmat = zeros(nstepsm,nvar); - r2mat = zeros(nstepsm,1); % simply one identified equation - % Must be here inside the loop because it's matrix of one column of Rcon - for j=1:length(stepcon{i}) - if DLSIdShock % Assuming the Fed can't see all other shocks within a month - Rmat(1:stepcon{i}(j),eq_ms) = Rmat(1:stepcon{i}(j),eq_ms) + ... - imf3s_h(stepcon{i}(j):-1:1,eq_ms,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks except - % the identified one are set to zero) for a particular - % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - else % Rcon random with (A0,A+) - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks are - % *not* set to zero) for a particular endogenous - % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - end - end - Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error - % i.e. "OVERR" is not transposed when overlaid to "CAPR" - Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr - end - % - [u d v]=svd(Rcon,0); %trial - vd=v.*(ones(size(v,2),1)*diag(d)'); %trial - dinv = 1./diag(d); % inv(diag(d)) - vdinv=v.*(ones(size(v,2),1)*dinv'); %trial - rtr=vd*vd'; % R'*R - rtrinv = vdinv*vdinv'; % inv(R'*R) - - Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks -else % Unconditional forecasts. - Econ = zeros(kts,1); % the mean of shocks is zero under no variable condition - Rcon = NaN; - rcon = NaN; - u = NaN; - d = NaN; - v = NaN; -end - - - -%--------------------------------------- -% No uncertainty at all. In other words, no future shocks. -%--------------------------------------- -if (~Sband) %| (nconstr & (length(eq_ms)==1)) - % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR - % if nstepsm==nconstr. If this condition does not hold, this procedure - % is incorrect. I don't have time to fix it now (3/20/99). So I use - % this as a proximation - Estr = reshape(Econ,nvar,nstepsm); - Estr = Estr'; % transpose so that - % Estr: structural shocks. Row--steps, Column--n shocks - Estr = [Estr;zeros(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Ures = Estr*A0in; % <<>>1 nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - % Note: We don't use /A0_h so as to eliminate small discrepancies to be - % completely compatible with the computation of Rmat and Estr, which uses A0in. - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -%--------------------------------------- -% With random future shocks. -%--------------------------------------- -else - if nconstr % Conditional forecasts. - %-------------- - % Condition on variables with all shocks backed out. Straight DLS forecasts. No A random but S random. - %-------------- - if ~DLSIdShock - Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - %[u1 d1 v1] = svd(Ome); % too slow - [u1 d1] = eig(Ome); - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % see Zha's forecast (1), p.17 - Estr1 = Econ + Stdcon*randn(kts,1); % Draws of constrained (conditioned) shocks. - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; % Second concatenated part: draws of free shocks. - % Now, forep-by-nvar -- ready for forecasts - %-------------- - % Condition on variables with identified MS shocks backed out, no A random but S random. - %-------------- - else % other shocks are indepedent of the eq_ms shock - % 3/20/99 The following may be problematic because Osk should depend - % on u (A0_h and Bh_h) in general. I have NOT worked out any good version. - %/* - % Osk = randn(kts,1); % other shocks - % for j=1:nstepsm - % Osk(nvar*(j-1)+eq_ms)=0; % no shock to the MS or identified equation - % end - % Estr = Econ + Osk; % Econ is non zero only at position - % % eq_ms*j where j=1:nstepsm - % Estr = reshape(Estr,nvar,nstepsm); - % Estr = Estr'; % transpose so that - % % Estr: structural shocks. Row--steps, Column--n shocks - % Estr = [Estr;randn(forep-nstepsm,nvar)]; - % % Now, forep-by-nvar -- ready for forecasts - % - disp('DLS') - Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - %[u1 d1 v1] = svd(Ome); % too slow - [u1 d1] = eig(Ome); - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % see Zha's forecast (1), p.17 - tmp1=zeros(nvar,nstepsm); - tmp1(eq_ms,:)=randn(1,nstepsm); - tmp2=tmp1(:); - %Estr1 = Econ + Stdcon*randn(kts,1); - %jnk = reshape(Stdcon*tmp2,nvar,nstepsm) - Estr1 = Econ + Stdcon*tmp2; - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - end - else % Unconditional forecasts. - Estr = randn(forep,nvar); % Unconditional draws. - end - - Ures = Estr*A0in; % <<>>1 nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - % Note: We don't use /A0_h so as to eliminate small discrepancies to be - % completely compatible with the computation of Rmat and Estr, which uses A0in. - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -end +function [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstcnd(valuecon,stepcon,varcon,nstepsm,... + nconstr,eq_ms,nvar,lags,phil,Sband,yfore_h,imf3s_h,Bh_h,forep) +% ******* There are some BUG problems when calling this fucntion. ******* 3/15/2004. +% [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstcnd(valuecon,stepcon,varcon,nstepsm,... +% nconstr,eq_ms,nvar,lags,phil,Sband,yfore_h,imf3s_h,Bh_h,forep) +% +% Conditional forecasting in the identified model with or without error bands +% It handles conditions on average values as well, so "valuecon" must be +% expressed at average (NOT sum) levels (i.e., arithmetic averages of log(y) over +% the period of stepcon{i}. 5/22/01. +% Unconditional forecast when imf3s_h, etc is fixed and nconstr=0. +% Note that length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR +% if nstepsm==nconstr. If this condition does not hold, this procedure is incorrect. +% I don't have time to fix it now (3/20/99). Meantime, consult or use the old code +% fidencond.m. +% +% valuecon: vector of values conditioned +% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition +% is then an arithmetic average of log(y) over the stepcon{i} period. +% varcon: vector of variables conditioned +% nstepsm: maximum number of steps in all DLS constraints +% nconstr: number of DLS constraints +% eq_ms: Equation location of MS shocks. If [], all shocks. +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% Sband: 1: draws from random shocks E; 0: no random shocks For now (4/27/01), no option +% for Aband because I don't think it works best to do both Aband and Sband in one function. +% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. +% In this case, may set it to []; +% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses +% Never used when nconstr=0. In this case, may set it to []; +% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% forep: # of forecast periods (e.g., monthly for a monthly model) +% eq_Cms: equation location of MS shocks +% ------ +% yhat: conditional forecasts: forep-by-nvar +% Estr: backed-out structural shocks (from constrained Gaussians) +% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) +% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that +% Rcon'*e = rcon where e is k-by-1 +% [u,d,v]: svd(Rcon,0) +% +%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r and k>=q +% +% See the old code fidencond.m. I wond't use fn_fcstidcnd?.m, 5/22/01. +% Written by Tao Zha March 1998 . +% Revised November 1998, May 2001 (Delete A0_h as +% input arg so that previous programs may not be compatible). + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS + +impsteps=size(imf3s_h,1); +if (forep<nstepsm) | (impsteps<nstepsm) + disp('Increase # of forecast or impulse steps!!') + disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') + error('Maximum of conditional steps > # of forecast or impulse steps!!') +end +kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others + % are free. +%*** initializing +Rcon = zeros(kts,nconstr); % R: k-by-q +Econ = zeros(kts,1); % E: k-by-1 +rcon = zeros(nconstr,1); % r: q-by-1 +%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. +tcwc = nvar*lags; % total coefficients without constant +phi=phil; + + + +%---------------------------------------------------- +% Form rcon, Rcon, and Econ (the mean of structural shocks) +%---------------------------------------------------- +A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % <<>>1 nvar shocks-by-nvar responses +if nconstr % Conditional forecasts. + for i=1:nconstr + rcon(i)=length(stepcon{i})*valuecon(i) - sum(yfore_h(stepcon{i},varcon(i)),1); + %<<>>2 Automatically taking care of average conditions. + Rmat = zeros(nstepsm,nvar); + r2mat = zeros(nstepsm,1); % simply one identified equation + % Must be here inside the loop because it's matrix of one column of Rcon + for j=1:length(stepcon{i}) + if DLSIdShock % Assuming the Fed can't see all other shocks within a month + Rmat(1:stepcon{i}(j),eq_ms) = Rmat(1:stepcon{i}(j),eq_ms) + ... + imf3s_h(stepcon{i}(j):-1:1,eq_ms,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks except + % the identified one are set to zero) for a particular + % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + else % Rcon random with (A0,A+) + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks are + % *not* set to zero) for a particular endogenous + % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + end + end + Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error + % i.e. "OVERR" is not transposed when overlaid to "CAPR" + Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr + end + % + [u d v]=svd(Rcon,0); %trial + vd=v.*(ones(size(v,2),1)*diag(d)'); %trial + dinv = 1./diag(d); % inv(diag(d)) + vdinv=v.*(ones(size(v,2),1)*dinv'); %trial + rtr=vd*vd'; % R'*R + rtrinv = vdinv*vdinv'; % inv(R'*R) + + Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks +else % Unconditional forecasts. + Econ = zeros(kts,1); % the mean of shocks is zero under no variable condition + Rcon = NaN; + rcon = NaN; + u = NaN; + d = NaN; + v = NaN; +end + + + +%--------------------------------------- +% No uncertainty at all. In other words, no future shocks. +%--------------------------------------- +if (~Sband) %| (nconstr & (length(eq_ms)==1)) + % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR + % if nstepsm==nconstr. If this condition does not hold, this procedure + % is incorrect. I don't have time to fix it now (3/20/99). So I use + % this as a proximation + Estr = reshape(Econ,nvar,nstepsm); + Estr = Estr'; % transpose so that + % Estr: structural shocks. Row--steps, Column--n shocks + Estr = [Estr;zeros(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Ures = Estr*A0in; % <<>>1 nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + % Note: We don't use /A0_h so as to eliminate small discrepancies to be + % completely compatible with the computation of Rmat and Estr, which uses A0in. + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +%--------------------------------------- +% With random future shocks. +%--------------------------------------- +else + if nconstr % Conditional forecasts. + %-------------- + % Condition on variables with all shocks backed out. Straight DLS forecasts. No A random but S random. + %-------------- + if ~DLSIdShock + Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + %[u1 d1 v1] = svd(Ome); % too slow + [u1 d1] = eig(Ome); + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % see Zha's forecast (1), p.17 + Estr1 = Econ + Stdcon*randn(kts,1); % Draws of constrained (conditioned) shocks. + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; % Second concatenated part: draws of free shocks. + % Now, forep-by-nvar -- ready for forecasts + %-------------- + % Condition on variables with identified MS shocks backed out, no A random but S random. + %-------------- + else % other shocks are indepedent of the eq_ms shock + % 3/20/99 The following may be problematic because Osk should depend + % on u (A0_h and Bh_h) in general. I have NOT worked out any good version. + %/* + % Osk = randn(kts,1); % other shocks + % for j=1:nstepsm + % Osk(nvar*(j-1)+eq_ms)=0; % no shock to the MS or identified equation + % end + % Estr = Econ + Osk; % Econ is non zero only at position + % % eq_ms*j where j=1:nstepsm + % Estr = reshape(Estr,nvar,nstepsm); + % Estr = Estr'; % transpose so that + % % Estr: structural shocks. Row--steps, Column--n shocks + % Estr = [Estr;randn(forep-nstepsm,nvar)]; + % % Now, forep-by-nvar -- ready for forecasts + % + disp('DLS') + Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + %[u1 d1 v1] = svd(Ome); % too slow + [u1 d1] = eig(Ome); + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % see Zha's forecast (1), p.17 + tmp1=zeros(nvar,nstepsm); + tmp1(eq_ms,:)=randn(1,nstepsm); + tmp2=tmp1(:); + %Estr1 = Econ + Stdcon*randn(kts,1); + %jnk = reshape(Stdcon*tmp2,nvar,nstepsm) + Estr1 = Econ + Stdcon*tmp2; + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + end + else % Unconditional forecasts. + Estr = randn(forep,nvar); % Unconditional draws. + end + + Ures = Estr*A0in; % <<>>1 nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + % Note: We don't use /A0_h so as to eliminate small discrepancies to be + % completely compatible with the computation of Rmat and Estr, which uses A0in. + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +end diff --git a/MatlabFiles/fn_fcstidcnd.m b/MatlabFiles/fn_fcstidcnd.m index 0bf66715fc968ca6385a7c9fe25b5300d6b93768..e77a1bf7c9b11523867a703c42800b3ac9090a3c 100644 --- a/MatlabFiles/fn_fcstidcnd.m +++ b/MatlabFiles/fn_fcstidcnd.m @@ -1,326 +1,327 @@ -function [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,... - nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... - forep,TLindx,TLnumber,nCms,eq_Cms) -% [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,... -% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... -% forep,TLindx,TLnumber,nCms,eq_Cms) -% -% Note that the case Aband=1 is not finished yet. -% -% Conditional forecasting in the identified model with or without error bands -% It handles conditions on average values as well, so "valuecon" must be -% expressed at average (NOT sum) level. -% Aband is used only once when nconstr>0 and Aband=1, where Gibbs sampler may be used. NOT yet finished. -% Unconditional forecast when imf3s_h, etc is fixed and nconstr=0, where yfore_h must set to []. -% -% valuecon: vector of values conditioned -% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition -% is then an arithmetic average of log(y) over the stepcon{i} period. -% varcon: vector of variables conditioned -% nconstr: number of DLS constraints. If zero, it leads to unconditional forecasts. -% nstepsm: maximum number of steps in all DLS constraints -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% Aband: 1: draws from A0 and Bh; 0: no draws. The case Aband=1 and nconstr>0 has NOT been finished yet. -% Sband: 1: draws from random shocks E; 0: no random shocks -% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. -% In this case, set it to []; -% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses -% Never used when nconstr=0. In this case, set it to []; -% A0_h: A0 contemporaneous parameter matrix -% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% forep: # of forecast periods (e.g., monthly for a monthly model) -% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser -% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. -% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose -% nCms: # of LZ conditions -% eq_Cms: equation location of MS shocks -% ------ -% yhat: conditional forecasts: forep-by-nvar -% Estr: backed-out structural shocks (from N(0,1)) -% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) -% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that -% Rcon'*e = rcon where e is k-by-1 -% [u,d,v]: svd(Rcon,0) -% -%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r and k>=q -% -% Copyright (c) March 1998 by Tao Zha. Revised November 1998; -% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part -% 3/20/99 Added A0_h and forep and deleted Cms as input argument. Previous -% programs may not be compatible. -% 3/15/2004 There are some BUG problems when calling fn_fcstcnd.m(). -% -% Comparing with the version fn_fcstidcnd2.m, this is a better version. -% See the note in fn_fcstidcnd2.m for explanation. April, 2009. TZ. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS - -impsteps=size(imf3s_h,1); -if (forep<nstepsm) | (impsteps<nstepsm) - disp('Increase # of forecast or impulse steps!!') - disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') - error('Maximum of conditional steps > # of forecast or impulse steps!!') -end -kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others - % are free. -%*** initializing -Rcon = zeros(kts,nconstr); % R: k-by-q -Econ = zeros(kts,1); % E: k-by-1 -rcon = zeros(nconstr,1); % r: q-by-1 -%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. -tcwc = nvar*lags; % total coefficients without constant -phi=phil; - - - -%---------------------------------------------------- -% Form rcon, Rcon, and Econ (the mean of structural shocks) -%---------------------------------------------------- -if nconstr - A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses - for i=1:nconstr - rcon(i)=length(stepcon{i})*valuecon(i) - ... - sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> - Rmat = zeros(nstepsm,nvar); - r2mat = zeros(nstepsm,1); % simply one identified equation - % Must be here inside the loop because it's matrix of one column of Rcon - for j=1:length(stepcon{i}) - if DLSIdShock % Assuming the Fed can't see all other shocks within a month - Rmat(1:stepcon{i}(j),eq_ms) = Rmat(1:stepcon{i}(j),eq_ms) + ... - imf3s_h(stepcon{i}(j):-1:1,eq_ms,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks except - % the identified one are set to zero) for a particular - % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - else % Rcon random with (A0,A+) - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks are - % *not* set to zero) for a particular endogenous - % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - end - end - Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error - % i.e. "OVERR" is not transposed when overlaid to "CAPR" - Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr - end - - [u d v]=svd(Rcon,0); %trial - %???? Can we reduce the time by computing inv(R'*R) directly? - % rtr = Rcon'*Rcon; %trial - % rtrinv = inv(Rcon'*Rcon); %trial - vd=v.*(ones(size(v,2),1)*diag(d)'); %trial - dinv = 1./diag(d); % inv(diag(d)) - vdinv=v.*(ones(size(v,2),1)*dinv'); %trial - rtr=vd*vd'; % R'*R - rtrinv = vdinv*vdinv'; % inv(R'*R) - - Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks -else - Econ = zeros(kts,1); % the mean of shocks is zero under no variable condition - Rcon = NaN; - rcon = NaN; - u = NaN; - d = NaN; - v = NaN; -end - - - -%--------------------------------------- -% No uncertainty at all or only random (A0,A+) -% In other words, no future shocks -%--------------------------------------- -if (~Sband) %| (nconstr & (length(eq_ms)==1)) - % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR - % if nstepsm==nconstr. If this condition does not hold, this procedure - % is incorrect. I don't have time to fix it now (3/20/99). So I use - % this as a proximation - Estr = reshape(Econ,nvar,nstepsm); - Estr = Estr'; % transpose so that - % Estr: structural shocks. Row--steps, Column--n shocks - Estr = [Estr;zeros(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - % - end - -%--------------------------------------- -% With random future shocks and possibly (A0,A+) depending -% on if imf3s_h is random -%--------------------------------------- -else - %-------------- - % Condition on variables and A random - %-------------- - if nconstr & Aband - warning(' ') - disp('This situation (both E and A random) is still under construction') - disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') - disp('Please press ctrl-c to abort') - pause - elseif nconstr - %-------------- - % Condition on variables and DLS MS shock, no A random but S random - %-------------- - if DLSIdShock % other shocks are indepedent of the eq_ms shock - % 3/20/99 The following may be problematic because Osk should depend - % on u (A0_h and Bh_h) in general. I haven't worked out any good version - %/* - % Osk = randn(kts,1); % other shocks - % for j=1:nstepsm - % Osk(nvar*(j-1)+eq_ms)=0; % no shock to the MS or identified equation - % end - % Estr = Econ + Osk; % Econ is non zero only at position - % % eq_ms*j where j=1:nstepsm - % Estr = reshape(Estr,nvar,nstepsm); - % Estr = Estr'; % transpose so that - % % Estr: structural shocks. Row--steps, Column--n shocks - % Estr = [Estr;randn(forep-nstepsm,nvar)]; - % % Now, forep-by-nvar -- ready for forecasts - % - disp('DLS') - Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - %[u1 d1 v1] = svd(Ome); % too slow - [u1 d1] = eig(Ome); - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % see Zha's forecast (1), p.17 - tmp1=zeros(nvar,nstepsm); - tmp1(eq_ms,:)=randn(1,nstepsm); - tmp2=tmp1(:); - %Estr1 = Econ + Stdcon*randn(kts,1); - %jnk = reshape(Stdcon*tmp2,nvar,nstepsm) - Estr1 = Econ + Stdcon*tmp2; - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - else - Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - %[u1 d1 v1] = svd(Ome); % too slow - [u1 d1] = eig(Ome); - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % see Zha's forecast (1), p.17 - %-------------- - % Condition on variables and LZ MS shock, no A random but S random - % This section has not be tested yet, 10/14/98 - %-------------- - if nCms - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - %-------------- - % Condition on variables only, no A random but S random - %-------------- - else - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - end - end - %-------------- - % Condition on LZ MS shocks only, S random and possibly A random depending on - % if A0_h and Bh_h are random - %-------------- - else - if nCms - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - else - Estr = randn(forep,nvar); % Unconditional forecast - % Now, forep-by-nvar -- ready for forecasts - end - end - % - - - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -end +function [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,... + nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... + forep,TLindx,TLnumber,nCms,eq_Cms) +% [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,... +% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... +% forep,TLindx,TLnumber,nCms,eq_Cms) +% +% Note that the case Aband=1 is not finished yet. +% +% Conditional forecasting in the identified model with or without error bands +% It handles conditions on average values as well, so "valuecon" must be +% expressed at average (NOT sum) level. +% Aband is used only once when nconstr>0 and Aband=1, where Gibbs sampler may be used. NOT yet finished. +% Unconditional forecast when imf3s_h, etc is fixed and nconstr=0, where yfore_h must set to []. +% +% valuecon: vector of values conditioned +% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition +% is then an arithmetic average of log(y) over the stepcon{i} period. +% varcon: vector of variables conditioned +% nconstr: number of DLS constraints. If zero, it leads to unconditional forecasts. +% nstepsm: maximum number of steps in all DLS constraints +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% Aband: 1: draws from A0 and Bh; 0: no draws. The case Aband=1 and nconstr>0 has NOT been finished yet. +% Sband: 1: draws from random shocks E; 0: no random shocks +% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. +% In this case, set it to []; +% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses +% Never used when nconstr=0. In this case, set it to []; +% A0_h: A0 contemporaneous parameter matrix +% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% forep: # of forecast periods (e.g., monthly for a monthly model) +% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser +% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. +% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose +% nCms: # of LZ conditions +% eq_Cms: equation location of MS shocks +% ------ +% yhat: conditional forecasts: forep-by-nvar +% Estr: backed-out structural shocks (from N(0,1)) +% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) +% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that +% Rcon'*e = rcon where e is k-by-1 +% [u,d,v]: svd(Rcon,0) +% +%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r and k>=q +% +% Revised November 1998; +% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part +% 3/20/99 Added A0_h and forep and deleted Cms as input argument. Previous +% programs may not be compatible. +% 3/15/2004 There are some BUG problems when calling fn_fcstcnd.m(). +% +% Comparing with the version fn_fcstidcnd2.m, this is a better version. +% See the note in fn_fcstidcnd2.m for explanation. April, 2009. TZ. +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS + +impsteps=size(imf3s_h,1); +if (forep<nstepsm) | (impsteps<nstepsm) + disp('Increase # of forecast or impulse steps!!') + disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') + error('Maximum of conditional steps > # of forecast or impulse steps!!') +end +kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others + % are free. +%*** initializing +Rcon = zeros(kts,nconstr); % R: k-by-q +Econ = zeros(kts,1); % E: k-by-1 +rcon = zeros(nconstr,1); % r: q-by-1 +%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. +tcwc = nvar*lags; % total coefficients without constant +phi=phil; + + + +%---------------------------------------------------- +% Form rcon, Rcon, and Econ (the mean of structural shocks) +%---------------------------------------------------- +if nconstr + A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses + for i=1:nconstr + rcon(i)=length(stepcon{i})*valuecon(i) - ... + sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> + Rmat = zeros(nstepsm,nvar); + r2mat = zeros(nstepsm,1); % simply one identified equation + % Must be here inside the loop because it's matrix of one column of Rcon + for j=1:length(stepcon{i}) + if DLSIdShock % Assuming the Fed can't see all other shocks within a month + Rmat(1:stepcon{i}(j),eq_ms) = Rmat(1:stepcon{i}(j),eq_ms) + ... + imf3s_h(stepcon{i}(j):-1:1,eq_ms,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks except + % the identified one are set to zero) for a particular + % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + else % Rcon random with (A0,A+) + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks are + % *not* set to zero) for a particular endogenous + % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + end + end + Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error + % i.e. "OVERR" is not transposed when overlaid to "CAPR" + Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr + end + + [u d v]=svd(Rcon,0); %trial + %???? Can we reduce the time by computing inv(R'*R) directly? + % rtr = Rcon'*Rcon; %trial + % rtrinv = inv(Rcon'*Rcon); %trial + vd=v.*(ones(size(v,2),1)*diag(d)'); %trial + dinv = 1./diag(d); % inv(diag(d)) + vdinv=v.*(ones(size(v,2),1)*dinv'); %trial + rtr=vd*vd'; % R'*R + rtrinv = vdinv*vdinv'; % inv(R'*R) + + Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks +else + Econ = zeros(kts,1); % the mean of shocks is zero under no variable condition + Rcon = NaN; + rcon = NaN; + u = NaN; + d = NaN; + v = NaN; +end + + + +%--------------------------------------- +% No uncertainty at all or only random (A0,A+) +% In other words, no future shocks +%--------------------------------------- +if (~Sband) %| (nconstr & (length(eq_ms)==1)) + % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR + % if nstepsm==nconstr. If this condition does not hold, this procedure + % is incorrect. I don't have time to fix it now (3/20/99). So I use + % this as a proximation + Estr = reshape(Econ,nvar,nstepsm); + Estr = Estr'; % transpose so that + % Estr: structural shocks. Row--steps, Column--n shocks + Estr = [Estr;zeros(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + % + end + +%--------------------------------------- +% With random future shocks and possibly (A0,A+) depending +% on if imf3s_h is random +%--------------------------------------- +else + %-------------- + % Condition on variables and A random + %-------------- + if nconstr & Aband + warning(' ') + disp('This situation (both E and A random) is still under construction') + disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') + disp('Please press ctrl-c to abort') + pause + elseif nconstr + %-------------- + % Condition on variables and DLS MS shock, no A random but S random + %-------------- + if DLSIdShock % other shocks are indepedent of the eq_ms shock + % 3/20/99 The following may be problematic because Osk should depend + % on u (A0_h and Bh_h) in general. I haven't worked out any good version + %/* + % Osk = randn(kts,1); % other shocks + % for j=1:nstepsm + % Osk(nvar*(j-1)+eq_ms)=0; % no shock to the MS or identified equation + % end + % Estr = Econ + Osk; % Econ is non zero only at position + % % eq_ms*j where j=1:nstepsm + % Estr = reshape(Estr,nvar,nstepsm); + % Estr = Estr'; % transpose so that + % % Estr: structural shocks. Row--steps, Column--n shocks + % Estr = [Estr;randn(forep-nstepsm,nvar)]; + % % Now, forep-by-nvar -- ready for forecasts + % + disp('DLS') + Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + %[u1 d1 v1] = svd(Ome); % too slow + [u1 d1] = eig(Ome); + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % see Zha's forecast (1), p.17 + tmp1=zeros(nvar,nstepsm); + tmp1(eq_ms,:)=randn(1,nstepsm); + tmp2=tmp1(:); + %Estr1 = Econ + Stdcon*randn(kts,1); + %jnk = reshape(Stdcon*tmp2,nvar,nstepsm) + Estr1 = Econ + Stdcon*tmp2; + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + else + Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + %[u1 d1 v1] = svd(Ome); % too slow + [u1 d1] = eig(Ome); + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % see Zha's forecast (1), p.17 + %-------------- + % Condition on variables and LZ MS shock, no A random but S random + % This section has not be tested yet, 10/14/98 + %-------------- + if nCms + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + %-------------- + % Condition on variables only, no A random but S random + %-------------- + else + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + end + end + %-------------- + % Condition on LZ MS shocks only, S random and possibly A random depending on + % if A0_h and Bh_h are random + %-------------- + else + if nCms + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + else + Estr = randn(forep,nvar); % Unconditional forecast + % Now, forep-by-nvar -- ready for forecasts + end + end + % + + + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +end diff --git a/MatlabFiles/fn_fcstidcnd2.m b/MatlabFiles/fn_fcstidcnd2.m index f88fe953b492bfe781bae9128b8391521c9bf72d..50e5972525e8e64d164cd0ec1187243f55f2d096 100644 --- a/MatlabFiles/fn_fcstidcnd2.m +++ b/MatlabFiles/fn_fcstidcnd2.m @@ -1,365 +1,365 @@ -function [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... - nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... - forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) -% [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... -% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... -% forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) -% -% 5/2/99: This one is much, much slower than fidcnderr.m when eq_ms=[] and -% nconstr>0 and length(eq_ms)*nstepsm>nconstr. Seems to me that fcstidcnd2.m -% is designed for the situation which eq_ms=2. The slow speed is due to -% "Radd" added. When I have time, I need to check to see if I can speed up -% this M file. -% -% Note that the case Aband=1 is not finished yet. -% -% Conditional forecasting in the identified model with or without error bands -% It handles conditions on average values as well, so "valuecon" must be -% expressed at average (NOT sum) level. Including unconditional forecasts -% when nconstr=nCms=0. Maybe slower than "fcstidcnd.m" when length(eq_ms)*nstepsm=nconstr -% because of Radd added. But "fsctidcnd.m" is incorrect when length(eq_ms) -% *nstepsm>nconstr (situations like the average annual FFR constraint). 3/22/99 -% Ref.: Zha Forecast (I), pp. 17-17c. -% -% valuecon: vector of values conditioned -% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition -% is then an arithmetic average of log(y) over the stepcon{i} period. -% varcon: vector of variables conditioned -% nconstr: number of DLS constraints -% nstepsm: maximum number of steps in all DLS constraints -% nvar: number of variables in the BVAR model -% lags: number of lags in the BVAR model -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% eq_ms: identified equation or shock (in terms of number). If equ_ms=[], then "fidencond" or -% 'fcstidcond' is, similar to RATS, to compute forecasts with *all* shocks. -% Aband: 1: draws from A0 and Bh; 0: no draws -% Sband: 1: draws from random shocks E; 0: no random shocks -% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. -% In this case, set it to []; -% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses -% Never used when nconstr=0. In this case, set it to []; -% A0_h: A0 contemporaneous parameter matrix -% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) -% where X(t) is k-by-nvar and y(t) is 1-by-nvar -% forep: # of forecast periods (e.g., monthly for a monthly model) -% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser -% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. -% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose -% nCms: # of LZ conditions -% eq_Cms: equation location of MS shocks -% nconadd: number of DLS added constraints DIRECTLY on structural shocks -% for identified version where eq_ms is not empty. Note -% nconadd=0 when eq_ms is empty. -% eq_oth: index for other structural shocks than those in eq_ms. -% If eq_ms=[], eq_oth=[]. Note length(eq_oth)+length(eq_ms)=nvar -% radd: sparse nconadd-by-1; nconadd values added to rcon in the text later -% Radd: sparce nvar*nstepsm-by-nconadd; added to Rcon in the text later -% ------ -% yhat: conditional forecasts: forep-by-nvar -% Estr: backed-out structural shocks (from N(0,1)) -% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) -% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that -% Rcon'*e = rcon where e is k-by-1 -% [u,d,v]: svd(Rcon,0) -% -% Copyright (c) March 1998 by Tao Zha. Revised November 1998; -% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part -% 3/20/99 Added A0_h and forep and deleted Cms as input argument. -% 3/21/99 Added nconadd and eq_oth. -% Previous programs may not be compatible. - -% -% This version differs from "fn_fcstidcnd.m" because nconadd, radd, and Radd are added to allow for -% both DLS-WZ conditions and structural-shock conditions to exist at the same time. My recognition -% is that it does not work well at all. So one should use the version "fn_fcstidcnd.m."" April, 2009 by TZ. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -% -%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. -%% See also Zha Forecast (I), pp. 17-17c. -% -%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. -%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse -%% response at t=1, C at t=2, etc. The row of inv(A0) or C is -%% all responses to one shock. -%% Let r be q-by-1 (such as r(1) = r(t+1) -%% = y(t+1) (constrained) - y(t+1) (forecast)). -%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps -%% where nsteps the largest constrained step. The key of the program -%% is to creat R using impulse responses -%% Optimal solution for shock e where R'*e=r and e is k-by-1 is -%% e = R*inv(R'*R)*r and k>=q -% - - -DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS - -impsteps=size(imf3s_h,1); -if (forep<nstepsm) | (impsteps<nstepsm) - disp('Increase # of forecast or impulse steps!!') - disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') - error('Maximum of conditional steps > # of forecast or impulse steps!!') -end -kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others - % are free. -%*** initializing -Rcon = zeros(kts,nconstr); % R: k-by-q where q include possible additional - % constraints directly on structural shocks for identified models. - % These addtional constraints will be added later. -Econ = sparse(zeros(kts,1)); % E: k-by-1 -rcon = zeros(nconstr,1); % r: q-by-1 -%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. -tcwc = nvar*lags; % total coefficients without constant -phi=phil; - - - -%---------------------------------------------------- -% Form rcon, Rcon, and Econ (the mean of structural shocks) -%---------------------------------------------------- -if nconstr - A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses - for i=1:nconstr - rcon(i)=length(stepcon{i})*valuecon(i) - ... - sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> - Rmat = zeros(nstepsm,nvar); - % Must be here inside the loop because it's matrix of one column of Rcon - for j=1:length(stepcon{i}) - if DLSIdShock % Assuming the Fed can't see all other shocks within a month - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks except - % the identified one are set to zero) for a particular - % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - else % Rcon random with (A0,A+) - Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... - imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); - % Rmat: row--nstepsm, column--nvar shocks (here all shocks are - % *not* set to zero) for a particular endogenous - % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 - end - end - Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error - % i.e. "OVERR" is not transposed when overlaid to "CAPR" - Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr - end - - rcon = [rcon;radd]; % added nconadd constrained values for identified model - % sparse because radd is sparse - Rcon = [Rcon Radd]; % added constraints on shocks for identified version - % sparse because Radd is sparse - Rcont=Rcon'; - rinvrtr=Rcon/(Rcont*Rcon); - Econ = rinvrtr*rcon; - - - %/* Too slow, I believe, when q is large. 3/21/99 - % [u d v]=svd(Rcon,0); %trial - % %???? Can we reduce the time by computing inv(R'*R) directly? - % % rtr = Rcon'*Rcon; %trial - % % rtrinv = inv(Rcon'*Rcon); %trial - % vd=v.*(ones(size(v,2),1)*diag(d)'); %trial - % dinv = 1./diag(d); % inv(diag(d)) - % vdinv=v.*(ones(size(v,2),1)*dinv'); %trial - % rtr=vd*vd'; % R'*R - % rtrinv = vdinv*vdinv'; % inv(R'*R) - % - % Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks -else - Econ = sparse(zeros(kts,1)); % the mean of shocks is zero under no variable condition - Rcon = NaN; - rcon = NaN; - u = NaN; - d = NaN; - v = NaN; -end - - - -%--------------------------------------- -% No uncertainty at all or only random (A0,A+) -% In other words, no future shocks -%--------------------------------------- -if (~Sband) | (nconstr & length(eq_ms)*nstepsm==nconstr) - % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR - % if nstepsm==nconstr. If this condition does not hold, this procedure - % is incorrect. I don't have time to fix it now (3/20/99). So I use - % this as a proximation - Estr = reshape(Econ,nvar,nstepsm); - Estr = Estr'; % transpose so that - % Estr: structural shocks. Row--steps, Column--n shocks - Estr = [Estr;zeros(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - % - end - -%--------------------------------------- -% With random future shocks and possibly (A0,A+) depending -% on if imf3s_h is random -%--------------------------------------- -else - %-------------- - % Condition on variables and A random - %-------------- - if nconstr & Aband - warning(' ') - disp('This situation (both E and A random) is still under construction') - disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') - disp('and related to "if DLSIdShock" in the following') - disp('Please press ctrl-c to abort') - pause - elseif nconstr - %-------------- - % Condition on variables and DLS MS shock, no A random but S random - %-------------- - if DLSIdShock % other shocks are indepedent of the eq_ms shock - Ome=speye(kts)-rinvrtr*Rcont; - Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it - % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very - % tight. After all, when the number in Ome is very small relative to - % 1 (which is the variance of structural shocks Estr), we can treat it - % as zero. - [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); - % We have exactly nconstr+nconadd zero singular values - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome - % see Zha's forecast (1), p.17 - Stdcon = [Stdcon sparse(zeros(kts,kts-size(d1,1)))]; - Estr1 = Econ + Stdcon*randn(kts,1); % We must have rand(kts,1). Assigning - % some of randn(kts,1) to be zero according to Radd is WRONG. - % For this argument, see Zha Forecast (I) p.17a - Estr2 = reshape(Estr1,nvar,nstepsm); - % nvar-by-nstepsm; Needed to be transposed later - Estr = [Estr2';randn(forep-nstepsm,nvar)]; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - % Now, forep-by-nvar -- ready for forecasts - else - Ome=speye(kts)-rinvrtr*Rcont; - Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it - % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very - % tight. After all, when the number in Ome is very small relative to - % 1 (which is the variance of structural shocks Estr), we can treat it - % as zero. - [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); - % We have exactly nconstr+nconadd zero singular values - Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome - % see Zha's forecast (1), p.17 - Stdcon = [Stdcon sparse(zeros(kts,nconstr+nconadd))]; - - %*** The following very inefficient - % Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' - % %[u1 d1 v1] = svd(Ome); % too slow - % [u1 d1] = eig(Ome); - % Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance - % % see Zha's forecast (1), p.17 - - %-------------- - % Condition on variables and LZ MS shock, no A random but S random - % This section has not be tested yet, 10/14/98 - %-------------- - if nCms - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - %-------------- - % Condition on variables only, no A random but S random - %-------------- - else - Estr1 = Econ + Stdcon*randn(kts,1); - Estr2 = reshape(Estr1,nvar,nstepsm); - Estr2 = Estr2'; % transpose so that - % Estr2: structural shocks. Row--nstepsm, Column--n shocks - Estr = [Estr2;randn(forep-nstepsm,nvar)]; - % Now, forep-by-nvar -- ready for forecasts - end - end - %-------------- - % Condition on LZ MS shocks only, S random and possibly A random depending on - % if A0_h and Bh_h are random - %-------------- - else - if nCms - Estr = randn(forep,nvar); - % Now, forep-by-nvar -- ready for forecasts - Estr(:,eq_Cms)=0; - Estr(1:nCms,eq_Cms) = TLnumber(:); - - %/* draw MS shocks - % for k=1:nCms - % if TLindx(k) % tighter - % while (Estr(k,eq_Cms)<TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % else % looser - % while (Estr(k,eq_Cms)>TLnumber(k)) - % Estr(k,eq_Cms) = randn(1,1); - % end - % end - % end - else - Estr = randn(forep,nvar); % Unconditional forecast - % Now, forep-by-nvar -- ready for forecasts - end - end - % - - - Ures = Estr/A0_h; % nstepsm-by-nvar - % Ures: reduced-form residuals. Row--steps; Column--n shocks - - % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B - % ** where phi = x(t+h-1) with last column being constant - % - yhat = zeros(forep,nvar); - for k=1:forep - yhat(k,:) = phi*Bh_h + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); - end -end \ No newline at end of file +function [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... + nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... + forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) +% [yhat,Estr,rcon,Rcon,u,v,d] = fn_fcstidcnd2(valuecon,stepcon,varcon,nstepsm,... +% nconstr,eq_ms,nvar,lags,phil,Aband,Sband,yfore_h,imf3s_h,A0_h,Bh_h,... +% forep,TLindx,TLnumber,nCms,eq_Cms,nconadd,eq_oth,radd,Radd) +% +% 5/2/99: This one is much, much slower than fidcnderr.m when eq_ms=[] and +% nconstr>0 and length(eq_ms)*nstepsm>nconstr. Seems to me that fcstidcnd2.m +% is designed for the situation which eq_ms=2. The slow speed is due to +% "Radd" added. When I have time, I need to check to see if I can speed up +% this M file. +% +% Note that the case Aband=1 is not finished yet. +% +% Conditional forecasting in the identified model with or without error bands +% It handles conditions on average values as well, so "valuecon" must be +% expressed at average (NOT sum) level. Including unconditional forecasts +% when nconstr=nCms=0. Maybe slower than "fcstidcnd.m" when length(eq_ms)*nstepsm=nconstr +% because of Radd added. But "fsctidcnd.m" is incorrect when length(eq_ms) +% *nstepsm>nconstr (situations like the average annual FFR constraint). 3/22/99 +% Ref.: Zha Forecast (I), pp. 17-17c. +% +% valuecon: vector of values conditioned +% stepcon: sequence (cell) of steps conditioned; if length(stepcon{i}) > 1, the condition +% is then an arithmetic average of log(y) over the stepcon{i} period. +% varcon: vector of variables conditioned +% nconstr: number of DLS constraints +% nstepsm: maximum number of steps in all DLS constraints +% nvar: number of variables in the BVAR model +% lags: number of lags in the BVAR model +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% eq_ms: identified equation or shock (in terms of number). If equ_ms=[], then "fidencond" or +% 'fcstidcond' is, similar to RATS, to compute forecasts with *all* shocks. +% Aband: 1: draws from A0 and Bh; 0: no draws +% Sband: 1: draws from random shocks E; 0: no random shocks +% yfore_h: uncondtional forecasts: forep-by-nvar. Never used when nconstr=0. +% In this case, set it to []; +% imf3s_h: 3-dimensional impulse responses matrix: impsteps-by-nvar shocks-by-nvar responses +% Never used when nconstr=0. In this case, set it to []; +% A0_h: A0 contemporaneous parameter matrix +% Bh_h: reduced-form parameter matrix: k-by-nvar, y(t) = X(t)*Bh+e(t) +% where X(t) is k-by-nvar and y(t) is 1-by-nvar +% forep: # of forecast periods (e.g., monthly for a monthly model) +% TLindx: 1-by-nCms vector of 1's and 0's, indicating tight or loose; 1: tighter, 0: looser +% Used only when /* (MS draws) is activated. Right now, MS shocks are deterministic. +% TLnumber: 1-by-nCms vector, lower bound for tight and upper bound for loose +% nCms: # of LZ conditions +% eq_Cms: equation location of MS shocks +% nconadd: number of DLS added constraints DIRECTLY on structural shocks +% for identified version where eq_ms is not empty. Note +% nconadd=0 when eq_ms is empty. +% eq_oth: index for other structural shocks than those in eq_ms. +% If eq_ms=[], eq_oth=[]. Note length(eq_oth)+length(eq_ms)=nvar +% radd: sparse nconadd-by-1; nconadd values added to rcon in the text later +% Radd: sparce nvar*nstepsm-by-nconadd; added to Rcon in the text later +% ------ +% yhat: conditional forecasts: forep-by-nvar +% Estr: backed-out structural shocks (from N(0,1)) +% rcon: vector - the difference between valuecon and log(yfore) (unconditional forecasts) +% Rcon: k-by-q (q constranits and k=nvar*max(nsteps)) so that +% Rcon'*e = rcon where e is k-by-1 +% [u,d,v]: svd(Rcon,0) +% +% Written by Tao Zha March 1998. Revised November 1998; +% 3/20/99 Disenabled draws of MS shcoks. To enable it, activate /* part +% 3/20/99 Added A0_h and forep and deleted Cms as input argument. +% 3/21/99 Added nconadd and eq_oth. +% Previous programs may not be compatible. + +% +% This version differs from "fn_fcstidcnd.m" because nconadd, radd, and Radd are added to allow for +% both DLS-WZ conditions and structural-shock conditions to exist at the same time. My recognition +% is that it does not work well at all. So one should use the version "fn_fcstidcnd.m."" April, 2009 by TZ. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +% +%% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc. +%% See also Zha Forecast (I), pp. 17-17c. +% +%% Some notations: y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n. +%% Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse +%% response at t=1, C at t=2, etc. The row of inv(A0) or C is +%% all responses to one shock. +%% Let r be q-by-1 (such as r(1) = r(t+1) +%% = y(t+1) (constrained) - y(t+1) (forecast)). +%% Use impulse responses to find out R (k-by-q) where k=nvar*nsteps +%% where nsteps the largest constrained step. The key of the program +%% is to creat R using impulse responses +%% Optimal solution for shock e where R'*e=r and e is k-by-1 is +%% e = R*inv(R'*R)*r and k>=q +% + + +DLSIdShock = ~isempty(eq_ms); % if not empty, the MS shock is identified as in DLS + +impsteps=size(imf3s_h,1); +if (forep<nstepsm) | (impsteps<nstepsm) + disp('Increase # of forecast or impulse steps!!') + disp('Or decrease # of constraints (nconstr) or constrained steps (stepcon(i))!!') + error('Maximum of conditional steps > # of forecast or impulse steps!!') +end +kts = nvar*nstepsm; % k -- ts: total shocks some of which are restricted and others + % are free. +%*** initializing +Rcon = zeros(kts,nconstr); % R: k-by-q where q include possible additional + % constraints directly on structural shocks for identified models. + % These addtional constraints will be added later. +Econ = sparse(zeros(kts,1)); % E: k-by-1 +rcon = zeros(nconstr,1); % r: q-by-1 +%rcon=valuecon-diag(yfore(stepcon,varcon)); % another way is to use "loop" below. +tcwc = nvar*lags; % total coefficients without constant +phi=phil; + + + +%---------------------------------------------------- +% Form rcon, Rcon, and Econ (the mean of structural shocks) +%---------------------------------------------------- +if nconstr + A0in = reshape(imf3s_h(1,:,:),nvar,nvar); % nvar shocks-by-nvar responses + for i=1:nconstr + rcon(i)=length(stepcon{i})*valuecon(i) - ... + sum(yfore_h(stepcon{i},varcon(i)),1); %<<>> + Rmat = zeros(nstepsm,nvar); + % Must be here inside the loop because it's matrix of one column of Rcon + for j=1:length(stepcon{i}) + if DLSIdShock % Assuming the Fed can't see all other shocks within a month + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks except + % the identified one are set to zero) for a particular + % endogenous variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + else % Rcon random with (A0,A+) + Rmat(1:stepcon{i}(j),:) = Rmat(1:stepcon{i}(j),:) + ... + imf3s_h(stepcon{i}(j):-1:1,:,varcon(i)); + % Rmat: row--nstepsm, column--nvar shocks (here all shocks are + % *not* set to zero) for a particular endogenous + % variable 'varcon(i)'. See Zha Forcast (1), pp.6-7 + end + end + Rmatt = Rmat'; % Now, nvar-by-nstepsm. I think here is where RATS has an error + % i.e. "OVERR" is not transposed when overlaid to "CAPR" + Rcon(:,i)=Rmatt(:); % Rcon: k-by-q where q=nconstr + end + + rcon = [rcon;radd]; % added nconadd constrained values for identified model + % sparse because radd is sparse + Rcon = [Rcon Radd]; % added constraints on shocks for identified version + % sparse because Radd is sparse + Rcont=Rcon'; + rinvrtr=Rcon/(Rcont*Rcon); + Econ = rinvrtr*rcon; + + + %/* Too slow, I believe, when q is large. 3/21/99 + % [u d v]=svd(Rcon,0); %trial + % %???? Can we reduce the time by computing inv(R'*R) directly? + % % rtr = Rcon'*Rcon; %trial + % % rtrinv = inv(Rcon'*Rcon); %trial + % vd=v.*(ones(size(v,2),1)*diag(d)'); %trial + % dinv = 1./diag(d); % inv(diag(d)) + % vdinv=v.*(ones(size(v,2),1)*dinv'); %trial + % rtr=vd*vd'; % R'*R + % rtrinv = vdinv*vdinv'; % inv(R'*R) + % + % Econ = Rcon*rtrinv*rcon; % E = R*inv(R'R)*r; the mean of structural shocks +else + Econ = sparse(zeros(kts,1)); % the mean of shocks is zero under no variable condition + Rcon = NaN; + rcon = NaN; + u = NaN; + d = NaN; + v = NaN; +end + + + +%--------------------------------------- +% No uncertainty at all or only random (A0,A+) +% In other words, no future shocks +%--------------------------------------- +if (~Sband) | (nconstr & length(eq_ms)*nstepsm==nconstr) + % length(eq_ms)==1 implies one-one mapping between MS shocks and, say, FFR + % if nstepsm==nconstr. If this condition does not hold, this procedure + % is incorrect. I don't have time to fix it now (3/20/99). So I use + % this as a proximation + Estr = reshape(Econ,nvar,nstepsm); + Estr = Estr'; % transpose so that + % Estr: structural shocks. Row--steps, Column--n shocks + Estr = [Estr;zeros(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + % + end + +%--------------------------------------- +% With random future shocks and possibly (A0,A+) depending +% on if imf3s_h is random +%--------------------------------------- +else + %-------------- + % Condition on variables and A random + %-------------- + if nconstr & Aband + warning(' ') + disp('This situation (both E and A random) is still under construction') + disp('It is closely related to Waggoner and Zha ReStat Gibbs sampling method') + disp('and related to "if DLSIdShock" in the following') + disp('Please press ctrl-c to abort') + pause + elseif nconstr + %-------------- + % Condition on variables and DLS MS shock, no A random but S random + %-------------- + if DLSIdShock % other shocks are indepedent of the eq_ms shock + Ome=speye(kts)-rinvrtr*Rcont; + Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it + % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very + % tight. After all, when the number in Ome is very small relative to + % 1 (which is the variance of structural shocks Estr), we can treat it + % as zero. + [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); + % We have exactly nconstr+nconadd zero singular values + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome + % see Zha's forecast (1), p.17 + Stdcon = [Stdcon sparse(zeros(kts,kts-size(d1,1)))]; + Estr1 = Econ + Stdcon*randn(kts,1); % We must have rand(kts,1). Assigning + % some of randn(kts,1) to be zero according to Radd is WRONG. + % For this argument, see Zha Forecast (I) p.17a + Estr2 = reshape(Estr1,nvar,nstepsm); + % nvar-by-nstepsm; Needed to be transposed later + Estr = [Estr2';randn(forep-nstepsm,nvar)]; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + % Now, forep-by-nvar -- ready for forecasts + else + Ome=speye(kts)-rinvrtr*Rcont; + Ome(find(abs(Ome)<1e-10))=0; % tighter the tolerance is, the longer it + % takes for svds to compute. E.g., size(Ome,1)*eps is perhaps very + % tight. After all, when the number in Ome is very small relative to + % 1 (which is the variance of structural shocks Estr), we can treat it + % as zero. + [u1 d1 v1] = svds(Ome,kts-nconstr-nconadd); + % We have exactly nconstr+nconadd zero singular values + Stdcon = u1*diag(sqrt(diag(abs(d1)))); % find a square root of Ome + % see Zha's forecast (1), p.17 + Stdcon = [Stdcon sparse(zeros(kts,nconstr+nconadd))]; + + %*** The following very inefficient + % Ome = eye(kts) - u*u'; % note, I-u*u' = I - R*inv(R'*R)*R' + % %[u1 d1 v1] = svd(Ome); % too slow + % [u1 d1] = eig(Ome); + % Stdcon = u1*diag(sqrt(diag(abs(d1)))); % lower triagular chol of conditional variance + % % see Zha's forecast (1), p.17 + + %-------------- + % Condition on variables and LZ MS shock, no A random but S random + % This section has not be tested yet, 10/14/98 + %-------------- + if nCms + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + %-------------- + % Condition on variables only, no A random but S random + %-------------- + else + Estr1 = Econ + Stdcon*randn(kts,1); + Estr2 = reshape(Estr1,nvar,nstepsm); + Estr2 = Estr2'; % transpose so that + % Estr2: structural shocks. Row--nstepsm, Column--n shocks + Estr = [Estr2;randn(forep-nstepsm,nvar)]; + % Now, forep-by-nvar -- ready for forecasts + end + end + %-------------- + % Condition on LZ MS shocks only, S random and possibly A random depending on + % if A0_h and Bh_h are random + %-------------- + else + if nCms + Estr = randn(forep,nvar); + % Now, forep-by-nvar -- ready for forecasts + Estr(:,eq_Cms)=0; + Estr(1:nCms,eq_Cms) = TLnumber(:); + + %/* draw MS shocks + % for k=1:nCms + % if TLindx(k) % tighter + % while (Estr(k,eq_Cms)<TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % else % looser + % while (Estr(k,eq_Cms)>TLnumber(k)) + % Estr(k,eq_Cms) = randn(1,1); + % end + % end + % end + else + Estr = randn(forep,nvar); % Unconditional forecast + % Now, forep-by-nvar -- ready for forecasts + end + end + % + + + Ures = Estr/A0_h; % nstepsm-by-nvar + % Ures: reduced-form residuals. Row--steps; Column--n shocks + + % ** reconstruct x(t) for y(t+h) = x(t+h-1)*B + % ** where phi = x(t+h-1) with last column being constant + % + yhat = zeros(forep,nvar); + for k=1:forep + yhat(k,:) = phi*Bh_h + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); + end +end diff --git a/MatlabFiles/fn_forecast.m b/MatlabFiles/fn_forecast.m index 86c50bbcde9efdcaf1fa85e854664cc1de475721..f5ac10173cf087372784bae4a51138950e5c8215 100644 --- a/MatlabFiles/fn_forecast.m +++ b/MatlabFiles/fn_forecast.m @@ -1,74 +1,74 @@ -function yhat = fn_forecast(Bh,phi,nn,nexo,Xfexo) -% yhat = fn_forecast(Bh,phi,nn,nexo,Xfexo) -% Unconditional forecating without shocks. -% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar -% -% Bh: k-by-nvar, the (posterior) estimate of B. -% phi: the 1-by-(nvar*lags+nexo) data matrix X where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast). -% nn: [nvar,lags,nfqm], nfqm: forecast periods (months or quarters). -% nexo: number of exogenous variables. The constant term is the default setting. -% Besides this term, we have nexo-1 exogenous variables. -% Xfexo: nfqm-by-nexo-1 vector of exoenous variables in the forecast horizon where -% nfqm: number of forecast periods. -%----------- -% yhat: nfqm-by-nvar forecast. -% -% See fn_forecastsim.m with shocks; fn_forecaststre.m. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin == 3 - nexo=1; % default for constant term -elseif nexo<1 - error('We need at least one exogenous term so nexo must >= 1') -end - -% ** setup -nvar = nn(1); -lags = nn(2); -nfqm = nn(3); -tcwx = nvar*lags; % total coefficeint without exogenous variables - -if nexo>1 - if (nfqm > size(Xfexo,1)) - disp(' ') - warning('Make sure the forecast horizon in the exogenous variable matrix Xfexo > forecast periods') - disp('Press ctrl-c to abort') - pause - elseif ((nexo-1) ~= size(Xfexo,2)) - disp(' ') - warning('Make sure that nexo matchs the exogenous variable matrix Xfexo') - disp('Press ctrl-c to abort') - pause - end -end - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -yhat = zeros(nfqm,nvar); -for k=1:nfqm - yhat(k,:) = phi*Bh; - %*** lagged endogenous variables - phi(1,nvar+1:tcwx) = phi(1,1:tcwx-nvar); - phi(1,1:nvar) = yhat(k,:); - %*** exogenous variables excluding constant terms - if (nexo>1) - phi(1,tcwx+1:tcwx+nexo-1) = Xfexo(k,:); - end -end +function yhat = fn_forecast(Bh,phi,nn,nexo,Xfexo) +% yhat = fn_forecast(Bh,phi,nn,nexo,Xfexo) +% Unconditional forecating without shocks. +% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar +% +% Bh: k-by-nvar, the (posterior) estimate of B. +% phi: the 1-by-(nvar*lags+nexo) data matrix X where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast). +% nn: [nvar,lags,nfqm], nfqm: forecast periods (months or quarters). +% nexo: number of exogenous variables. The constant term is the default setting. +% Besides this term, we have nexo-1 exogenous variables. +% Xfexo: nfqm-by-nexo-1 vector of exoenous variables in the forecast horizon where +% nfqm: number of forecast periods. +%----------- +% yhat: nfqm-by-nvar forecast. +% +% See fn_forecastsim.m with shocks; fn_forecaststre.m. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin == 3 + nexo=1; % default for constant term +elseif nexo<1 + error('We need at least one exogenous term so nexo must >= 1') +end + +% ** setup +nvar = nn(1); +lags = nn(2); +nfqm = nn(3); +tcwx = nvar*lags; % total coefficeint without exogenous variables + +if nexo>1 + if (nfqm > size(Xfexo,1)) + disp(' ') + warning('Make sure the forecast horizon in the exogenous variable matrix Xfexo > forecast periods') + disp('Press ctrl-c to abort') + pause + elseif ((nexo-1) ~= size(Xfexo,2)) + disp(' ') + warning('Make sure that nexo matchs the exogenous variable matrix Xfexo') + disp('Press ctrl-c to abort') + pause + end +end + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +yhat = zeros(nfqm,nvar); +for k=1:nfqm + yhat(k,:) = phi*Bh; + %*** lagged endogenous variables + phi(1,nvar+1:tcwx) = phi(1,1:tcwx-nvar); + phi(1,1:nvar) = yhat(k,:); + %*** exogenous variables excluding constant terms + if (nexo>1) + phi(1,tcwx+1:tcwx+nexo-1) = Xfexo(k,:); + end +end diff --git a/MatlabFiles/fn_forecastfixe.m b/MatlabFiles/fn_forecastfixe.m index e378dc4617edecacd837d0b97e355fff366211f2..3facb577faedde27ea9aa7359c78022067417eb1 100644 --- a/MatlabFiles/fn_forecastfixe.m +++ b/MatlabFiles/fn_forecastfixe.m @@ -1,78 +1,78 @@ -function yhat = fn_forecastfixe(Bh,A0h,phi,nn,Estr,nexo,Xfexo) -% yhat = fn_forecastfixe(Bh,A0h,phi,nn,Estr,nexo,Xfexo) -% Forecasts conditional on fixed structural shocks -% y_hat(t+h) = c + x_hat(t+h-1)*Bh + Estr(t+h,:), X: 1*k; Bh: k*nvar; y_hat: 1*nvar -% -% Bh: k-by-nvar, the (posterior) estimate of B; -% A0h: nvar-by-nvar, columns correponding to equations -% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast). -% nn: [nvar,lags,nfqm], nfqm: forecast periods (months or quarters). -% Estr: nfqm-by-nvar, each column corresponds to strcutural shocks from a particular -% source such as MS; -% nexo: number of exogenous variables. The constant term is the default setting. -% Besides this term, we have nexo-1 exogenous variables. -% Xfexo: nfqm-by-nexo-1 vector of exoenous variables in the forecast horizon where -% nfqm: number of forecast periods. -%----------------- -% yhat: nfqm*nvar matrix of forecasts. -% -% See also fn_forecast.m and fn_forecastsim.m. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin == 5 - nexo=1; % default for constant term -elseif nexo<1 - error('We need at least one exogenous term so nexo must >= 1') -end - -% ** setup -nvar = nn(1); -lags = nn(2); -nfqm = nn(3); -tcwx = nvar*lags; % total coefficeint without exogenous variables - -if nexo>1 - if (nfqm > size(Xfexo,1)) - disp(' ') - warning('Make sure the forecast horizon in the exogenous variable matrix Xfexo > forecast periods') - disp('Press ctrl-c to abort') - pause - elseif ((nexo-1) ~= size(Xfexo,2)) - disp(' ') - warning('Make sure that nexo matchs the exogenous variable matrix Xfexo') - disp('Press ctrl-c to abort') - pause - end -end - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -Ures = Estr/A0h; -yhat = zeros(nfqm,nvar); -for k=1:nfqm - yhat(k,:) = phi*Bh + Ures(k,:); - %*** lagged endogenous variables - phi(1,nvar+1:tcwx) = phi(1,1:tcwx-nvar); - phi(1,1:nvar) = yhat(k,:); - %*** exogenous variables excluding constant terms - if (nexo>1) - phi(1,tcwx+1:tcwx+nexo-1) = Xfexo(k,:); - end -end +function yhat = fn_forecastfixe(Bh,A0h,phi,nn,Estr,nexo,Xfexo) +% yhat = fn_forecastfixe(Bh,A0h,phi,nn,Estr,nexo,Xfexo) +% Forecasts conditional on fixed structural shocks +% y_hat(t+h) = c + x_hat(t+h-1)*Bh + Estr(t+h,:), X: 1*k; Bh: k*nvar; y_hat: 1*nvar +% +% Bh: k-by-nvar, the (posterior) estimate of B; +% A0h: nvar-by-nvar, columns correponding to equations +% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast). +% nn: [nvar,lags,nfqm], nfqm: forecast periods (months or quarters). +% Estr: nfqm-by-nvar, each column corresponds to strcutural shocks from a particular +% source such as MS; +% nexo: number of exogenous variables. The constant term is the default setting. +% Besides this term, we have nexo-1 exogenous variables. +% Xfexo: nfqm-by-nexo-1 vector of exoenous variables in the forecast horizon where +% nfqm: number of forecast periods. +%----------------- +% yhat: nfqm*nvar matrix of forecasts. +% +% See also fn_forecast.m and fn_forecastsim.m. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin == 5 + nexo=1; % default for constant term +elseif nexo<1 + error('We need at least one exogenous term so nexo must >= 1') +end + +% ** setup +nvar = nn(1); +lags = nn(2); +nfqm = nn(3); +tcwx = nvar*lags; % total coefficeint without exogenous variables + +if nexo>1 + if (nfqm > size(Xfexo,1)) + disp(' ') + warning('Make sure the forecast horizon in the exogenous variable matrix Xfexo > forecast periods') + disp('Press ctrl-c to abort') + pause + elseif ((nexo-1) ~= size(Xfexo,2)) + disp(' ') + warning('Make sure that nexo matchs the exogenous variable matrix Xfexo') + disp('Press ctrl-c to abort') + pause + end +end + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +Ures = Estr/A0h; +yhat = zeros(nfqm,nvar); +for k=1:nfqm + yhat(k,:) = phi*Bh + Ures(k,:); + %*** lagged endogenous variables + phi(1,nvar+1:tcwx) = phi(1,1:tcwx-nvar); + phi(1,1:nvar) = yhat(k,:); + %*** exogenous variables excluding constant terms + if (nexo>1) + phi(1,tcwx+1:tcwx+nexo-1) = Xfexo(k,:); + end +end diff --git a/MatlabFiles/fn_forecastsim.m b/MatlabFiles/fn_forecastsim.m index 79a04c27fad04ec95748f2f7f03862a5d0e568e1..c3382dd38062f3e8355033d95134afcf420c0df0 100644 --- a/MatlabFiles/fn_forecastsim.m +++ b/MatlabFiles/fn_forecastsim.m @@ -1,79 +1,79 @@ -function yhat = fn_forecastsim(Bh,A0h,phi,nn,nexo,Xfexo) -% yhat = fn_forecastsim(Bh,A0h,phi,nn,nexo,Xfexo) -% Unconditional forecasts with simulated shocks, not depending on reduced-form or structural shocks. -% y_hat(t+h) = c + x_hat(t+h-1)*Bh + u, X: 1*k; Bh: k*nvar; y_hat: 1*nvar; u: simulated shocks. -% -% Bh: k-by-nvar, the (posterior) estimate of B; -% A0h: nvar-by-nvar, columns correponding to equations -% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast). -% nn: [nvar,lags,nfqm], nfqm: forecast periods (months or quarters). -% nexo: number of exogenous variables. The constant term is the default setting. -% Besides this term, we have nexo-1 exogenous variables. -% Xfexo: nfqm-by-nexo-1 vector of exoenous variables in the forecast horizon where -% nfqm: number of forecast periods. -%----------------- -% yhat: nfqm*nvar matrix of forecasts. -% -% See fn_forecast.m without shocks and forecasterr.m when A0h_in (instead of A0h) is used; -% fn_forecaststre.m. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin == 4 - nexo=1; % default for constant term -elseif nexo<1 - error('We need at least one exogenous term so nexo must >= 1') -end - -% ** setup -nvar = nn(1); -lags = nn(2); -nfqm = nn(3); -tcwx = nvar*lags; % total coefficeint without exogenous variables - -if nexo>1 - if (nfqm > size(Xfexo,1)) - disp(' ') - warning('Make sure the forecast horizon in the exogenous variable matrix Xfexo > forecast periods') - disp('Press ctrl-c to abort') - pause - elseif ((nexo-1) ~= size(Xfexo,2)) - disp(' ') - warning('Make sure that nexo matchs the exogenous variable matrix Xfexo') - disp('Press ctrl-c to abort') - pause - end -end - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -Ures = randn(nfqm,nvar)/A0h; % Unconditional forecast - % Now, nfqm-by-nvar -- ready for forecasts - % Ures: reduced-form residuals. Row--steps; Column--n shocks -yhat = zeros(nfqm,nvar); -for k=1:nfqm - yhat(k,:) = phi*Bh + Ures(k,:);; - %*** lagged endogenous variables - phi(1,nvar+1:tcwx) = phi(1,1:tcwx-nvar); - phi(1,1:nvar) = yhat(k,:); - %*** exogenous variables excluding constant terms - if (nexo>1) - phi(1,tcwx+1:tcwx+nexo-1) = Xfexo(k,:); - end -end +function yhat = fn_forecastsim(Bh,A0h,phi,nn,nexo,Xfexo) +% yhat = fn_forecastsim(Bh,A0h,phi,nn,nexo,Xfexo) +% Unconditional forecasts with simulated shocks, not depending on reduced-form or structural shocks. +% y_hat(t+h) = c + x_hat(t+h-1)*Bh + u, X: 1*k; Bh: k*nvar; y_hat: 1*nvar; u: simulated shocks. +% +% Bh: k-by-nvar, the (posterior) estimate of B; +% A0h: nvar-by-nvar, columns correponding to equations +% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast). +% nn: [nvar,lags,nfqm], nfqm: forecast periods (months or quarters). +% nexo: number of exogenous variables. The constant term is the default setting. +% Besides this term, we have nexo-1 exogenous variables. +% Xfexo: nfqm-by-nexo-1 vector of exoenous variables in the forecast horizon where +% nfqm: number of forecast periods. +%----------------- +% yhat: nfqm*nvar matrix of forecasts. +% +% See fn_forecast.m without shocks and forecasterr.m when A0h_in (instead of A0h) is used; +% fn_forecaststre.m. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin == 4 + nexo=1; % default for constant term +elseif nexo<1 + error('We need at least one exogenous term so nexo must >= 1') +end + +% ** setup +nvar = nn(1); +lags = nn(2); +nfqm = nn(3); +tcwx = nvar*lags; % total coefficeint without exogenous variables + +if nexo>1 + if (nfqm > size(Xfexo,1)) + disp(' ') + warning('Make sure the forecast horizon in the exogenous variable matrix Xfexo > forecast periods') + disp('Press ctrl-c to abort') + pause + elseif ((nexo-1) ~= size(Xfexo,2)) + disp(' ') + warning('Make sure that nexo matchs the exogenous variable matrix Xfexo') + disp('Press ctrl-c to abort') + pause + end +end + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +Ures = randn(nfqm,nvar)/A0h; % Unconditional forecast + % Now, nfqm-by-nvar -- ready for forecasts + % Ures: reduced-form residuals. Row--steps; Column--n shocks +yhat = zeros(nfqm,nvar); +for k=1:nfqm + yhat(k,:) = phi*Bh + Ures(k,:);; + %*** lagged endogenous variables + phi(1,nvar+1:tcwx) = phi(1,1:tcwx-nvar); + phi(1,1:nvar) = yhat(k,:); + %*** exogenous variables excluding constant terms + if (nexo>1) + phi(1,tcwx+1:tcwx+nexo-1) = Xfexo(k,:); + end +end diff --git a/MatlabFiles/fn_foregraph.m b/MatlabFiles/fn_foregraph.m index 424870f2481a7746ff4f5845f2f05163825719a8..0af4377773e5f830732a8b2809937e550cb8ce39 100644 --- a/MatlabFiles/fn_foregraph.m +++ b/MatlabFiles/fn_foregraph.m @@ -1,66 +1,66 @@ -function fn_foregraph(yfore,yacte,keyindx,rnum,cnum,q_m,ylab,forelabel,conlab) -% -% Graph annual (or calendar year) forecasts vs actual (all data from "msstart.m") -% -% yfore: actual and forecast annual growth data with dates. -% yacte: actual annual growth data with dates. -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -% q_m: if 4 or 12, quarterly or monthly data -% ylab: string array for the length(keyindx)-by-1 variables -% forelabel: title label for as of time of forecast -% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -%------------- -% No output argument for this graph file -% See fn_seriesgraph.m, fn_forerrgraph.m. -% -% Tao Zha, March 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -vyrs = yfore(:,1); -hornum = cell(length(vyrs),1); % horizontal year (number) -count=0; -for k=vyrs' - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - plot(yacte(:,1)+yacte(:,2)/q_m,yacte(:,2+i),yfore(:,1)+yfore(:,2)/q_m,yfore(:,2+i),'--') - - if (yfore(1,2)==0) % only for annual growth rates (not for, say, monthly annualized rates) - set(gca,'XLim',[vyrs(1) vyrs(end)]) - set(gca,'XTick',vyrs) - set(gca,'XTickLabel',char(hornum)) - end - - if i==keyindx(1) - title(forelabel) - elseif i>=length(keyindx) %i>=length(keyindx)-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end +function fn_foregraph(yfore,yacte,keyindx,rnum,cnum,q_m,ylab,forelabel,conlab) +% +% Graph annual (or calendar year) forecasts vs actual (all data from "msstart.m") +% +% yfore: actual and forecast annual growth data with dates. +% yacte: actual annual growth data with dates. +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +% q_m: if 4 or 12, quarterly or monthly data +% ylab: string array for the length(keyindx)-by-1 variables +% forelabel: title label for as of time of forecast +% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +%------------- +% No output argument for this graph file +% See fn_seriesgraph.m, fn_forerrgraph.m. +% +% Tao Zha, March 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +vyrs = yfore(:,1); +hornum = cell(length(vyrs),1); % horizontal year (number) +count=0; +for k=vyrs' + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + plot(yacte(:,1)+yacte(:,2)/q_m,yacte(:,2+i),yfore(:,1)+yfore(:,2)/q_m,yfore(:,2+i),'--') + + if (yfore(1,2)==0) % only for annual growth rates (not for, say, monthly annualized rates) + set(gca,'XLim',[vyrs(1) vyrs(end)]) + set(gca,'XTick',vyrs) + set(gca,'XTickLabel',char(hornum)) + end + + if i==keyindx(1) + title(forelabel) + elseif i>=length(keyindx) %i>=length(keyindx)-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/fn_forerrgraph.m b/MatlabFiles/fn_forerrgraph.m index b2fc21a9dd3fc9090a5d69c98fb44397e0787832..0a6beada1559f7669fa22c2b9be7ce8c417b6114 100644 --- a/MatlabFiles/fn_forerrgraph.m +++ b/MatlabFiles/fn_forerrgraph.m @@ -1,71 +1,71 @@ -function fn_forerrgraph(yfore,yforel,yforeh,yacte,keyindx,rnum,cnum,q_m,ylab,forelabel,conlab) -% -% Graph annual (or calendar year) forecasts with one error band vs actual -% Import some data from "msstart.m" -% -% yfore: both actual and forecast annual growth data with dates in the first 2 columns -% in the order of year and month (or quarter). -% yforel: lower bound of the forecast. -% yforeh: high bound of the forecast. -% yacte: actual annual growth data with dates. -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -% q_m: if 4 or 12, quarterly or monthly data. -% ylab: string array for the length(keyindx)-by-1 variables -% forelabel: title label for as of time of forecast -% conlab: x-axis label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -%------------- -% No output argument for this graph file. -% See fn_seriesgraph.m, fn_foregraph.m. -% -% Tao Zha, August 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -vyrs = yfore(:,1); % vectorized -hornum = cell(length(vyrs),1); % horizontal year (number) -count=0; -for k=vyrs' - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - plot(yacte(:,1)+yacte(:,2)/q_m,yacte(:,2+i),yfore(:,1)+yfore(:,2)/q_m,yfore(:,2+i),'--',... - yforel(:,1)+yforel(:,2)/q_m,yforel(:,2+i),'-.',yforeh(:,1)+yforeh(:,2)/q_m,yforeh(:,2+i),'-.') - - if (yfore(1,2)==0) % only for annual growth rates (not for, say, monthly annualized rates) - set(gca,'XLim',[vyrs(1) vyrs(end)]) - set(gca,'XTick',vyrs) - set(gca,'XTickLabel',char(hornum)) - end - - if i==keyindx(1) - title(forelabel) - elseif i>=length(keyindx) %i>=length(keyindx)-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end +function fn_forerrgraph(yfore,yforel,yforeh,yacte,keyindx,rnum,cnum,q_m,ylab,forelabel,conlab) +% +% Graph annual (or calendar year) forecasts with one error band vs actual +% Import some data from "msstart.m" +% +% yfore: both actual and forecast annual growth data with dates in the first 2 columns +% in the order of year and month (or quarter). +% yforel: lower bound of the forecast. +% yforeh: high bound of the forecast. +% yacte: actual annual growth data with dates. +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +% q_m: if 4 or 12, quarterly or monthly data. +% ylab: string array for the length(keyindx)-by-1 variables +% forelabel: title label for as of time of forecast +% conlab: x-axis label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +%------------- +% No output argument for this graph file. +% See fn_seriesgraph.m, fn_foregraph.m. +% +% Tao Zha, August 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +vyrs = yfore(:,1); % vectorized +hornum = cell(length(vyrs),1); % horizontal year (number) +count=0; +for k=vyrs' + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + plot(yacte(:,1)+yacte(:,2)/q_m,yacte(:,2+i),yfore(:,1)+yfore(:,2)/q_m,yfore(:,2+i),'--',... + yforel(:,1)+yforel(:,2)/q_m,yforel(:,2+i),'-.',yforeh(:,1)+yforeh(:,2)/q_m,yforeh(:,2+i),'-.') + + if (yfore(1,2)==0) % only for annual growth rates (not for, say, monthly annualized rates) + set(gca,'XLim',[vyrs(1) vyrs(end)]) + set(gca,'XTick',vyrs) + set(gca,'XTickLabel',char(hornum)) + end + + if i==keyindx(1) + title(forelabel) + elseif i>=length(keyindx) %i>=length(keyindx)-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/fn_fprintmatrix.m b/MatlabFiles/fn_fprintmatrix.m index 2bd5cc2376706ed67b2263ac5d4059100040ee7e..2e9598f0a4ca59803dd0098a1f74c5688a240811 100644 --- a/MatlabFiles/fn_fprintmatrix.m +++ b/MatlabFiles/fn_fprintmatrix.m @@ -1,55 +1,55 @@ -function fn_fprintmatrix(fid, M, nrows, ncols, indxFloat) -% Prints the matrix to an ascii file indexed by fid. -% -% Inputs: -% fid: Ascii file id. Example: fid = fopen('outdatainp_3s_stv_tvms6lags.prn','a'); -% M: The matrix to be written to the file. -% nrows: Number of rows of M. -% ncols: Number of columns of M. -% indxFloat: 1 if double; -% 2 if single; -% 3 if only 3 significant digits -% 0 if integer. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% -if nrows~=size(M,1) - error('fn_fprintmatrix(): Make sure the row number supplied match that of the matrix'); -end -if ncols~=size(M,2) - error('fn_fprintmatrix(): Make sure the column number supplied match that of the matrix'); -end -for ki=1:nrows - for kj=1:ncols - if (indxFloat == 1) - fprintf(fid,' %.16e ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 2) - fprintf(fid,' %.8e ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 3) - fprintf(fid,' %.3e ',M((kj-1)*nrows+ki)); - else - fprintf(fid,' %d ',M((kj-1)*nrows+ki)); - end - if (kj==ncols) - fprintf(fid,'\n'); - end - end - if (ki==nrows) - fprintf(fid,'\n\n'); - end -end +function fn_fprintmatrix(fid, M, nrows, ncols, indxFloat) +% Prints the matrix to an ascii file indexed by fid. +% +% Inputs: +% fid: Ascii file id. Example: fid = fopen('outdatainp_3s_stv_tvms6lags.prn','a'); +% M: The matrix to be written to the file. +% nrows: Number of rows of M. +% ncols: Number of columns of M. +% indxFloat: 1 if double; +% 2 if single; +% 3 if only 3 significant digits +% 0 if integer. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% +if nrows~=size(M,1) + error('fn_fprintmatrix(): Make sure the row number supplied match that of the matrix'); +end +if ncols~=size(M,2) + error('fn_fprintmatrix(): Make sure the column number supplied match that of the matrix'); +end +for ki=1:nrows + for kj=1:ncols + if (indxFloat == 1) + fprintf(fid,' %.16e ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 2) + fprintf(fid,' %.8e ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 3) + fprintf(fid,' %.3e ',M((kj-1)*nrows+ki)); + else + fprintf(fid,' %d ',M((kj-1)*nrows+ki)); + end + if (kj==ncols) + fprintf(fid,'\n'); + end + end + if (ki==nrows) + fprintf(fid,'\n\n'); + end +end diff --git a/MatlabFiles/fn_fprintvector.m b/MatlabFiles/fn_fprintvector.m index 2329c6c76a6ca65da3da24ff1336ca41c5dac246..c7f9752a561ea95ada5451b60bfe1852ec27673e 100644 --- a/MatlabFiles/fn_fprintvector.m +++ b/MatlabFiles/fn_fprintvector.m @@ -1,46 +1,46 @@ -function fn_fprintvector(fid, vec, ncols, indxFloat) -% Prints a row vector to an ascii file indexed by fid without any spacing. -% -% Inputs: -% fid: Ascii file id. Example: fid = fopen('outdatainp_3s_stv_tvms6lags.prn','a'); -% vec: A row vector to be written to the file. -% ncols: Number of columns of vec. -% indxFloat: 1 if double; -% 2 if single; -% 0 if integer. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% -if size(vec,1)~=1 - error('fn_fprintvector(): The vector must be a row vector'); -end -if ncols~=size(vec,2) - error('fn_fprintvector(): The column number supplied match that of the vector'); -end -for kj=1:ncols - if (indxFloat == 1) - fprintf(fid,' %.16e ',vec(kj)); - elseif (indxFloat == 2) - fprintf(fid,' %.8e ',vec(kj)); - else - fprintf(fid,' %d ',vec(kj)); - end - if (kj==ncols) - fprintf(fid,'\n'); - end -end +function fn_fprintvector(fid, vec, ncols, indxFloat) +% Prints a row vector to an ascii file indexed by fid without any spacing. +% +% Inputs: +% fid: Ascii file id. Example: fid = fopen('outdatainp_3s_stv_tvms6lags.prn','a'); +% vec: A row vector to be written to the file. +% ncols: Number of columns of vec. +% indxFloat: 1 if double; +% 2 if single; +% 0 if integer. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% +if size(vec,1)~=1 + error('fn_fprintvector(): The vector must be a row vector'); +end +if ncols~=size(vec,2) + error('fn_fprintvector(): The column number supplied match that of the vector'); +end +for kj=1:ncols + if (indxFloat == 1) + fprintf(fid,' %.16e ',vec(kj)); + elseif (indxFloat == 2) + fprintf(fid,' %.8e ',vec(kj)); + else + fprintf(fid,' %d ',vec(kj)); + end + if (kj==ncols) + fprintf(fid,'\n'); + end +end diff --git a/MatlabFiles/fn_gfmean.m b/MatlabFiles/fn_gfmean.m index b0dd67b61f6ae5a0d48e107f5519714f62d5ab7d..34c4b605e9f338407c9f1448a264418d39dad151 100644 --- a/MatlabFiles/fn_gfmean.m +++ b/MatlabFiles/fn_gfmean.m @@ -1,58 +1,58 @@ -function [Fmat,gvec] = fn_gfmean(b,P,Vi,nvar,ncoef,n0,np) -% [Fmat,gvec] = fn_gfmean(b,P,Vi,nvar,ncoef,n0,np) -% -% Mean of free lagged parameters g and original lagged parameters F, conditional on comtemporaneous b's -% See Waggoner and Zha's Gibbs sampling -% -% b: sum(n0)-element vector of mean estimate of A0 free parameters -% P: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. -% nvar: number of endogeous variables -% ncoef: number of original lagged variables per equation -% n0: nvar-element vector, ith element represents the number of free A0 parameters in ith equation -% np: nvar-element vector, ith element represents the number of free A+ parameters in ith equation -%--------------- -% Fmat: ncoef-by-nvar matrix of original lagged parameters A+. Column corresponding to equation. -% gvec: sum(np)-by-1 stacked vector of all free lagged parameters A+. -% -% Tao Zha, February 2000. Revised, August 2000. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -b=b(:); n0=n0(:); np=np(:); - -n0cum = [0;cumsum(n0)]; -npcum = [0;cumsum(np)]; -gvec = zeros(npcum(end),1); -Fmat = zeros(ncoef,nvar); % ncoef: maximum original lagged parameters per equation - -if ~(length(b)==n0cum(end)) - error('Make inputs n0 and length(b) match exactly') -end - -for kj=1:nvar - bj = b(n0cum(kj)+1:n0cum(kj+1)); - gj = P{kj}*bj; - gvec(npcum(kj)+1:npcum(kj+1)) = gj; - Fmat(:,kj) = Vi{kj}*gj; -end +function [Fmat,gvec] = fn_gfmean(b,P,Vi,nvar,ncoef,n0,np) +% [Fmat,gvec] = fn_gfmean(b,P,Vi,nvar,ncoef,n0,np) +% +% Mean of free lagged parameters g and original lagged parameters F, conditional on comtemporaneous b's +% See Waggoner and Zha's Gibbs sampling +% +% b: sum(n0)-element vector of mean estimate of A0 free parameters +% P: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. +% nvar: number of endogeous variables +% ncoef: number of original lagged variables per equation +% n0: nvar-element vector, ith element represents the number of free A0 parameters in ith equation +% np: nvar-element vector, ith element represents the number of free A+ parameters in ith equation +%--------------- +% Fmat: ncoef-by-nvar matrix of original lagged parameters A+. Column corresponding to equation. +% gvec: sum(np)-by-1 stacked vector of all free lagged parameters A+. +% +% Tao Zha, February 2000. Revised, August 2000. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +b=b(:); n0=n0(:); np=np(:); + +n0cum = [0;cumsum(n0)]; +npcum = [0;cumsum(np)]; +gvec = zeros(npcum(end),1); +Fmat = zeros(ncoef,nvar); % ncoef: maximum original lagged parameters per equation + +if ~(length(b)==n0cum(end)) + error('Make inputs n0 and length(b) match exactly') +end + +for kj=1:nvar + bj = b(n0cum(kj)+1:n0cum(kj+1)); + gj = P{kj}*bj; + gvec(npcum(kj)+1:npcum(kj+1)) = gj; + Fmat(:,kj) = Vi{kj}*gj; +end diff --git a/MatlabFiles/fn_gibbsglb.m b/MatlabFiles/fn_gibbsglb.m index cace135b1279b447be12035f3155929e196685e5..bb6277fa8db6a514e6ecb8ef81042bd5ec118e1b 100644 --- a/MatlabFiles/fn_gibbsglb.m +++ b/MatlabFiles/fn_gibbsglb.m @@ -1,73 +1,72 @@ -function [cT,vR,kdf] = fn_gibbsglb(Sbd,idmat0,nvar,fss) -% [cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss) -% Global setup outside the Gibbs loop -- c.f. gibbsvar -% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" -% See Note Forecast (2) pp. 44-51 -% -% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the -% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. -% Note,"bd" stands for block diagonal. -% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. -% nvar: rank of A0 or # of variables -% fss: effective sample size (in the exponential term) -- -% # of observations + # of dummy observations -% (or nSample - lags + # of dummy observations) -%------------- -% cT{i}: nvar-by-nvar where T'*T=Sbd{i} which is kind of covariance martrix -% divided by fss already -% vR{i}: nvar-by-q{i} -- orthonormral basis for T*R, which is obtained through -% single value decomposition of Q*inv(T) -% kdf: the polynomial power in the Gamma or 1d Wishart distribution, used in -% "gibbsvar.m" -% -% Written by Tao Zha; Copyright (c) 1999 by Waggoner and Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -kdf = fss; %2; %fss; - -cT = cell(nvar,1); -for k=1:nvar - cT{k} = chol(Sbd{k}); % upper triangular but lower triangular Choleski -end - -Q = cell(nvar,1); - % Q{i}: nvar-by-nvar with rank nvar-q(i) with ith equation a and - % q(i) which is # of non-zero elements in a. Note: Q*a=0. - -vR = cell(nvar,1); -for k=1:nvar - Q{k} = diag(idmat0(:,k)==0); % constructing Q{k} - % - [jnk1,d1,v1] = svd(Q{k}/cT{k}); - d1max=max(diag(d1)); - if d1max==0 - Idxk=1:nvar; - else - Idxk = find(diag(d1)<eps*d1max); - end - lenk = length(find(idmat0(:,k))); - if ( length(Idxk)<lenk ) - warning('Dimension of non-zero A0(:,k) is different from svd(Q*inv(T))') - disp('Press ctrl-c to abort') - pause - else - jnk1 = v1(:,Idxk); - vR{k} = jnk1(:,1:lenk); % orthonormal basis for T*R - end -end +function [cT,vR,kdf] = fn_gibbsglb(Sbd,idmat0,nvar,fss) +% [cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss) +% Global setup outside the Gibbs loop -- c.f. gibbsvar +% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" +% See Note Forecast (2) pp. 44-51 +% +% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the +% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. +% Note,"bd" stands for block diagonal. +% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. +% nvar: rank of A0 or # of variables +% fss: effective sample size (in the exponential term) -- +% # of observations + # of dummy observations +% (or nSample - lags + # of dummy observations) +%------------- +% cT{i}: nvar-by-nvar where T'*T=Sbd{i} which is kind of covariance martrix +% divided by fss already +% vR{i}: nvar-by-q{i} -- orthonormral basis for T*R, which is obtained through +% single value decomposition of Q*inv(T) +% kdf: the polynomial power in the Gamma or 1d Wishart distribution, used in +% "gibbsvar.m" +% +% +% Copyright (C) 1997-2012 Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +kdf = fss; %2; %fss; + +cT = cell(nvar,1); +for k=1:nvar + cT{k} = chol(Sbd{k}); % upper triangular but lower triangular Choleski +end + +Q = cell(nvar,1); + % Q{i}: nvar-by-nvar with rank nvar-q(i) with ith equation a and + % q(i) which is # of non-zero elements in a. Note: Q*a=0. + +vR = cell(nvar,1); +for k=1:nvar + Q{k} = diag(idmat0(:,k)==0); % constructing Q{k} + % + [jnk1,d1,v1] = svd(Q{k}/cT{k}); + d1max=max(diag(d1)); + if d1max==0 + Idxk=1:nvar; + else + Idxk = find(diag(d1)<eps*d1max); + end + lenk = length(find(idmat0(:,k))); + if ( length(Idxk)<lenk ) + warning('Dimension of non-zero A0(:,k) is different from svd(Q*inv(T))') + disp('Press ctrl-c to abort') + pause + else + jnk1 = v1(:,Idxk); + vR{k} = jnk1(:,1:lenk); % orthonormal basis for T*R + end +end diff --git a/MatlabFiles/fn_gibbsrvar.m b/MatlabFiles/fn_gibbsrvar.m index 6e0d2e253aa7105bc0002a8dd22251bcf3893b75..bbbbd65898d39ecdb75091c05b1d4bce9aaaaee0 100644 --- a/MatlabFiles/fn_gibbsrvar.m +++ b/MatlabFiles/fn_gibbsrvar.m @@ -1,83 +1,83 @@ -function [A0gbs, Wcell] = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) -% [A0gbs, Wcell] = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) -% One-step Gibbs sampler for restricted VARs in the structural form (including over-identified cases). -% Reference: "A Gibbs sampler for structural VARs" by D.F. Waggoner and T. Zha, `` -% Journal of Economic Dynamics & Control (JEDC) 28 (2003) 349-366. -% See Note Forecast (2) pp. 44-51, 70-71, and Theorem 1 and Section 3.1 in the WZ JEDC paper. -% -% A0gbs: the last draw of A0 matrix -% UT: cell(nvar,1) -- U_i*T_i in the proof of Theorem 1 where -% (1) a_i = U_i*b_i with b_i being a vector of free parameters -% (2) T_i (q_i-by-q_i) is from T_i*T_i'= S_i = inv(H0inv{i}/T) where H0inv is the inverse of -% the covariance martrix NOT divided by fss and S_i is defined in (14) on p.355 of the WZ JEDC paper. -% nvar: rank of A0 or # of variables -% fss: effective sample size == nSample (T)-lags+# of dummy observations -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -% Indxcol: a row vector indicating random columns this Gibbs draws. -% When this input is not supplied, the Gibbs draws all columns -%------------------ -% A0bgs: nvar-by-nvar. New draw of A0 matrix in this Gibbs step -% Wcell: cell(nvar,1). In each cell, columns of Wcell{i} form an orthonormal basis w_1,...,w_qi in Section 3.1 in the WZ paper. Added 9/04. -% -% Written by Tao Zha, August 2000. Revised, September 2004. -% Copyright (c) by Waggoner and Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if (nargin==5), Indxcol=[1:nvar]; end - -%---------------- Local loop for Gibbs given last A0gbs ---------- -Wcell = cell(length(Indxcol),1); -w = zeros(nvar,1); -for ki=Indxcol % given last A0gbs and generate new A0bgs - X = A0gbs; % WZ's Section 4.3 - X(:,ki) = 0; % want to find non-zero sw s.t., X'*w=0 - - - %*** Solving for w and getting an orthonormal basis. See Theorem 1 and also p.48 in Forecast II - [jL,Ux] = lu(X'); - jIx0 = min(find(abs(diag(Ux))<eps)); % if isempty(jIx0), then something is wrong here - w(jIx0+1:end) = 0; % if jIx0+1>end, no effect on w0 - w(jIx0) = 1; - jA = Ux(1:jIx0-1,1:jIx0-1); - jb = Ux(1:jIx0-1,jIx0); - jy = -jA\jb; - w(1:jIx0-1) = jy; - % Note: if jIx0=1 (which almost never happens for numerical stability reasons), no effect on w. - - %*** Constructing orthonormal basis w_1, ..., w_qi at each Gibbs step - w0 = UT{ki}'*w; - w1 = w0/sqrt(sum(w0.^2)); - [W,jnk] = qr(w1); % Columns of W form an orthonormal basis w_1,...,w_qi in Section 3.1 in the WZ paper - - %*** Draw beta's according to Theorem 1 in the WZ JEDC paper. - gkbeta = zeros(n0(ki),1); % qi-by-1: greak beta's - jstd = sqrt(1/fss); - gkbeta(2:end) = jstd*randn(n0(ki)-1,1); % for beta_2, ..., beta_qi - %--- Unnormalized (i.e., not normalized) gamma or 1-d Wishart draw of beta_1 in Theorem 1 of the WZ JEDC paper. - jr = jstd*randn(fss+1,1); - if rand(1)<0.5 - gkbeta(1) = sqrt(jr'*jr); - else - gkbeta(1) = -sqrt(jr'*jr); - end - - %*** Getting a new ki_th column in A0 - A0gbs(:,ki) = UT{ki}*(W*gkbeta); % n-by-1: U_i*T_i*W*beta; - Wcell{ki} = W; %q_i-by-1. -end +function [A0gbs, Wcell] = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) +% [A0gbs, Wcell] = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) +% One-step Gibbs sampler for restricted VARs in the structural form (including over-identified cases). +% Reference: "A Gibbs sampler for structural VARs" by D.F. Waggoner and T. Zha, `` +% Journal of Economic Dynamics & Control (JEDC) 28 (2003) 349-366. +% See Note Forecast (2) pp. 44-51, 70-71, and Theorem 1 and Section 3.1 in the WZ JEDC paper. +% +% A0gbs: the last draw of A0 matrix +% UT: cell(nvar,1) -- U_i*T_i in the proof of Theorem 1 where +% (1) a_i = U_i*b_i with b_i being a vector of free parameters +% (2) T_i (q_i-by-q_i) is from T_i*T_i'= S_i = inv(H0inv{i}/T) where H0inv is the inverse of +% the covariance martrix NOT divided by fss and S_i is defined in (14) on p.355 of the WZ JEDC paper. +% nvar: rank of A0 or # of variables +% fss: effective sample size == nSample (T)-lags+# of dummy observations +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +% Indxcol: a row vector indicating random columns this Gibbs draws. +% When this input is not supplied, the Gibbs draws all columns +%------------------ +% A0bgs: nvar-by-nvar. New draw of A0 matrix in this Gibbs step +% Wcell: cell(nvar,1). In each cell, columns of Wcell{i} form an orthonormal basis w_1,...,w_qi in Section 3.1 in the WZ paper. Added 9/04. +% +% Written by Tao Zha, August 2000. Revised, September 2004. +% +% +% Copyright (C) 1997-2012 Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if (nargin==5), Indxcol=[1:nvar]; end + +%---------------- Local loop for Gibbs given last A0gbs ---------- +Wcell = cell(length(Indxcol),1); +w = zeros(nvar,1); +for ki=Indxcol % given last A0gbs and generate new A0bgs + X = A0gbs; % WZ's Section 4.3 + X(:,ki) = 0; % want to find non-zero sw s.t., X'*w=0 + + + %*** Solving for w and getting an orthonormal basis. See Theorem 1 and also p.48 in Forecast II + [jL,Ux] = lu(X'); + jIx0 = min(find(abs(diag(Ux))<eps)); % if isempty(jIx0), then something is wrong here + w(jIx0+1:end) = 0; % if jIx0+1>end, no effect on w0 + w(jIx0) = 1; + jA = Ux(1:jIx0-1,1:jIx0-1); + jb = Ux(1:jIx0-1,jIx0); + jy = -jA\jb; + w(1:jIx0-1) = jy; + % Note: if jIx0=1 (which almost never happens for numerical stability reasons), no effect on w. + + %*** Constructing orthonormal basis w_1, ..., w_qi at each Gibbs step + w0 = UT{ki}'*w; + w1 = w0/sqrt(sum(w0.^2)); + [W,jnk] = qr(w1); % Columns of W form an orthonormal basis w_1,...,w_qi in Section 3.1 in the WZ paper + + %*** Draw beta's according to Theorem 1 in the WZ JEDC paper. + gkbeta = zeros(n0(ki),1); % qi-by-1: greak beta's + jstd = sqrt(1/fss); + gkbeta(2:end) = jstd*randn(n0(ki)-1,1); % for beta_2, ..., beta_qi + %--- Unnormalized (i.e., not normalized) gamma or 1-d Wishart draw of beta_1 in Theorem 1 of the WZ JEDC paper. + jr = jstd*randn(fss+1,1); + if rand(1)<0.5 + gkbeta(1) = sqrt(jr'*jr); + else + gkbeta(1) = -sqrt(jr'*jr); + end + + %*** Getting a new ki_th column in A0 + A0gbs(:,ki) = UT{ki}*(W*gkbeta); % n-by-1: U_i*T_i*W*beta; + Wcell{ki} = W; %q_i-by-1. +end diff --git a/MatlabFiles/fn_gibbsrvar_setup.m b/MatlabFiles/fn_gibbsrvar_setup.m index 2c3049829de4c90fcb9f868b2885ff499e45b0d3..8f3046d5c827cdc3f8d91de1bf939a46902e6cb4 100644 --- a/MatlabFiles/fn_gibbsrvar_setup.m +++ b/MatlabFiles/fn_gibbsrvar_setup.m @@ -1,75 +1,75 @@ -function [Tinv,UT,VHphalf,PU,VPU] = fn_gibbsrvar_setup(H0inv, Ui, Hpinv, Pmat, Vi, nvar, fss) -% [Tinv,UT,VHphalf,PU,VPU] = fn_gibbsrvar_setup.m(H0inv, Ui, Hpinv, Pmat, Vi, fss, nvar) -% Global setup outside the Gibbs loop to be used by fn_gibbsvar(). -% Reference: "A Gibbs sampler for structural VARs" by D.F. Waggoner and T. Zha, `` -% Journal of Economic Dynamics & Control (JEDC) 28 (2003) 349-366. -% See Note Forecast (2) pp. 44-51, 70-71, and Theorem 1 and Section 3.1 in the WZ JEDC paper. -% -% H0inv: cell(nvar,1). Not divided by T yet. In each cell, inverse of posterior covariance matrix H0. -% The exponential term is b_i'*inv(H0)*b_i for the ith equation where b_i = U_i*a0_i. -% It resembles old SpH or Sbd in the exponent term in posterior of A0, but not divided by T yet. -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. Imported from dnrprior.m. -% Hpinv: cell(nvar,1). In each cell, posterior inverse of covariance matrix Hp (A+) for the free parameters -% g_i = V_i*A+(:,i) in the ith equation. -% Pmat: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. -% In other words, the posterior mean (of g_i) = Pmat{i}*b_i where g_i is a column vector of free parameters -% of A+(:,i)) given b_i (b_i is a column vector of free parameters of A0(:,i)). -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. Imported from dnrprior.m. -% nvar: number of endogenous variables or rank of A0. -% fss: effective sample size (in the exponential term) = nSample - lags + ndobs (ndobs = # of dummy observations -% is set to 0 when fn_rnrprior_covres_dobs() is used where dummy observations are included as part of the explicit prior. -%------------- -% Tinv: cell(nvar,1). In each cell, inv(T_i) for T_iT_i'=S_i where S_i is defined on p.355 of the WZ JEDC paper. -% UT: cell(nvar,1). In each cell, U_i*T_i. -% VHphalf: cell(nvar,1). In each cell, V_i*sqrt(Hp_i). -% PU: cell(nvar,1). In each cell, Pmat{i}*U_i where Pmat{i} = P_i defined in (13) on p.353 of the WZ JEDC paper. -% VPU: cell(nvar,1). In each cell, V_i*P_i*U_i -% -% Written by Tao Zha, September 2004. -% Copyright (c) 2004 by Waggoner and Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -%--- For A0. -Tinv = cell(nvar,1); % in each cell, inv(T_i) for T_iT_i'=S_i where S_i is defined on p.355 of the WZ JEDC paper. -UT = cell(nvar,1); % in each cell, U_i*T_i. -%--- For A+. -VHphalf = cell(nvar,1); % in each cell, V_i*sqrt(Hp_i). -PU = cell(nvar,1); % in each cell, Pmat{i}*U_i where Pmat{i} = P_i defined in (13) on p.353 of the WZ JEDC paper. -VPU = cell(nvar,1); % in each cell, V_i*P_i*U_i -% -for ki=1:nvar - %--- For A0. - Tinv{ki} = chol(H0inv{ki}/fss); % Tinv_i'*Tinv_i = inv(S_i) ==> T_i*T_i' = S_i where S_i = H0inv{i}/fss is defined on p.355 of the WZ JEDC paper. - UT{ki} = Ui{ki}/Tinv{ki}; % n-by-qi: U_i*T_i in (14) on p. 255 of the WZ JEDC paper. - %--- For A+. - VHphalf{ki} = Vi{ki}/chol(Hpinv{ki}); % where chol(Hpinv_i)*chol(Hpinv_i)'=Hpinv_i. - PU{ki} = Pmat{ki}*Ui{ki}'; - VPU{ki} = Vi{ki}*PU{ki}; -end +function [Tinv,UT,VHphalf,PU,VPU] = fn_gibbsrvar_setup(H0inv, Ui, Hpinv, Pmat, Vi, nvar, fss) +% [Tinv,UT,VHphalf,PU,VPU] = fn_gibbsrvar_setup.m(H0inv, Ui, Hpinv, Pmat, Vi, fss, nvar) +% Global setup outside the Gibbs loop to be used by fn_gibbsvar(). +% Reference: "A Gibbs sampler for structural VARs" by D.F. Waggoner and T. Zha, `` +% Journal of Economic Dynamics & Control (JEDC) 28 (2003) 349-366. +% See Note Forecast (2) pp. 44-51, 70-71, and Theorem 1 and Section 3.1 in the WZ JEDC paper. +% +% H0inv: cell(nvar,1). Not divided by T yet. In each cell, inverse of posterior covariance matrix H0. +% The exponential term is b_i'*inv(H0)*b_i for the ith equation where b_i = U_i*a0_i. +% It resembles old SpH or Sbd in the exponent term in posterior of A0, but not divided by T yet. +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. Imported from dnrprior.m. +% Hpinv: cell(nvar,1). In each cell, posterior inverse of covariance matrix Hp (A+) for the free parameters +% g_i = V_i*A+(:,i) in the ith equation. +% Pmat: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. +% In other words, the posterior mean (of g_i) = Pmat{i}*b_i where g_i is a column vector of free parameters +% of A+(:,i)) given b_i (b_i is a column vector of free parameters of A0(:,i)). +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. Imported from dnrprior.m. +% nvar: number of endogenous variables or rank of A0. +% fss: effective sample size (in the exponential term) = nSample - lags + ndobs (ndobs = # of dummy observations +% is set to 0 when fn_rnrprior_covres_dobs() is used where dummy observations are included as part of the explicit prior. +%------------- +% Tinv: cell(nvar,1). In each cell, inv(T_i) for T_iT_i'=S_i where S_i is defined on p.355 of the WZ JEDC paper. +% UT: cell(nvar,1). In each cell, U_i*T_i. +% VHphalf: cell(nvar,1). In each cell, V_i*sqrt(Hp_i). +% PU: cell(nvar,1). In each cell, Pmat{i}*U_i where Pmat{i} = P_i defined in (13) on p.353 of the WZ JEDC paper. +% VPU: cell(nvar,1). In each cell, V_i*P_i*U_i +% +% Written by Tao Zha, September 2004. +% +% +% Copyright (C) 1997-2012 Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +%--- For A0. +Tinv = cell(nvar,1); % in each cell, inv(T_i) for T_iT_i'=S_i where S_i is defined on p.355 of the WZ JEDC paper. +UT = cell(nvar,1); % in each cell, U_i*T_i. +%--- For A+. +VHphalf = cell(nvar,1); % in each cell, V_i*sqrt(Hp_i). +PU = cell(nvar,1); % in each cell, Pmat{i}*U_i where Pmat{i} = P_i defined in (13) on p.353 of the WZ JEDC paper. +VPU = cell(nvar,1); % in each cell, V_i*P_i*U_i +% +for ki=1:nvar + %--- For A0. + Tinv{ki} = chol(H0inv{ki}/fss); % Tinv_i'*Tinv_i = inv(S_i) ==> T_i*T_i' = S_i where S_i = H0inv{i}/fss is defined on p.355 of the WZ JEDC paper. + UT{ki} = Ui{ki}/Tinv{ki}; % n-by-qi: U_i*T_i in (14) on p. 255 of the WZ JEDC paper. + %--- For A+. + VHphalf{ki} = Vi{ki}/chol(Hpinv{ki}); % where chol(Hpinv_i)*chol(Hpinv_i)'=Hpinv_i. + PU{ki} = Pmat{ki}*Ui{ki}'; + VPU{ki} = Vi{ki}*PU{ki}; +end diff --git a/MatlabFiles/fn_gibbsrvaroldworks.m b/MatlabFiles/fn_gibbsrvaroldworks.m index ed20ecc93a81e8da5787049c030705edc461d0bf..1469ac22a3d9549c2d50de196ce58d9ace8f135d 100644 --- a/MatlabFiles/fn_gibbsrvaroldworks.m +++ b/MatlabFiles/fn_gibbsrvaroldworks.m @@ -1,79 +1,80 @@ -function A0gbs = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) -% A0gbs = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) -% One-step Gibbs sampler for restricted VARs in the structural form -% Ref.: D.F. Waggoner and T. Zha: ``A Gibbs sampler for structural VARs'' -% See Note Forecast (2) pp. 44-51 and Theorem 1 and Section 3 in the WZ paper. -% -% A0gbs: the last draw of A0 matrix -% UT: cell(nvar,1) -- U_i*T_i in the proof of Theorem 1 where -% (1) a_i = U_i*b_i with b_i being a vector of free parameters -% (2) T_i (q_i-by-q_i) is from T_i*T_i'=H0inv{i}/T. Note that H0inv is the inverse of -% the covariance martrix NOT divided by fss. See Theorem 1. -% nvar: rank of A0 or # of variables -% fss: effective sample size == nSample (T)-lags+# of dummy observations -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -% Indxcol: a row vector indicating random columns this Gibbs draws. -% When this input is not supplied, the Gibbs draws all columns -%------------------ -% A0bgs: new draw of A0 matrix in this Gibbs step -% -% Written by Tao Zha, August 2000; Copyright (c) by Waggoner and Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (nargin==5), Indxcol=[1:nvar]; end - -%---------------- Local loop for Gibbs given last A0gbs ---------- -% -w = zeros(nvar,1); -for ki=Indxcol % given last A0gbs and generate new A0bgs - X = A0gbs; % WZ's Section 4.3 - X(:,ki) = 0; % want to find non-zero sw s.t., X'*w=0 - - - %*** Solving for w and getting an orthonormal basis. See Theorem 1 and also p.48 in Forecast II - [jL,Ux] = lu(X'); - jIx0 = min(find(abs(diag(Ux))<eps)); % if isempty(jIx0), then something is wrong here - w(jIx0+1:end) = 0; % if jIx0+1>end, no effect on w0 - w(jIx0) = 1; - jA = Ux(1:jIx0-1,1:jIx0-1); - jb = Ux(1:jIx0-1,jIx0); - jy = -jA\jb; - w(1:jIx0-1) = jy; - % Note: if jIx0=1 (which almost never happens for numerical stability reasons), no effect on w. - - %*** Constructing orthonormal basis w_1, ..., w_qi at each Gibbs step - w0 = UT{ki}'*w; - w1 = w0/sqrt(sum(w0.^2)); - [W,jnk] = qr(w1); % columns of W form an orthonormal basis w_1,...,w_qi in Section 4.2 in the WZ paper - - %*** Draw beta's in Theorem 1 - gkbeta = zeros(n0(ki),1); % qi-by-1: greak beta's - jstd = sqrt(1/fss); - gkbeta(2:end) = jstd*randn(n0(ki)-1,1); % for beta_2, ..., beta_qi - %--- Unnormalized (i.e., not normalized) gamma or 1-d Wishart draw of beta_1 in Theorem 1. - %* gamma or 1-d Wishart draw of beta_1 - jr = jstd*randn(fss+1,1); - if rand(1)<0.5 - gkbeta(1) = sqrt(jr'*jr); - else - gkbeta(1) = -sqrt(jr'*jr); - end - - %*** Getting a new ki_th column in A0 - A0gbs(:,ki) = UT{ki}*(W*gkbeta); % n-by-1 -end +function A0gbs = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) +% A0gbs = fn_gibbsrvar(A0gbs,UT,nvar,fss,n0,Indxcol) +% One-step Gibbs sampler for restricted VARs in the structural form +% Ref.: D.F. Waggoner and T. Zha: ``A Gibbs sampler for structural VARs'' +% See Note Forecast (2) pp. 44-51 and Theorem 1 and Section 3 in the WZ paper. +% +% A0gbs: the last draw of A0 matrix +% UT: cell(nvar,1) -- U_i*T_i in the proof of Theorem 1 where +% (1) a_i = U_i*b_i with b_i being a vector of free parameters +% (2) T_i (q_i-by-q_i) is from T_i*T_i'=H0inv{i}/T. Note that H0inv is the inverse of +% the covariance martrix NOT divided by fss. See Theorem 1. +% nvar: rank of A0 or # of variables +% fss: effective sample size == nSample (T)-lags+# of dummy observations +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +% Indxcol: a row vector indicating random columns this Gibbs draws. +% When this input is not supplied, the Gibbs draws all columns +%------------------ +% A0bgs: new draw of A0 matrix in this Gibbs step +% +% Written by Tao Zha, August 2000 +% +% +% Copyright (C) 1997-2012 Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (nargin==5), Indxcol=[1:nvar]; end + +%---------------- Local loop for Gibbs given last A0gbs ---------- +% +w = zeros(nvar,1); +for ki=Indxcol % given last A0gbs and generate new A0bgs + X = A0gbs; % WZ's Section 4.3 + X(:,ki) = 0; % want to find non-zero sw s.t., X'*w=0 + + + %*** Solving for w and getting an orthonormal basis. See Theorem 1 and also p.48 in Forecast II + [jL,Ux] = lu(X'); + jIx0 = min(find(abs(diag(Ux))<eps)); % if isempty(jIx0), then something is wrong here + w(jIx0+1:end) = 0; % if jIx0+1>end, no effect on w0 + w(jIx0) = 1; + jA = Ux(1:jIx0-1,1:jIx0-1); + jb = Ux(1:jIx0-1,jIx0); + jy = -jA\jb; + w(1:jIx0-1) = jy; + % Note: if jIx0=1 (which almost never happens for numerical stability reasons), no effect on w. + + %*** Constructing orthonormal basis w_1, ..., w_qi at each Gibbs step + w0 = UT{ki}'*w; + w1 = w0/sqrt(sum(w0.^2)); + [W,jnk] = qr(w1); % columns of W form an orthonormal basis w_1,...,w_qi in Section 4.2 in the WZ paper + + %*** Draw beta's in Theorem 1 + gkbeta = zeros(n0(ki),1); % qi-by-1: greak beta's + jstd = sqrt(1/fss); + gkbeta(2:end) = jstd*randn(n0(ki)-1,1); % for beta_2, ..., beta_qi + %--- Unnormalized (i.e., not normalized) gamma or 1-d Wishart draw of beta_1 in Theorem 1. + %* gamma or 1-d Wishart draw of beta_1 + jr = jstd*randn(fss+1,1); + if rand(1)<0.5 + gkbeta(1) = sqrt(jr'*jr); + else + gkbeta(1) = -sqrt(jr'*jr); + end + + %*** Getting a new ki_th column in A0 + A0gbs(:,ki) = UT{ki}*(W*gkbeta); % n-by-1 +end diff --git a/MatlabFiles/fn_gradcd.m b/MatlabFiles/fn_gradcd.m index 276c9e966ace6bdc5c27ccc1c0b6810552d6996a..e1bd79e6aa61eab406a816e59d71086e9723338f 100644 --- a/MatlabFiles/fn_gradcd.m +++ b/MatlabFiles/fn_gradcd.m @@ -1,86 +1,86 @@ -function grdd = fn_gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... - P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -%function grdd = fn_gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... -% P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -% computes numerical gradient of a single-valued function or Jacobian -% matrix of a vector-valued function using a central difference with -% function grdd = gradcd(fcn,x0,grdh) -% -% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). -% x0: a column vector n-by-1, at which point the hessian is evaluated. -% grdh: step size, n*1. Set as follows -% step = eps^(1/3); -% %step = 1e-04; -% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); -%-------------------- -% grdd: n-by-k Jacobian matrix (gradients). -% -% Written by Tao Zha, 2002. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -stps = eps^(1/3); -% eps: floating point relative accuracy or machine precision: 2.22e-16 -% stps: step size recommended by Dennis and Schnabel: 6.006e-6 - -x0 = x0(:); -tailstr = ')'; -for i=nargin-3:-1:1 - tailstr=[ ',P' num2str(i) tailstr]; -end -f0 = eval([fcn '(x0' tailstr]); - -% ** initializations -n = length(x0); -k = length(f0); % dimension of "fcn" - -% ** Computation of stepsize (dh) -if all(grdh) - dh = grdh; -else - ax0 = abs(x0); - if all(x0) - dax0 = x0 ./ ax0; - else - dax0 = 1; - end - dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; -end - -xdh = x0 + dh; -dh = xdh - x0; % This increases precision slightly -% -argplus = x0(:,ones(n,1)); -argminus = argplus; -dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). -argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". -argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". - -grdd = zeros(k,n); % preallocate to speed the loop. -i = 0; -while i ~= n - i = i+1; - fp = eval([fcn '(argplus(:,i)' tailstr]); - fm = eval([fcn '(argminus(:,i)' tailstr]); - grdd(:,i) = fp - fm; -end -dhm = dh(:,ones(k,1)); -dhm = dhm'; % k*n -grdd = grdd ./ (2*dhm); % k-by-n. -grdd = grdd'; % n-by-k. - +function grdd = fn_gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... + P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +%function grdd = fn_gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... +% P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +% computes numerical gradient of a single-valued function or Jacobian +% matrix of a vector-valued function using a central difference with +% function grdd = gradcd(fcn,x0,grdh) +% +% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). +% x0: a column vector n-by-1, at which point the hessian is evaluated. +% grdh: step size, n*1. Set as follows +% step = eps^(1/3); +% %step = 1e-04; +% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); +%-------------------- +% grdd: n-by-k Jacobian matrix (gradients). +% +% Written by Tao Zha, 2002. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +stps = eps^(1/3); +% eps: floating point relative accuracy or machine precision: 2.22e-16 +% stps: step size recommended by Dennis and Schnabel: 6.006e-6 + +x0 = x0(:); +tailstr = ')'; +for i=nargin-3:-1:1 + tailstr=[ ',P' num2str(i) tailstr]; +end +f0 = eval([fcn '(x0' tailstr]); + +% ** initializations +n = length(x0); +k = length(f0); % dimension of "fcn" + +% ** Computation of stepsize (dh) +if all(grdh) + dh = grdh; +else + ax0 = abs(x0); + if all(x0) + dax0 = x0 ./ ax0; + else + dax0 = 1; + end + dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; +end + +xdh = x0 + dh; +dh = xdh - x0; % This increases precision slightly +% +argplus = x0(:,ones(n,1)); +argminus = argplus; +dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). +argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". +argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". + +grdd = zeros(k,n); % preallocate to speed the loop. +i = 0; +while i ~= n + i = i+1; + fp = eval([fcn '(argplus(:,i)' tailstr]); + fm = eval([fcn '(argminus(:,i)' tailstr]); + grdd(:,i) = fp - fm; +end +dhm = dh(:,ones(k,1)); +dhm = dhm'; % k*n +grdd = grdd ./ (2*dhm); % k-by-n. +grdd = grdd'; % n-by-k. + diff --git a/MatlabFiles/fn_gradcd2.m b/MatlabFiles/fn_gradcd2.m index 7712ac8935bd81689f4f50c9ce500bc81a5b3c2d..e7d433152e6eba28b5115595ec236b1acea46b03 100644 --- a/MatlabFiles/fn_gradcd2.m +++ b/MatlabFiles/fn_gradcd2.m @@ -1,98 +1,98 @@ -function grdd = fn_gradcd2(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... - P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -%function grdd = fn_gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... -% P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -% computes numerical gradient of a single-valued function or Jacobian -% matrix of a vector-valued function using a central difference with -% function grdd = gradcd(fcn,x0,grdh) -% -% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). -% x0: a column vector n-by-1, at which point the hessian is evaluated. -% grdh: step size, n*1. Set as follows -% step = eps^(1/3); -% %step = 1e-04; -% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); -%-------------------- -% grdd: n-by-k Jacobian matrix (gradients). -% -% Written by Tao Zha, 2002. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -stps = eps^(1/3); -% eps: floating point relative accuracy or machine precision: 2.22e-16 -% stps: step size recommended by Dennis and Schnabel: 6.006e-6 - -NEARINFINITY = 1.0e+100; -GRADMANUAL = 0.0; %Arbitrarily (manually) set gradient. - - -x0 = x0(:); -tailstr = ')'; -for i=nargin-3:-1:1 - tailstr=[ ',P' num2str(i) tailstr]; -end -f0 = eval([fcn '(x0' tailstr]); - -% ** initializations -n = length(x0); -k = length(f0); % dimension of "fcn" - -% ** Computation of stepsize (dh) -if all(grdh) - dh = grdh; -else - ax0 = abs(x0); - if all(x0) - dax0 = x0 ./ ax0; - else - dax0 = 1; - end - dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; -end - -xdh = x0 + dh; -dh = xdh - x0; % This increases precision slightly -% -argplus = x0(:,ones(n,1)); -argminus = argplus; -dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). -argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". -argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". - -grdd = zeros(k,n); % preallocate to speed the loop. -i = 0; -while i ~= n - i = i+1; - fp = eval([fcn '(argplus(:,i)' tailstr]); - fm = eval([fcn '(argminus(:,i)' tailstr]); - if ((fp < NEARINFINITY) && (fm < NEARINFINITY)) - grdd(:,i) = (fp - fm) ./ (2*dh(i)); - elseif (fp < NEARINFINITY) - grdd(:,i) = (fp - f0) ./ (dh(i)); - elseif (fm < NEARINFINITY) - grdd(:,i) = (f0 - fm) ./ (dh(i)); - else - grdd(:,i) = GRADMANUAL; %Arbitrarily (manually) set gradient. - end -end -%dhm = dh(:,ones(k,1)); -%dhm = dhm'; % k*n -%grdd = grdd ./ (2*dhm); % k-by-n. -grdd = grdd'; % n-by-k. - - +function grdd = fn_gradcd2(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... + P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +%function grdd = fn_gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... +% P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +% computes numerical gradient of a single-valued function or Jacobian +% matrix of a vector-valued function using a central difference with +% function grdd = gradcd(fcn,x0,grdh) +% +% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). +% x0: a column vector n-by-1, at which point the hessian is evaluated. +% grdh: step size, n*1. Set as follows +% step = eps^(1/3); +% %step = 1e-04; +% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); +%-------------------- +% grdd: n-by-k Jacobian matrix (gradients). +% +% Written by Tao Zha, 2002. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +stps = eps^(1/3); +% eps: floating point relative accuracy or machine precision: 2.22e-16 +% stps: step size recommended by Dennis and Schnabel: 6.006e-6 + +NEARINFINITY = 1.0e+100; +GRADMANUAL = 0.0; %Arbitrarily (manually) set gradient. + + +x0 = x0(:); +tailstr = ')'; +for i=nargin-3:-1:1 + tailstr=[ ',P' num2str(i) tailstr]; +end +f0 = eval([fcn '(x0' tailstr]); + +% ** initializations +n = length(x0); +k = length(f0); % dimension of "fcn" + +% ** Computation of stepsize (dh) +if all(grdh) + dh = grdh; +else + ax0 = abs(x0); + if all(x0) + dax0 = x0 ./ ax0; + else + dax0 = 1; + end + dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; +end + +xdh = x0 + dh; +dh = xdh - x0; % This increases precision slightly +% +argplus = x0(:,ones(n,1)); +argminus = argplus; +dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). +argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". +argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". + +grdd = zeros(k,n); % preallocate to speed the loop. +i = 0; +while i ~= n + i = i+1; + fp = eval([fcn '(argplus(:,i)' tailstr]); + fm = eval([fcn '(argminus(:,i)' tailstr]); + if ((fp < NEARINFINITY) && (fm < NEARINFINITY)) + grdd(:,i) = (fp - fm) ./ (2*dh(i)); + elseif (fp < NEARINFINITY) + grdd(:,i) = (fp - f0) ./ (dh(i)); + elseif (fm < NEARINFINITY) + grdd(:,i) = (f0 - fm) ./ (dh(i)); + else + grdd(:,i) = GRADMANUAL; %Arbitrarily (manually) set gradient. + end +end +%dhm = dh(:,ones(k,1)); +%dhm = dhm'; % k*n +%grdd = grdd ./ (2*dhm); % k-by-n. +grdd = grdd'; % n-by-k. + + diff --git a/MatlabFiles/fn_gyrfore.m b/MatlabFiles/fn_gyrfore.m index 6218ae685c4d8d9e0cf110e564b44e9b3176e8de..967291249dcdbbed8cb4ce0227c4d47a534c2f66 100644 --- a/MatlabFiles/fn_gyrfore.m +++ b/MatlabFiles/fn_gyrfore.m @@ -1,61 +1,61 @@ -function fn_gyrfore(yfore,yacte,keyindx,rnum,cnum,ylab,forelabel,conlab) -% -% Graph annual (or calendar year) forecasts vs actual (all data from "msstart.m") -% -% yfore: actual and forecast annual growth data with dates. -% yacte: actual annual growth data with dates. -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -% ylab: label for the variables -% forelabel: title label for as of time of forecast -% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -%------------- -% No output argument for this graph file -% -% Tao Zha, March 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -vyrs = yfore(:,1); -hornum = cell(length(vyrs),1); % horizontal year (number) -count=0; -for k=vyrs' - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - % - plot(yacte(:,1),yacte(:,2+i),vyrs,yfore(:,2+i),'--') - set(gca,'XLim',[vyrs(1) vyrs(end)]) - set(gca,'XTick',vyrs) - set(gca,'XTickLabel',char(hornum)) - if i==keyindx(1) - title(forelabel) - elseif i>=length(keyindx) %i>=length(keyindx)-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end +function fn_gyrfore(yfore,yacte,keyindx,rnum,cnum,ylab,forelabel,conlab) +% +% Graph annual (or calendar year) forecasts vs actual (all data from "msstart.m") +% +% yfore: actual and forecast annual growth data with dates. +% yacte: actual annual growth data with dates. +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +% ylab: label for the variables +% forelabel: title label for as of time of forecast +% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +%------------- +% No output argument for this graph file +% +% Tao Zha, March 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +vyrs = yfore(:,1); +hornum = cell(length(vyrs),1); % horizontal year (number) +count=0; +for k=vyrs' + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + % + plot(yacte(:,1),yacte(:,2+i),vyrs,yfore(:,2+i),'--') + set(gca,'XLim',[vyrs(1) vyrs(end)]) + set(gca,'XTick',vyrs) + set(gca,'XTickLabel',char(hornum)) + if i==keyindx(1) + title(forelabel) + elseif i>=length(keyindx) %i>=length(keyindx)-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/fn_hesscd.m b/MatlabFiles/fn_hesscd.m index a46716b77e30096bc9c788ece3b795b9f21a126c..88889b9b60232af70210efdb38e41d5bbbba4b37 100644 --- a/MatlabFiles/fn_hesscd.m +++ b/MatlabFiles/fn_hesscd.m @@ -1,82 +1,82 @@ -function grdd = fn_hesscd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... - P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -% Computing numerical hessian using a central difference with -% function grdd = hesscd(fcn,x0,grdh,Passed variables1) -% -% fcn: a string naming the objective function. -% x0: a column vector n*1, at which point the hessian is evaluated. -% grdh: step size. -% grdd: hessian matrix (second derivative), n*n. -% -% Written by Tao Zha, May 1998. Revised June 1002. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -stps = eps^(1/3); -% eps: floating point relative accuracy or machine precision: 2.22e-16 -% stps: step size recommended by Dennis and Schnabel: 6.006e-6 - -x0 = x0(:); -tailstr = ')'; -for i=nargin-3:-1:1 - tailstr=[ ',P' num2str(i) tailstr]; -end -f0 = eval([fcn '(x0' tailstr]); - -% ** initializations -k = length(x0); -grdd = zeros(k); - -% ** Computation of stepsize (dh) -if all(grdh) - dh = grdh; -else - ax0 = abs(x0); - if all(x0) - dax0 = x0 ./ ax0; - else - dax0 = 1; - end - dh = stps * (max([ax0 (1e-2)*ones(k,1)]'))' .* dax0; -end - -xdh = x0 + dh; -dh = xdh - x0; % This increases precision slightly -dhm = dh(:,ones(k,1)); -ee = eye(k) .* dhm; - -i = 1; -while i <= k - j = i; - while j <= k - - fune1 = eval([fcn '(x0 + ee(:,i) + ee(:,j)' tailstr]); - fune2 = eval([fcn '(x0 - ee(:,i) + ee(:,j)' tailstr]); - fune3 = eval([fcn '(x0 + ee(:,i) - ee(:,j)' tailstr]); - fune4 = eval([fcn '(x0 - ee(:,i) - ee(:,j)' tailstr]); - grdd(i,j) = (fune1 - fune2 - fune3 + fune4) / (4 * dh(i) * dh(j)); - - if i ~= j - grdd(j,i) = grdd(i,j); - end - - j = j+1; - end - i = i+1; -end - +function grdd = fn_hesscd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... + P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +% Computing numerical hessian using a central difference with +% function grdd = hesscd(fcn,x0,grdh,Passed variables1) +% +% fcn: a string naming the objective function. +% x0: a column vector n*1, at which point the hessian is evaluated. +% grdh: step size. +% grdd: hessian matrix (second derivative), n*n. +% +% Written by Tao Zha, May 1998. Revised June 1002. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +stps = eps^(1/3); +% eps: floating point relative accuracy or machine precision: 2.22e-16 +% stps: step size recommended by Dennis and Schnabel: 6.006e-6 + +x0 = x0(:); +tailstr = ')'; +for i=nargin-3:-1:1 + tailstr=[ ',P' num2str(i) tailstr]; +end +f0 = eval([fcn '(x0' tailstr]); + +% ** initializations +k = length(x0); +grdd = zeros(k); + +% ** Computation of stepsize (dh) +if all(grdh) + dh = grdh; +else + ax0 = abs(x0); + if all(x0) + dax0 = x0 ./ ax0; + else + dax0 = 1; + end + dh = stps * (max([ax0 (1e-2)*ones(k,1)]'))' .* dax0; +end + +xdh = x0 + dh; +dh = xdh - x0; % This increases precision slightly +dhm = dh(:,ones(k,1)); +ee = eye(k) .* dhm; + +i = 1; +while i <= k + j = i; + while j <= k + + fune1 = eval([fcn '(x0 + ee(:,i) + ee(:,j)' tailstr]); + fune2 = eval([fcn '(x0 - ee(:,i) + ee(:,j)' tailstr]); + fune3 = eval([fcn '(x0 + ee(:,i) - ee(:,j)' tailstr]); + fune4 = eval([fcn '(x0 - ee(:,i) - ee(:,j)' tailstr]); + grdd(i,j) = (fune1 - fune2 - fune3 + fune4) / (4 * dh(i) * dh(j)); + + if i ~= j + grdd(j,i) = grdd(i,j); + end + + j = j+1; + end + i = i+1; +end + diff --git a/MatlabFiles/fn_histpdfcnt.m b/MatlabFiles/fn_histpdfcnt.m index 007fb892b4ee702a9619efcba19cef097cc58667..31a662b06704afe2f19e40235babb950719fb06d 100644 --- a/MatlabFiles/fn_histpdfcnt.m +++ b/MatlabFiles/fn_histpdfcnt.m @@ -1,95 +1,95 @@ -function [imfpdf,imfpo,imfprob] = fn_histpdfcnt(imfcnt,ndrawscnt,imfloor,hbin,ninv,... - gIndx,ncom,kIndx,lval,hval) -% [imfpdf,imfpo,imfprob] = fn_histpdfcnt(imfcnt,ndrawscnt,imfloor,hbin,ninv,gIndx,ncom,kIndx,lval,hval) -% From already ordered and binned (cnt: count) series (not pdf yet). -% Produce (1) the dataset for generating p.d.f.; -% (2) the dataset for probability (NOT density) at each bin; -% (3) with option gIndx=1, graph density functions. -% -% imfcnt: 2+ninv-by-k. Counted structural parameters, qmygcnt, ygcnt, or impulse responses. -% ndrawscnt: a total number of draws used in imfcnt -% imfloor: k-element vector of low values of imf but imf_h can be below "imfloor" and above "imceiling" -% hbin: k-element vector of bin lengths = (imceilling-imfloor)/ninv. Need not be a 1-by-k row vector. -% ninv: the number of bins (small interior intervals) between ``imfloor'' and ``imfceiling'' -% gIndx: 1: plot graphs of pdf's; 0: no plot. -% If gIndx=0, ncom, kIndx, lval, and hval are irrelevant and no densities will be plotted. -% ncom: number of combined intervals. Large ncom implies large size of the bin. -% Must set ncom so that ninv can be divided -% kIndx: index for selected variables. Length(kIndx)<=k. -% If kIndx=[], lval and hval are irrelevant and no densities will be plotted. -% lval: length(kIndx)-element vector of the lowest values on the axis; -% The vector corresponds to kIndx. This option is disenabled by setting it to []. -% hval: length(kIndx)-element vector of the highest values on the axis; -% The vector corresponds to kIndx. This option is disenabled by setting it to []. -%----------------- -% imfpdf: 2+ninv-by-k. Density (NOT probability) -% imfpo: 2+ninv-by-k. Bin position (x-axis) in relation to imfs3 -% imfprob: 2+ninv-by-k. Probability (NOT density) at each bin -% -% 27 August 1998 Tao Zha -% Revised, October 1998, March 1999, August 2000. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if (nargin==5), gIndx=0; end -if (nargin==8), lval=[]; hval=[]; end - -imfloor=imfloor(:); hbin=hbin(:); -k=size(imfcnt,2); -invlengthM = repmat(hbin',[2+ninv,1]); -%invlengthM([1 2+ninv],:) = 1; % August 2000. I comment this out because it leads to an extorted picture - % when the rest of invlengthM is much smaller or larger than 1. - % For the first interval (-inf, low bound) and last interval (high bound, +inf), - % the length is set at 1. Of course, theoretically, the interval length should be set - % to infinity. Adjust low and high bounds if 1 is not large enough compared with hbin. -imfprob = imfcnt ./ ndrawscnt; % probability (NOT density) -imfpdf = imfprob ./ invlengthM; % density - -imfpo = [1:2+ninv]'; % positions for each forecast -imfpo = imfpo - 2; % the first step to put back to original form -imfpo = repmat(imfpo,[1,k]); -imfloorM = repmat(imfloor',[2+ninv,1]); -imfpo = (imfpo .* invlengthM) + imfloorM; % 2+ninv-by-k - % the final step to put back to original form of impulse responses - -if gIndx - if mod(ninv,ncom) - warning('Set ncom so that ninv can be divided') - return - end - % - ninv2=ninv/ncom; - imfpdfn=zeros(2+ninv2,size(imfcnt,2)); %<<>> - imfpon=imfpdfn; - % - for ik=1:ninv2 % from 2 to 1+ninv2 for imfpdfn and imfpon - imfpdfn(1+ik,:) = sum(imfpdf(1+(ik-1)*ncom+1:1+ik*ncom,:))/ncom; - imfpon(1+ik,:) = mean(imfpo(1+(ik-1)*ncom+1:1+ik*ncom,:)); - end - - ck1=0; - for k1=kIndx - ck1=ck1+1; - figure - plot(imfpon(2:1+ninv2,k1),imfpdfn(2:1+ninv2,k1)) % do not plot the values at -infty and +infty - if ~isempty(lval) & ~isempty(hval) - set(gca,'XLim',[lval(ck1) hval(ck1)]) - end - grid - end -end +function [imfpdf,imfpo,imfprob] = fn_histpdfcnt(imfcnt,ndrawscnt,imfloor,hbin,ninv,... + gIndx,ncom,kIndx,lval,hval) +% [imfpdf,imfpo,imfprob] = fn_histpdfcnt(imfcnt,ndrawscnt,imfloor,hbin,ninv,gIndx,ncom,kIndx,lval,hval) +% From already ordered and binned (cnt: count) series (not pdf yet). +% Produce (1) the dataset for generating p.d.f.; +% (2) the dataset for probability (NOT density) at each bin; +% (3) with option gIndx=1, graph density functions. +% +% imfcnt: 2+ninv-by-k. Counted structural parameters, qmygcnt, ygcnt, or impulse responses. +% ndrawscnt: a total number of draws used in imfcnt +% imfloor: k-element vector of low values of imf but imf_h can be below "imfloor" and above "imceiling" +% hbin: k-element vector of bin lengths = (imceilling-imfloor)/ninv. Need not be a 1-by-k row vector. +% ninv: the number of bins (small interior intervals) between ``imfloor'' and ``imfceiling'' +% gIndx: 1: plot graphs of pdf's; 0: no plot. +% If gIndx=0, ncom, kIndx, lval, and hval are irrelevant and no densities will be plotted. +% ncom: number of combined intervals. Large ncom implies large size of the bin. +% Must set ncom so that ninv can be divided +% kIndx: index for selected variables. Length(kIndx)<=k. +% If kIndx=[], lval and hval are irrelevant and no densities will be plotted. +% lval: length(kIndx)-element vector of the lowest values on the axis; +% The vector corresponds to kIndx. This option is disenabled by setting it to []. +% hval: length(kIndx)-element vector of the highest values on the axis; +% The vector corresponds to kIndx. This option is disenabled by setting it to []. +%----------------- +% imfpdf: 2+ninv-by-k. Density (NOT probability) +% imfpo: 2+ninv-by-k. Bin position (x-axis) in relation to imfs3 +% imfprob: 2+ninv-by-k. Probability (NOT density) at each bin +% +% 27 August 1998 Tao Zha +% Revised, October 1998, March 1999, August 2000. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if (nargin==5), gIndx=0; end +if (nargin==8), lval=[]; hval=[]; end + +imfloor=imfloor(:); hbin=hbin(:); +k=size(imfcnt,2); +invlengthM = repmat(hbin',[2+ninv,1]); +%invlengthM([1 2+ninv],:) = 1; % August 2000. I comment this out because it leads to an extorted picture + % when the rest of invlengthM is much smaller or larger than 1. + % For the first interval (-inf, low bound) and last interval (high bound, +inf), + % the length is set at 1. Of course, theoretically, the interval length should be set + % to infinity. Adjust low and high bounds if 1 is not large enough compared with hbin. +imfprob = imfcnt ./ ndrawscnt; % probability (NOT density) +imfpdf = imfprob ./ invlengthM; % density + +imfpo = [1:2+ninv]'; % positions for each forecast +imfpo = imfpo - 2; % the first step to put back to original form +imfpo = repmat(imfpo,[1,k]); +imfloorM = repmat(imfloor',[2+ninv,1]); +imfpo = (imfpo .* invlengthM) + imfloorM; % 2+ninv-by-k + % the final step to put back to original form of impulse responses + +if gIndx + if mod(ninv,ncom) + warning('Set ncom so that ninv can be divided') + return + end + % + ninv2=ninv/ncom; + imfpdfn=zeros(2+ninv2,size(imfcnt,2)); %<<>> + imfpon=imfpdfn; + % + for ik=1:ninv2 % from 2 to 1+ninv2 for imfpdfn and imfpon + imfpdfn(1+ik,:) = sum(imfpdf(1+(ik-1)*ncom+1:1+ik*ncom,:))/ncom; + imfpon(1+ik,:) = mean(imfpo(1+(ik-1)*ncom+1:1+ik*ncom,:)); + end + + ck1=0; + for k1=kIndx + ck1=ck1+1; + figure + plot(imfpon(2:1+ninv2,k1),imfpdfn(2:1+ninv2,k1)) % do not plot the values at -infty and +infty + if ~isempty(lval) & ~isempty(hval) + set(gca,'XLim',[lval(ck1) hval(ck1)]) + end + grid + end +end diff --git a/MatlabFiles/fn_histwpdfg.m b/MatlabFiles/fn_histwpdfg.m index 288fa60df22be932fa63db2026f6c109e1a6767f..ced2d72c38b2e7b3dd22a1146606c3df12d7900e 100644 --- a/MatlabFiles/fn_histwpdfg.m +++ b/MatlabFiles/fn_histwpdfg.m @@ -1,84 +1,84 @@ -function [xpd,xc,xp,w,bw] = fn_histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) -% [xpd,xc,xp,w,bw] = fn_histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) -% Generate probabilities and plot scaled densitys, given the unsorted draws and weights -% -% s: ndraws-by-n draws where ndraws is # of draws and n is # of series -% nbin: the number of bins (the maximum is ndraws) -% gIdx: 1 if plotting the pdf; 0 if no graph -% w (optional): ndraws-by-n (unscaled) weights where ndraws is # of draws and n is # of series -% xlabstr (optional): xlabel string -% ylabstr (optional): ylabel string -% titstr (optional): title string -%------------- -% xpd: nbin-by-n: density or pdf (not probability) in the centered bin on x-axis. -% xc: nbin-by-n: the position of centered bin on x-axis, from top to bottom. -% All columns are identical -% xp: nbin-by-n: probability (not density) in the centered bin on x-axis. -% NOTE: sum(xp) must be 1 for each column -% w: ndraws-by-n scaled weights so that sum(w)=1 for each column -% bw: bandwidth -% -% August 1999 by Tao Zha -% July 18 2000. Place w after gIdx so that previous programs need modifications accordingly. -% Oct 1 2000. Change the order of xpd, xc, and xp so that previous programs need modifications accordingly. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (nargin<=4), titstr=[]; xlabstr=[]; ylabstr=[]; end -[m,n] = size(s); -if (nargin<=3) - w=ones(m,n)/m; -else - %** normalized to 1 for the probability - wsum = repmat(sum(w), [m 1]); - w = w ./ wsum; -end - -%if min(size(s))==1, s=s(:); w=w(:); end % making sure they are column vectors - -%*** the position of the center of the bin on the x-axis -mins = min(min(s)); -maxs = max(max(s)); -bw = (maxs-mins)/nbin; % binwidth for x-axis -x = mins + bw*(0:nbin); -x(end) = maxs; % in case nbin is not an integer -xc = x(1:end-1) + bw/2; % the position of the center of the x-bin -xc = xc'; % nbin-by-1 row vector: from top to bottom -xc = repmat(xc,[1 n]); % nbin-by-n, same for each column - - -%*** the probability at each bin on the x-axis -nbin = nbin+1; % + 1 to get the difference for getting probability xp -nn = zeros(nbin,n); -for i=2:nbin - for k=1:n - xidx = find(s(:,k) <= x(i)); % index for the positions - nn(i,k) = sum(w(xidx,k)); - end -end -xp = nn(2:nbin,:) - nn(1:nbin-1,:); -if (bw<eps) - xpd=Inf*ones(size(xp)); -else - xpd = xp/bw; % the density, NOT the probability as xp -end - -if gIdx - plot(xc,xpd) - %set(gca,'XLim',[-5 5]) % put the limit only on the y-axis - title(titstr), xlabel(xlabstr), ylabel(ylabstr); -end +function [xpd,xc,xp,w,bw] = fn_histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) +% [xpd,xc,xp,w,bw] = fn_histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) +% Generate probabilities and plot scaled densitys, given the unsorted draws and weights +% +% s: ndraws-by-n draws where ndraws is # of draws and n is # of series +% nbin: the number of bins (the maximum is ndraws) +% gIdx: 1 if plotting the pdf; 0 if no graph +% w (optional): ndraws-by-n (unscaled) weights where ndraws is # of draws and n is # of series +% xlabstr (optional): xlabel string +% ylabstr (optional): ylabel string +% titstr (optional): title string +%------------- +% xpd: nbin-by-n: density or pdf (not probability) in the centered bin on x-axis. +% xc: nbin-by-n: the position of centered bin on x-axis, from top to bottom. +% All columns are identical +% xp: nbin-by-n: probability (not density) in the centered bin on x-axis. +% NOTE: sum(xp) must be 1 for each column +% w: ndraws-by-n scaled weights so that sum(w)=1 for each column +% bw: bandwidth +% +% August 1999 by Tao Zha +% July 18 2000. Place w after gIdx so that previous programs need modifications accordingly. +% Oct 1 2000. Change the order of xpd, xc, and xp so that previous programs need modifications accordingly. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (nargin<=4), titstr=[]; xlabstr=[]; ylabstr=[]; end +[m,n] = size(s); +if (nargin<=3) + w=ones(m,n)/m; +else + %** normalized to 1 for the probability + wsum = repmat(sum(w), [m 1]); + w = w ./ wsum; +end + +%if min(size(s))==1, s=s(:); w=w(:); end % making sure they are column vectors + +%*** the position of the center of the bin on the x-axis +mins = min(min(s)); +maxs = max(max(s)); +bw = (maxs-mins)/nbin; % binwidth for x-axis +x = mins + bw*(0:nbin); +x(end) = maxs; % in case nbin is not an integer +xc = x(1:end-1) + bw/2; % the position of the center of the x-bin +xc = xc'; % nbin-by-1 row vector: from top to bottom +xc = repmat(xc,[1 n]); % nbin-by-n, same for each column + + +%*** the probability at each bin on the x-axis +nbin = nbin+1; % + 1 to get the difference for getting probability xp +nn = zeros(nbin,n); +for i=2:nbin + for k=1:n + xidx = find(s(:,k) <= x(i)); % index for the positions + nn(i,k) = sum(w(xidx,k)); + end +end +xp = nn(2:nbin,:) - nn(1:nbin-1,:); +if (bw<eps) + xpd=Inf*ones(size(xp)); +else + xpd = xp/bw; % the density, NOT the probability as xp +end + +if gIdx + plot(xc,xpd) + %set(gca,'XLim',[-5 5]) % put the limit only on the y-axis + title(titstr), xlabel(xlabstr), ylabel(ylabstr); +end diff --git a/MatlabFiles/fn_histwpdfg2d.m b/MatlabFiles/fn_histwpdfg2d.m index 1e203a6725f28f29fc0731a12ba395b26e5dd1c7..f7d6dcbc8e84a9a65b5b8e276f5b64d016c7a83a 100644 --- a/MatlabFiles/fn_histwpdfg2d.m +++ b/MatlabFiles/fn_histwpdfg2d.m @@ -1,134 +1,134 @@ -function [xc,yc,z,zn] = fn_histwpdfg2D(s,n,w,ditp,xlabstr,ylabstr) -% [xc,yc,z,zn] = histwpdfg2D(s,w,n,ditp,xlabstr,ylabstr) -% Given uneven weights and 2D draws, generate 2D pdf and probabilites by scaling 2D histogram -% -% s: ndraws-by-2 matrix where ndraws is # of draws and 2 variables -% n: 1-by-2 vector -- # of bins (integers in general) for both x-axis and y-axis -% w: ndraws-by-1 vector of (uneven) weights. Optional. If [] or no entry, even weights are given. -% ditp: Postive number -- degrees of bicubic interpolation. Bigger ditp is, more points for z with -% finer the (x,y) plance are interpolated. Optional. If [] or no entry, no interpolation. -% xlabstr: xlabel string. Optional. If [] or no entry, no x label. -% ylabstr: ylabel string. Optional. If [] or no entry, no y label. -%--------------------------------- -% xc: the position of centered bin on x-axis, from left to right. All rows are identical -% yc: the position of centered bin on y-axis, from top to bottom. All columns are identical -% z: size(xc,2)-by-size(yc,1) -- the pdf value in each rectangular cell -% zn: size(xc,2)-by-size(yc,1) -- the probability value in each rectangular cell -% if nargout==0, plot 2D p.d.f. graphics -% -% January 1999 by Tao Zha. Revised, March 2002. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (size(s,2)~=2) - error('The size of 1st argument must be *-by-2 (i.e., 2 columns)') -end - -if (nargin<3), w=[]; ditp=[]; xlabstr=[]; ylabstr=[]; end -if (nargin<4), ditp=[]; xlabstr=[]; ylabstr=[]; end -if (nargin<5), xlabstr=[]; ylabstr=[]; end -if (nargin<6), ylabstr=[]; end - -if (length(n(:))~=2) - error('2nd argument must have exactly 2 elements') -end - -if (min(n)<3) - error('2nd argument -- bin size -- must have at least 3 for each axis') -end - -ndraws=size(s,1); - -%** normalized to 1 for the probability -if isempty(w) - w = ones(ndraws,1)/ndraws; -else - w=w(:); % make sure it's a column vector - w = w/sum(w); -end - - -%*** x-axis -minx = min(min(s(:,1))); -maxx = max(max(s(:,1))); -h1 = (maxx-minx)/n(1); % binwidth for x-axis -x = minx + h1*(0:n(1)); -xlen = length(x); % n(1)+1 -x(xlen) = maxx; % in case n(1) is not an integer -xc = x(1:xlen-1) + h1/2; % the position of the center of the x-bin - % 1-by-n(1) row vector: from left to right -xc = repmat(xc,[n(2) 1]); - -%*** y-axis -miny = min(min(s(:,2))); -maxy = max(max(s(:,2))); -h2 = (maxy-miny)/n(2); % binwidth for y-axis -y = miny + h2*(0:n(2)); -ylen = length(y); -y(ylen) = maxy; % in case n(2) is not an integer -yc = y(1:ylen-1) + h2/2; % the position of the center of the y-bin -yc = yc(:); % n(2)-by-1 column vector: from top to bottom -yc = repmat(yc,[1 n(1)]); - - -zn = zeros(n(2),n(1)); % the reverse of x and y is designed for mesh. - % see meshgrid to understand this. -tic -for draws=1:ndraws - k1 = floor((s(draws,1)-minx)/h1)+1; - k2 = floor((s(draws,2)-miny)/h2)+1; - % - % if k1==0 - % k1=1; - % end - % if k2==0; - % k2=1; - % end - % - if k1>n(1) - k1=n(1); - end - if k2>n(2) - k2=n(2) - end - zn(k2,k1) = zn(k2,k1)+w(draws); % probability in each rectangular cell -end -timeloop=toc; -disp(['Loop time -- minutes ' num2str(timeloop/60)]) - -z=zn/(h1*h2); % converted to the height of the p.d.f. - - -%*** scaled 2D histogram or p.d.f. -%figure(1) -%*** interpolation -if isempty(ditp) - colormap(zeros(1,3)); % Set color to black - mesh(xc,yc,z) - title('Scaled histogram or p.d.f.') - xlabel(xlabstr) - ylabel(ylabstr) -else - [xi,yi]=meshgrid(minx:h1/ditp:maxx,miny:h2/ditp:maxy); - zi = interp2(xc,yc,z,xi,yi,'bicubic'); - figure(30) - colormap(zeros(1,3)); % Set color to black - mesh(xi,yi,zi) % or mesh - title('Interpolated p.d.f.') - xlabel(xlabstr) - ylabel(ylabstr) -end +function [xc,yc,z,zn] = fn_histwpdfg2D(s,n,w,ditp,xlabstr,ylabstr) +% [xc,yc,z,zn] = histwpdfg2D(s,w,n,ditp,xlabstr,ylabstr) +% Given uneven weights and 2D draws, generate 2D pdf and probabilites by scaling 2D histogram +% +% s: ndraws-by-2 matrix where ndraws is # of draws and 2 variables +% n: 1-by-2 vector -- # of bins (integers in general) for both x-axis and y-axis +% w: ndraws-by-1 vector of (uneven) weights. Optional. If [] or no entry, even weights are given. +% ditp: Postive number -- degrees of bicubic interpolation. Bigger ditp is, more points for z with +% finer the (x,y) plance are interpolated. Optional. If [] or no entry, no interpolation. +% xlabstr: xlabel string. Optional. If [] or no entry, no x label. +% ylabstr: ylabel string. Optional. If [] or no entry, no y label. +%--------------------------------- +% xc: the position of centered bin on x-axis, from left to right. All rows are identical +% yc: the position of centered bin on y-axis, from top to bottom. All columns are identical +% z: size(xc,2)-by-size(yc,1) -- the pdf value in each rectangular cell +% zn: size(xc,2)-by-size(yc,1) -- the probability value in each rectangular cell +% if nargout==0, plot 2D p.d.f. graphics +% +% January 1999 by Tao Zha. Revised, March 2002. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (size(s,2)~=2) + error('The size of 1st argument must be *-by-2 (i.e., 2 columns)') +end + +if (nargin<3), w=[]; ditp=[]; xlabstr=[]; ylabstr=[]; end +if (nargin<4), ditp=[]; xlabstr=[]; ylabstr=[]; end +if (nargin<5), xlabstr=[]; ylabstr=[]; end +if (nargin<6), ylabstr=[]; end + +if (length(n(:))~=2) + error('2nd argument must have exactly 2 elements') +end + +if (min(n)<3) + error('2nd argument -- bin size -- must have at least 3 for each axis') +end + +ndraws=size(s,1); + +%** normalized to 1 for the probability +if isempty(w) + w = ones(ndraws,1)/ndraws; +else + w=w(:); % make sure it's a column vector + w = w/sum(w); +end + + +%*** x-axis +minx = min(min(s(:,1))); +maxx = max(max(s(:,1))); +h1 = (maxx-minx)/n(1); % binwidth for x-axis +x = minx + h1*(0:n(1)); +xlen = length(x); % n(1)+1 +x(xlen) = maxx; % in case n(1) is not an integer +xc = x(1:xlen-1) + h1/2; % the position of the center of the x-bin + % 1-by-n(1) row vector: from left to right +xc = repmat(xc,[n(2) 1]); + +%*** y-axis +miny = min(min(s(:,2))); +maxy = max(max(s(:,2))); +h2 = (maxy-miny)/n(2); % binwidth for y-axis +y = miny + h2*(0:n(2)); +ylen = length(y); +y(ylen) = maxy; % in case n(2) is not an integer +yc = y(1:ylen-1) + h2/2; % the position of the center of the y-bin +yc = yc(:); % n(2)-by-1 column vector: from top to bottom +yc = repmat(yc,[1 n(1)]); + + +zn = zeros(n(2),n(1)); % the reverse of x and y is designed for mesh. + % see meshgrid to understand this. +tic +for draws=1:ndraws + k1 = floor((s(draws,1)-minx)/h1)+1; + k2 = floor((s(draws,2)-miny)/h2)+1; + % + % if k1==0 + % k1=1; + % end + % if k2==0; + % k2=1; + % end + % + if k1>n(1) + k1=n(1); + end + if k2>n(2) + k2=n(2) + end + zn(k2,k1) = zn(k2,k1)+w(draws); % probability in each rectangular cell +end +timeloop=toc; +disp(['Loop time -- minutes ' num2str(timeloop/60)]) + +z=zn/(h1*h2); % converted to the height of the p.d.f. + + +%*** scaled 2D histogram or p.d.f. +%figure(1) +%*** interpolation +if isempty(ditp) + colormap(zeros(1,3)); % Set color to black + mesh(xc,yc,z) + title('Scaled histogram or p.d.f.') + xlabel(xlabstr) + ylabel(ylabstr) +else + [xi,yi]=meshgrid(minx:h1/ditp:maxx,miny:h2/ditp:maxy); + zi = interp2(xc,yc,z,xi,yi,'bicubic'); + figure(30) + colormap(zeros(1,3)); % Set color to black + mesh(xi,yi,zi) % or mesh + title('Interpolated p.d.f.') + xlabel(xlabstr) + ylabel(ylabstr) +end diff --git a/MatlabFiles/fn_histwpdfg_bound.m b/MatlabFiles/fn_histwpdfg_bound.m index b017cd7a7271741f104a866e4368b960fac8b5f5..679f9ebe02bd08e26a40c4d4a6bb70b8f3359b58 100644 --- a/MatlabFiles/fn_histwpdfg_bound.m +++ b/MatlabFiles/fn_histwpdfg_bound.m @@ -1,85 +1,85 @@ -function [xpd,xc,xp,w,bw] = fn_histwpdfg_bound(s,nbin,gIdx,bound,w,xlabstr,ylabstr,titstr) -% [xpd,xc,xp,w,bw] = fn_histwpdfg_bound(s,nbin,gIdx,bound,w,xlabstr,ylabstr,titstr) -% Generate probabilities and plot scaled densitys, given the unsorted draws and weights -% -% s: ndraws-by-n draws where ndraws is # of draws and n is # of series -% nbin: the number of bins (the maximum is ndraws) -% gIdx: 1 if plotting the pdf; 0 if no graph -% bound: bounds for XLim. Example: bound = [-2 2]; -% w (optional): ndraws-by-n (unscaled) weights where ndraws is # of draws and n is # of series -% xlabstr (optional): xlabel string -% ylabstr (optional): ylabel string -% titstr (optional): title string -%------------- -% xpd: nbin-by-n: density or pdf (not probability) in the centered bin on x-axis. -% xc: nbin-by-n: the position of centered bin on x-axis, from top to bottom. -% All columns are identical -% xp: nbin-by-n: probability (not density) in the centered bin on x-axis. -% NOTE: sum(xp) must be 1 for each column -% w: ndraws-by-n scaled weights so that sum(w)=1 for each column -% bw: bandwidth -% -% August 1999 by Tao Zha -% July 18 2000. Place w after gIdx so that previous programs need modifications accordingly. -% Oct 1 2000. Change the order of xpd, xc, and xp so that previous programs need modifications accordingly. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (nargin<=5), titstr=[]; xlabstr=[]; ylabstr=[]; end -[m,n] = size(s); -if (nargin<=4) - w=ones(m,n)/m; -else - %** normalized to 1 for the probability - wsum = repmat(sum(w), [m 1]); - w = w ./ wsum; -end - -%if min(size(s))==1, s=s(:); w=w(:); end % making sure they are column vectors - -%*** the position of the center of the bin on the x-axis -mins = min(min(s)); -maxs = max(max(s)); -bw = (maxs-mins)/nbin; % binwidth for x-axis -x = mins + bw*(0:nbin); -x(end) = maxs; % in case nbin is not an integer -xc = x(1:end-1) + bw/2; % the position of the center of the x-bin -xc = xc'; % nbin-by-1 row vector: from top to bottom -xc = repmat(xc,[1 n]); % nbin-by-n, same for each column - - -%*** the probability at each bin on the x-axis -nbin = nbin+1; % + 1 to get the difference for getting probability xp -nn = zeros(nbin,n); -for i=2:nbin - for k=1:n - xidx = find(s(:,k) <= x(i)); % index for the positions - nn(i,k) = sum(w(xidx,k)); - end -end -xp = nn(2:nbin,:) - nn(1:nbin-1,:); -if (bw<eps) - xpd=Inf*ones(size(xp)); -else - xpd = xp/bw; % the density, NOT the probability as xp -end - -if gIdx - plot(xc,xpd) - set(gca,'XLim',bound) % put the limit only on the y-axis - title(titstr), xlabel(xlabstr), ylabel(ylabstr); -end +function [xpd,xc,xp,w,bw] = fn_histwpdfg_bound(s,nbin,gIdx,bound,w,xlabstr,ylabstr,titstr) +% [xpd,xc,xp,w,bw] = fn_histwpdfg_bound(s,nbin,gIdx,bound,w,xlabstr,ylabstr,titstr) +% Generate probabilities and plot scaled densitys, given the unsorted draws and weights +% +% s: ndraws-by-n draws where ndraws is # of draws and n is # of series +% nbin: the number of bins (the maximum is ndraws) +% gIdx: 1 if plotting the pdf; 0 if no graph +% bound: bounds for XLim. Example: bound = [-2 2]; +% w (optional): ndraws-by-n (unscaled) weights where ndraws is # of draws and n is # of series +% xlabstr (optional): xlabel string +% ylabstr (optional): ylabel string +% titstr (optional): title string +%------------- +% xpd: nbin-by-n: density or pdf (not probability) in the centered bin on x-axis. +% xc: nbin-by-n: the position of centered bin on x-axis, from top to bottom. +% All columns are identical +% xp: nbin-by-n: probability (not density) in the centered bin on x-axis. +% NOTE: sum(xp) must be 1 for each column +% w: ndraws-by-n scaled weights so that sum(w)=1 for each column +% bw: bandwidth +% +% August 1999 by Tao Zha +% July 18 2000. Place w after gIdx so that previous programs need modifications accordingly. +% Oct 1 2000. Change the order of xpd, xc, and xp so that previous programs need modifications accordingly. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (nargin<=5), titstr=[]; xlabstr=[]; ylabstr=[]; end +[m,n] = size(s); +if (nargin<=4) + w=ones(m,n)/m; +else + %** normalized to 1 for the probability + wsum = repmat(sum(w), [m 1]); + w = w ./ wsum; +end + +%if min(size(s))==1, s=s(:); w=w(:); end % making sure they are column vectors + +%*** the position of the center of the bin on the x-axis +mins = min(min(s)); +maxs = max(max(s)); +bw = (maxs-mins)/nbin; % binwidth for x-axis +x = mins + bw*(0:nbin); +x(end) = maxs; % in case nbin is not an integer +xc = x(1:end-1) + bw/2; % the position of the center of the x-bin +xc = xc'; % nbin-by-1 row vector: from top to bottom +xc = repmat(xc,[1 n]); % nbin-by-n, same for each column + + +%*** the probability at each bin on the x-axis +nbin = nbin+1; % + 1 to get the difference for getting probability xp +nn = zeros(nbin,n); +for i=2:nbin + for k=1:n + xidx = find(s(:,k) <= x(i)); % index for the positions + nn(i,k) = sum(w(xidx,k)); + end +end +xp = nn(2:nbin,:) - nn(1:nbin-1,:); +if (bw<eps) + xpd=Inf*ones(size(xp)); +else + xpd = xp/bw; % the density, NOT the probability as xp +end + +if gIdx + plot(xc,xpd) + set(gca,'XLim',bound) % put the limit only on the y-axis + title(titstr), xlabel(xlabstr), ylabel(ylabstr); +end diff --git a/MatlabFiles/fn_imc2errgraph.m b/MatlabFiles/fn_imc2errgraph.m index f19134c686473c1dff47af40c1521ec77ac376c9..1ea73b4435d0ff906ce4a3925a0fc4b45217edc1 100644 --- a/MatlabFiles/fn_imc2errgraph.m +++ b/MatlabFiles/fn_imc2errgraph.m @@ -1,132 +1,132 @@ -function scaleout = imc2errgraph(imf,firstl1,firsth1,... - firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick) -% imc2errgraph: impulse, c (column: shock 1 to N), 2 error bands, graph -% -% imf: imstp-by-nvar^2 matrix of impulse responses. Column (responses to 1st shock, responses to 2nd shock -% etc), Row (impusle steps), -% firstl1: lower band, .68 -% highth1: high band, .68 -% firstl: lower band, .90 -% highth: high band, .90 -% nvar: number of variables -% imstp: number of steps of impulse responses -% xlab,ylab: labels -% indxGimfml: 1, graph; 0, no graph -% xTick: optional. Eg: [12 24 36]. -%--------------- -% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. -% -% See imrgraph, fn_imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin < 11, xTick = []; end - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -maxval=zeros(nvar,1); -minval=zeros(nvar,1); -for i = 1:nvar - for j = 1:nvar - jnk1=max(firsth(:,(j-1)*nvar+i)); - jnk2=max(firstl(:,(j-1)*nvar+i)); - jnk3=max(firsth1(:,(j-1)*nvar+i)); - jnk4=max(firstl1(:,(j-1)*nvar+i)); - jnk5=max(imf(:,(j-1)*nvar+i)); - - temp1(j)=max([jnk1 jnk2 jnk3 jnk4 jnk5]); - % - jnk1=min(firstl(:,(j-1)*nvar+i)); - jnk2=min(firsth(:,(j-1)*nvar+i)); - jnk3=min(firstl1(:,(j-1)*nvar+i)); - jnk4=min(firsth1(:,(j-1)*nvar+i)); - jnk5=min(imf(:,(j-1)*nvar+i)); - - temp2(j)=min([jnk1 jnk2 jnk3 jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -if indxGimfml - %figure - rowlabel = 1; - for i = 1:nvar - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - scale=[1 imstp minval(i) maxval(i)]; - for j = 1:nvar - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,[firstl1(:,k2) firsth1(:,k2)],'--',... - t,[firstl(:,k2) firsth(:,k2)],'-.',t,zeros(length(imf(:,k2)),1),'-'); - - set(gca,'XTick',xTick) - set(gca,'YTick',yt) - grid; - - axis(scale); % put limits on both axes. - %set(gca,'YLim',[minval(i) maxval(i)]) - if 1 % no numbers on axes - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - else % put numbers on both axes - if i<nvar - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - if j>1 - set(gca,'YTickLabel',' '); - end - end - - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; - end -end +function scaleout = imc2errgraph(imf,firstl1,firsth1,... + firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick) +% imc2errgraph: impulse, c (column: shock 1 to N), 2 error bands, graph +% +% imf: imstp-by-nvar^2 matrix of impulse responses. Column (responses to 1st shock, responses to 2nd shock +% etc), Row (impusle steps), +% firstl1: lower band, .68 +% highth1: high band, .68 +% firstl: lower band, .90 +% highth: high band, .90 +% nvar: number of variables +% imstp: number of steps of impulse responses +% xlab,ylab: labels +% indxGimfml: 1, graph; 0, no graph +% xTick: optional. Eg: [12 24 36]. +%--------------- +% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. +% +% See imrgraph, fn_imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin < 11, xTick = []; end + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +maxval=zeros(nvar,1); +minval=zeros(nvar,1); +for i = 1:nvar + for j = 1:nvar + jnk1=max(firsth(:,(j-1)*nvar+i)); + jnk2=max(firstl(:,(j-1)*nvar+i)); + jnk3=max(firsth1(:,(j-1)*nvar+i)); + jnk4=max(firstl1(:,(j-1)*nvar+i)); + jnk5=max(imf(:,(j-1)*nvar+i)); + + temp1(j)=max([jnk1 jnk2 jnk3 jnk4 jnk5]); + % + jnk1=min(firstl(:,(j-1)*nvar+i)); + jnk2=min(firsth(:,(j-1)*nvar+i)); + jnk3=min(firstl1(:,(j-1)*nvar+i)); + jnk4=min(firsth1(:,(j-1)*nvar+i)); + jnk5=min(imf(:,(j-1)*nvar+i)); + + temp2(j)=min([jnk1 jnk2 jnk3 jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +if indxGimfml + %figure + rowlabel = 1; + for i = 1:nvar + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + scale=[1 imstp minval(i) maxval(i)]; + for j = 1:nvar + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,[firstl1(:,k2) firsth1(:,k2)],'--',... + t,[firstl(:,k2) firsth(:,k2)],'-.',t,zeros(length(imf(:,k2)),1),'-'); + + set(gca,'XTick',xTick) + set(gca,'YTick',yt) + grid; + + axis(scale); % put limits on both axes. + %set(gca,'YLim',[minval(i) maxval(i)]) + if 1 % no numbers on axes + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + else % put numbers on both axes + if i<nvar + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + if j>1 + set(gca,'YTickLabel',' '); + end + end + + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; + end +end diff --git a/MatlabFiles/fn_imcerrgraph.m b/MatlabFiles/fn_imcerrgraph.m index 36501975f049e5df2b090adc0186efdf9a3e37d9..b5888cd312870947cebe3d306b5676b99a44679c 100644 --- a/MatlabFiles/fn_imcerrgraph.m +++ b/MatlabFiles/fn_imcerrgraph.m @@ -1,123 +1,123 @@ -function scaleout = fn_imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick,indx_num) -% scaleout = fn_imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick) -% imcerrgraph: impulse, c (column: shock 1 to N), 1 error band, graph -% -% imf: imstp-by-nvar^2 matrix of impulse responses. Column (responses to 1st shock, responses to 2nd shock -% etc), Row (impusle steps), -% firstl: lower band -% highth: high band -% nvar: number of variables -% imstp: number of steps of impulse responses -% xlab,ylab: labels -% indxGimfml: 1, graph; 0, no graph -% xTick: optional. Eg: [12 24 36]. -% indx_num: 0: no number on either axis (default), 1: number on both x-axis and y-axis. -%--------------- -% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. -% -% See fn_imcgraph, fn_imc2errgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin < 9, xTick = []; end -if nargin < 10, indx_num = 0; end - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -maxval=zeros(nvar,1); -minval=zeros(nvar,1); -for i = 1:nvar - for j = 1:nvar - temp1(j)=max(firsth(:,(j-1)*nvar+i)); - temp2(j)=min(firstl(:,(j-1)*nvar+i)); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -if indxGimfml - %figure - rowlabel = 1; - for i = 1:nvar - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - scale=[1 imstp minval(i) maxval(i)]; - for j = 1:nvar - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,[firstl(:,k2) firsth(:,k2)],'--',... - t,zeros(length(imf(:,k2)),1),'-'); - - set(gca,'XTick',xTick) - set(gca,'YTick',yt) - grid - - axis(scale); % put limits on both axes. - %set(gca,'YLim',[minval(i) maxval(i)]) - if (indx_num==0) % no numbers on axes - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); -% elseif (indx_num==1) %numbers on x-axis. -% if i<nvar -% set(gca,'XTickLabelMode','manual','XTickLabel',[]) -% end - else % put numbers on both axes - if i<nvar - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - if j>1 - set(gca,'YTickLabel',' '); - end - end - - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; - end -end +function scaleout = fn_imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick,indx_num) +% scaleout = fn_imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick) +% imcerrgraph: impulse, c (column: shock 1 to N), 1 error band, graph +% +% imf: imstp-by-nvar^2 matrix of impulse responses. Column (responses to 1st shock, responses to 2nd shock +% etc), Row (impusle steps), +% firstl: lower band +% highth: high band +% nvar: number of variables +% imstp: number of steps of impulse responses +% xlab,ylab: labels +% indxGimfml: 1, graph; 0, no graph +% xTick: optional. Eg: [12 24 36]. +% indx_num: 0: no number on either axis (default), 1: number on both x-axis and y-axis. +%--------------- +% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. +% +% See fn_imcgraph, fn_imc2errgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin < 9, xTick = []; end +if nargin < 10, indx_num = 0; end + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +maxval=zeros(nvar,1); +minval=zeros(nvar,1); +for i = 1:nvar + for j = 1:nvar + temp1(j)=max(firsth(:,(j-1)*nvar+i)); + temp2(j)=min(firstl(:,(j-1)*nvar+i)); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +if indxGimfml + %figure + rowlabel = 1; + for i = 1:nvar + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + scale=[1 imstp minval(i) maxval(i)]; + for j = 1:nvar + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,[firstl(:,k2) firsth(:,k2)],'--',... + t,zeros(length(imf(:,k2)),1),'-'); + + set(gca,'XTick',xTick) + set(gca,'YTick',yt) + grid + + axis(scale); % put limits on both axes. + %set(gca,'YLim',[minval(i) maxval(i)]) + if (indx_num==0) % no numbers on axes + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); +% elseif (indx_num==1) %numbers on x-axis. +% if i<nvar +% set(gca,'XTickLabelMode','manual','XTickLabel',[]) +% end + else % put numbers on both axes + if i<nvar + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + if j>1 + set(gca,'YTickLabel',' '); + end + end + + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; + end +end diff --git a/MatlabFiles/fn_imcerrgraph_scl.m b/MatlabFiles/fn_imcerrgraph_scl.m index 733d3700d75d3c699ca24c26570ead903927d9d2..46c9953ad45cbf9d49a4292af5ff0de01533f652 100644 --- a/MatlabFiles/fn_imcerrgraph_scl.m +++ b/MatlabFiles/fn_imcerrgraph_scl.m @@ -1,122 +1,122 @@ -function scaleout = fn_imcerrgraph_scl(imf,firstl,firsth,nvar,imstp,scaleout,xlab,ylab,indxGimfml,xTick) -% scaleout = fn_imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick) -% imcerrgraph: impulse, c (column: shock 1 to N), 1 error band, graph -% -% imf: imstp-by-nvar^2 matrix of impulse responses. Column (responses to 1st shock, responses to 2nd shock -% etc), Row (impusle steps), -% firstl: lower band -% highth: high band -% nvar: number of variables -% imstp: number of steps of impulse responses -% xlab,ylab: labels -% indxGimfml: 1, graph; 0, no graph -% xTick: optional. Eg: [12 24 36]. -%--------------- -% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. -% -% See fn_imcgraph, fn_imc2errgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin < 10, xTick = []; end - -t = 1:imstp; -if isempty(scaleout) - temp1=zeros(nvar,1); - temp2=zeros(nvar,1); - maxval=zeros(nvar,1); - minval=zeros(nvar,1); - for i = 1:nvar - for j = 1:nvar - temp1(j)=max(firsth(:,(j-1)*nvar+i)); - temp2(j)=min(firstl(:,(j-1)*nvar+i)); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); - end - scaleout = [maxval(:) minval(:)]; -else - maxval = scaleout(:,1); - minval = scaleout(:,2); -end - - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -if indxGimfml - %figure - rowlabel = 1; - for i = 1:nvar - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - scale=[1 imstp minval(i) maxval(i)]; - for j = 1:nvar - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,[firstl(:,k2) firsth(:,k2)],'--',... - t,zeros(length(imf(:,k2)),1),'-'); - - set(gca,'XTick',xTick) - set(gca,'YTick',yt) - grid - - axis(scale); % put limits on both axes. - %set(gca,'YLim',[minval(i) maxval(i)]) - if 1 % no numbers on axes - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - else % put numbers on both axes - if i<nvar - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - if j>1 - set(gca,'YTickLabel',' '); - end - end - - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; - end -end +function scaleout = fn_imcerrgraph_scl(imf,firstl,firsth,nvar,imstp,scaleout,xlab,ylab,indxGimfml,xTick) +% scaleout = fn_imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab,indxGimfml,xTick) +% imcerrgraph: impulse, c (column: shock 1 to N), 1 error band, graph +% +% imf: imstp-by-nvar^2 matrix of impulse responses. Column (responses to 1st shock, responses to 2nd shock +% etc), Row (impusle steps), +% firstl: lower band +% highth: high band +% nvar: number of variables +% imstp: number of steps of impulse responses +% xlab,ylab: labels +% indxGimfml: 1, graph; 0, no graph +% xTick: optional. Eg: [12 24 36]. +%--------------- +% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. +% +% See fn_imcgraph, fn_imc2errgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin < 10, xTick = []; end + +t = 1:imstp; +if isempty(scaleout) + temp1=zeros(nvar,1); + temp2=zeros(nvar,1); + maxval=zeros(nvar,1); + minval=zeros(nvar,1); + for i = 1:nvar + for j = 1:nvar + temp1(j)=max(firsth(:,(j-1)*nvar+i)); + temp2(j)=min(firstl(:,(j-1)*nvar+i)); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); + end + scaleout = [maxval(:) minval(:)]; +else + maxval = scaleout(:,1); + minval = scaleout(:,2); +end + + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +if indxGimfml + %figure + rowlabel = 1; + for i = 1:nvar + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + scale=[1 imstp minval(i) maxval(i)]; + for j = 1:nvar + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,[firstl(:,k2) firsth(:,k2)],'--',... + t,zeros(length(imf(:,k2)),1),'-'); + + set(gca,'XTick',xTick) + set(gca,'YTick',yt) + grid + + axis(scale); % put limits on both axes. + %set(gca,'YLim',[minval(i) maxval(i)]) + if 1 % no numbers on axes + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + else % put numbers on both axes + if i<nvar + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + if j>1 + set(gca,'YTickLabel',' '); + end + end + + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; + end +end diff --git a/MatlabFiles/fn_imcgraph.m b/MatlabFiles/fn_imcgraph.m index cdc7cfb9e2906b7e9aef79825c1a9599aecba7a0..e42b97f52ede418954938fa0ab966542f366bcd6 100644 --- a/MatlabFiles/fn_imcgraph.m +++ b/MatlabFiles/fn_imcgraph.m @@ -1,123 +1,123 @@ -function scaleout = fn_imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml,xTick) -% scaleout = fn_imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml,xTick) -% imcgraph: impulse, c (column: shock 1 to N), graph the ML point impulse response -% -% imf: imstp-by-nvar^2 matrix of impulse responses, column (responses to 1st shock, responses to 2nd shock -% etc), row (impusle steps), -% nvar: number of variables -% imstp: number of steps of impulse responses -% xlab,ylab: labels -% indxGimfml: 1, graph; 0, no graph -% xTick: optional. Eg: [12 24 36]. -%--------------- -% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. -% -% NOTE: I added "indxGimfml" so this function may not be compatible with programs -% older than 03/06/99, TZ -% -% See imrgraph, fn_imcerrgraph, fn_imc2errgraph, imrerrgraph, fn_gyrfore in RVARcode -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if nargin < 7, xTick = []; end - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -maxval=zeros(nvar,1); -minval=zeros(nvar,1); -for i = 1:nvar - for j = 1:nvar - temp1(j)=max(imf(:,(j-1)*nvar+i)); - temp2(j)=min(imf(:,(j-1)*nvar+i)); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -if indxGimfml - %figure - rowlabel = 1; - for i = 1:nvar % Responses of - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 imstp minval(i) maxval(i)]; - for j = 1:nvar % To shocks - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,zeros(length(imf(:,k2)),1),'r:'); - - set(gca,'XTick',xTick) - set(gca,'YTick',yt) - grid - - axis(scale); % put limits on both axes. - % - % if maxval(i)>minval(i) - % set(gca,'YLim',[minval(i) maxval(i)]) - % end - - - if isempty(xTick) %1 % No numbers on both axes - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - else % Put numbers on both axes - if i<nvar - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - if j>1 - set(gca,'YTickLabel',' '); - end - end - - - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; - end -end +function scaleout = fn_imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml,xTick) +% scaleout = fn_imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml,xTick) +% imcgraph: impulse, c (column: shock 1 to N), graph the ML point impulse response +% +% imf: imstp-by-nvar^2 matrix of impulse responses, column (responses to 1st shock, responses to 2nd shock +% etc), row (impusle steps), +% nvar: number of variables +% imstp: number of steps of impulse responses +% xlab,ylab: labels +% indxGimfml: 1, graph; 0, no graph +% xTick: optional. Eg: [12 24 36]. +%--------------- +% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. +% +% NOTE: I added "indxGimfml" so this function may not be compatible with programs +% older than 03/06/99, TZ +% +% See imrgraph, fn_imcerrgraph, fn_imc2errgraph, imrerrgraph, fn_gyrfore in RVARcode +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if nargin < 7, xTick = []; end + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +maxval=zeros(nvar,1); +minval=zeros(nvar,1); +for i = 1:nvar + for j = 1:nvar + temp1(j)=max(imf(:,(j-1)*nvar+i)); + temp2(j)=min(imf(:,(j-1)*nvar+i)); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +if indxGimfml + %figure + rowlabel = 1; + for i = 1:nvar % Responses of + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 imstp minval(i) maxval(i)]; + for j = 1:nvar % To shocks + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,zeros(length(imf(:,k2)),1),'r:'); + + set(gca,'XTick',xTick) + set(gca,'YTick',yt) + grid + + axis(scale); % put limits on both axes. + % + % if maxval(i)>minval(i) + % set(gca,'YLim',[minval(i) maxval(i)]) + % end + + + if isempty(xTick) %1 % No numbers on both axes + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + else % Put numbers on both axes + if i<nvar + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + if j>1 + set(gca,'YTickLabel',' '); + end + end + + + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; + end +end diff --git a/MatlabFiles/fn_imcgraph_scl.m b/MatlabFiles/fn_imcgraph_scl.m index 6fd2acfc499df92a71c1a1a5abef1a163ae1ab4d..4fc5e0a8161783f6652afd24805d1b3919e87ef6 100644 --- a/MatlabFiles/fn_imcgraph_scl.m +++ b/MatlabFiles/fn_imcgraph_scl.m @@ -1,128 +1,128 @@ -function scaleout = fn_imcgraph_scl(imf,nvar,imstp,scaleout,xlab,ylab,indxGimfml,xTick) -% scaleout = fn_imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml,xTick) -% imcgraph: impulse, c (column: shock 1 to N), graph the ML point impulse response -% -% imf: imstp-by-nvar^2 matrix of impulse responses, column (responses to 1st shock, responses to 2nd shock -% etc), row (impusle steps), -% nvar: number of variables -% imstp: number of steps of impulse responses -% xlab,ylab: labels -% indxGimfml: 1, graph; 0, no graph -% xTick: optional. Eg: [12 24 36]. -%--------------- -% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. -% -% NOTE: I added "indxGimfml" so this function may not be compatible with programs -% older than 03/06/99, TZ -% -% See imrgraph, fn_imcerrgraph, fn_imc2errgraph, imrerrgraph, fn_gyrfore in RVARcode -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if nargin < 7, xTick = []; end - -t = 1:imstp; -if isempty(scaleout) - temp1=zeros(nvar,1); - temp2=zeros(nvar,1); - maxval=zeros(nvar,1); - minval=zeros(nvar,1); - for i = 1:nvar - for j = 1:nvar - temp1(j)=max(imf(:,(j-1)*nvar+i)); - temp2(j)=min(imf(:,(j-1)*nvar+i)); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); - end - scaleout = [maxval(:) minval(:)]; -else - maxval = scaleout(:,1); - minval = scaleout(:,2); -end - - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -if indxGimfml - %figure - rowlabel = 1; - for i = 1:nvar % Responses of - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 imstp minval(i) maxval(i)]; - for j = 1:nvar % To shocks - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,zeros(length(imf(:,k2)),1),'r:'); - - set(gca,'XTick',xTick) - set(gca,'YTick',yt) - grid - - axis(scale); % put limits on both axes. - % - % if maxval(i)>minval(i) - % set(gca,'YLim',[minval(i) maxval(i)]) - % end - - - if isempty(xTick) %1 % No numbers on both axes - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - else % Put numbers on both axes - if i<nvar - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - if j>1 - set(gca,'YTickLabel',' '); - end - end - - - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; - end -end +function scaleout = fn_imcgraph_scl(imf,nvar,imstp,scaleout,xlab,ylab,indxGimfml,xTick) +% scaleout = fn_imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml,xTick) +% imcgraph: impulse, c (column: shock 1 to N), graph the ML point impulse response +% +% imf: imstp-by-nvar^2 matrix of impulse responses, column (responses to 1st shock, responses to 2nd shock +% etc), row (impusle steps), +% nvar: number of variables +% imstp: number of steps of impulse responses +% xlab,ylab: labels +% indxGimfml: 1, graph; 0, no graph +% xTick: optional. Eg: [12 24 36]. +%--------------- +% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. +% +% NOTE: I added "indxGimfml" so this function may not be compatible with programs +% older than 03/06/99, TZ +% +% See imrgraph, fn_imcerrgraph, fn_imc2errgraph, imrerrgraph, fn_gyrfore in RVARcode +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if nargin < 7, xTick = []; end + +t = 1:imstp; +if isempty(scaleout) + temp1=zeros(nvar,1); + temp2=zeros(nvar,1); + maxval=zeros(nvar,1); + minval=zeros(nvar,1); + for i = 1:nvar + for j = 1:nvar + temp1(j)=max(imf(:,(j-1)*nvar+i)); + temp2(j)=min(imf(:,(j-1)*nvar+i)); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); + end + scaleout = [maxval(:) minval(:)]; +else + maxval = scaleout(:,1); + minval = scaleout(:,2); +end + + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +if indxGimfml + %figure + rowlabel = 1; + for i = 1:nvar % Responses of + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 imstp minval(i) maxval(i)]; + for j = 1:nvar % To shocks + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,zeros(length(imf(:,k2)),1),'r:'); + + set(gca,'XTick',xTick) + set(gca,'YTick',yt) + grid + + axis(scale); % put limits on both axes. + % + % if maxval(i)>minval(i) + % set(gca,'YLim',[minval(i) maxval(i)]) + % end + + + if isempty(xTick) %1 % No numbers on both axes + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + else % Put numbers on both axes + if i<nvar + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + if j>1 + set(gca,'YTickLabel',' '); + end + end + + + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; + end +end diff --git a/MatlabFiles/fn_impulse.m b/MatlabFiles/fn_impulse.m index 77e618f97d307d7979c6f00c1c142592c161a7ca..7c1e7e26bbccea42c1e3c3efb6fff0100f2939bc 100644 --- a/MatlabFiles/fn_impulse.m +++ b/MatlabFiles/fn_impulse.m @@ -1,75 +1,75 @@ -function imf = fn_impulse(Bh,swish,nn) -% Computing impulse functions with -% imf = fn_impulse(Bh,swish,nn) -% imf is in a format that is the SAME as in RATS. -% Column: nvar responses to 1st shock, -% nvar responses to 2nd shock, and so on. -% Row: steps of impulse responses. -%----------------- -% Bh is the estimated reduced form coefficient in the form -% Y(T*nvar) = XB + U, X: T*k (may include all exogenous terms), B: k*nvar. -% The matrix form and dimension are the same as "Bh" from the function "sye.m"; -% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. -% Note: columns correspond to equations. -% swish is the inv(A0) in the structural model y'(t)*A0 = e'(t). -% Note: columns corresponding to equations. -% nn is the numbers of inputs [nvar,lags,# of steps of impulse responses]. -% -% Written by Tao Zha. -% Copyright (c) 1994 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nvar = nn(1); -lags = nn(2); -imstep = nn(3); % number of steps for impulse responses - -Ah = Bh'; -% Row: nvar equations -% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. - -imf = zeros(imstep,nvar*nvar); -% Column: nvar responses to 1st shock, nvar responses to 2nd shock, and so on. -% Row: steps of impulse responses. -M = zeros(nvar*(lags+1),nvar); -% Stack lags M's in the order of, e.g., [Mlags, ..., M2,M1;M0] -M(1:nvar,:) = swish'; -Mtem = M(1:nvar,:); % temporary M. -% first (initial) responses to 1 standard deviation shock. Row: responses; Column: shocks -% * put in the form of "imf" -imf(1,:) = Mtem(:)'; - -t = 1; -ims1 = min([imstep-1 lags]); -while t <= ims1 - Mtem = Ah(:,1:nvar*t)*M(1:nvar*t,:); - % Row: nvar equations, each for the nvar variables at tth lag - M(nvar+1:nvar*(t+1),:)=M(1:nvar*t,:); - M(1:nvar,:) = Mtem; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. - t= t+1; -end - -for t = lags+1:imstep-1 - Mtem = Ah(:,1:nvar*lags)*M(1:nvar*lags,:); - % Row: nvar equations, each for the nvar variables at tth lag - M(nvar+1:nvar*(t+1),:) = M(1:nvar*t,:); - M(1:nvar,:)=Mtem; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. -end +function imf = fn_impulse(Bh,swish,nn) +% Computing impulse functions with +% imf = fn_impulse(Bh,swish,nn) +% imf is in a format that is the SAME as in RATS. +% Column: nvar responses to 1st shock, +% nvar responses to 2nd shock, and so on. +% Row: steps of impulse responses. +%----------------- +% Bh is the estimated reduced form coefficient in the form +% Y(T*nvar) = XB + U, X: T*k (may include all exogenous terms), B: k*nvar. +% The matrix form and dimension are the same as "Bh" from the function "sye.m"; +% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. +% Note: columns correspond to equations. +% swish is the inv(A0) in the structural model y'(t)*A0 = e'(t). +% Note: columns corresponding to equations. +% nn is the numbers of inputs [nvar,lags,# of steps of impulse responses]. +% +% Written by Tao Zha. +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nvar = nn(1); +lags = nn(2); +imstep = nn(3); % number of steps for impulse responses + +Ah = Bh'; +% Row: nvar equations +% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. + +imf = zeros(imstep,nvar*nvar); +% Column: nvar responses to 1st shock, nvar responses to 2nd shock, and so on. +% Row: steps of impulse responses. +M = zeros(nvar*(lags+1),nvar); +% Stack lags M's in the order of, e.g., [Mlags, ..., M2,M1;M0] +M(1:nvar,:) = swish'; +Mtem = M(1:nvar,:); % temporary M. +% first (initial) responses to 1 standard deviation shock. Row: responses; Column: shocks +% * put in the form of "imf" +imf(1,:) = Mtem(:)'; + +t = 1; +ims1 = min([imstep-1 lags]); +while t <= ims1 + Mtem = Ah(:,1:nvar*t)*M(1:nvar*t,:); + % Row: nvar equations, each for the nvar variables at tth lag + M(nvar+1:nvar*(t+1),:)=M(1:nvar*t,:); + M(1:nvar,:) = Mtem; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. + t= t+1; +end + +for t = lags+1:imstep-1 + Mtem = Ah(:,1:nvar*lags)*M(1:nvar*lags,:); + % Row: nvar equations, each for the nvar variables at tth lag + M(nvar+1:nvar*(t+1),:) = M(1:nvar*t,:); + M(1:nvar,:)=Mtem; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. +end diff --git a/MatlabFiles/fn_irf_var1.m b/MatlabFiles/fn_irf_var1.m index 490a31f7ee7b4f03f19bbc18557869ca757b071e..00106de102a765c23682f796a3e8a9127f4861fe 100644 --- a/MatlabFiles/fn_irf_var1.m +++ b/MatlabFiles/fn_irf_var1.m @@ -1,51 +1,51 @@ -function irfs = fn_irf_var1(G1, impact, nsteps); -%irfs = fn_irf_var1(G1, impact,nsteps); -% Inputs: -% G1: n-by-n; -% impact: n-by-r; -% nsteps: number of steps for impulse responses. -%--- -% Outputs: -% irfs: nsteps-by-n-by-r. For each shock of r shocks, impulse responses are nsteps-by-n. -% -% See fn_vds.m and fn_uncondfcst_var1.m. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[n,r] = size(impact); - -[n1,n2] = size(G1); -if (n1 ~= n2) || (n1 ~= n) - error('fn_irf_var1.m: make sure that (1) G1 is square and (2) size(G1,1) = size(impact,1)'); -end - -irfs = zeros(nsteps,n,r); - - -%---- Impuse responses at the first step. -M = impact; -for ri=1:r - irfs(1,:,ri) = M(:,ri)'; -end - -for ti = 2:nsteps - M = G1*M; - for ri=1:r - irfs(ti,:,ri) = M(:,ri)'; - end -end +function irfs = fn_irf_var1(G1, impact, nsteps); +%irfs = fn_irf_var1(G1, impact,nsteps); +% Inputs: +% G1: n-by-n; +% impact: n-by-r; +% nsteps: number of steps for impulse responses. +%--- +% Outputs: +% irfs: nsteps-by-n-by-r. For each shock of r shocks, impulse responses are nsteps-by-n. +% +% See fn_vds.m and fn_uncondfcst_var1.m. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[n,r] = size(impact); + +[n1,n2] = size(G1); +if (n1 ~= n2) || (n1 ~= n) + error('fn_irf_var1.m: make sure that (1) G1 is square and (2) size(G1,1) = size(impact,1)'); +end + +irfs = zeros(nsteps,n,r); + + +%---- Impuse responses at the first step. +M = impact; +for ri=1:r + irfs(1,:,ri) = M(:,ri)'; +end + +for ti = 2:nsteps + M = G1*M; + for ri=1:r + irfs(ti,:,ri) = M(:,ri)'; + end +end diff --git a/MatlabFiles/fn_kalfil_tv.m b/MatlabFiles/fn_kalfil_tv.m index 262a6a97e7d41bc85628d759c52f31183f4504bc..13badcfaf30d227469d2b9721862d9b292c2cfc0 100644 --- a/MatlabFiles/fn_kalfil_tv.m +++ b/MatlabFiles/fn_kalfil_tv.m @@ -1,154 +1,154 @@ -function [loglh,zt_tm1,Pt_tm1, loglh_t_allvalues] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni,z0,P0) -%[loglh,zt_tm1,Pt_tm1] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni,z0,P0) -%Time-varying Kalman filter (conditional on all the regimes in a Markov-switching model). It computes -% a sequence of one-step predictions and their covariance matrices, and the log likelihood. -% The function uses a forward recursion algorithm. -% -% Note: for b, F, V, zt_tm1, and Pt_tm1, there is not need for the T+1 length because the values at T+1 have -% never been used in the likelihood function. See tz_kalfiltv() in kalman.c for an illustration. -% -% State space model is defined as follows: -% y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation) -% z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation) -% where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given. -% -% Inputs are as follows: -% Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)]. -% a is an n_y-by-T matrix of time-varying input vectors in the measurement equation. -% H is an n_y-by-n_z-by-T 3-D of time-varying matrices in the measurement equation. -% R is an n_y-by-n_y-by-T 3-D of time-varying covariance matrices for the error in the measurement equation. -% G is an n_z-by-n_y-by-T 3-D of time-varying E(eta_t * eps_t'). -% ------ -% b is an n_z-by-(T+1) matrix of time-varying input vectors in the state equation with b(:,1) as an initial condition. -% F is an n_z-by-n_z-by-(T+1) 3-D of time-varying transition matrices in the state equation with F(:,:,1) as an initial condition. -% V is an n_z-by-n_z-by-(T+1) 3-D of time-varying covariance matrices for the error in the state equation with V(:,:,1) as an initial condition. -% ------ -% indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0; -% 0: using the unconditional mean for any given regime at time 0. -% z0 is an n_z-by-1 vector of initial condition when indxIni=1. (Do not enter if indxIni=0.) -% P0 is an n_z-by-n_z matrix of initial condition when indxIni=1. (Do not enter if indxIni=0.) -% -% Outputs are as follows: -% loglh is a value of the log likelihood function of the state-space model -% under the assumption that errors are multivariate Gaussian. -% zt_tm1 is an n_z-by-(T+1) matrices of one-step predicted state vectors with z0_0m1 as a initial condition. -% Pt_tm1 is an n_z-by-n_z-by-(T+1) 3-D of covariance matrices of zt_tm1 with P0_0m1 as a initial condition. -% loglh_t_allvalues is a T-by-1 vector of loglh at time t for t=1:T. -% -% The initial state vector and its covariance matrix are computed under the bounded (stationary) condition: -% z0_0m1 = (I-F(:,:,1))\b(:,1) -% vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1)) -% Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary). -% -% March 2007, written by Tao Zha -% See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003. -%========================================================================== -% Revision history: -% -% -% -%========================================================================== -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -Tp1 = size(Y_T,2) + 1; %T+1; -n_y = size(a,1); -n_z = size(b,1); -%--- Checking input matrix dimensions -if (size(Y_T,1)~=n_y) - error('kalf_tv(): Y_T and a must have the same number of rows') -end -%--- Allocating memory. -zt_tm1 = zeros(n_z,Tp1); -Pt_tm1 = zeros(n_z,n_z,Tp1); -loglh_t_allvalues = zeros(Tp1-1,1); -%--- Initializing. -loglh = 0.0; -if (indxIni) - zt_tm1(:,1) = z0; - Pt_tm1(:,:,1) = P0; -else - eigmax4F = max(abs(eig(F(:,:,1)))); - format long e - eigmax4F - if (eigmax4F < 1.0) - zt_tm1(:,1) = (eye(n_z)-F(:,:,1))\b(:,1); - V1 = V(:,:,1); - Pt_tm1(:,:,1) = reshape((eye(n_z^2)-kron(F(:,:,1),F(:,:,1)))\V1(:) ,n_z,n_z); - else - %--- Do NOT use the following option. It turns out that this will often generate explosive conditional liklihood - %--- at the end of the sample, because Pt_tm1 shrinks to zero overtime due to the sigularity of the initila condition P_{1|0}. - % zt_tm1(:,1) = zeros(size(zt_tm1(:,1))); - % Pt_tm1(:,:,1) = V(:,:,1); %+eye(size(V(:,:,1))); - - nearinfinity = -1.0e+300 - loglh = nearinfinity; - return; %Eearly exit. - %error('kalf_tv(): For non-stationary solutions, the initial conditions must be supplied by, say, input arguments') - end -end - - -%====== See p.002 in LiuWZ. ====== -indx_badlh = 0; %1: bad likelihood with, say, -infinity of the LH value. -for t=2:Tp1 - tdata = t-1; - - %--- Setup. - Htdata = H(:,:,tdata); - Htdatatran = Htdata'; - ztdata = zt_tm1(:,tdata); - Ptdata = Pt_tm1(:,:,tdata); - PHtran_tdata = Ptdata*Htdatatran; - Ft = F(:,:,t); - Fttran = Ft'; - - %--- Data. - etdata = Y_T(:,tdata) - a(:,tdata) - Htdata*ztdata; - etdatatran = etdata'; - Dtdata = Htdata*PHtran_tdata + R(:,:,tdata); - Dtdata = 0.5*(Dtdata + Dtdata'); %Making it symmetric against some rounding errors. - %This making-symmetric is very IMPORTANT; otherwise, we will get the matrix being singular message - % and eigenvalues being negative for the SPD matrix, etc. Then the likelihood becomes either - % a bad number or a complex number. - - %--- State (updating). - Kt_tdata = (Ft*PHtran_tdata+G(:,:,tdata))/Dtdata; - Kt_tdatatran = Kt_tdata'; - zt_tm1(:,t) = b(:,t) + Ft*zt_tm1(:,tdata) + Kt_tdata*etdata; - Pt_tm1(:,:,t) = Ft*Ptdata*Fttran - Kt_tdata*Dtdata*Kt_tdatatran + V(:,:,t); - - %--- Forming the log likelihood. - detDtdata = det(Dtdata); - %if (~isfinite(detDtdata)) - if (detDtdata < realmin) - indx_badlh = 1; - break; - else - loglh_tdata = -(0.5*n_y)*log(2*pi) - 0.5*log(detDtdata) - 0.5*(etdatatran/Dtdata)*etdata; - loglh = loglh + loglh_tdata; - loglh_t_allvalues(tdata) = loglh_tdata; - end -end - -if (indx_badlh) - nearinfinity = -1.0e+300; - loglh = nearinfinity; - loglh_t_allvalues(tdata) = nearinfinity; -end - +function [loglh,zt_tm1,Pt_tm1, loglh_t_allvalues] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni,z0,P0) +%[loglh,zt_tm1,Pt_tm1] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni,z0,P0) +%Time-varying Kalman filter (conditional on all the regimes in a Markov-switching model). It computes +% a sequence of one-step predictions and their covariance matrices, and the log likelihood. +% The function uses a forward recursion algorithm. +% +% Note: for b, F, V, zt_tm1, and Pt_tm1, there is not need for the T+1 length because the values at T+1 have +% never been used in the likelihood function. See tz_kalfiltv() in kalman.c for an illustration. +% +% State space model is defined as follows: +% y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation) +% z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation) +% where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given. +% +% Inputs are as follows: +% Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)]. +% a is an n_y-by-T matrix of time-varying input vectors in the measurement equation. +% H is an n_y-by-n_z-by-T 3-D of time-varying matrices in the measurement equation. +% R is an n_y-by-n_y-by-T 3-D of time-varying covariance matrices for the error in the measurement equation. +% G is an n_z-by-n_y-by-T 3-D of time-varying E(eta_t * eps_t'). +% ------ +% b is an n_z-by-(T+1) matrix of time-varying input vectors in the state equation with b(:,1) as an initial condition. +% F is an n_z-by-n_z-by-(T+1) 3-D of time-varying transition matrices in the state equation with F(:,:,1) as an initial condition. +% V is an n_z-by-n_z-by-(T+1) 3-D of time-varying covariance matrices for the error in the state equation with V(:,:,1) as an initial condition. +% ------ +% indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0; +% 0: using the unconditional mean for any given regime at time 0. +% z0 is an n_z-by-1 vector of initial condition when indxIni=1. (Do not enter if indxIni=0.) +% P0 is an n_z-by-n_z matrix of initial condition when indxIni=1. (Do not enter if indxIni=0.) +% +% Outputs are as follows: +% loglh is a value of the log likelihood function of the state-space model +% under the assumption that errors are multivariate Gaussian. +% zt_tm1 is an n_z-by-(T+1) matrices of one-step predicted state vectors with z0_0m1 as a initial condition. +% Pt_tm1 is an n_z-by-n_z-by-(T+1) 3-D of covariance matrices of zt_tm1 with P0_0m1 as a initial condition. +% loglh_t_allvalues is a T-by-1 vector of loglh at time t for t=1:T. +% +% The initial state vector and its covariance matrix are computed under the bounded (stationary) condition: +% z0_0m1 = (I-F(:,:,1))\b(:,1) +% vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1)) +% Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary). +% +% March 2007, written by Tao Zha +% See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003. +%========================================================================== +% Revision history: +% +% +% +%========================================================================== +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +Tp1 = size(Y_T,2) + 1; %T+1; +n_y = size(a,1); +n_z = size(b,1); +%--- Checking input matrix dimensions +if (size(Y_T,1)~=n_y) + error('kalf_tv(): Y_T and a must have the same number of rows') +end +%--- Allocating memory. +zt_tm1 = zeros(n_z,Tp1); +Pt_tm1 = zeros(n_z,n_z,Tp1); +loglh_t_allvalues = zeros(Tp1-1,1); +%--- Initializing. +loglh = 0.0; +if (indxIni) + zt_tm1(:,1) = z0; + Pt_tm1(:,:,1) = P0; +else + eigmax4F = max(abs(eig(F(:,:,1)))); + format long e + eigmax4F + if (eigmax4F < 1.0) + zt_tm1(:,1) = (eye(n_z)-F(:,:,1))\b(:,1); + V1 = V(:,:,1); + Pt_tm1(:,:,1) = reshape((eye(n_z^2)-kron(F(:,:,1),F(:,:,1)))\V1(:) ,n_z,n_z); + else + %--- Do NOT use the following option. It turns out that this will often generate explosive conditional liklihood + %--- at the end of the sample, because Pt_tm1 shrinks to zero overtime due to the sigularity of the initila condition P_{1|0}. + % zt_tm1(:,1) = zeros(size(zt_tm1(:,1))); + % Pt_tm1(:,:,1) = V(:,:,1); %+eye(size(V(:,:,1))); + + nearinfinity = -1.0e+300 + loglh = nearinfinity; + return; %Eearly exit. + %error('kalf_tv(): For non-stationary solutions, the initial conditions must be supplied by, say, input arguments') + end +end + + +%====== See p.002 in LiuWZ. ====== +indx_badlh = 0; %1: bad likelihood with, say, -infinity of the LH value. +for t=2:Tp1 + tdata = t-1; + + %--- Setup. + Htdata = H(:,:,tdata); + Htdatatran = Htdata'; + ztdata = zt_tm1(:,tdata); + Ptdata = Pt_tm1(:,:,tdata); + PHtran_tdata = Ptdata*Htdatatran; + Ft = F(:,:,t); + Fttran = Ft'; + + %--- Data. + etdata = Y_T(:,tdata) - a(:,tdata) - Htdata*ztdata; + etdatatran = etdata'; + Dtdata = Htdata*PHtran_tdata + R(:,:,tdata); + Dtdata = 0.5*(Dtdata + Dtdata'); %Making it symmetric against some rounding errors. + %This making-symmetric is very IMPORTANT; otherwise, we will get the matrix being singular message + % and eigenvalues being negative for the SPD matrix, etc. Then the likelihood becomes either + % a bad number or a complex number. + + %--- State (updating). + Kt_tdata = (Ft*PHtran_tdata+G(:,:,tdata))/Dtdata; + Kt_tdatatran = Kt_tdata'; + zt_tm1(:,t) = b(:,t) + Ft*zt_tm1(:,tdata) + Kt_tdata*etdata; + Pt_tm1(:,:,t) = Ft*Ptdata*Fttran - Kt_tdata*Dtdata*Kt_tdatatran + V(:,:,t); + + %--- Forming the log likelihood. + detDtdata = det(Dtdata); + %if (~isfinite(detDtdata)) + if (detDtdata < realmin) + indx_badlh = 1; + break; + else + loglh_tdata = -(0.5*n_y)*log(2*pi) - 0.5*log(detDtdata) - 0.5*(etdatatran/Dtdata)*etdata; + loglh = loglh + loglh_tdata; + loglh_t_allvalues(tdata) = loglh_tdata; + end +end + +if (indx_badlh) + nearinfinity = -1.0e+300; + loglh = nearinfinity; + loglh_t_allvalues(tdata) = nearinfinity; +end + diff --git a/MatlabFiles/fn_kalfil_tv2.m b/MatlabFiles/fn_kalfil_tv2.m index 31003da7e073e811c325794fb0f20de406901731..2accf365a4886d496d9582d3115b9d50cb86c478 100644 --- a/MatlabFiles/fn_kalfil_tv2.m +++ b/MatlabFiles/fn_kalfil_tv2.m @@ -1,163 +1,163 @@ -function [loglh,zt_tm1,Pt_tm1, loglh_t_allvalues] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni, indxDiffuse, z0,P0) -%[loglh,zt_tm1,Pt_tm1, loglh_t_allvalues] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni, indxDiffuse, z0,P0) -%Time-varying Kalman filter (conditional on all the regimes in a Markov-switching model). It computes -% a sequence of one-step predictions and their covariance matrices, and the log likelihood. -% The function uses a forward recursion algorithm. -% -% Note: for b, F, V, zt_tm1, and Pt_tm1, there is not need for the T+1 length because the values at T+1 have -% never been used in the likelihood function. See tz_kalfiltv() in kalman.c for an illustration. -% -% State space model is defined as follows: -% y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation) -% z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation) -% where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given. -% -% Inputs are as follows: -% Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)]. -% a is an n_y-by-T matrix of time-varying input vectors in the measurement equation. -% H is an n_y-by-n_z-by-T 3-D of time-varying matrices in the measurement equation. -% R is an n_y-by-n_y-by-T 3-D of time-varying covariance matrices for the error in the measurement equation. -% G is an n_z-by-n_y-by-T 3-D of time-varying E(eta_t * eps_t'). -% ------ -% b is an n_z-by-(T+1) matrix of time-varying input vectors in the state equation with b(:,1) as an initial condition. -% F is an n_z-by-n_z-by-(T+1) 3-D of time-varying transition matrices in the state equation with F(:,:,1) as an initial condition. -% V is an n_z-by-n_z-by-(T+1) 3-D of time-varying covariance matrices for the error in the state equation with V(:,:,1) as an initial condition. -% ------ -% indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0 -% (thus, indxDiffuse is automatically not enativated).; -% 0: creating the initial condition depending on indxDiffuse (thus, indxDiffuse is active). -% indxDiffuse: 1: using the diffuse initial condition by setting P=100*I and z=0; -% 0: using the unconditional mean and variance for any given regime at time 0. -% z0 is an n_z-by-1 vector of initial condition when indxIni=1. (Do not enter if indxIni=0.) -% P0 is an n_z-by-n_z matrix of initial condition when indxIni=1. (Do not enter if indxIni=0.) -% -% Outputs are as follows: -% loglh is a value of the log likelihood function of the state-space model -% under the assumption that errors are multivariate Gaussian. -% zt_tm1 is an n_z-by-(T+1) matrices of one-step predicted state vectors with z0_0m1 as a initial condition. -% Pt_tm1 is an n_z-by-n_z-by-(T+1) 3-D of covariance matrices of zt_tm1 with P0_0m1 as a initial condition. -% loglh_t_allvalues is a T-by-1 vector of loglh at time t for t=1:T. -% -% The initial state vector and its covariance matrix are computed under the bounded (stationary) condition: -% z0_0m1 = (I-F(:,:,1))\b(:,1) -% vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1)) -% Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary). -% -% March 2007, written by Tao Zha -% See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003. -%========================================================================== -% Revision history: -% -% -% -%========================================================================== - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -Tp1 = size(Y_T,2) + 1; %T+1; -n_y = size(a,1); -n_z = size(b,1); -%--- Checking input matrix dimensions -if (size(Y_T,1)~=n_y) - error('kalf_tv(): Y_T and a must have the same number of rows') -end -%--- Allocating memory. -zt_tm1 = zeros(n_z,Tp1); -Pt_tm1 = zeros(n_z,n_z,Tp1); -loglh_t_allvalues = zeros(Tp1-1,1); -%--- Initializing. -loglh = 0.0; -if (indxIni) - zt_tm1(:,1) = z0; - Pt_tm1(:,:,1) = P0; -else - if (indxDiffuse) - %See Koopman and Durbin, "Filtering and Smoothing of State Vector for Diffuse State-Space Models," J. of Time Series Analysis, Vol 24(1), pp.85-99. - zt_tm1(:,1) = zeros(n_z, 1); - Pt_tm1(:,:,1) = 100*eye(n_z); - else - eigmax4F = max(abs(eig(F(:,:,1)))); - format long e - eigmax4F - if (eigmax4F < 1.0) - zt_tm1(:,1) = (eye(n_z)-F(:,:,1))\b(:,1); - V1 = V(:,:,1); - Pt_tm1(:,:,1) = reshape((eye(n_z^2)-kron(F(:,:,1),F(:,:,1)))\V1(:) ,n_z,n_z); - else - %--- Do NOT use the following option. It turns out that this will often generate explosive conditional liklihood - %--- at the end of the sample, because Pt_tm1 shrinks to zero overtime due to the sigularity of the initila condition P_{1|0}. - % zt_tm1(:,1) = zeros(size(zt_tm1(:,1))); - % Pt_tm1(:,:,1) = V(:,:,1); %+eye(size(V(:,:,1))); - - nearinfinity = -1.0e+300 - loglh = nearinfinity; - return; %Eearly exit. - %error('kalf_tv(): For non-stationary solutions, the initial conditions must be supplied by, say, input arguments') - end - end -end - - -%====== See p.002 in LiuWZ. ====== -indx_badlh = 0; %1: bad likelihood with, say, -infinity of the LH value. -for t=2:Tp1 - tdata = t-1; - - %--- Setup. - Htdata = H(:,:,tdata); - Htdatatran = Htdata'; - ztdata = zt_tm1(:,tdata); - Ptdata = Pt_tm1(:,:,tdata); - PHtran_tdata = Ptdata*Htdatatran; - Ft = F(:,:,t); - Fttran = Ft'; - - %--- Data. - etdata = Y_T(:,tdata) - a(:,tdata) - Htdata*ztdata; - etdatatran = etdata'; - Dtdata = Htdata*PHtran_tdata + R(:,:,tdata); - Dtdata = 0.5*(Dtdata + Dtdata'); %Making it symmetric against some rounding errors. - %This making-symmetric is very IMPORTANT; otherwise, we will get the matrix being singular message - % and eigenvalues being negative for the SPD matrix, etc. Then the likelihood becomes either - % a bad number or a complex number. - - %--- State (updating). - Kt_tdata = (Ft*PHtran_tdata+G(:,:,tdata))/Dtdata; - Kt_tdatatran = Kt_tdata'; - zt_tm1(:,t) = b(:,t) + Ft*zt_tm1(:,tdata) + Kt_tdata*etdata; - Pt_tm1(:,:,t) = Ft*Ptdata*Fttran - Kt_tdata*Dtdata*Kt_tdatatran + V(:,:,t); - - %--- Forming the log likelihood. - detDtdata = det(Dtdata); - %if (~isfinite(detDtdata)) - if (detDtdata < realmin) - indx_badlh = 1; - break; - else - loglh_tdata = -(0.5*n_y)*log(2*pi) - 0.5*log(detDtdata) - 0.5*(etdatatran/Dtdata)*etdata; - loglh = loglh + loglh_tdata; - loglh_t_allvalues(tdata) = loglh_tdata; - end -end - -if (indx_badlh) - nearinfinity = -1.0e+300; - loglh = nearinfinity; - loglh_t_allvalues(tdata) = nearinfinity; -end - +function [loglh,zt_tm1,Pt_tm1, loglh_t_allvalues] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni, indxDiffuse, z0,P0) +%[loglh,zt_tm1,Pt_tm1, loglh_t_allvalues] = fn_kalfil_tv(Y_T, a, H, R, G, b, F, V, indxIni, indxDiffuse, z0,P0) +%Time-varying Kalman filter (conditional on all the regimes in a Markov-switching model). It computes +% a sequence of one-step predictions and their covariance matrices, and the log likelihood. +% The function uses a forward recursion algorithm. +% +% Note: for b, F, V, zt_tm1, and Pt_tm1, there is not need for the T+1 length because the values at T+1 have +% never been used in the likelihood function. See tz_kalfiltv() in kalman.c for an illustration. +% +% State space model is defined as follows: +% y(t) = a(t) + H(t)*z(t) + eps(t) (observation or measurement equation) +% z(t) = b(t) + F(t)*z(t) + eta(t) (state or transition equation) +% where a(t), H(t), b(t), and F(t) depend on s_t that follows a Markov-chain process and are taken as given. +% +% Inputs are as follows: +% Y_T is a n_y-by-T matrix containing data [y(1), ... , y(T)]. +% a is an n_y-by-T matrix of time-varying input vectors in the measurement equation. +% H is an n_y-by-n_z-by-T 3-D of time-varying matrices in the measurement equation. +% R is an n_y-by-n_y-by-T 3-D of time-varying covariance matrices for the error in the measurement equation. +% G is an n_z-by-n_y-by-T 3-D of time-varying E(eta_t * eps_t'). +% ------ +% b is an n_z-by-(T+1) matrix of time-varying input vectors in the state equation with b(:,1) as an initial condition. +% F is an n_z-by-n_z-by-(T+1) 3-D of time-varying transition matrices in the state equation with F(:,:,1) as an initial condition. +% V is an n_z-by-n_z-by-(T+1) 3-D of time-varying covariance matrices for the error in the state equation with V(:,:,1) as an initial condition. +% ------ +% indxIni: 1: using the initial condition with zt_tm1(:,1)=z0 and Pt_tm1(:,:,1)=P0 +% (thus, indxDiffuse is automatically not enativated).; +% 0: creating the initial condition depending on indxDiffuse (thus, indxDiffuse is active). +% indxDiffuse: 1: using the diffuse initial condition by setting P=100*I and z=0; +% 0: using the unconditional mean and variance for any given regime at time 0. +% z0 is an n_z-by-1 vector of initial condition when indxIni=1. (Do not enter if indxIni=0.) +% P0 is an n_z-by-n_z matrix of initial condition when indxIni=1. (Do not enter if indxIni=0.) +% +% Outputs are as follows: +% loglh is a value of the log likelihood function of the state-space model +% under the assumption that errors are multivariate Gaussian. +% zt_tm1 is an n_z-by-(T+1) matrices of one-step predicted state vectors with z0_0m1 as a initial condition. +% Pt_tm1 is an n_z-by-n_z-by-(T+1) 3-D of covariance matrices of zt_tm1 with P0_0m1 as a initial condition. +% loglh_t_allvalues is a T-by-1 vector of loglh at time t for t=1:T. +% +% The initial state vector and its covariance matrix are computed under the bounded (stationary) condition: +% z0_0m1 = (I-F(:,:,1))\b(:,1) +% vec(P0_0m1) = (I-kron(F(:,:,1),F(:,:,1)))\vec(V(:,:,1)) +% Note that all eigenvalues of the matrix F(:,:,1) are inside the unit circle when the state-space model is bounded (stationary). +% +% March 2007, written by Tao Zha +% See Hamilton's book ([13.2.13] -- [13.2.22]), Harvey (pp.100-106), and LiuWZ Model I NOTES pp.001-003. +%========================================================================== +% Revision history: +% +% +% +%========================================================================== + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +Tp1 = size(Y_T,2) + 1; %T+1; +n_y = size(a,1); +n_z = size(b,1); +%--- Checking input matrix dimensions +if (size(Y_T,1)~=n_y) + error('kalf_tv(): Y_T and a must have the same number of rows') +end +%--- Allocating memory. +zt_tm1 = zeros(n_z,Tp1); +Pt_tm1 = zeros(n_z,n_z,Tp1); +loglh_t_allvalues = zeros(Tp1-1,1); +%--- Initializing. +loglh = 0.0; +if (indxIni) + zt_tm1(:,1) = z0; + Pt_tm1(:,:,1) = P0; +else + if (indxDiffuse) + %See Koopman and Durbin, "Filtering and Smoothing of State Vector for Diffuse State-Space Models," J. of Time Series Analysis, Vol 24(1), pp.85-99. + zt_tm1(:,1) = zeros(n_z, 1); + Pt_tm1(:,:,1) = 100*eye(n_z); + else + eigmax4F = max(abs(eig(F(:,:,1)))); + format long e + eigmax4F + if (eigmax4F < 1.0) + zt_tm1(:,1) = (eye(n_z)-F(:,:,1))\b(:,1); + V1 = V(:,:,1); + Pt_tm1(:,:,1) = reshape((eye(n_z^2)-kron(F(:,:,1),F(:,:,1)))\V1(:) ,n_z,n_z); + else + %--- Do NOT use the following option. It turns out that this will often generate explosive conditional liklihood + %--- at the end of the sample, because Pt_tm1 shrinks to zero overtime due to the sigularity of the initila condition P_{1|0}. + % zt_tm1(:,1) = zeros(size(zt_tm1(:,1))); + % Pt_tm1(:,:,1) = V(:,:,1); %+eye(size(V(:,:,1))); + + nearinfinity = -1.0e+300 + loglh = nearinfinity; + return; %Eearly exit. + %error('kalf_tv(): For non-stationary solutions, the initial conditions must be supplied by, say, input arguments') + end + end +end + + +%====== See p.002 in LiuWZ. ====== +indx_badlh = 0; %1: bad likelihood with, say, -infinity of the LH value. +for t=2:Tp1 + tdata = t-1; + + %--- Setup. + Htdata = H(:,:,tdata); + Htdatatran = Htdata'; + ztdata = zt_tm1(:,tdata); + Ptdata = Pt_tm1(:,:,tdata); + PHtran_tdata = Ptdata*Htdatatran; + Ft = F(:,:,t); + Fttran = Ft'; + + %--- Data. + etdata = Y_T(:,tdata) - a(:,tdata) - Htdata*ztdata; + etdatatran = etdata'; + Dtdata = Htdata*PHtran_tdata + R(:,:,tdata); + Dtdata = 0.5*(Dtdata + Dtdata'); %Making it symmetric against some rounding errors. + %This making-symmetric is very IMPORTANT; otherwise, we will get the matrix being singular message + % and eigenvalues being negative for the SPD matrix, etc. Then the likelihood becomes either + % a bad number or a complex number. + + %--- State (updating). + Kt_tdata = (Ft*PHtran_tdata+G(:,:,tdata))/Dtdata; + Kt_tdatatran = Kt_tdata'; + zt_tm1(:,t) = b(:,t) + Ft*zt_tm1(:,tdata) + Kt_tdata*etdata; + Pt_tm1(:,:,t) = Ft*Ptdata*Fttran - Kt_tdata*Dtdata*Kt_tdatatran + V(:,:,t); + + %--- Forming the log likelihood. + detDtdata = det(Dtdata); + %if (~isfinite(detDtdata)) + if (detDtdata < realmin) + indx_badlh = 1; + break; + else + loglh_tdata = -(0.5*n_y)*log(2*pi) - 0.5*log(detDtdata) - 0.5*(etdatatran/Dtdata)*etdata; + loglh = loglh + loglh_tdata; + loglh_t_allvalues(tdata) = loglh_tdata; + end +end + +if (indx_badlh) + nearinfinity = -1.0e+300; + loglh = nearinfinity; + loglh_t_allvalues(tdata) = nearinfinity; +end + diff --git a/MatlabFiles/fn_logsum.m b/MatlabFiles/fn_logsum.m index a891cf85147bc1b0124a4106fb52ecc200f9ae45..436905fdf502bcb5e3016d715756bf6effb767d8 100644 --- a/MatlabFiles/fn_logsum.m +++ b/MatlabFiles/fn_logsum.m @@ -1,38 +1,38 @@ -function [log_sum, log_max] = fn_logsum(log_sum, log_max, log_new) -% [log_sum, log_max] = fn_logsum(log_sum, log_max, log_new) -% -%Outputs: -% log_sum: updated log(sum of x_1, ..., x_{N+1}) -% log_max: updated max of log(x_1), ..., log(x_{N+1}). -%-------------- -%Inputs: -% log_sum: log(sum of x_1, ..., x_N) -% log_max: max of log(x_1), ..., log(x_N). -% log_new: log(x_{N+1}). -% -%Written by T. Zha; 12:20PM 06/28/2005 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%=== Updates log_sumpdf with an additional pdf value. See TVBVAR Notes p.81a. -if (log_max>=log_new) - log_sum = log( exp(log_sum-log_max) + exp(log_new-log_max) ) + log_max; -else - log_sum = log( exp(log_sum-log_new) + 1.0 ) + log_new; - log_max = log_new; -end +function [log_sum, log_max] = fn_logsum(log_sum, log_max, log_new) +% [log_sum, log_max] = fn_logsum(log_sum, log_max, log_new) +% +%Outputs: +% log_sum: updated log(sum of x_1, ..., x_{N+1}) +% log_max: updated max of log(x_1), ..., log(x_{N+1}). +%-------------- +%Inputs: +% log_sum: log(sum of x_1, ..., x_N) +% log_max: max of log(x_1), ..., log(x_N). +% log_new: log(x_{N+1}). +% +%Written by T. Zha; 12:20PM 06/28/2005 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%=== Updates log_sumpdf with an additional pdf value. See TVBVAR Notes p.81a. +if (log_max>=log_new) + log_sum = log( exp(log_sum-log_max) + exp(log_new-log_max) ) + log_max; +else + log_sum = log( exp(log_sum-log_new) + 1.0 ) + log_new; + log_max = log_new; +end diff --git a/MatlabFiles/fn_mimfgraph.m b/MatlabFiles/fn_mimfgraph.m index f21aecd167a6f5b655e4a74b5a7f1b2c3f61932a..2dc83dd0ed01efce8ecf606a1392235030347296 100644 --- a/MatlabFiles/fn_mimfgraph.m +++ b/MatlabFiles/fn_mimfgraph.m @@ -1,152 +1,152 @@ -function scaleout = fn_mimfgraph(imfe,nvar,q_m,imstp,xlab,ylab,tlab,xTick) -% mimfgraph: multiple impulse functions plotted in subplots put in one chart. -% -% imfe: imstp-by-n^2+2-by-h series data with dates in the first 2 columns in the order of year and month (or quarter). -% imstp: the number of impulse response steps. -% nvar^2+2: n series plus the first 2 columns indicating dates. For the last nvar^2 columns, -% the order is: nvar responses to the 1st shock, ..., nvar responses to the last shock. -% h: The number of sereies on the 3rd dimension, put in the same subplot as in each of the n series. -% The first 2 columns in the 3rd dimension can be NaN while some other columns -% are also allowed to be NaN if no data are available. -% The last 2 columns in the 3rd dimension must be used for error bands if "area" -% is used to plot these bands. -% nvar: number of variables -% q_m: monthly (12) or quarterly (4) -% imstp: number of steps of impulse responses -% xlab,ylab,tlab: x-axis, y-axis, and title labels -% xTick: optional. Eg: [12 24 36]. -%--------------- -% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. -% -% See ftd_mseriesgraph.m and fn_mseriesgraph.m -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin < 7, xTick = []; end - -if nvar^2~=size(imfe,2)-2 - disp(' ') - warning('The number of columns in imfe must be nvar^2+2 (columns of dates)') - disp('Press ctrl-c to abort') - pause -end - - - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -minval=zeros(nvar,1); % for each variable to nvar shocks -maxval=zeros(nvar,1); % for each variable to nvar shocks -for i = 1:nvar % variable - for j = 1:nvar % shock - tmpimf = squeeze(imfe(:,2+(j-1)*nvar+i,:)); - temp1(j) = min(min(tmpimf)); - temp2(j) = max(max(tmpimf)); - end - minval(i)=min(temp1); - maxval(i)=max(temp2); -end - -scaleout = [minval(:) maxval(:)]; - -%-------------- -% Column j: Shocks 1 to N; Row i: Variable responses to -%------------- - -rowlabel = 1; -for i = 1:nvar % variable - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - scale=[1 imstp minval(i) maxval(i)]; - for j = 1:nvar % shock - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - if 0 % Plot area for error bands at the last two 3-rd dimensions. - area(imfe(:,1)+imfe(:,2)/q_m,squeeze(imfe(:,2+k2,end)),-100,'EdgeColor','none','FaceColor','y') % yellow - hold on - area(imfe(:,1)+imfe(:,2)/q_m,squeeze(imfe(:,2+k2,end-1)),-100,'EdgeColor','none','FaceColor',[1 1 1]) % white - set(gca,'ColorOrder',[0 0 0]); % turn the color off and set it to black - set(gca,'LineStyleOrder', '-|-.|--|:'); % cycle through the newly defined LineSytleOrder - plot(t,squeeze(imfe(:,2+k2,1:end-2)),t,zeros(length(imfe(:,k2)),1),'-'); - set(gca,'Layer','top') - hold off - else % No error bands plotted - %=== set color to black and cycle through the newly defined LineSytleOrder - set(0,'DefaultAxesColorOrder',[0 0 0], ... - 'DefaultAxesLineStyleOrder','-|-.|--|:') - %set(gca,'ColorOrder',[0 0 0]); % turn the color off and set it to black - %set(gca,'LineStyleOrder', '-|-.|--|:'); % cycle through the newly defined LineSytleOrder - plot(t,squeeze(imfe(:,2+k2,1:end)),t,zeros(length(imfe(:,k2)),1),'-'); - end - if 1 % Get legends - if (i==2) & (j==3) % | (i==6) - legend('Const','S1','S2','S3',0) - % legend('Actual Data','Absent policy shocks',0) - end - end - - set(gca,'XTick',xTick) - set(gca,'YTick',yt) - grid - - axis(scale); % put limits on both axes. - %set(gca,'YLim',[minval(i) maxval(i)]) % put the limit only on the y-axis - if isempty(xTick) %1 % no numbers on axes - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - else % put numbers on both axes - if i<nvar - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - if j>1 - set(gca,'YTickLabel',' '); - end - end - - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; -end - -subtitle(tlab) +function scaleout = fn_mimfgraph(imfe,nvar,q_m,imstp,xlab,ylab,tlab,xTick) +% mimfgraph: multiple impulse functions plotted in subplots put in one chart. +% +% imfe: imstp-by-n^2+2-by-h series data with dates in the first 2 columns in the order of year and month (or quarter). +% imstp: the number of impulse response steps. +% nvar^2+2: n series plus the first 2 columns indicating dates. For the last nvar^2 columns, +% the order is: nvar responses to the 1st shock, ..., nvar responses to the last shock. +% h: The number of sereies on the 3rd dimension, put in the same subplot as in each of the n series. +% The first 2 columns in the 3rd dimension can be NaN while some other columns +% are also allowed to be NaN if no data are available. +% The last 2 columns in the 3rd dimension must be used for error bands if "area" +% is used to plot these bands. +% nvar: number of variables +% q_m: monthly (12) or quarterly (4) +% imstp: number of steps of impulse responses +% xlab,ylab,tlab: x-axis, y-axis, and title labels +% xTick: optional. Eg: [12 24 36]. +%--------------- +% scaleout: column 1 represents maximums; column 2 minimums. Rows: nvar variables. +% +% See ftd_mseriesgraph.m and fn_mseriesgraph.m +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin < 7, xTick = []; end + +if nvar^2~=size(imfe,2)-2 + disp(' ') + warning('The number of columns in imfe must be nvar^2+2 (columns of dates)') + disp('Press ctrl-c to abort') + pause +end + + + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +minval=zeros(nvar,1); % for each variable to nvar shocks +maxval=zeros(nvar,1); % for each variable to nvar shocks +for i = 1:nvar % variable + for j = 1:nvar % shock + tmpimf = squeeze(imfe(:,2+(j-1)*nvar+i,:)); + temp1(j) = min(min(tmpimf)); + temp2(j) = max(max(tmpimf)); + end + minval(i)=min(temp1); + maxval(i)=max(temp2); +end + +scaleout = [minval(:) maxval(:)]; + +%-------------- +% Column j: Shocks 1 to N; Row i: Variable responses to +%------------- + +rowlabel = 1; +for i = 1:nvar % variable + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + scale=[1 imstp minval(i) maxval(i)]; + for j = 1:nvar % shock + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + if 0 % Plot area for error bands at the last two 3-rd dimensions. + area(imfe(:,1)+imfe(:,2)/q_m,squeeze(imfe(:,2+k2,end)),-100,'EdgeColor','none','FaceColor','y') % yellow + hold on + area(imfe(:,1)+imfe(:,2)/q_m,squeeze(imfe(:,2+k2,end-1)),-100,'EdgeColor','none','FaceColor',[1 1 1]) % white + set(gca,'ColorOrder',[0 0 0]); % turn the color off and set it to black + set(gca,'LineStyleOrder', '-|-.|--|:'); % cycle through the newly defined LineSytleOrder + plot(t,squeeze(imfe(:,2+k2,1:end-2)),t,zeros(length(imfe(:,k2)),1),'-'); + set(gca,'Layer','top') + hold off + else % No error bands plotted + %=== set color to black and cycle through the newly defined LineSytleOrder + set(0,'DefaultAxesColorOrder',[0 0 0], ... + 'DefaultAxesLineStyleOrder','-|-.|--|:') + %set(gca,'ColorOrder',[0 0 0]); % turn the color off and set it to black + %set(gca,'LineStyleOrder', '-|-.|--|:'); % cycle through the newly defined LineSytleOrder + plot(t,squeeze(imfe(:,2+k2,1:end)),t,zeros(length(imfe(:,k2)),1),'-'); + end + if 1 % Get legends + if (i==2) & (j==3) % | (i==6) + legend('Const','S1','S2','S3',0) + % legend('Actual Data','Absent policy shocks',0) + end + end + + set(gca,'XTick',xTick) + set(gca,'YTick',yt) + grid + + axis(scale); % put limits on both axes. + %set(gca,'YLim',[minval(i) maxval(i)]) % put the limit only on the y-axis + if isempty(xTick) %1 % no numbers on axes + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + else % put numbers on both axes + if i<nvar + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + if j>1 + set(gca,'YTickLabel',' '); + end + end + + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; +end + +subtitle(tlab) diff --git a/MatlabFiles/fn_mseriesgraph.m b/MatlabFiles/fn_mseriesgraph.m index 78d3d5dcc774c5845cac74c6b59284f992852105..8c2c9f1cd03714e0e366a8103e142382007b43c4 100644 --- a/MatlabFiles/fn_mseriesgraph.m +++ b/MatlabFiles/fn_mseriesgraph.m @@ -1,83 +1,83 @@ -function fn_mseriesgraph(ydate,keyindx,rnum,cnum,q_m,xlab,ylab,tlab) -% fn_mseriesgraph(ydate,keyindx,rnum,cnum,q_m,xlab,ylab,tlab) -% Graph actual series or point forecasts or both (annual or monthly or quarterly) -% with multiple series in one subplot. -% -% ydate: T-by-n+2-by-h series data with dates in the first 2 columns in the order of year and month (or quarter). -% T: the length of an individual series. -% n+2: n series plus the first 2 columns indicating dates. -% h: the number of sereies on the 3rd dimension, put in the same subplot as in each of the n series. -% Thus, the first 2 columns in the 3rd dimension can be NaN while -% some elements are also allowed to be NaN if no data are available. -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -% q_m: if 4 or 12, quarterly or monthly data -% xlab: 1-by-1 x-axis label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -% ylab: string array for the length(keyindx)-by-1 variables -% tlab: 1-by-1 title label for (e.g., as of time of forecast) -%------------- -% No output argument for this graph file -% See fn_foregraph.m, fn_forerrgraph.m. -% -% Tao Zha, September 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -vyrs = ydate(:,1); % vector column -hornum = cell(length(vyrs),1); % horizontal year (number) -count=0; -for k=vyrs' - count=count+1; - jnk=num2str(k); - if length(jnk)==4 % years - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' - else - hornum{count}=jnk; % e.g., with '1', '2', ... - end -end - -if rnum*cnum<length(keyindx) - disp(' ') - warning('The total number of subplots must be greater that the number of selected series for graphing!') - disp('Press ctrl-c to abort') - pause -end - -count=0; -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - plot(ydate(:,1)+ydate(:,2)/q_m,squeeze(ydate(:,2+i,:)),... - ydate(:,1)+ydate(:,2)/q_m,zeros(length(vyrs),1),'-') - - if (ydate(1,2)==0) & (length(num2str(ydate(1,1)))==4) % only for annual growth rates (not for, say, monthly annualized rates) - set(gca,'XLim',[vyrs(1) vyrs(end)]) - set(gca,'XTick',vyrs) - set(gca,'XTickLabel',char(hornum)) - end - - if i==keyindx(1) - title(tlab) - elseif i>=length(keyindx) %i>=length(keyindx)-1 - xlabel(xlab) - end - % - grid - ylabel(char(ylab(i))) -end +function fn_mseriesgraph(ydate,keyindx,rnum,cnum,q_m,xlab,ylab,tlab) +% fn_mseriesgraph(ydate,keyindx,rnum,cnum,q_m,xlab,ylab,tlab) +% Graph actual series or point forecasts or both (annual or monthly or quarterly) +% with multiple series in one subplot. +% +% ydate: T-by-n+2-by-h series data with dates in the first 2 columns in the order of year and month (or quarter). +% T: the length of an individual series. +% n+2: n series plus the first 2 columns indicating dates. +% h: the number of sereies on the 3rd dimension, put in the same subplot as in each of the n series. +% Thus, the first 2 columns in the 3rd dimension can be NaN while +% some elements are also allowed to be NaN if no data are available. +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +% q_m: if 4 or 12, quarterly or monthly data +% xlab: 1-by-1 x-axis label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +% ylab: string array for the length(keyindx)-by-1 variables +% tlab: 1-by-1 title label for (e.g., as of time of forecast) +%------------- +% No output argument for this graph file +% See fn_foregraph.m, fn_forerrgraph.m. +% +% Tao Zha, September 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +vyrs = ydate(:,1); % vector column +hornum = cell(length(vyrs),1); % horizontal year (number) +count=0; +for k=vyrs' + count=count+1; + jnk=num2str(k); + if length(jnk)==4 % years + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' + else + hornum{count}=jnk; % e.g., with '1', '2', ... + end +end + +if rnum*cnum<length(keyindx) + disp(' ') + warning('The total number of subplots must be greater that the number of selected series for graphing!') + disp('Press ctrl-c to abort') + pause +end + +count=0; +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + plot(ydate(:,1)+ydate(:,2)/q_m,squeeze(ydate(:,2+i,:)),... + ydate(:,1)+ydate(:,2)/q_m,zeros(length(vyrs),1),'-') + + if (ydate(1,2)==0) & (length(num2str(ydate(1,1)))==4) % only for annual growth rates (not for, say, monthly annualized rates) + set(gca,'XLim',[vyrs(1) vyrs(end)]) + set(gca,'XTick',vyrs) + set(gca,'XTickLabel',char(hornum)) + end + + if i==keyindx(1) + title(tlab) + elseif i>=length(keyindx) %i>=length(keyindx)-1 + xlabel(xlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/fn_msv_sw.m b/MatlabFiles/fn_msv_sw.m index 8d3756a5d9944dc357c9a94c67fe5044439e8a16..6cefecbfd6231e0d450e133ab529549da3c229f7 100644 --- a/MatlabFiles/fn_msv_sw.m +++ b/MatlabFiles/fn_msv_sw.m @@ -1,78 +1,78 @@ -function [G1cell_sw, err] = fn_msv_sw(G1cell_0, A11cell, A12cell, A21cell, A22cell, Hcell, P) -%G1cell_sw = fn_msv_sw(G1cell_0, A11cell, A12cell, A21cell, A22cell, Hcell,P) -% -% Model: X_{t+1} = A11_{t+1} X_t + A12_{t+1} x_t + C_{t+1} episilon_{t+1} -% E_t(H_{t+1} x_{t+1}) = A21_t X_t + A22_t x_t -% Solution: x_t = G1_t X_t where G1_t is nx-by-nX. -% -%Output: -% G1cell_sw: solution. -% err: if the value > sqrt(eps), then not converged ==> no solution. -%Inputs: -% G1cell_0: initial guess (starting point) for the Svensson-William algorithm. -% If G1cell_0 is empty, G1_0 will be randomly selected. -% A11cell, A12cell, A21cell, A22cell, and Hcell are all ns-by-1 cells -- the model coefficients depending on regime. -% In each cell, the dimensions must be -% A11=zeros(nX,nX); A12=zeros(nX,nx); -% A21=zeros(nx,nX); A22=zeros(nx,nx); -% H=diag(ones(nx,1)); -% P: ns-by-ns transition matrix with each column summing up to 1. -% -% See ZhaNotes on FWZ MSV solution, p. AA.1. For the SW solution, see (7) on p. AA.1. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -%--- Convergence criteria -tol = 1.0e-09; -maxiter = 1e+04; - -%--- Dimensions. -ns = length(A11cell); %number of states (regimes) -nX = size(A11cell{1},1); -nx = size(A22cell{1},1); - -%--- Initialization. -if isempty(G1cell_0) - G1cell_0 = cell(ns,1); - for si=1:ns - G1cell_0{si} = 1000.0*randn(nx,nX); - end -end - -%====== Iterative procedure. ====== -Gerr = zeros(ns,1); -err = 1.0; -iter = 1; -while ( (iter<maxiter) && (err>tol) ) - for j=1:ns - M1 = zeros(nx,nx); - M2 = zeros(nx,nX); - for k=1:ns - HGk = Hcell{k}*G1cell_0{k}; - M1 = M1 + P(k,j)*HGk*A12cell{k}; - M2 = M2 + P(k,j)*HGk*A11cell{k}; - end % k loop - Mden = A22cell{j} - M1; - Mnum = M2 - A21cell{j}; - G1cell_sw{j} = Mden\Mnum; - Gerr(j)=norm(G1cell_sw{j} - G1cell_0{j}); - G1cell_0{j} = G1cell_sw{j}; % Updated for the next iteration. - end %j loop - err=sum(Gerr); - iter=iter+1; -end % err loop - +function [G1cell_sw, err] = fn_msv_sw(G1cell_0, A11cell, A12cell, A21cell, A22cell, Hcell, P) +%G1cell_sw = fn_msv_sw(G1cell_0, A11cell, A12cell, A21cell, A22cell, Hcell,P) +% +% Model: X_{t+1} = A11_{t+1} X_t + A12_{t+1} x_t + C_{t+1} episilon_{t+1} +% E_t(H_{t+1} x_{t+1}) = A21_t X_t + A22_t x_t +% Solution: x_t = G1_t X_t where G1_t is nx-by-nX. +% +%Output: +% G1cell_sw: solution. +% err: if the value > sqrt(eps), then not converged ==> no solution. +%Inputs: +% G1cell_0: initial guess (starting point) for the Svensson-William algorithm. +% If G1cell_0 is empty, G1_0 will be randomly selected. +% A11cell, A12cell, A21cell, A22cell, and Hcell are all ns-by-1 cells -- the model coefficients depending on regime. +% In each cell, the dimensions must be +% A11=zeros(nX,nX); A12=zeros(nX,nx); +% A21=zeros(nx,nX); A22=zeros(nx,nx); +% H=diag(ones(nx,1)); +% P: ns-by-ns transition matrix with each column summing up to 1. +% +% See ZhaNotes on FWZ MSV solution, p. AA.1. For the SW solution, see (7) on p. AA.1. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +%--- Convergence criteria +tol = 1.0e-09; +maxiter = 1e+04; + +%--- Dimensions. +ns = length(A11cell); %number of states (regimes) +nX = size(A11cell{1},1); +nx = size(A22cell{1},1); + +%--- Initialization. +if isempty(G1cell_0) + G1cell_0 = cell(ns,1); + for si=1:ns + G1cell_0{si} = 1000.0*randn(nx,nX); + end +end + +%====== Iterative procedure. ====== +Gerr = zeros(ns,1); +err = 1.0; +iter = 1; +while ( (iter<maxiter) && (err>tol) ) + for j=1:ns + M1 = zeros(nx,nx); + M2 = zeros(nx,nX); + for k=1:ns + HGk = Hcell{k}*G1cell_0{k}; + M1 = M1 + P(k,j)*HGk*A12cell{k}; + M2 = M2 + P(k,j)*HGk*A11cell{k}; + end % k loop + Mden = A22cell{j} - M1; + Mnum = M2 - A21cell{j}; + G1cell_sw{j} = Mden\Mnum; + Gerr(j)=norm(G1cell_sw{j} - G1cell_0{j}); + G1cell_0{j} = G1cell_sw{j}; % Updated for the next iteration. + end %j loop + err=sum(Gerr); + iter=iter+1; +end % err loop + diff --git a/MatlabFiles/fn_mtpdf.m b/MatlabFiles/fn_mtpdf.m index f4085fcb761dc24336c2e59007c41de220d10e58..4087aa9d8c16ded5afc030b7258e5d12def3fa60 100644 --- a/MatlabFiles/fn_mtpdf.m +++ b/MatlabFiles/fn_mtpdf.m @@ -1,54 +1,54 @@ -function y = fn_mtpdf(x,xm,C,v,covIx,constIx) -% y = mtpdf(x,xm,C,v,covIx,constIx) -% The pdf value for multivariate Student t distribution allowing many values (draws) stored in columns. -% -% x: p-by-draws matrix of values evaluated at where p=size(x,1) is # of variables -% xm: p-by-draws matrix of the mean of x -% C: p-by-p Choleski square root of PDS S, which is the covariance matrix in the normal case -% so that S = C*C'. That is, C=chol(S)' (notice the transpose ' here). -% v (>0): A scalar value for the degrees of freedom. -% covIx: An index for a decomposition of the covariance matrix. If 1, C=chol(S)' (notice the transpose '); -% if 0, C=chol(inv(S)) (note that there is no transpose here). -% constIx: An index for the constant. 1: constant (normalized); 0: no constant (unnormalized) -%---------- -% y: p-by-draws matrix of pdf's for multivariate Student t distribution with v degrees of freedom -% -% Christian P. Robert, "The Bayesian Choice," Springer-Verlag, New York, 1994, -% p. 382. -% -% Tao Zha, December 1998; Revised, January 2002. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -[p,nx]=size(x); -if covIx - z = C\(x-xm); -else - z = C*(x-xm); -end - - -if constIx - dSh=sum(log(diag(C))); % (detSigma)^(1/2) - %* Use gammaln function to avoid overflows. - term = exp(gammaln((v + p) / 2) - gammaln(v/2) - dSh); - y = (term*(v*pi)^(-p/2)) * (1 + sum(z.*z,1)/v).^(-(v + p)/2); - y = y'; -else - y = (1 + sum(z.*z,1)/v).^(-(v + p)/2); - y = y'; -end +function y = fn_mtpdf(x,xm,C,v,covIx,constIx) +% y = mtpdf(x,xm,C,v,covIx,constIx) +% The pdf value for multivariate Student t distribution allowing many values (draws) stored in columns. +% +% x: p-by-draws matrix of values evaluated at where p=size(x,1) is # of variables +% xm: p-by-draws matrix of the mean of x +% C: p-by-p Choleski square root of PDS S, which is the covariance matrix in the normal case +% so that S = C*C'. That is, C=chol(S)' (notice the transpose ' here). +% v (>0): A scalar value for the degrees of freedom. +% covIx: An index for a decomposition of the covariance matrix. If 1, C=chol(S)' (notice the transpose '); +% if 0, C=chol(inv(S)) (note that there is no transpose here). +% constIx: An index for the constant. 1: constant (normalized); 0: no constant (unnormalized) +%---------- +% y: p-by-draws matrix of pdf's for multivariate Student t distribution with v degrees of freedom +% +% Christian P. Robert, "The Bayesian Choice," Springer-Verlag, New York, 1994, +% p. 382. +% +% Tao Zha, December 1998; Revised, January 2002. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +[p,nx]=size(x); +if covIx + z = C\(x-xm); +else + z = C*(x-xm); +end + + +if constIx + dSh=sum(log(diag(C))); % (detSigma)^(1/2) + %* Use gammaln function to avoid overflows. + term = exp(gammaln((v + p) / 2) - gammaln(v/2) - dSh); + y = (term*(v*pi)^(-p/2)) * (1 + sum(z.*z,1)/v).^(-(v + p)/2); + y = y'; +else + y = (1 + sum(z.*z,1)/v).^(-(v + p)/2); + y = y'; +end diff --git a/MatlabFiles/fn_multigraph1.m b/MatlabFiles/fn_multigraph1.m index f8f96f56b9a2333af28d4b50e8a4f7d51a1786fe..a6435241401f0bea57379d1ddb7e0ba8b428c270 100644 --- a/MatlabFiles/fn_multigraph1.m +++ b/MatlabFiles/fn_multigraph1.m @@ -1,126 +1,126 @@ -function scaleout = fn_multigraph1(imf1,nrow,ncol,xlab,ylab,XTick,YTickIndx,scaleIndx) -%Plot only one set of impulse responses in one graph. See fn_multigraph2.m. -%imf1 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as regimes 1 and 2. -% imf: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in -% the graphics), 3rd D: across "ncol" different situations (column in -% the graphics) -% nrow: # of rows for the graphics -% ncol: # of columns for the graphics -% YTickIndx: 1: enable YTick; 0: disable -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imf1,1); -t = 1:nstp; -nrow; -ncol; - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - %jnk3=max(firsth1(:,i,j)); - %jnk4=max(imf2(:,i,j)); - jnk5=max(imf1(:,i,j)); - - temp1(j)=max([jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - %jnk3=min(firstl1(:,i,j)); - %jnk4=min(imf2(:,i,j)); - jnk5=min(imf1(:,i,j)); - - temp2(j)=min([jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: situation 1 to N; Row i: variables (ie responses to) -%------------- -%figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrow,ncol,k1) - plot(t,imf1(:,i,j)) %,t,imf2(:,i,j),'--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if j>1 - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - if i==nrow - xlabel('Quarters') - end - columnlabel = 0; - end - rowlabel = 0; -end +function scaleout = fn_multigraph1(imf1,nrow,ncol,xlab,ylab,XTick,YTickIndx,scaleIndx) +%Plot only one set of impulse responses in one graph. See fn_multigraph2.m. +%imf1 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as regimes 1 and 2. +% imf: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in +% the graphics), 3rd D: across "ncol" different situations (column in +% the graphics) +% nrow: # of rows for the graphics +% ncol: # of columns for the graphics +% YTickIndx: 1: enable YTick; 0: disable +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imf1,1); +t = 1:nstp; +nrow; +ncol; + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + %jnk3=max(firsth1(:,i,j)); + %jnk4=max(imf2(:,i,j)); + jnk5=max(imf1(:,i,j)); + + temp1(j)=max([jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + %jnk3=min(firstl1(:,i,j)); + %jnk4=min(imf2(:,i,j)); + jnk5=min(imf1(:,i,j)); + + temp2(j)=min([jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: situation 1 to N; Row i: variables (ie responses to) +%------------- +%figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrow,ncol,k1) + plot(t,imf1(:,i,j)) %,t,imf2(:,i,j),'--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if j>1 + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + if i==nrow + xlabel('Quarters') + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/fn_multigraph1_ver2.m b/MatlabFiles/fn_multigraph1_ver2.m index 46b422f5c156f5a67f5cd0d9c59da28eb8eebcd7..874f9307a7e10e334ca9f58391de6b8d7be01c47 100644 --- a/MatlabFiles/fn_multigraph1_ver2.m +++ b/MatlabFiles/fn_multigraph1_ver2.m @@ -1,139 +1,139 @@ -function scaleout = fn_multigraph1_ver2(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -%scaleout = fn_multigraph1_ver2(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -% -% Version 2 for plotting only one set of impulse responses in one graph. See fn_multigraph2.m. -% imf1 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as shocks or regimes. -% imf1: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in -% the graphics), 3rd D: across "ncol" different situations such as shocks or regimes (column in the graphics) -% xlab: x-axis labels on the top -% ylab: y-axis labels on the left -% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom -% YTickIndx: 1: enable YTick; 0: disable; -% To get a better picture, it is sometimes better to set YtickIndx to zero. -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% nrowg: number of rows in the graph -% ncolg: number of columns in the graph -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imf1,1); -nrow = size(imf1,2); -ncol = size(imf1,3); -t = 1:nstp; - -if (nargin < 8) - nrowg = nrow; - ncolg = ncol; -end -if (nrowg*ncolg < nrow*ncol) - error('fn_multigraph1_ver2.m: nrowg*ncolg must equal to or less than nrow*ncol') -end - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - %jnk3=max(firsth1(:,i,j)); - %jnk4=max(imf2(:,i,j)); - jnk5=max(imf1(:,i,j)); - - temp1(j)=max([jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - %jnk3=min(firstl1(:,i,j)); - %jnk4=min(imf2(:,i,j)); - jnk5=min(imf1(:,i,j)); - - temp2(j)=min([jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: situation 1 to N; Row i: variables (ie responses to) -%------------- -%figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrowg,ncolg,k1) - plot(t,imf1(:,i,j)) %,t,imf2(:,i,j),'--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if (scaleIndx) && (j>1) - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - if i==nrow - xlabel(tstring) - end - columnlabel = 0; - end - rowlabel = 0; -end +function scaleout = fn_multigraph1_ver2(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +%scaleout = fn_multigraph1_ver2(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +% +% Version 2 for plotting only one set of impulse responses in one graph. See fn_multigraph2.m. +% imf1 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as shocks or regimes. +% imf1: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in +% the graphics), 3rd D: across "ncol" different situations such as shocks or regimes (column in the graphics) +% xlab: x-axis labels on the top +% ylab: y-axis labels on the left +% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom +% YTickIndx: 1: enable YTick; 0: disable; +% To get a better picture, it is sometimes better to set YtickIndx to zero. +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% nrowg: number of rows in the graph +% ncolg: number of columns in the graph +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imf1,1); +nrow = size(imf1,2); +ncol = size(imf1,3); +t = 1:nstp; + +if (nargin < 8) + nrowg = nrow; + ncolg = ncol; +end +if (nrowg*ncolg < nrow*ncol) + error('fn_multigraph1_ver2.m: nrowg*ncolg must equal to or less than nrow*ncol') +end + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + %jnk3=max(firsth1(:,i,j)); + %jnk4=max(imf2(:,i,j)); + jnk5=max(imf1(:,i,j)); + + temp1(j)=max([jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + %jnk3=min(firstl1(:,i,j)); + %jnk4=min(imf2(:,i,j)); + jnk5=min(imf1(:,i,j)); + + temp2(j)=min([jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: situation 1 to N; Row i: variables (ie responses to) +%------------- +%figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrowg,ncolg,k1) + plot(t,imf1(:,i,j)) %,t,imf2(:,i,j),'--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if (scaleIndx) && (j>1) + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + if i==nrow + xlabel(tstring) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/fn_multigraph1_ver2_all_labels.m b/MatlabFiles/fn_multigraph1_ver2_all_labels.m index 4d359fcb1b73245efc98724ecb24d39deca9ade0..455e662d9021252dbf17825bce5bcbb92b1d37a9 100644 --- a/MatlabFiles/fn_multigraph1_ver2_all_labels.m +++ b/MatlabFiles/fn_multigraph1_ver2_all_labels.m @@ -1,144 +1,144 @@ -function scaleout = fn_multigraph1_ver2_all_labels(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -%scaleout = fn_multigraph1_ver2_all_labels(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -% -% Version 2 for plotting only one set of impulse responses in one graph. See fn_multigraph1_ver2. -% imf1 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as shocks or regimes. -% imf1: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in -% the graphics), 3rd D: across "ncol" different situations such as shocks or regimes (column in the graphics) -% xlab: x-axis labels on the top. Use [] if no label is needed. -% ylab: y-axis labels on the left. Use [] if no label is needed. -% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom. Use [] if no label is needed. -% YTickIndx: 1: enable YTick; 0: disable. Often set to zero to get a better picture. -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% nrowg: number of rows in the graph -% ncolg: number of columns in the graph -% -% See fn_multigraph1_ver2, imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imf1,1); -nrow = size(imf1,2); -ncol = size(imf1,3); -t = 1:nstp; - -if (nargin < 8) - nrowg = nrow; - ncolg = ncol; -end -if (nrowg*ncolg < nrow*ncol) - error('fn_multigraph1_ver2.m: nrowg*ncolg must equal to or greater than nrow*ncol') -end - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - %jnk3=max(firsth1(:,i,j)); - %jnk4=max(imf2(:,i,j)); - jnk5=max(imf1(:,i,j)); - - temp1(j)=max([jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - %jnk3=min(firstl1(:,i,j)); - %jnk4=min(imf2(:,i,j)); - jnk5=min(imf1(:,i,j)); - - temp2(j)=min([jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: situation 1 to N; Row i: variables (ie responses to) -%------------- -%figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrowg,ncolg,k1) - plot(t,imf1(:,i,j)) %,t,imf2(:,i,j),'--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - % if i<nrow - % set(gca,'XTickLabelMode','manual','XTickLabel',[]) - % end - %set(gca,'XTickLabel',' '); - if (scaleIndx) && (j>1) - set(gca,'YTickLabel',' '); - end - %if rowlabel == 1 - % %title(['x' num2str(j)]) - % %title(eval(['x' num2str(j)])) - % title(char(xlab(j))) - %end - if (~isempty(xlab)) - title(char(xlab(i))) - end - %if columnlabel == 1 - % %ylabel(['x' num2str(i)]) - % %ylabel(eval(['x' num2str(i)])) - % ylabel(char(ylab(i))) - %end - if (~isempty(ylab)) - ylabel(char(ylab(i))) - end - if (i==nrow) && (~isempty(tstring)) - xlabel(tstring) - end - columnlabel = 0; - end - rowlabel = 0; -end +function scaleout = fn_multigraph1_ver2_all_labels(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +%scaleout = fn_multigraph1_ver2_all_labels(imf1,xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +% +% Version 2 for plotting only one set of impulse responses in one graph. See fn_multigraph1_ver2. +% imf1 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as shocks or regimes. +% imf1: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in +% the graphics), 3rd D: across "ncol" different situations such as shocks or regimes (column in the graphics) +% xlab: x-axis labels on the top. Use [] if no label is needed. +% ylab: y-axis labels on the left. Use [] if no label is needed. +% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom. Use [] if no label is needed. +% YTickIndx: 1: enable YTick; 0: disable. Often set to zero to get a better picture. +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% nrowg: number of rows in the graph +% ncolg: number of columns in the graph +% +% See fn_multigraph1_ver2, imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imf1,1); +nrow = size(imf1,2); +ncol = size(imf1,3); +t = 1:nstp; + +if (nargin < 8) + nrowg = nrow; + ncolg = ncol; +end +if (nrowg*ncolg < nrow*ncol) + error('fn_multigraph1_ver2.m: nrowg*ncolg must equal to or greater than nrow*ncol') +end + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + %jnk3=max(firsth1(:,i,j)); + %jnk4=max(imf2(:,i,j)); + jnk5=max(imf1(:,i,j)); + + temp1(j)=max([jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + %jnk3=min(firstl1(:,i,j)); + %jnk4=min(imf2(:,i,j)); + jnk5=min(imf1(:,i,j)); + + temp2(j)=min([jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: situation 1 to N; Row i: variables (ie responses to) +%------------- +%figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrowg,ncolg,k1) + plot(t,imf1(:,i,j)) %,t,imf2(:,i,j),'--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + % if i<nrow + % set(gca,'XTickLabelMode','manual','XTickLabel',[]) + % end + %set(gca,'XTickLabel',' '); + if (scaleIndx) && (j>1) + set(gca,'YTickLabel',' '); + end + %if rowlabel == 1 + % %title(['x' num2str(j)]) + % %title(eval(['x' num2str(j)])) + % title(char(xlab(j))) + %end + if (~isempty(xlab)) + title(char(xlab(i))) + end + %if columnlabel == 1 + % %ylabel(['x' num2str(i)]) + % %ylabel(eval(['x' num2str(i)])) + % ylabel(char(ylab(i))) + %end + if (~isempty(ylab)) + ylabel(char(ylab(i))) + end + if (i==nrow) && (~isempty(tstring)) + xlabel(tstring) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/fn_multigraph2.m b/MatlabFiles/fn_multigraph2.m index 4fe7e3f853a6644e95344be9895ad378bcd32e9d..fda226691fa46e4864f3c21c4382d9755ccdc808 100644 --- a/MatlabFiles/fn_multigraph2.m +++ b/MatlabFiles/fn_multigraph2.m @@ -1,126 +1,126 @@ -function scaleout = fn_multigraph2(imf1,imf2,... - nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) -%Stacking two sets of impulse responses in one graph. See fn_multigraph1.m. -%imf1, imf2 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as regimes 1 and 2. -% imf: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in -% the graphics), 3rd D: across "ncol" different situations (column in -% the graphics) -% nrow: # of rows for the graphics -% ncol: # of columns for the graphics -% YTickIndx: 1: enable YTick; 0: disable -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -t = 1:nstp; -nrow -ncol - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - %jnk3=max(firsth1(:,i,j)); - jnk4=max(imf2(:,i,j)); - jnk5=max(imf1(:,i,j)); - - temp1(j)=max([jnk4 jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - %jnk3=min(firstl1(:,i,j)); - jnk4=min(imf2(:,i,j)); - jnk5=min(imf1(:,i,j)); - - temp2(j)=min([jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrow,ncol,k1) - plot(t,imf1(:,i,j),t,imf2(:,i,j),'--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if j>1 - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - if i==nrow - xlabel('Quarters') - end - columnlabel = 0; - end - rowlabel = 0; -end +function scaleout = fn_multigraph2(imf1,imf2,... + nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) +%Stacking two sets of impulse responses in one graph. See fn_multigraph1.m. +%imf1, imf2 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as regimes 1 and 2. +% imf: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in +% the graphics), 3rd D: across "ncol" different situations (column in +% the graphics) +% nrow: # of rows for the graphics +% ncol: # of columns for the graphics +% YTickIndx: 1: enable YTick; 0: disable +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +t = 1:nstp; +nrow +ncol + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + %jnk3=max(firsth1(:,i,j)); + jnk4=max(imf2(:,i,j)); + jnk5=max(imf1(:,i,j)); + + temp1(j)=max([jnk4 jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + %jnk3=min(firstl1(:,i,j)); + jnk4=min(imf2(:,i,j)); + jnk5=min(imf1(:,i,j)); + + temp2(j)=min([jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrow,ncol,k1) + plot(t,imf1(:,i,j),t,imf2(:,i,j),'--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if j>1 + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + if i==nrow + xlabel('Quarters') + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/fn_multigraph2_ver2.m b/MatlabFiles/fn_multigraph2_ver2.m index 3781941c587ba82047b6b8481586293fc156f116..6c5ae89d3d70d7759a164553fffa26eeed81eb17 100644 --- a/MatlabFiles/fn_multigraph2_ver2.m +++ b/MatlabFiles/fn_multigraph2_ver2.m @@ -1,139 +1,139 @@ -function scaleout = fn_multigraph2(imf1,imf2,... - xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -%Stacking two sets of impulse responses in one graph. See fn_multigraph1_ver2.m. -%imf1, imf2 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as shocks or regimes. -% imf#: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in -% the graphics), 3rd D: across "ncol" different situations (column in the graphics) -% xlab: x-axis labels on the top -% ylab: y-axis labels on the left -% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom -% YTickIndx: 1: enable YTick; 0: disable; -% To get a better picture, it is sometimes better to set YtickIndx to zero. -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% nrowg: number of rows in the graph -% ncolg: number of columns in the graph -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imf1,1); -nrow = size(imf1,2); -ncol = size(imf1,3); -t = 1:nstp; - -if (nargin < 9) - nrowg = nrow; - ncolg = ncol; -end -if (nrowg*ncolg ~= nrow*ncol) - error('fn_multigraph2_ver2.m: nrowg*ncolg must equal nrow*ncol') -end - - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - %jnk3=max(firsth1(:,i,j)); - jnk4=max(imf2(:,i,j)); - jnk5=max(imf1(:,i,j)); - - temp1(j)=max([jnk4 jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - %jnk3=min(firstl1(:,i,j)); - jnk4=min(imf2(:,i,j)); - jnk5=min(imf1(:,i,j)); - - temp2(j)=min([jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -%figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrowg,ncolg,k1) - plot(t,imf1(:,i,j),t,imf2(:,i,j),'--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if (scaleIndx) && (j>1) - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - if i==nrow - xlabel(tstring) - end - columnlabel = 0; - end - rowlabel = 0; -end +function scaleout = fn_multigraph2(imf1,imf2,... + xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +%Stacking two sets of impulse responses in one graph. See fn_multigraph1_ver2.m. +%imf1, imf2 -- each has 3 dimensions. Row: horizon; column: 'nrow' variables; 3rd dim: 'ncol' situations such as shocks or regimes. +% imf#: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in +% the graphics), 3rd D: across "ncol" different situations (column in the graphics) +% xlab: x-axis labels on the top +% ylab: y-axis labels on the left +% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom +% YTickIndx: 1: enable YTick; 0: disable; +% To get a better picture, it is sometimes better to set YtickIndx to zero. +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% nrowg: number of rows in the graph +% ncolg: number of columns in the graph +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imf1,1); +nrow = size(imf1,2); +ncol = size(imf1,3); +t = 1:nstp; + +if (nargin < 9) + nrowg = nrow; + ncolg = ncol; +end +if (nrowg*ncolg ~= nrow*ncol) + error('fn_multigraph2_ver2.m: nrowg*ncolg must equal nrow*ncol') +end + + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + %jnk3=max(firsth1(:,i,j)); + jnk4=max(imf2(:,i,j)); + jnk5=max(imf1(:,i,j)); + + temp1(j)=max([jnk4 jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + %jnk3=min(firstl1(:,i,j)); + jnk4=min(imf2(:,i,j)); + jnk5=min(imf1(:,i,j)); + + temp2(j)=min([jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +%figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrowg,ncolg,k1) + plot(t,imf1(:,i,j),t,imf2(:,i,j),'--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if (scaleIndx) && (j>1) + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + if i==nrow + xlabel(tstring) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/fn_multigraph2_ver2_all_labels.m b/MatlabFiles/fn_multigraph2_ver2_all_labels.m index 9dbcd7b322079f55690f814c8d1d805df572cf7f..f4fa3d5da7b593123158b771d12c57de232d5a73 100644 --- a/MatlabFiles/fn_multigraph2_ver2_all_labels.m +++ b/MatlabFiles/fn_multigraph2_ver2_all_labels.m @@ -1,150 +1,150 @@ -function scaleout = fn_multigraph2_ver2_all_labels(imf1,imf2,... - xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -%scaleout = fn_multigraph2_ver2_all_labels(imf1,imf2,... -% xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -% -%Stacking two sets of impulse responses in one graph. See fn_multigraph2_ver2.m. -% imf1, imf2: row: "nstp" time horizon (in the graphics), -% column: "nrow "variables (row in the graphics), -% 3rd dim: across "ncol" different situations (column in the graphics, but may be overwritten by ncolg). -% If the 3rd D is only 1, then we can specifiy nrowg and ncolg. -% xlab: x-axis labels on the top. Use [] if no label is needed. -% ylab: y-axis labels on the left. Use [] if no label is needed. -% XTick: ticks on the x-axis with grids on. Set to [] if no x-ticks and no grids. -% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom. Use [] if no label is needed. -% YTickIndx: 1: enable YTick; 0: disable. Often set to zero to get a better picture. -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% nrowg: number of rows in the graph (valid when the 3rd D is one) -% ncolg: number of columns in the graph (valid when the 3rd D is one) -% -% See fn_multigraph2_ver2, imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imf1,1); -nrow = size(imf1,2); -ncol = size(imf1,3); -t = 1:nstp; - -if (nargin < 9) - nrowg = nrow; - ncolg = ncol; -end -if (nrowg*ncolg < nrow*ncol) - error('fn_multigraph2_ver2_all_labels.m: nrowg*ncolg must be greater or equal to nrow*ncol') -end - - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - %jnk3=max(firsth1(:,i,j)); - jnk4=max(imf2(:,i,j)); - jnk5=max(imf1(:,i,j)); - - temp1(j)=max([jnk4 jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - %jnk3=min(firstl1(:,i,j)); - jnk4=min(imf2(:,i,j)); - jnk5=min(imf1(:,i,j)); - - temp2(j)=min([jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -%figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrowg,ncolg,k1) - plot(t,imf1(:,i,j),'k-',t,imf2(:,i,j),'k--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - % if i<nrow - % set(gca,'XTickLabelMode','manual','XTickLabel',[]) - % end - %set(gca,'XTickLabel',' '); - if (scaleIndx) && (j>1) - set(gca,'YTickLabel',' '); - end - % if rowlabel == 1 - % %title(['x' num2str(j)]) - % %title(eval(['x' num2str(j)])) - % title(char(xlab(j))) - % end - if (~isempty(xlab)) - title(char(xlab(i))) - end - % - % if columnlabel == 1 - % %ylabel(['x' num2str(i)]) - % %ylabel(eval(['x' num2str(i)])) - % ylabel(char(ylab(i))) - % end - if (~isempty(ylab)) - ylabel(char(ylab(i))) - end - if (i==nrow) && (~isempty(tstring)) - xlabel(tstring) - end - columnlabel = 0; - end - rowlabel = 0; -end +function scaleout = fn_multigraph2_ver2_all_labels(imf1,imf2,... + xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +%scaleout = fn_multigraph2_ver2_all_labels(imf1,imf2,... +% xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +% +%Stacking two sets of impulse responses in one graph. See fn_multigraph2_ver2.m. +% imf1, imf2: row: "nstp" time horizon (in the graphics), +% column: "nrow "variables (row in the graphics), +% 3rd dim: across "ncol" different situations (column in the graphics, but may be overwritten by ncolg). +% If the 3rd D is only 1, then we can specifiy nrowg and ncolg. +% xlab: x-axis labels on the top. Use [] if no label is needed. +% ylab: y-axis labels on the left. Use [] if no label is needed. +% XTick: ticks on the x-axis with grids on. Set to [] if no x-ticks and no grids. +% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom. Use [] if no label is needed. +% YTickIndx: 1: enable YTick; 0: disable. Often set to zero to get a better picture. +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% nrowg: number of rows in the graph (valid when the 3rd D is one) +% ncolg: number of columns in the graph (valid when the 3rd D is one) +% +% See fn_multigraph2_ver2, imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imf1,1); +nrow = size(imf1,2); +ncol = size(imf1,3); +t = 1:nstp; + +if (nargin < 9) + nrowg = nrow; + ncolg = ncol; +end +if (nrowg*ncolg < nrow*ncol) + error('fn_multigraph2_ver2_all_labels.m: nrowg*ncolg must be greater or equal to nrow*ncol') +end + + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + %jnk3=max(firsth1(:,i,j)); + jnk4=max(imf2(:,i,j)); + jnk5=max(imf1(:,i,j)); + + temp1(j)=max([jnk4 jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + %jnk3=min(firstl1(:,i,j)); + jnk4=min(imf2(:,i,j)); + jnk5=min(imf1(:,i,j)); + + temp2(j)=min([jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +%figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrowg,ncolg,k1) + plot(t,imf1(:,i,j),'k-',t,imf2(:,i,j),'k--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + % if i<nrow + % set(gca,'XTickLabelMode','manual','XTickLabel',[]) + % end + %set(gca,'XTickLabel',' '); + if (scaleIndx) && (j>1) + set(gca,'YTickLabel',' '); + end + % if rowlabel == 1 + % %title(['x' num2str(j)]) + % %title(eval(['x' num2str(j)])) + % title(char(xlab(j))) + % end + if (~isempty(xlab)) + title(char(xlab(i))) + end + % + % if columnlabel == 1 + % %ylabel(['x' num2str(i)]) + % %ylabel(eval(['x' num2str(i)])) + % ylabel(char(ylab(i))) + % end + if (~isempty(ylab)) + ylabel(char(ylab(i))) + end + if (i==nrow) && (~isempty(tstring)) + xlabel(tstring) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/fn_multigraph2_ver2_all_labels_dates.m b/MatlabFiles/fn_multigraph2_ver2_all_labels_dates.m index 1352c0db4008cab61d02ea13364b926b78bb945d..01d62eb9382c774f94a922082bb0dcdb8a46de7e 100644 --- a/MatlabFiles/fn_multigraph2_ver2_all_labels_dates.m +++ b/MatlabFiles/fn_multigraph2_ver2_all_labels_dates.m @@ -1,159 +1,159 @@ -function scaleout = fn_multigraph2_ver2_all_labels_dates(dates,imf1,imf2,... - xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,legend_inp, nrowg,ncolg) -%scaleout = fn_multigraph2_ver2_all_labels_dates(dates,imf1,imf2,... -% xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -% -%Stacking two sets of impulse responses in one graph. See fn_multigraph2_ver2_all_labels.m. -% dates: time horizon in the graphics, -% imf1, imf2: row: the same dimension as the dates (in the graphics), -% column: "nrow "variables (row in the graphics), -% 3rd dim: across "ncol" different situations (column in the graphics, but may be overwritten by ncolg). -% If the 3rd D is only 1, then we can specifiy nrowg and ncolg. -% xlab: x-axis labels on the top. Use [] if no label is needed. -% ylab: y-axis labels on the left. Use [] if no label is needed. -% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom. Use [] if no label is needed. -% XTick: ticks on the x-axis with grids on. If [], no x-ticks and no grids. -% YTickIndx: 1: enable YTick; 0: disable. Often set to zero to get a better picture. -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% legend_inp: legend inputs. If [], no legend. -% nrowg: number of rows in the graph (valid when the 3rd D is one) -% ncolg: number of columns in the graph (valid when the 3rd D is one) -% -% See fn_multigraph2_ver2_all_labels.m, fn_multigraph2_ver2, imrgraph, imcerrgraph, imrerrgraph - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imf1,1); -nrow = size(imf1,2); -ncol = size(imf1,3); - -if (length(dates) ~= nstp) - error('.../fn_multigraph2_ver2_all_labels_dates: dates must have the dimension as the row number of imf1 and imf2!') -end - -if (nargin < 11) - nrowg = nrow; - ncolg = ncol; -end -if (nrowg*ncolg < nrow*ncol) - error('fn_multigraph2_ver2_all_labels_dates.m: nrowg*ncolg must be greater or equal to nrow*ncol') -end - - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - %jnk3=max(firsth1(:,i,j)); - jnk4=max(imf2(:,i,j)); - jnk5=max(imf1(:,i,j)); - - temp1(j)=max([jnk4 jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - %jnk3=min(firstl1(:,i,j)); - jnk4=min(imf2(:,i,j)); - jnk5=min(imf1(:,i,j)); - - temp2(j)=min([jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -%figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[dates(1) dates(end) minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrowg,ncolg,k1) - plot(dates,imf1(:,i,j),'k-',dates,imf2(:,i,j),'k--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if (~isempty(legend_inp)) - legend(legend_inp) - end - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - % if i<nrow - % set(gca,'XTickLabelMode','manual','XTickLabel',[]) - % end - %set(gca,'XTickLabel',' '); - if (scaleIndx) && (j>1) - set(gca,'YTickLabel',' '); - end - % if rowlabel == 1 - % %title(['x' num2str(j)]) - % %title(eval(['x' num2str(j)])) - % title(char(xlab(j))) - % end - if (~isempty(xlab)) - title(char(xlab(i))) - end - % - % if columnlabel == 1 - % %ylabel(['x' num2str(i)]) - % %ylabel(eval(['x' num2str(i)])) - % ylabel(char(ylab(i))) - % end - if (~isempty(ylab)) - ylabel(char(ylab(i))) - end - if (i==nrow) && (~isempty(tstring)) - xlabel(tstring) - end - columnlabel = 0; - end - rowlabel = 0; -end +function scaleout = fn_multigraph2_ver2_all_labels_dates(dates,imf1,imf2,... + xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,legend_inp, nrowg,ncolg) +%scaleout = fn_multigraph2_ver2_all_labels_dates(dates,imf1,imf2,... +% xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +% +%Stacking two sets of impulse responses in one graph. See fn_multigraph2_ver2_all_labels.m. +% dates: time horizon in the graphics, +% imf1, imf2: row: the same dimension as the dates (in the graphics), +% column: "nrow "variables (row in the graphics), +% 3rd dim: across "ncol" different situations (column in the graphics, but may be overwritten by ncolg). +% If the 3rd D is only 1, then we can specifiy nrowg and ncolg. +% xlab: x-axis labels on the top. Use [] if no label is needed. +% ylab: y-axis labels on the left. Use [] if no label is needed. +% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom. Use [] if no label is needed. +% XTick: ticks on the x-axis with grids on. If [], no x-ticks and no grids. +% YTickIndx: 1: enable YTick; 0: disable. Often set to zero to get a better picture. +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% legend_inp: legend inputs. If [], no legend. +% nrowg: number of rows in the graph (valid when the 3rd D is one) +% ncolg: number of columns in the graph (valid when the 3rd D is one) +% +% See fn_multigraph2_ver2_all_labels.m, fn_multigraph2_ver2, imrgraph, imcerrgraph, imrerrgraph + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imf1,1); +nrow = size(imf1,2); +ncol = size(imf1,3); + +if (length(dates) ~= nstp) + error('.../fn_multigraph2_ver2_all_labels_dates: dates must have the dimension as the row number of imf1 and imf2!') +end + +if (nargin < 11) + nrowg = nrow; + ncolg = ncol; +end +if (nrowg*ncolg < nrow*ncol) + error('fn_multigraph2_ver2_all_labels_dates.m: nrowg*ncolg must be greater or equal to nrow*ncol') +end + + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + %jnk3=max(firsth1(:,i,j)); + jnk4=max(imf2(:,i,j)); + jnk5=max(imf1(:,i,j)); + + temp1(j)=max([jnk4 jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + %jnk3=min(firstl1(:,i,j)); + jnk4=min(imf2(:,i,j)); + jnk5=min(imf1(:,i,j)); + + temp2(j)=min([jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +%figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[dates(1) dates(end) minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrowg,ncolg,k1) + plot(dates,imf1(:,i,j),'k-',dates,imf2(:,i,j),'k--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if (~isempty(legend_inp)) + legend(legend_inp) + end + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + % if i<nrow + % set(gca,'XTickLabelMode','manual','XTickLabel',[]) + % end + %set(gca,'XTickLabel',' '); + if (scaleIndx) && (j>1) + set(gca,'YTickLabel',' '); + end + % if rowlabel == 1 + % %title(['x' num2str(j)]) + % %title(eval(['x' num2str(j)])) + % title(char(xlab(j))) + % end + if (~isempty(xlab)) + title(char(xlab(i))) + end + % + % if columnlabel == 1 + % %ylabel(['x' num2str(i)]) + % %ylabel(eval(['x' num2str(i)])) + % ylabel(char(ylab(i))) + % end + if (~isempty(ylab)) + ylabel(char(ylab(i))) + end + if (i==nrow) && (~isempty(tstring)) + xlabel(tstring) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/fn_multigraphn_3g_shadedbands.m b/MatlabFiles/fn_multigraphn_3g_shadedbands.m index 6b21b3a12e5952f75c731a07c9d321d66ccc2517..a92c96ae53f7bbcd5db8a2cfc2273ab2863061bd 100644 --- a/MatlabFiles/fn_multigraphn_3g_shadedbands.m +++ b/MatlabFiles/fn_multigraphn_3g_shadedbands.m @@ -1,188 +1,188 @@ -function scaleout = fn_multigraphn_3g_shadedbands(imfn,... - xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -%Searching <<>> for ad hoc and specific changes. -% -%Stacking n sets of impulse responses in one graph. See fn_multigraph2_ver2.m. -% imfn: row: "nstp" time horizon (in the graphics), -% column: "nrow "variables such as responses (row in the graphics), -% 3rd D: across "ncol" different situations such as shocks (column in the graphics), -% 4th D: low band, estimate, high band (in each graph). -% xlab: x-axis labels on the top -% ylab: y-axis labels on the left -% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom -% YTickIndx: 1: enable YTick; 0: disable; -% To get a better picture, it is sometimes better to set YtickIndx to zero. -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% nrowg: number of rows in the graph -% ncolg: number of columns in the graph -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imfn,1); -nrow = size(imfn,2); -ncol = size(imfn,3); -nmodels = size(imfn,4); -t = 1:nstp; -treverse = fliplr(t); - -if (nargin < 9) - nrowg = nrow; - ncolg = ncol; -end -if (nrowg*ncolg < nrow*ncol) - nrowg - ncolg - nrow - ncol - - error('fn_multigraphn_3g_shadedbands.m: nrowg*ncolg must be greater than nrow*ncol') -end - - -tempmax=zeros(ncol,1); -tempmin=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - tempmax(j) = -realmax; - tempmin(j) = realmax; - for k=1:nmodels - jnk = max(imfn(:,i,j,k)); - tempmax(j) = max([jnk tempmax(j)]); - % - jnk = min(imfn(:,i,j,k)); - tempmin(j) = min([jnk tempmin(j)]); - end - end - maxval(i)=max(tempmax); - minval(i)=min(tempmin); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -%figure - - -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrowg,ncolg,k1) - - %set(0,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1],... - % 'DefaultAxesLineStyleOrder','-|--|:') - %set(0,'DefaultAxesLineStyleOrder','-|--|:|-.') - %---<<>> - %set(0,'DefaultAxesColorOrder',[0 0 0],... - % 'DefaultAxesLineStyleOrder','-.|-.|-|--|-.|-*|--o|:d') - - nseries = zeros(nstp, nmodels); - for k=1:nmodels - nseries(:,k) = imfn(:,i,j,k); - end - - %---<<>> - fill([t treverse],[nseries(:,[3])' fliplr(nseries(:,[1])')],[0.8,0.8,0.8],'EdgeColor','none'); - %plot(t,nseries(:,[1 3]), '-.k','LineWidth',1.0); %,'Color','k'); - hold on - plot(t,nseries(:,[2]), '-k','LineWidth',1.5); - %plot(t,nseries(:,[4]), '--k','LineWidth',1.6); - hold off - - %set(gca,'LineStyleOrder','-|--|:|-.') - %set(gca,'LineStyleOrder',{'-*',':','o'}) - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if (scaleIndx) && (j>1) - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - if (~isempty(xlab)), title(char(xlab(j))), end - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - if (~isempty(ylab)), ylabel(char(ylab(i))), end - end - if (i==nrow) && (~isempty(tstring)) - xlabel(tstring) - end - columnlabel = 0; - end - rowlabel = 0; -end - - -%Order of line styles and markers used in a plot. -%This property specifies which line styles and markers to use and in what order -%when creating multiple-line plots. For example,set(gca,'LineStyleOrder', '-*|:|o')sets LineStyleOrder to solid line with asterisk -%marker, dotted line, and hollow circle marker. The default is (-), which specifies -%a solid line for all data plotted. Alternatively, you can create a cell array -%of character strings to define the line styles:set(gca,'LineStyleOrder',{'-*',':','o'})MATLAB supports four line styles, which you can specify any number of -%times in any order. MATLAB cycles through the line styles only after using -%all colors defined by the ColorOrder property. For example, -%the first eight lines plotted use the different colors defined by ColorOrder with -%the first line style. MATLAB then cycles through the colors again, using the -%second line style specified, and so on.You can also specify line style and color directly with the plot and plot3 functions -%or by altering the properties of theline or -%lineseries objects after creating the graph. High-Level Functions and LineStyleOrderNote that, if the axes NextPlot property is set -%to replace (the default), high-level functions like plot reset -%the LineStyleOrder property before determining the line -%style to use. If you want MATLAB to use a LineStyleOrder that -%is different from the default, set NextPlot to replacechildren. Specifying a Default LineStyleOrderYou can also specify your own default LineStyleOrder. -%For example, this statementset(0,'DefaultAxesLineStyleOrder',{'-*',':','o'}) -%creates a default value for +function scaleout = fn_multigraphn_3g_shadedbands(imfn,... + xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +%Searching <<>> for ad hoc and specific changes. +% +%Stacking n sets of impulse responses in one graph. See fn_multigraph2_ver2.m. +% imfn: row: "nstp" time horizon (in the graphics), +% column: "nrow "variables such as responses (row in the graphics), +% 3rd D: across "ncol" different situations such as shocks (column in the graphics), +% 4th D: low band, estimate, high band (in each graph). +% xlab: x-axis labels on the top +% ylab: y-axis labels on the left +% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom +% YTickIndx: 1: enable YTick; 0: disable; +% To get a better picture, it is sometimes better to set YtickIndx to zero. +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% nrowg: number of rows in the graph +% ncolg: number of columns in the graph +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imfn,1); +nrow = size(imfn,2); +ncol = size(imfn,3); +nmodels = size(imfn,4); +t = 1:nstp; +treverse = fliplr(t); + +if (nargin < 9) + nrowg = nrow; + ncolg = ncol; +end +if (nrowg*ncolg < nrow*ncol) + nrowg + ncolg + nrow + ncol + + error('fn_multigraphn_3g_shadedbands.m: nrowg*ncolg must be greater than nrow*ncol') +end + + +tempmax=zeros(ncol,1); +tempmin=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + tempmax(j) = -realmax; + tempmin(j) = realmax; + for k=1:nmodels + jnk = max(imfn(:,i,j,k)); + tempmax(j) = max([jnk tempmax(j)]); + % + jnk = min(imfn(:,i,j,k)); + tempmin(j) = min([jnk tempmin(j)]); + end + end + maxval(i)=max(tempmax); + minval(i)=min(tempmin); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +%figure + + +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrowg,ncolg,k1) + + %set(0,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1],... + % 'DefaultAxesLineStyleOrder','-|--|:') + %set(0,'DefaultAxesLineStyleOrder','-|--|:|-.') + %---<<>> + %set(0,'DefaultAxesColorOrder',[0 0 0],... + % 'DefaultAxesLineStyleOrder','-.|-.|-|--|-.|-*|--o|:d') + + nseries = zeros(nstp, nmodels); + for k=1:nmodels + nseries(:,k) = imfn(:,i,j,k); + end + + %---<<>> + fill([t treverse],[nseries(:,[3])' fliplr(nseries(:,[1])')],[0.8,0.8,0.8],'EdgeColor','none'); + %plot(t,nseries(:,[1 3]), '-.k','LineWidth',1.0); %,'Color','k'); + hold on + plot(t,nseries(:,[2]), '-k','LineWidth',1.5); + %plot(t,nseries(:,[4]), '--k','LineWidth',1.6); + hold off + + %set(gca,'LineStyleOrder','-|--|:|-.') + %set(gca,'LineStyleOrder',{'-*',':','o'}) + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if (scaleIndx) && (j>1) + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + if (~isempty(xlab)), title(char(xlab(j))), end + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + if (~isempty(ylab)), ylabel(char(ylab(i))), end + end + if (i==nrow) && (~isempty(tstring)) + xlabel(tstring) + end + columnlabel = 0; + end + rowlabel = 0; +end + + +%Order of line styles and markers used in a plot. +%This property specifies which line styles and markers to use and in what order +%when creating multiple-line plots. For example,set(gca,'LineStyleOrder', '-*|:|o')sets LineStyleOrder to solid line with asterisk +%marker, dotted line, and hollow circle marker. The default is (-), which specifies +%a solid line for all data plotted. Alternatively, you can create a cell array +%of character strings to define the line styles:set(gca,'LineStyleOrder',{'-*',':','o'})MATLAB supports four line styles, which you can specify any number of +%times in any order. MATLAB cycles through the line styles only after using +%all colors defined by the ColorOrder property. For example, +%the first eight lines plotted use the different colors defined by ColorOrder with +%the first line style. MATLAB then cycles through the colors again, using the +%second line style specified, and so on.You can also specify line style and color directly with the plot and plot3 functions +%or by altering the properties of theline or +%lineseries objects after creating the graph. High-Level Functions and LineStyleOrderNote that, if the axes NextPlot property is set +%to replace (the default), high-level functions like plot reset +%the LineStyleOrder property before determining the line +%style to use. If you want MATLAB to use a LineStyleOrder that +%is different from the default, set NextPlot to replacechildren. Specifying a Default LineStyleOrderYou can also specify your own default LineStyleOrder. +%For example, this statementset(0,'DefaultAxesLineStyleOrder',{'-*',':','o'}) +%creates a default value for diff --git a/MatlabFiles/fn_multigraphn_ver2.m b/MatlabFiles/fn_multigraphn_ver2.m index a6bd030e1604006f8a88b839bc2f8b28eaa22e7f..63e55c6fceccea9353ba07e9c0de12b939d06732 100644 --- a/MatlabFiles/fn_multigraphn_ver2.m +++ b/MatlabFiles/fn_multigraphn_ver2.m @@ -1,175 +1,175 @@ -function scaleout = fn_multigraphn_ver2(imfn,... - xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) -%Stacking n sets of impulse responses in one graph. See fn_multigraph2_ver2.m. -% imfn: row: "nstp" time horizon (in the graphics), -% column: "nrow "variables such as responses (row in the graphics), -% 3rd D: across "ncol" different situations such as shocks (column in the graphics), -% 4th D: across different scenarios such as error bands or different models (in each graph). -% xlab: x-axis labels on the top -% ylab: y-axis labels on the left -% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom -% YTickIndx: 1: enable YTick; 0: disable; -% To get a better picture, it is sometimes better to set YtickIndx to zero. -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% nrowg: number of rows in the graph -% ncolg: number of columns in the graph -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nstp = size(imfn,1); -nrow = size(imfn,2); -ncol = size(imfn,3); -nmodels = size(imfn,4); -t = 1:nstp; - -if (nargin < 9) - nrowg = nrow; - ncolg = ncol; -end -if (nrowg*ncolg < nrow*ncol) - nrowg - ncolg - nrow - ncol - - error('fn_multigraphn_ver2.m: nrowg*ncolg must be greater than nrow*ncol') -end - - -tempmax=zeros(ncol,1); -tempmin=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - tempmax(j) = -realmax; - tempmin(j) = realmax; - for k=1:nmodels - jnk = max(imfn(:,i,j,k)); - tempmax(j) = max([jnk tempmax(j)]); - % - jnk = min(imfn(:,i,j,k)); - tempmin(j) = min([jnk tempmin(j)]); - end - end - maxval(i)=max(tempmax); - minval(i)=min(tempmin); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -%figure - - -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrowg,ncolg,k1) - - %set(0,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1],... - % 'DefaultAxesLineStyleOrder','-|--|:') - %set(0,'DefaultAxesLineStyleOrder','-|--|:|-.') - set(0,'DefaultAxesColorOrder',[0 0 0],... - 'DefaultAxesLineStyleOrder','-|--|--|:*|-.|-*|--o|:d') - - nseries = zeros(nstp, nmodels); - for k=1:nmodels - nseries(:,k) = imfn(:,i,j,k); - end - plot(t,nseries, 'LineWidth',1.7); %,'Color','k'); - %set(gca,'LineStyleOrder','-|--|:|-.') - %set(gca,'LineStyleOrder',{'-*',':','o'}) - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if (scaleIndx) && (j>1) - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - if i==nrow - xlabel(tstring) - end - columnlabel = 0; - end - rowlabel = 0; -end - - -%Order of line styles and markers used in a plot. -%This property specifies which line styles and markers to use and in what order -%when creating multiple-line plots. For example,set(gca,'LineStyleOrder', '-*|:|o')sets LineStyleOrder to solid line with asterisk -%marker, dotted line, and hollow circle marker. The default is (-), which specifies -%a solid line for all data plotted. Alternatively, you can create a cell array -%of character strings to define the line styles:set(gca,'LineStyleOrder',{'-*',':','o'})MATLAB supports four line styles, which you can specify any number of -%times in any order. MATLAB cycles through the line styles only after using -%all colors defined by the ColorOrder property. For example, -%the first eight lines plotted use the different colors defined by ColorOrder with -%the first line style. MATLAB then cycles through the colors again, using the -%second line style specified, and so on.You can also specify line style and color directly with the plot and plot3 functions -%or by altering the properties of theline or -%lineseries objects after creating the graph. High-Level Functions and LineStyleOrderNote that, if the axes NextPlot property is set -%to replace (the default), high-level functions like plot reset -%the LineStyleOrder property before determining the line -%style to use. If you want MATLAB to use a LineStyleOrder that -%is different from the default, set NextPlot to replacechildren. Specifying a Default LineStyleOrderYou can also specify your own default LineStyleOrder. -%For example, this statementset(0,'DefaultAxesLineStyleOrder',{'-*',':','o'}) -%creates a default value for +function scaleout = fn_multigraphn_ver2(imfn,... + xlab,ylab,tstring,XTick,YTickIndx,scaleIndx,nrowg,ncolg) +%Stacking n sets of impulse responses in one graph. See fn_multigraph2_ver2.m. +% imfn: row: "nstp" time horizon (in the graphics), +% column: "nrow "variables such as responses (row in the graphics), +% 3rd D: across "ncol" different situations such as shocks (column in the graphics), +% 4th D: across different scenarios such as error bands or different models (in each graph). +% xlab: x-axis labels on the top +% ylab: y-axis labels on the left +% tstring: string for time (e.g., month or quarter) -- x-axis labels at the bottom +% YTickIndx: 1: enable YTick; 0: disable; +% To get a better picture, it is sometimes better to set YtickIndx to zero. +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% nrowg: number of rows in the graph +% ncolg: number of columns in the graph +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nstp = size(imfn,1); +nrow = size(imfn,2); +ncol = size(imfn,3); +nmodels = size(imfn,4); +t = 1:nstp; + +if (nargin < 9) + nrowg = nrow; + ncolg = ncol; +end +if (nrowg*ncolg < nrow*ncol) + nrowg + ncolg + nrow + ncol + + error('fn_multigraphn_ver2.m: nrowg*ncolg must be greater than nrow*ncol') +end + + +tempmax=zeros(ncol,1); +tempmin=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + tempmax(j) = -realmax; + tempmin(j) = realmax; + for k=1:nmodels + jnk = max(imfn(:,i,j,k)); + tempmax(j) = max([jnk tempmax(j)]); + % + jnk = min(imfn(:,i,j,k)); + tempmin(j) = min([jnk tempmin(j)]); + end + end + maxval(i)=max(tempmax); + minval(i)=min(tempmin); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +%figure + + +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrowg,ncolg,k1) + + %set(0,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1],... + % 'DefaultAxesLineStyleOrder','-|--|:') + %set(0,'DefaultAxesLineStyleOrder','-|--|:|-.') + set(0,'DefaultAxesColorOrder',[0 0 0],... + 'DefaultAxesLineStyleOrder','-|--|--|:*|-.|-*|--o|:d') + + nseries = zeros(nstp, nmodels); + for k=1:nmodels + nseries(:,k) = imfn(:,i,j,k); + end + plot(t,nseries, 'LineWidth',1.7); %,'Color','k'); + %set(gca,'LineStyleOrder','-|--|:|-.') + %set(gca,'LineStyleOrder',{'-*',':','o'}) + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if (scaleIndx) && (j>1) + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + if i==nrow + xlabel(tstring) + end + columnlabel = 0; + end + rowlabel = 0; +end + + +%Order of line styles and markers used in a plot. +%This property specifies which line styles and markers to use and in what order +%when creating multiple-line plots. For example,set(gca,'LineStyleOrder', '-*|:|o')sets LineStyleOrder to solid line with asterisk +%marker, dotted line, and hollow circle marker. The default is (-), which specifies +%a solid line for all data plotted. Alternatively, you can create a cell array +%of character strings to define the line styles:set(gca,'LineStyleOrder',{'-*',':','o'})MATLAB supports four line styles, which you can specify any number of +%times in any order. MATLAB cycles through the line styles only after using +%all colors defined by the ColorOrder property. For example, +%the first eight lines plotted use the different colors defined by ColorOrder with +%the first line style. MATLAB then cycles through the colors again, using the +%second line style specified, and so on.You can also specify line style and color directly with the plot and plot3 functions +%or by altering the properties of theline or +%lineseries objects after creating the graph. High-Level Functions and LineStyleOrderNote that, if the axes NextPlot property is set +%to replace (the default), high-level functions like plot reset +%the LineStyleOrder property before determining the line +%style to use. If you want MATLAB to use a LineStyleOrder that +%is different from the default, set NextPlot to replacechildren. Specifying a Default LineStyleOrderYou can also specify your own default LineStyleOrder. +%For example, this statementset(0,'DefaultAxesLineStyleOrder',{'-*',':','o'}) +%creates a default value for diff --git a/MatlabFiles/fn_nmlzvar.m b/MatlabFiles/fn_nmlzvar.m index 51c7f25f9fee564967be491684b85dea8a76f477..e8244db8be16872d7b1617f1d4c605804a51ce7b 100644 --- a/MatlabFiles/fn_nmlzvar.m +++ b/MatlabFiles/fn_nmlzvar.m @@ -1,108 +1,108 @@ -function [A0n,a0dpindx,nswitch,A0inn] = fn_nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) -% [A0n,nswitch,A0inn] = nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) -% Export normalized new draw A0 (and inv(A0) only if IndxNmlr(5)) and the number of sign switches -% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" -% See Note Forecast (2) pp. 52-53 -% -% A0u: unnormalized A0; column--equation -% A0xhat: ML estimate or posterior mode of A0 -% A0inxhat: inv(A0xhat) -% IndxNmlr: index for which normalization rule to choose -% Only one of the elments in IndxNmlr can be non-zero -% IndxNmlr(1): ML A distance rule (supposed to be the best) -% IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1)) -% IndxNmlr(3): ML Euclidean distance rule (not invariant to scale) -% IndxNmlr(4): Positive diagonal rule -% IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu, -% so we set A0inn=[]) -% IndxNmlr(6): Assigned postive rule (such as off-diagonal elements). Added 1/3/00 -% nswitch: # of sign switches -% A0inu: unnormalized inv(A0); used only if IndxNmlr(5) -%----------------- -% A0n: normalized new A0; column--equation -% a0dpindx: Index of the columns in A0 or A+ whose signs need to be switched. -% nswitch: updated # of sign switches -% A0inn: normalized inv(A0); used only if IndxNmlr(5) -% -% Written by Tao Zha -% 1/3/00: added IndxNmlr(6) so that previous programs may not be compatible. -% 10/11/01: added a0dpindx in front of nswitch as an output argument so that previous programs may not be compatible. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -A0inn = []; % no output for normalized A0in unless IndxNmlr(5) - -if (length(find(IndxNmlr))>1) - warning('You cannot choose more than one normalization rule at a time') - disp('Press ctrl-c to abort') - pause -elseif isempty(find(IndxNmlr)) % no normalization - A0n=A0u; nswitch=0; -elseif IndxNmlr(1) - a0dpindx = find(diag(A0u\A0xhat)<0); - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(2) - a0dpindx = find(diag(A0inxhat*A0u)<0); - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(3) - Adiff = (A0u - A0xhat).^2; % distance that may be far from axhat or A0xhat - Adiffn = (-A0u - A0xhat).^2; % distance by chaning the sign of Atem - cAdiff = sum(Adiff); % each column summed up - cAdiffn = sum(Adiffn); % each column summed up - cAindx = find(cAdiffn<cAdiff); % index for shorter distance - A0n = A0u; - if ~isempty(cAindx) - A0n(:,cAindx) = -A0u(:,cAindx); % find the shortest or nearest distance - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(4) - a0dpindx = find(diag(A0u)<0); - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(5) - a0dpindx = find(diag(A0inu)<0); - A0n = A0u; - A0inn = A0inu; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); - A0inn(a0dpindx,:) = -A0inu(a0dpindx,:); - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(6) %*** This one has to be MANUALLY handled - [jnk,nvar]=size(A0u); - A0dummy=A0u; - A0dummy(:,1:2)=-A0u(:,1:2); % keep it to a sign that coincide with Brooking paper - a0dpindx = find(A0dummy(nvar,:)<0); % the last row - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -end +function [A0n,a0dpindx,nswitch,A0inn] = fn_nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) +% [A0n,nswitch,A0inn] = nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) +% Export normalized new draw A0 (and inv(A0) only if IndxNmlr(5)) and the number of sign switches +% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" +% See Note Forecast (2) pp. 52-53 +% +% A0u: unnormalized A0; column--equation +% A0xhat: ML estimate or posterior mode of A0 +% A0inxhat: inv(A0xhat) +% IndxNmlr: index for which normalization rule to choose +% Only one of the elments in IndxNmlr can be non-zero +% IndxNmlr(1): ML A distance rule (supposed to be the best) +% IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1)) +% IndxNmlr(3): ML Euclidean distance rule (not invariant to scale) +% IndxNmlr(4): Positive diagonal rule +% IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu, +% so we set A0inn=[]) +% IndxNmlr(6): Assigned postive rule (such as off-diagonal elements). Added 1/3/00 +% nswitch: # of sign switches +% A0inu: unnormalized inv(A0); used only if IndxNmlr(5) +%----------------- +% A0n: normalized new A0; column--equation +% a0dpindx: Index of the columns in A0 or A+ whose signs need to be switched. +% nswitch: updated # of sign switches +% A0inn: normalized inv(A0); used only if IndxNmlr(5) +% +% Written by Tao Zha +% 1/3/00: added IndxNmlr(6) so that previous programs may not be compatible. +% 10/11/01: added a0dpindx in front of nswitch as an output argument so that previous programs may not be compatible. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +A0inn = []; % no output for normalized A0in unless IndxNmlr(5) + +if (length(find(IndxNmlr))>1) + warning('You cannot choose more than one normalization rule at a time') + disp('Press ctrl-c to abort') + pause +elseif isempty(find(IndxNmlr)) % no normalization + A0n=A0u; nswitch=0; +elseif IndxNmlr(1) + a0dpindx = find(diag(A0u\A0xhat)<0); + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(2) + a0dpindx = find(diag(A0inxhat*A0u)<0); + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(3) + Adiff = (A0u - A0xhat).^2; % distance that may be far from axhat or A0xhat + Adiffn = (-A0u - A0xhat).^2; % distance by chaning the sign of Atem + cAdiff = sum(Adiff); % each column summed up + cAdiffn = sum(Adiffn); % each column summed up + cAindx = find(cAdiffn<cAdiff); % index for shorter distance + A0n = A0u; + if ~isempty(cAindx) + A0n(:,cAindx) = -A0u(:,cAindx); % find the shortest or nearest distance + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(4) + a0dpindx = find(diag(A0u)<0); + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(5) + a0dpindx = find(diag(A0inu)<0); + A0n = A0u; + A0inn = A0inu; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); + A0inn(a0dpindx,:) = -A0inu(a0dpindx,:); + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(6) %*** This one has to be MANUALLY handled + [jnk,nvar]=size(A0u); + A0dummy=A0u; + A0dummy(:,1:2)=-A0u(:,1:2); % keep it to a sign that coincide with Brooking paper + a0dpindx = find(A0dummy(nvar,:)<0); % the last row + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +end diff --git a/MatlabFiles/fn_numstruct2numcell_nummatrix.m b/MatlabFiles/fn_numstruct2numcell_nummatrix.m index 3f530d2ef95b8a60e4b4a190fe601ee9fbc430e5..0b8a9adbe5dab09c078627059bb54bba7c7e0b83 100644 --- a/MatlabFiles/fn_numstruct2numcell_nummatrix.m +++ b/MatlabFiles/fn_numstruct2numcell_nummatrix.m @@ -1,31 +1,31 @@ function [uniform_cell, uniform_matrix3D, names_fields] = fn_numstruct2numcell_nummatrix(uniform_ps) %[uniform_cell, uniform_matrix3D, names_fields] = fn_numstruct2numcell_nummatrix(uniform_ps) -% +% % Inputs: % uniform_ps: a structure where each field has the same nrows-by-ncols matrix. This function does NOT work % if each field has different data types. % Outputs: -% uniform_cell: nfields cells where each cell has a nrows-by-ncols matrix. +% uniform_cell: nfields cells where each cell has a nrows-by-ncols matrix. % uniform_matrix3D: 3-D array: nrows-by-ncols-by-nfields -% Copyright (C) 1997-2012 Tao Zha % -% This file is part of Dynare. +% Copyright (C) 1997-2012 Tao Zha % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% names_fields = fieldnames(uniform_ps); -nfields = length(names_fields); +nfields = length(names_fields); uniform_cell = struct2cell(uniform_ps); nrows = size(uniform_cell{1},1); ncols = size(uniform_cell{1},2); @@ -33,4 +33,4 @@ ncols = size(uniform_cell{1},2); uniform_matrix3D = zeros(nrows,ncols,nfields); for (ni=1:nfields) uniform_matrix3D(:,:,ni) = uniform_cell{ni}; -end \ No newline at end of file +end diff --git a/MatlabFiles/fn_ols.m b/MatlabFiles/fn_ols.m index 33d4c5762733e72dcdfa9c4cdcf807c25f25b281..9f7a85671f0a600718861455002e2150f6463c71 100644 --- a/MatlabFiles/fn_ols.m +++ b/MatlabFiles/fn_ols.m @@ -1,48 +1,48 @@ -function [Bh,e,xtx,xty] = fn_ols(y,phi) -% [Bh,e,xtx,xty] = fn_ols(y,phi) -% ols: estimate a system of equations: Y(T*nvar) = XB + u, X: T*k, B: k*nvar. -% -% y: Y: T-by-nvar -% phi: X; T-by-k; column: number of r.h.s. variables (including -%------------ -% Bh: the estimated B; column: nvar; row: number of r.h.s. variables. -% e: estimated residual e = y -xBh, T*nvar -% xtx: X'X: k-by-k -% xty: X'Y: k-by-nvar -% deterministic terms)% -% See also sye.m and syed.m - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -% ** setup of orders and lengths ** - -[u d v]=svd(phi,0); %trial -%xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -dinv = 1./diag(d); % inv(diag(d)) -vdinv=v.*(ones(size(v,2),1)*dinv'); %trial -xtx=vd*vd'; -xtxinv = vdinv*vdinv'; -%xty = phi'*y; % X'Y -uy = u'*y; %trial -xty = vd*uy; %trial -%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). -Bh = xtxinv*xty; -%e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar -e = y - u*uy; +function [Bh,e,xtx,xty] = fn_ols(y,phi) +% [Bh,e,xtx,xty] = fn_ols(y,phi) +% ols: estimate a system of equations: Y(T*nvar) = XB + u, X: T*k, B: k*nvar. +% +% y: Y: T-by-nvar +% phi: X; T-by-k; column: number of r.h.s. variables (including +%------------ +% Bh: the estimated B; column: nvar; row: number of r.h.s. variables. +% e: estimated residual e = y -xBh, T*nvar +% xtx: X'X: k-by-k +% xty: X'Y: k-by-nvar +% deterministic terms)% +% See also sye.m and syed.m + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +% ** setup of orders and lengths ** + +[u d v]=svd(phi,0); %trial +%xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +dinv = 1./diag(d); % inv(diag(d)) +vdinv=v.*(ones(size(v,2),1)*dinv'); %trial +xtx=vd*vd'; +xtxinv = vdinv*vdinv'; +%xty = phi'*y; % X'Y +uy = u'*y; %trial +xty = vd*uy; %trial +%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). +Bh = xtxinv*xty; +%e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar +e = y - u*uy; diff --git a/MatlabFiles/fn_plotrecessionshades57_01.m b/MatlabFiles/fn_plotrecessionshades57_01.m index bebb443441579b75979f157d6bc0c4ed282212a9..fa872ee46d4ee3b258614c7d9d72ccaee2adb861 100644 --- a/MatlabFiles/fn_plotrecessionshades57_01.m +++ b/MatlabFiles/fn_plotrecessionshades57_01.m @@ -1,25 +1,25 @@ -function fn_PlotRecessionShades57_01(rec_dates, AxisDat) -% Recession shades. For some reasons, Matlab code will only take pairs of rec_dates when using rectangle. -% Inputs: rec_dates -- must be in pairs for rectangle to work. -% AxisDat -- example: AxisDat=axis([1976 2010 -.2 .15]); -% 1976 will automatically cut off the dates before 1976 in the following lines. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -for RecessionNumber=1:length(rec_dates); - rectangle('Position', [rec_dates(RecessionNumber,1) AxisDat(3) (rec_dates(RecessionNumber,2)-rec_dates(RecessionNumber,1)) (AxisDat(4)-AxisDat(3))], 'FaceColor','y'); -end +function fn_PlotRecessionShades57_01(rec_dates, AxisDat) +% Recession shades. For some reasons, Matlab code will only take pairs of rec_dates when using rectangle. +% Inputs: rec_dates -- must be in pairs for rectangle to work. +% AxisDat -- example: AxisDat=axis([1976 2010 -.2 .15]); +% 1976 will automatically cut off the dates before 1976 in the following lines. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +for RecessionNumber=1:length(rec_dates); + rectangle('Position', [rec_dates(RecessionNumber,1) AxisDat(3) (rec_dates(RecessionNumber,2)-rec_dates(RecessionNumber,1)) (AxisDat(4)-AxisDat(3))], 'FaceColor','y'); +end diff --git a/MatlabFiles/fn_posteriorvariancedecomposition.m b/MatlabFiles/fn_posteriorvariancedecomposition.m index b091ae1e61ba2da4e5e107efe3b05abbad64b44a..e203583af8ac940c54d1b850eab6b6a5d2604d38 100644 --- a/MatlabFiles/fn_posteriorvariancedecomposition.m +++ b/MatlabFiles/fn_posteriorvariancedecomposition.m @@ -10,55 +10,55 @@ function [VarXAll, E_YVarXGivenY, Var_YEXGivenY] = fn_PosteriorVarianceDecomposi % Mathematically and numerically, it must be that VarXAll = E_YVarXGivenY + Var_YEXGivenY. % % Written by T. Zha, October 2009 -% Copyright (C) 1997-2012 Tao Zha % -% This file is part of Dynare. +% Copyright (C) 1997-2012 Tao Zha % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% n_ydraws = size(xydraws,2); if (nargin==1), probs = (1/n_ydraws)*ones(n_ydraws,1); end - + %---------------- Overall variance -------------------- -VarXAll1st = 0.0; -VarXAll2nd = 0.0; +VarXAll1st = 0.0; +VarXAll2nd = 0.0; xy1st = mean(mean(xydraws)); xy2nd = mean(mean(xydraws.^2)); -for (yi=1:n_ydraws) +for (yi=1:n_ydraws) xGiveny1st = mean(xydraws(:,yi)); xGiveny2nd = mean(xydraws(:,yi).^2); VarXAll1st = VarXAll1st + probs(yi) * xGiveny1st; VarXAll2nd = VarXAll2nd + probs(yi) * xGiveny2nd; -end -VarXAll = VarXAll2nd - VarXAll1st^2; +end +VarXAll = VarXAll2nd - VarXAll1st^2; %-------------- The component E_YVarXGivenY -------------------- E_YVarXGivenY = 0.0; -for (yi=1:n_ydraws) +for (yi=1:n_ydraws) VarXGivenY = mean(xydraws(:,yi).^2) - (mean(xydraws(:,yi)))^2; E_YVarXGivenY = E_YVarXGivenY + probs(yi) * VarXGivenY; -end +end E_YVarXGivenY = E_YVarXGivenY; -%-------------- The component Var_YEXGivenY -------------------- -Var_YEXGivenY1st = 0.0; -Var_YEXGivenY2nd = 0.0; -for (yi=1:n_ydraws) +%-------------- The component Var_YEXGivenY -------------------- +Var_YEXGivenY1st = 0.0; +Var_YEXGivenY2nd = 0.0; +for (yi=1:n_ydraws) EXGivenY = mean(xydraws(:,yi)); Var_YEXGivenY1st = Var_YEXGivenY1st + probs(yi) * EXGivenY; Var_YEXGivenY2nd = Var_YEXGivenY2nd + probs(yi) * EXGivenY^2; -end +end Var_YEXGivenY = Var_YEXGivenY2nd - Var_YEXGivenY1st^2; diff --git a/MatlabFiles/fn_printmatrix4tex.m b/MatlabFiles/fn_printmatrix4tex.m index c7e8b432eb3eab23ee61ec38cccf98b9f75dada8..34acfa433c4df4f08247ec9fe27957adf02f2e2b 100644 --- a/MatlabFiles/fn_printmatrix4tex.m +++ b/MatlabFiles/fn_printmatrix4tex.m @@ -1,55 +1,55 @@ -function fn_printmatrix4tex(M, nrows, ncols, indxFloat) -% Prints the matrix to a screen for a tex file. -% -% Inputs: -% M: The matrix to be written to the file. -% nrows: Number of rows of M. -% ncols: Number of columns of M. -% indxFloat: 1 if double; -% 2 if single; -% 3 if only 2 significant digits -% 0 if integer. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% -if nrows~=size(M,1) - error('fn_fprintmatrix(): Make sure the row number supplied match that of the matrix'); -end -if ncols~=size(M,2) - error('fn_fprintmatrix(): Make sure the column number supplied match that of the matrix'); -end -for ki=1:nrows - for kj=1:ncols - fprintf(1,' & '); - if (indxFloat == 1) - fprintf(1,' %.16e ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 2) - fprintf(1,' %.8e ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 3) - fprintf(1,' %5.2f ',M((kj-1)*nrows+ki)); - else - fprintf(1,' %d ',M((kj-1)*nrows+ki)); - end - if (kj==ncols) - fprintf(1,'\\\\\n'); - end - end - if (ki==nrows) - fprintf(1,'\n\n'); - end -end +function fn_printmatrix4tex(M, nrows, ncols, indxFloat) +% Prints the matrix to a screen for a tex file. +% +% Inputs: +% M: The matrix to be written to the file. +% nrows: Number of rows of M. +% ncols: Number of columns of M. +% indxFloat: 1 if double; +% 2 if single; +% 3 if only 2 significant digits +% 0 if integer. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% +if nrows~=size(M,1) + error('fn_fprintmatrix(): Make sure the row number supplied match that of the matrix'); +end +if ncols~=size(M,2) + error('fn_fprintmatrix(): Make sure the column number supplied match that of the matrix'); +end +for ki=1:nrows + for kj=1:ncols + fprintf(1,' & '); + if (indxFloat == 1) + fprintf(1,' %.16e ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 2) + fprintf(1,' %.8e ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 3) + fprintf(1,' %5.2f ',M((kj-1)*nrows+ki)); + else + fprintf(1,' %d ',M((kj-1)*nrows+ki)); + end + if (kj==ncols) + fprintf(1,'\\\\\n'); + end + end + if (ki==nrows) + fprintf(1,'\n\n'); + end +end diff --git a/MatlabFiles/fn_printmatrix4tex_ver2.m b/MatlabFiles/fn_printmatrix4tex_ver2.m index ef0cdc37c236c3164c12375f55f94df4c2554f3f..220325fca8408b1c1920685597eccabc2b7a618a 100644 --- a/MatlabFiles/fn_printmatrix4tex_ver2.m +++ b/MatlabFiles/fn_printmatrix4tex_ver2.m @@ -1,65 +1,65 @@ -function fn_printmatrix4tex_ver2(M, nrows, ncols, indxFloat) -%fn_printmatrix4tex_ver2(M, nrows, ncols, indxFloat) -% -% Prints the matrix to a screen for a tex file. -% Inputs: -% M: The matrix to be written to the file. -% nrows: Number of rows of M. -% ncols: Number of columns of M. -% indxFloat: 1 if only 1 digits after decimal point -% 2 if only 2 digits after decimal point -% 3 if only 3 digits after decimal point -% 4 if only 4 digits after decimal point -% 0 if integer. -% 1001 if double and %.16e -% 1002 if single and %.8e -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% -if nrows~=size(M,1) - error('fn_fprintmatrix(): Make sure the row number supplied match that of the matrix'); -end -if ncols~=size(M,2) - error('fn_fprintmatrix(): Make sure the column number supplied match that of the matrix'); -end -for ki=1:nrows - for kj=1:ncols - fprintf(1,' & '); - if (indxFloat == 1001) - fprintf(1,' %.16e ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 1002) - fprintf(1,' %.8e ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 1) - fprintf(1,' %5.1f ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 2) - fprintf(1,' %5.2f ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 3) - fprintf(1,' %5.3f ',M((kj-1)*nrows+ki)); - elseif (indxFloat == 4) - fprintf(1,' %5.4f ',M((kj-1)*nrows+ki)); - else - fprintf(1,' %d ',M((kj-1)*nrows+ki)); - end - if (kj==ncols) - fprintf(1,'\\\\\n'); - end - end - if (ki==nrows) - fprintf(1,'\n\n'); - end -end +function fn_printmatrix4tex_ver2(M, nrows, ncols, indxFloat) +%fn_printmatrix4tex_ver2(M, nrows, ncols, indxFloat) +% +% Prints the matrix to a screen for a tex file. +% Inputs: +% M: The matrix to be written to the file. +% nrows: Number of rows of M. +% ncols: Number of columns of M. +% indxFloat: 1 if only 1 digits after decimal point +% 2 if only 2 digits after decimal point +% 3 if only 3 digits after decimal point +% 4 if only 4 digits after decimal point +% 0 if integer. +% 1001 if double and %.16e +% 1002 if single and %.8e +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% +if nrows~=size(M,1) + error('fn_fprintmatrix(): Make sure the row number supplied match that of the matrix'); +end +if ncols~=size(M,2) + error('fn_fprintmatrix(): Make sure the column number supplied match that of the matrix'); +end +for ki=1:nrows + for kj=1:ncols + fprintf(1,' & '); + if (indxFloat == 1001) + fprintf(1,' %.16e ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 1002) + fprintf(1,' %.8e ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 1) + fprintf(1,' %5.1f ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 2) + fprintf(1,' %5.2f ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 3) + fprintf(1,' %5.3f ',M((kj-1)*nrows+ki)); + elseif (indxFloat == 4) + fprintf(1,' %5.4f ',M((kj-1)*nrows+ki)); + else + fprintf(1,' %d ',M((kj-1)*nrows+ki)); + end + if (kj==ncols) + fprintf(1,'\\\\\n'); + end + end + if (ki==nrows) + fprintf(1,'\n\n'); + end +end diff --git a/MatlabFiles/fn_readrecessiondates57_01.m b/MatlabFiles/fn_readrecessiondates57_01.m index d75c90dfd38608f110490e2f1ac418ec34775faa..edc2827328814741f6ca8ccf3199234a95864c79 100644 --- a/MatlabFiles/fn_readrecessiondates57_01.m +++ b/MatlabFiles/fn_readrecessiondates57_01.m @@ -1,32 +1,32 @@ -function rec_dates = fn_ReadRecessionDates57_01() -% Recession dates. For some reasons, Matlab code will only take pairs of rec_dates when using rectangle. -% Note that -1 in the following is for the graph lie in the correct position. -% For example, 1961+(1-1)/12 means Jan 1961 plotted right at 1961. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -rec_dates=[ - 1957+(7-1)/12 1958+(3-1)/12 - 1960+(3-1)/12 1961+(1-1)/12 - 1969+(11-1)/12 1970+(10-1)/12 - 1973+(10-1)/12 1975+(2-1)/12 - 1980+(1-1)/12 1980+(6-1)/12 - 1981+(6-1)/12 1982+(10-1)/12 - 1990+(6-1)/12 1991+(2-1)/12 - 2001+(2-1)/12 2001+(10-1)/12 - 2007+(12-1)/12 2008+(12-1)/12]; - +function rec_dates = fn_ReadRecessionDates57_01() +% Recession dates. For some reasons, Matlab code will only take pairs of rec_dates when using rectangle. +% Note that -1 in the following is for the graph lie in the correct position. +% For example, 1961+(1-1)/12 means Jan 1961 plotted right at 1961. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +rec_dates=[ + 1957+(7-1)/12 1958+(3-1)/12 + 1960+(3-1)/12 1961+(1-1)/12 + 1969+(11-1)/12 1970+(10-1)/12 + 1973+(10-1)/12 1975+(2-1)/12 + 1980+(1-1)/12 1980+(6-1)/12 + 1981+(6-1)/12 1982+(10-1)/12 + 1990+(6-1)/12 1991+(2-1)/12 + 2001+(2-1)/12 2001+(10-1)/12 + 2007+(12-1)/12 2008+(12-1)/12]; + diff --git a/MatlabFiles/fn_reset_ini_seed.m b/MatlabFiles/fn_reset_ini_seed.m index f0db11e51d8cae2be7c5a7cf6233439da9f004b0..29053328f0b4fd91a9dc41b3982e34c6f509a4a8 100644 --- a/MatlabFiles/fn_reset_ini_seed.m +++ b/MatlabFiles/fn_reset_ini_seed.m @@ -1,29 +1,29 @@ -function fn_reset_ini_seed(seednumber) -%fn_reset_ini_seed(seednumber) -% -% After Matlab starts, run this function to reset the seed number; otherwise, Matlab automatically resets to the same initial seed. -% seednumber: 0 -- random state reset to the clock time; -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if seednumber - randn('state',seednumber); - rand('state',seednumber); -else - randn('state',fix(100*sum(clock))); - rand('state',fix(100*sum(clock))); -end +function fn_reset_ini_seed(seednumber) +%fn_reset_ini_seed(seednumber) +% +% After Matlab starts, run this function to reset the seed number; otherwise, Matlab automatically resets to the same initial seed. +% seednumber: 0 -- random state reset to the clock time; +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if seednumber + randn('state',seednumber); + rand('state',seednumber); +else + randn('state',fix(100*sum(clock))); + rand('state',fix(100*sum(clock))); +end diff --git a/MatlabFiles/fn_rlrpostr.m b/MatlabFiles/fn_rlrpostr.m index 4350f99300455d7816e240aacad91251bd381147..50b3faf0299917c2bfe59f2aa175b961c62a6700 100644 --- a/MatlabFiles/fn_rlrpostr.m +++ b/MatlabFiles/fn_rlrpostr.m @@ -1,67 +1,67 @@ -function [P,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Ui,Vi) -% [P,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0tld,Hptld,Ui,Vi) -% -% Exporting random (i.e., random prior) Bayesian posterior matrices with linear restrictions -% See Waggoner and Zha's Gibbs sampling paper -% -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% Ptld: cell(nvar,1), transformation matrix that affects the (random walk) prior mean of A+ conditional on A0. -% H0invtld: cell(nvar,1), transformed inv covaraince for free parameters in A0(:,i). -% Hpinvtld: cell(nvar,1), transformed inv covaraince for free parameters in A+(:,i); -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. Imported from dnrprior.m. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. Imported from dnrprior.m. -%----------------- -% P: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. -% In other words, the posterior mean (of g_i) = P{i}*b_i where g_i is a column vector of free parameters -% of A+(:,i)) given b_i (b_i is a column vector of free parameters of A0(:,i)). -% H0inv: cell(nvar,1). Not divided by T yet. In each cell, inverse of posterior covariance matrix H0. -% The exponential term is b_i'*inv(H0)*b_i for the ith equation where b_i = U_i*a0_i. -% It resembles old SpH or Sbd in the exponent term in posterior of A0, but not divided by T yet. -% Hpinv: cell(nvar,1). In each cell, posterior inverse of covariance matrix Hp (A+) for the free parameters -% g_i = V_i*A+(:,i) in the ith equation. -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -nvar = size(yty,1); - -P = cell(nvar,1); % tld: tilda -H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. -Hpinv = cell(nvar,1); % posterior inv(Hp). - - -for n=1:nvar % one for each equation - Hpinv{n} = Vi{n}'*xtx*Vi{n} + Hpinvtld{n}; - P1 = Vi{n}'*xty*Ui{n} + Hpinvtld{n}*Ptld{n}; - P{n} = Hpinv{n}\P1; - H0inv{n} = Ui{n}'*yty*Ui{n} + H0invtld{n} + Ptld{n}'*Hpinvtld{n}*Ptld{n} ... - - P1'*P{n}; %P{n} = (Hpinv{n}\P1); -end +function [P,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Ui,Vi) +% [P,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0tld,Hptld,Ui,Vi) +% +% Exporting random (i.e., random prior) Bayesian posterior matrices with linear restrictions +% See Waggoner and Zha's Gibbs sampling paper +% +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% Ptld: cell(nvar,1), transformation matrix that affects the (random walk) prior mean of A+ conditional on A0. +% H0invtld: cell(nvar,1), transformed inv covaraince for free parameters in A0(:,i). +% Hpinvtld: cell(nvar,1), transformed inv covaraince for free parameters in A+(:,i); +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. Imported from dnrprior.m. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. Imported from dnrprior.m. +%----------------- +% P: cell(nvar,1). In each cell, the transformation matrix that affects the posterior mean of A+ conditional on A0. +% In other words, the posterior mean (of g_i) = P{i}*b_i where g_i is a column vector of free parameters +% of A+(:,i)) given b_i (b_i is a column vector of free parameters of A0(:,i)). +% H0inv: cell(nvar,1). Not divided by T yet. In each cell, inverse of posterior covariance matrix H0. +% The exponential term is b_i'*inv(H0)*b_i for the ith equation where b_i = U_i*a0_i. +% It resembles old SpH or Sbd in the exponent term in posterior of A0, but not divided by T yet. +% Hpinv: cell(nvar,1). In each cell, posterior inverse of covariance matrix Hp (A+) for the free parameters +% g_i = V_i*A+(:,i) in the ith equation. +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +nvar = size(yty,1); + +P = cell(nvar,1); % tld: tilda +H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. +Hpinv = cell(nvar,1); % posterior inv(Hp). + + +for n=1:nvar % one for each equation + Hpinv{n} = Vi{n}'*xtx*Vi{n} + Hpinvtld{n}; + P1 = Vi{n}'*xty*Ui{n} + Hpinvtld{n}*Ptld{n}; + P{n} = Hpinv{n}\P1; + H0inv{n} = Ui{n}'*yty*Ui{n} + H0invtld{n} + Ptld{n}'*Hpinvtld{n}*Ptld{n} ... + - P1'*P{n}; %P{n} = (Hpinv{n}\P1); +end diff --git a/MatlabFiles/fn_rlrprior.m b/MatlabFiles/fn_rlrprior.m index ad7f0e5e3920a53e14961abaf2019418d884e458..626ec0e63f0e766e33b6c63ac2f19d601fd2d508 100644 --- a/MatlabFiles/fn_rlrprior.m +++ b/MatlabFiles/fn_rlrprior.m @@ -1,55 +1,55 @@ -function [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) -% [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) -% -% Exporting random Bayesian prior with linear restrictions -% See Waggoner and Zha's Gibbs sampling paper -% -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. Imported from dnrprior.m. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. Imported from dnrprior.m. -% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior -% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior -% nvar: number of endogenous variables -% -------------------- -% Ptld: cell(nvar,1). The prior mean of g_i is Ptld{i}*b_i; -% H0invtld: cell(nvar,1). Transformed inv covaraince for b_i, the free parameters in A0(:,i); -% Hpinvtld: cell(nvar,1). Transformed inv covaraince for g_i, the free parameters in A+(:,i); -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -Ptld = cell(nvar,1); % tld: tilda -H0invtld = cell(nvar,1); % H0 for different equations under linear restrictions -Hpinvtld = cell(nvar,1); % H+ for different equations under linear restrictions - -for n=1:nvar % one for each equation - Hpinvtld{n} = Vi{n}'*(Hpmulti(:,:,n)\Vi{n}); - Ptld{n} = (Hpinvtld{n}\Vi{n}')*(Hpmulti(:,:,n)\Pi)*Ui{n}; - H0invtld{n} = Ui{n}'*(H0multi(:,:,n)\Ui{n}) + Ui{n}'*Pi'*(Hpmulti(:,:,n)\Pi)*Ui{n} ... - - Ptld{n}'*Hpinvtld{n}*Ptld{n}; -end +function [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) +% [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) +% +% Exporting random Bayesian prior with linear restrictions +% See Waggoner and Zha's Gibbs sampling paper +% +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. Imported from dnrprior.m. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. Imported from dnrprior.m. +% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior +% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior +% nvar: number of endogenous variables +% -------------------- +% Ptld: cell(nvar,1). The prior mean of g_i is Ptld{i}*b_i; +% H0invtld: cell(nvar,1). Transformed inv covaraince for b_i, the free parameters in A0(:,i); +% Hpinvtld: cell(nvar,1). Transformed inv covaraince for g_i, the free parameters in A+(:,i); +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +Ptld = cell(nvar,1); % tld: tilda +H0invtld = cell(nvar,1); % H0 for different equations under linear restrictions +Hpinvtld = cell(nvar,1); % H+ for different equations under linear restrictions + +for n=1:nvar % one for each equation + Hpinvtld{n} = Vi{n}'*(Hpmulti(:,:,n)\Vi{n}); + Ptld{n} = (Hpinvtld{n}\Vi{n}')*(Hpmulti(:,:,n)\Pi)*Ui{n}; + H0invtld{n} = Ui{n}'*(H0multi(:,:,n)\Ui{n}) + Ui{n}'*Pi'*(Hpmulti(:,:,n)\Pi)*Ui{n} ... + - Ptld{n}'*Hpinvtld{n}*Ptld{n}; +end diff --git a/MatlabFiles/fn_rnrprior.m b/MatlabFiles/fn_rnrprior.m index c431895989446b31d7feace5729f18a9dae2307a..c7fdf10e77acd2568de23a69df14b220356e4271 100644 --- a/MatlabFiles/fn_rnrprior.m +++ b/MatlabFiles/fn_rnrprior.m @@ -1,240 +1,240 @@ -function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... - = fn_rnrprior(nvar,q_m,lags,xdgel,mu,nexo,asym0,asymp) -% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... -% = fn_rnrprior(nvar,q_m,lags,xdgel,mu,nexo,asym0,asymp) -% Exporting random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions) -% See Waggoner and Zha's Gibbs sampling paper -% -% nvar: number of endogenous variables -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags. Used only to get variances of residuals for -% the scaling purpose; NOT used for mu(5) and mu(6). -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% NOTE: for this subdirectory, mu(5) and mu(6) are not used. -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% -------------------- -% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior -% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior -% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior -% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior -% -% Tao Zha, February 2000. Revised, September 2000. -% See fn_dataxy.m for using mu(5) and mu(6). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin==5, nexo=1; end -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior -Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior -H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior -Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior - -%*** Constructing Pi for the ith equation under the random walk assumption -Pi = zeros(ncoef,nvar); % same for all equations -Pi(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<7 % the default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. - sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - H0tdinv = diag(sg0bdinv); - % - H0multi(:,:,i)=H0td; - H0invmulti(:,:,i)=H0tdinv; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - Hpmulti(:,:,i)=Hptd; - Hpinvmulti(:,:,i)=Hptdinv; -end - - +function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... + = fn_rnrprior(nvar,q_m,lags,xdgel,mu,nexo,asym0,asymp) +% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... +% = fn_rnrprior(nvar,q_m,lags,xdgel,mu,nexo,asym0,asymp) +% Exporting random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions) +% See Waggoner and Zha's Gibbs sampling paper +% +% nvar: number of endogenous variables +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags. Used only to get variances of residuals for +% the scaling purpose; NOT used for mu(5) and mu(6). +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% NOTE: for this subdirectory, mu(5) and mu(6) are not used. +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% -------------------- +% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior +% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior +% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior +% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior +% +% Tao Zha, February 2000. Revised, September 2000. +% See fn_dataxy.m for using mu(5) and mu(6). +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin==5, nexo=1; end +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior +Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior +H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior +Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior + +%*** Constructing Pi for the ith equation under the random walk assumption +Pi = zeros(ncoef,nvar); % same for all equations +Pi(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<7 % the default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. + sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + H0tdinv = diag(sg0bdinv); + % + H0multi(:,:,i)=H0td; + H0invmulti(:,:,i)=H0tdinv; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + Hpmulti(:,:,i)=Hptd; + Hpinvmulti(:,:,i)=Hptdinv; +end + + diff --git a/MatlabFiles/fn_rnrprior2.m b/MatlabFiles/fn_rnrprior2.m index fd7c332d86d4972166e76eeb46cb472b73952a37..adc9fbdd176d130af2ff578830f1807e3aa16fbe 100644 --- a/MatlabFiles/fn_rnrprior2.m +++ b/MatlabFiles/fn_rnrprior2.m @@ -1,236 +1,236 @@ -function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... - = fn_rnrprior2(nvar,q_m,lags,xdgel,mu1_4,nexo,asym0,asymp) -% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... -% = fn_rnrprior2(nvar,q_m,lags,xdgel,mu1_4,nexo,asym0,asymp) -% Exporting random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions) -% See Waggoner and Zha's Gibbs sampling paper -% -% nvar: number of endogenous variables -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags. Used only to get variances of residuals for -% the scaling purpose; NOT used for hyperparameters on dummy observations. -% mu1_4: 4-by-1 vector of hyperparameters (the numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy2.m for using mu(5) and mu(6). -% mu1_4(1): overall tightness and also for A0; (0.57) -% mu1_4(2): relative tightness for A+; (0.13) -% mu1_4(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu1_4(4): tightness on lag decay; (1) -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% -------------------- -% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior -% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior -% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior -% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior -% -% Tao Zha, February 2000. Revised, September 2000. -% See fn_dataxy2.m for using dummy hyperparameters mu5 and mu6. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin==5, nexo=1; end -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior -Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior -H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior -Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior - -%*** Constructing Pi for the ith equation under the random walk assumption -Pi = zeros(ncoef,nvar); % same for all equations -Pi(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu1_4(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu1_4(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu1_4(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu1_4(1)^2*sg0bid; % ith equation -sgpbida = mu1_4(1)^2*mu1_4(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu1_4(1)^2*mu1_4(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<7 % the default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. - sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - H0tdinv = diag(sg0bdinv); - % - H0multi(:,:,i)=H0td; - H0invmulti(:,:,i)=H0tdinv; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - Hpmulti(:,:,i)=Hptd; - Hpinvmulti(:,:,i)=Hptdinv; -end - - +function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... + = fn_rnrprior2(nvar,q_m,lags,xdgel,mu1_4,nexo,asym0,asymp) +% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... +% = fn_rnrprior2(nvar,q_m,lags,xdgel,mu1_4,nexo,asym0,asymp) +% Exporting random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions) +% See Waggoner and Zha's Gibbs sampling paper +% +% nvar: number of endogenous variables +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags. Used only to get variances of residuals for +% the scaling purpose; NOT used for hyperparameters on dummy observations. +% mu1_4: 4-by-1 vector of hyperparameters (the numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy2.m for using mu(5) and mu(6). +% mu1_4(1): overall tightness and also for A0; (0.57) +% mu1_4(2): relative tightness for A+; (0.13) +% mu1_4(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu1_4(4): tightness on lag decay; (1) +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% -------------------- +% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior +% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior +% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior +% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior +% +% Tao Zha, February 2000. Revised, September 2000. +% See fn_dataxy2.m for using dummy hyperparameters mu5 and mu6. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin==5, nexo=1; end +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior +Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior +H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior +Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior + +%*** Constructing Pi for the ith equation under the random walk assumption +Pi = zeros(ncoef,nvar); % same for all equations +Pi(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu1_4(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu1_4(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu1_4(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu1_4(1)^2*sg0bid; % ith equation +sgpbida = mu1_4(1)^2*mu1_4(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu1_4(1)^2*mu1_4(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<7 % the default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. + sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + H0tdinv = diag(sg0bdinv); + % + H0multi(:,:,i)=H0td; + H0invmulti(:,:,i)=H0tdinv; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + Hpmulti(:,:,i)=Hptd; + Hpinvmulti(:,:,i)=Hptdinv; +end + + diff --git a/MatlabFiles/fn_rnrprior_covres.m b/MatlabFiles/fn_rnrprior_covres.m index 9d84cc8873762daae7b5273354729fbbffbe6f65..f600f9258d3183206c0ad86676259021620d8923 100644 --- a/MatlabFiles/fn_rnrprior_covres.m +++ b/MatlabFiles/fn_rnrprior_covres.m @@ -1,259 +1,259 @@ -function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... - = fn_rnrprior_covres(nvar,q_m,lags,xdgel,mu,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) -% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... -% = fn_rnrprior_covres(nvar,q_m,lags,xdgel,mu,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) -% -% More general than fn_rnrprior.m because when hpmsmd=0, fn_rnrprior_covres() is the same as fn_rnrprior(). -% Allows for prior covariances for the MS and MD equations to achieve liquidity effects. -% Exports random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions yet) -% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p. 71k.0. -% -% nvar: number of endogenous variables -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags. Used only to get variances of residuals for -% the scaling purpose; NOT used for mu(5) and mu(6). -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% NOTE: for this subdirectory, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). -% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. -% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. -% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. -% This will give us a liquidity effect. -% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. -% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. -% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% -------------------- -% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior -% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior -% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior -% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior -% -% Tao Zha, February 2000. Revised, September 2000, February 2003. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -if nargin==7, nexo=1; end -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior -Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior -H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior -Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior - -%*** Constructing Pi for the ith equation under the random walk assumption -Pi = zeros(ncoef,nvar); % same for all equations -Pi(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<9 % the default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to the inverse to get inv(Sg(i)). - %sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - %=== Correlation in the MS equation to get a liquidity effect. - if (i==indxmsmdeqn(1)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - else - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - end - H0tdinv = inv(H0td); - %H0tdinv = diag(sg0bdinv); - % - H0multi(:,:,i)=H0td; - H0invmulti(:,:,i)=H0tdinv; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - Hpmulti(:,:,i)=Hptd; - Hpinvmulti(:,:,i)=Hptdinv; -end - - +function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... + = fn_rnrprior_covres(nvar,q_m,lags,xdgel,mu,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) +% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] ... +% = fn_rnrprior_covres(nvar,q_m,lags,xdgel,mu,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) +% +% More general than fn_rnrprior.m because when hpmsmd=0, fn_rnrprior_covres() is the same as fn_rnrprior(). +% Allows for prior covariances for the MS and MD equations to achieve liquidity effects. +% Exports random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions yet) +% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p. 71k.0. +% +% nvar: number of endogenous variables +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags. Used only to get variances of residuals for +% the scaling purpose; NOT used for mu(5) and mu(6). +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% NOTE: for this subdirectory, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). +% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. +% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. +% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. +% This will give us a liquidity effect. +% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. +% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. +% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% -------------------- +% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior +% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior +% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior +% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior +% +% Tao Zha, February 2000. Revised, September 2000, February 2003. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +if nargin==7, nexo=1; end +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior +Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior +H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior +Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior + +%*** Constructing Pi for the ith equation under the random walk assumption +Pi = zeros(ncoef,nvar); % same for all equations +Pi(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<9 % the default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to the inverse to get inv(Sg(i)). + %sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + %=== Correlation in the MS equation to get a liquidity effect. + if (i==indxmsmdeqn(1)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + else + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + end + H0tdinv = inv(H0td); + %H0tdinv = diag(sg0bdinv); + % + H0multi(:,:,i)=H0td; + H0invmulti(:,:,i)=H0tdinv; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + Hpmulti(:,:,i)=Hptd; + Hpinvmulti(:,:,i)=Hptdinv; +end + + diff --git a/MatlabFiles/fn_rnrprior_covres_dobs.m b/MatlabFiles/fn_rnrprior_covres_dobs.m index e0f7b3b4ae55c9b639e09b4f7f6240e112e22170..1586290a18011efe8de2d3f59e1262bcfa501c49 100644 --- a/MatlabFiles/fn_rnrprior_covres_dobs.m +++ b/MatlabFiles/fn_rnrprior_covres_dobs.m @@ -1,297 +1,297 @@ -function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti,sgh] ... - = fn_rnrprior_covres_dobs(nvar,q_m,lags,xdgel,mu,indxDummy,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) -% Differs from fn_rnrprior_covres_dobs_tv(): no linear restrictions (Ui and Vi) have applied yet to this function, but -% linear restrictions are incorported in fn_rnrprior_covres_dobs_tv(). -% -% Only works for the nexo=1 (constant term) case. To extend this to other exogenous variables, see fn_dataxy.m. 01/14/03. -% Differs from fn_rnrprior_covres.m in that dummy observations are included as part of the explicit prior. See Forcast II, pp.68-69b. -% More general than fn_rnrprior.m because when hpmsmd=0, fn_rnrprior_covres() is the same as fn_rnrprior(). -% Allows for prior covariances for the MS and MD equations to achieve liquidity effects. -% Exports random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions yet) -% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p. 71k.0. -% -% nvar: number of endogenous variables -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: T*nvar endogenous-variable matrix of raw or original data (no manipulation involved) with sample size including lags. -% Order of columns: (1) nvar endogenous variables; (2) constants will be automatically put in the last column. -% Used only to get variances of residuals for mu(1)-mu(5) and for dummy observations mu(5) and mu(6). -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% indxDummy: 1: uses dummy observations to form part of an explicit prior; 0: no dummy observations as part of the prior. -% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. -% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. -% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. -% This will give us a liquidity effect. -% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. -% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. -% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% -------------------- -% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior -% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior -% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior -% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior -% sgh: nvar-by-1 standard deviations of residuals for each equation. -% -% Tao Zha, February 2000. Revised, September 2000, February, May 2003. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if (nargin<=8), nexo=1; end -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior -Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior -H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior -Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior - -%*** Constructing Pi for the ith equation under the random walk assumption -Pi = zeros(ncoef,nvar); % same for all equations -Pi(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% - -if indxDummy % Dummy observations as part of the explicit prior. - ndobs=nvar+1; % Number of dummy observations: nvar unit roots and 1 cointegration prior. - phibar = zeros(ndobs,ncoef); - %* constant term - const = ones(nvar+1,1); - const(1:nvar) = 0.0; - phibar(:,ncoef) = const; % the first nvar periods: no or zero constant! - - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %* Dummies - for k=1:nvar - for m=1:lags - phibar(ndobs,nvar*(m-1)+k) = xdgelint(k); - phibar(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - phibar(1:nvar,:) = 1*mu(5)*phibar(1:nvar,:); % standard Sims and Zha prior - phibar(ndobs,:) = mu(6)*phibar(ndobs,:); - [phiq,phir]=qr(phibar,0); - xtxbar=phir'*phir; % phibar'*phibar. ncoef-by-ncoef. Reduced (not full) rank. See Forcast II, pp.69-69b. -end - -%================================================= -% Computing the (prior) covariance matrix for A0, no data yet. -% As proved in pp.69a-69b, Forecast II, the following prior covariance of A0 -% will remain the same after the dummy observations prior is incorporated. -% The dummy observation prior only affects the prior covariance of A+|A0. -% See pp.69a-69b for the proof. -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<10 % the default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to the inverse to get inv(Sg(i)). - %sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - %=== Correlation in the MS equation to get a liquidity effect. - if (i==indxmsmdeqn(1)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - elseif (i==indxmsmdeqn(2)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - end - H0tdinv = inv(H0td); - %H0tdinv = diag(sg0bdinv); - % - H0multi(:,:,i)=H0td; - H0invmulti(:,:,i)=H0tdinv; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - %--------------- - % The dummy observation prior affects only the prior covariance of A+|A0, - % but not the covariance of A0. See pp.69a-69b for the proof. - %--------------- - if indxDummy % Dummy observations as part of the explicit prior. - Hpinvmulti(:,:,i)=Hptdinv + xtxbar; - Hpmulti(:,:,i) = inv(Hpinvmulti(:,:,i)); - else - Hpmulti(:,:,i)=Hptd; - Hpinvmulti(:,:,i)=Hptdinv; - end -end - - +function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti,sgh] ... + = fn_rnrprior_covres_dobs(nvar,q_m,lags,xdgel,mu,indxDummy,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) +% Differs from fn_rnrprior_covres_dobs_tv(): no linear restrictions (Ui and Vi) have applied yet to this function, but +% linear restrictions are incorported in fn_rnrprior_covres_dobs_tv(). +% +% Only works for the nexo=1 (constant term) case. To extend this to other exogenous variables, see fn_dataxy.m. 01/14/03. +% Differs from fn_rnrprior_covres.m in that dummy observations are included as part of the explicit prior. See Forcast II, pp.68-69b. +% More general than fn_rnrprior.m because when hpmsmd=0, fn_rnrprior_covres() is the same as fn_rnrprior(). +% Allows for prior covariances for the MS and MD equations to achieve liquidity effects. +% Exports random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions yet) +% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p. 71k.0. +% +% nvar: number of endogenous variables +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: T*nvar endogenous-variable matrix of raw or original data (no manipulation involved) with sample size including lags. +% Order of columns: (1) nvar endogenous variables; (2) constants will be automatically put in the last column. +% Used only to get variances of residuals for mu(1)-mu(5) and for dummy observations mu(5) and mu(6). +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% indxDummy: 1: uses dummy observations to form part of an explicit prior; 0: no dummy observations as part of the prior. +% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. +% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. +% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. +% This will give us a liquidity effect. +% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. +% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. +% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% -------------------- +% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior +% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior +% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior +% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior +% sgh: nvar-by-1 standard deviations of residuals for each equation. +% +% Tao Zha, February 2000. Revised, September 2000, February, May 2003. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if (nargin<=8), nexo=1; end +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior +Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior +H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior +Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior + +%*** Constructing Pi for the ith equation under the random walk assumption +Pi = zeros(ncoef,nvar); % same for all equations +Pi(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% + +if indxDummy % Dummy observations as part of the explicit prior. + ndobs=nvar+1; % Number of dummy observations: nvar unit roots and 1 cointegration prior. + phibar = zeros(ndobs,ncoef); + %* constant term + const = ones(nvar+1,1); + const(1:nvar) = 0.0; + phibar(:,ncoef) = const; % the first nvar periods: no or zero constant! + + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %* Dummies + for k=1:nvar + for m=1:lags + phibar(ndobs,nvar*(m-1)+k) = xdgelint(k); + phibar(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + phibar(1:nvar,:) = 1*mu(5)*phibar(1:nvar,:); % standard Sims and Zha prior + phibar(ndobs,:) = mu(6)*phibar(ndobs,:); + [phiq,phir]=qr(phibar,0); + xtxbar=phir'*phir; % phibar'*phibar. ncoef-by-ncoef. Reduced (not full) rank. See Forcast II, pp.69-69b. +end + +%================================================= +% Computing the (prior) covariance matrix for A0, no data yet. +% As proved in pp.69a-69b, Forecast II, the following prior covariance of A0 +% will remain the same after the dummy observations prior is incorporated. +% The dummy observation prior only affects the prior covariance of A+|A0. +% See pp.69a-69b for the proof. +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<10 % the default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to the inverse to get inv(Sg(i)). + %sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + %=== Correlation in the MS equation to get a liquidity effect. + if (i==indxmsmdeqn(1)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + elseif (i==indxmsmdeqn(2)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + end + H0tdinv = inv(H0td); + %H0tdinv = diag(sg0bdinv); + % + H0multi(:,:,i)=H0td; + H0invmulti(:,:,i)=H0tdinv; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + %--------------- + % The dummy observation prior affects only the prior covariance of A+|A0, + % but not the covariance of A0. See pp.69a-69b for the proof. + %--------------- + if indxDummy % Dummy observations as part of the explicit prior. + Hpinvmulti(:,:,i)=Hptdinv + xtxbar; + Hpmulti(:,:,i) = inv(Hpinvmulti(:,:,i)); + else + Hpmulti(:,:,i)=Hptd; + Hpinvmulti(:,:,i)=Hptdinv; + end +end + + diff --git a/MatlabFiles/fn_rnrprior_covres_dobs_tv.m b/MatlabFiles/fn_rnrprior_covres_dobs_tv.m index e89ccd480a5d8a78d680f383a0829c56c568f86c..1a9c9c3eb9e5af7c79a6ec8e4ad6e9adabf699b2 100644 --- a/MatlabFiles/fn_rnrprior_covres_dobs_tv.m +++ b/MatlabFiles/fn_rnrprior_covres_dobs_tv.m @@ -1,310 +1,310 @@ -function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... - = fn_rnrprior_covres_dobs_tv(nvar,nStates,q_m,lags,xdgel,mu,indxDummy,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) -% Differs from fn_rnrprior_covres_dobs_tv(): no linear restrictions (Ui and Vi) have applied yet to this function, but -% linear restrictions are incorported in fn_rnrprior_covres_dobs_tv(). -% -% Only works for the nexo=1 (constant term) case. To extend this to other exogenous variables, see fn_dataxy.m. 01/14/03. -% Differs from fn_rnrprior_covres_tv.m in that dummy observations are included as part of the explicit prior. See Forcast II, pp.68-69b. -% Exports random Bayesian prior of Sims and Zha with asymmetric rior with linear restrictions already applied -% and with dummy observations (i.e., mu(5) and mu(6)) used as part of an explicit prior. -% This function allows for prior covariances for the MS and MD equations to achieve liquidity effects. -% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES pp. 71k.0 and 50-61. -% -% nvar: number of endogenous variables -% nStates: Number of states. -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: T*nvar endogenous-variable matrix of raw or original data (no manipulation involved) with sample size including lags. -% Order of columns: (1) nvar endogenous variables; (2) constants will be automatically put in the last column. -% Used only to get variances of residuals for mu(1)-mu(5) and for dummy observations mu(5) and mu(6). -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% NOTE: for this function, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). -% indxDummy: 1: uses dummy observations to form part of an explicit prior; 0: no dummy observations as part of the prior. -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi*si orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters -% within the state and si is the number of free states. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state]. -% Vi: nvar-by-1 cell. In each cell, k-by-ri*ti orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters within the state and ti is the number of free states. -% With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. The ith equation is in the order of [nvar variables -% for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar -% variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on]. -% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. -% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. -% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. -% This will give us a liquidity effect. If hpmsmd=0, no such restrictions will be imposed. -% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. -% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. -% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% -------------------- -% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% qi*si-by-qi*si. The inverse of H0tld on p.60. -% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% ri*ti-by-ri*ti.The inverse of Hptld on p.60. -% -% Tao Zha, February 2000. Revised, September 2000, 2001, February, May 2003. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin<=11, nexo=1; end % <<>>1 -ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. -ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. - -H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. -Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. - -%*** Constructing Pi_bar for the ith equation under the random walk assumption -Pi_bar = zeros(ncoef,nvar); % same for all equations -Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% -if indxDummy % Dummy observations as part of the explicit prior. - ndobs=nvar+1; % Number of dummy observations: nvar unit roots and 1 cointegration prior. - phibar = zeros(ndobs,ncoef); - %* constant term - const = ones(nvar+1,1); - const(1:nvar) = 0.0; - phibar(:,ncoef) = const; % the first nvar periods: no or zero constant! - - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %* Dummies - for k=1:nvar - for m=1:lags - phibar(ndobs,nvar*(m-1)+k) = xdgelint(k); - phibar(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - phibar(1:nvar,:) = 1*mu(5)*phibar(1:nvar,:); % standard Sims and Zha prior - phibar(ndobs,:) = mu(6)*phibar(ndobs,:); - [phiq,phir]=qr(phibar,0); - xtxbar=phir'*phir; % phibar'*phibar. ncoef-by-ncoef. Reduced (not full) rank. See Forcast II, pp.69-69b. -end - - - - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<13 % <<>>1 Default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to the inverse to get inv(Sg(i)). - %sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - %=== Correlation in the MS equation to get a liquidity effect. - if (i==indxmsmdeqn(1)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - elseif (i==indxmsmdeqn(2)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - end - H0tdinv = inv(H0td); - %H0tdinv = diag(sg0bdinv); - % - H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - %--------------- - % The dummy observation prior affects only the prior covariance of A+|A0, - % but not the covariance of A0. See pp.69a-69b for the proof. - %--------------- - if indxDummy % Dummy observations as part of the explicit prior. - Hptdinv2 = Hptdinv + xtxbar; % Rename Hptdinv to Hptdinv2 because we want to keep Hptdinv diagonal in the next loop of i. - else - Hptdinv2 = Hptdinv; - end - Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv2/nStates))*Vi{i}; - %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? -end - - +function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... + = fn_rnrprior_covres_dobs_tv(nvar,nStates,q_m,lags,xdgel,mu,indxDummy,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) +% Differs from fn_rnrprior_covres_dobs_tv(): no linear restrictions (Ui and Vi) have applied yet to this function, but +% linear restrictions are incorported in fn_rnrprior_covres_dobs_tv(). +% +% Only works for the nexo=1 (constant term) case. To extend this to other exogenous variables, see fn_dataxy.m. 01/14/03. +% Differs from fn_rnrprior_covres_tv.m in that dummy observations are included as part of the explicit prior. See Forcast II, pp.68-69b. +% Exports random Bayesian prior of Sims and Zha with asymmetric rior with linear restrictions already applied +% and with dummy observations (i.e., mu(5) and mu(6)) used as part of an explicit prior. +% This function allows for prior covariances for the MS and MD equations to achieve liquidity effects. +% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES pp. 71k.0 and 50-61. +% +% nvar: number of endogenous variables +% nStates: Number of states. +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: T*nvar endogenous-variable matrix of raw or original data (no manipulation involved) with sample size including lags. +% Order of columns: (1) nvar endogenous variables; (2) constants will be automatically put in the last column. +% Used only to get variances of residuals for mu(1)-mu(5) and for dummy observations mu(5) and mu(6). +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% NOTE: for this function, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). +% indxDummy: 1: uses dummy observations to form part of an explicit prior; 0: no dummy observations as part of the prior. +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi*si orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters +% within the state and si is the number of free states. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state]. +% Vi: nvar-by-1 cell. In each cell, k-by-ri*ti orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters within the state and ti is the number of free states. +% With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. The ith equation is in the order of [nvar variables +% for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar +% variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on]. +% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. +% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. +% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. +% This will give us a liquidity effect. If hpmsmd=0, no such restrictions will be imposed. +% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. +% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. +% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% -------------------- +% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% qi*si-by-qi*si. The inverse of H0tld on p.60. +% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% ri*ti-by-ri*ti.The inverse of Hptld on p.60. +% +% Tao Zha, February 2000. Revised, September 2000, 2001, February, May 2003. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin<=11, nexo=1; end % <<>>1 +ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. +ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. + +H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. +Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. + +%*** Constructing Pi_bar for the ith equation under the random walk assumption +Pi_bar = zeros(ncoef,nvar); % same for all equations +Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% +if indxDummy % Dummy observations as part of the explicit prior. + ndobs=nvar+1; % Number of dummy observations: nvar unit roots and 1 cointegration prior. + phibar = zeros(ndobs,ncoef); + %* constant term + const = ones(nvar+1,1); + const(1:nvar) = 0.0; + phibar(:,ncoef) = const; % the first nvar periods: no or zero constant! + + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %* Dummies + for k=1:nvar + for m=1:lags + phibar(ndobs,nvar*(m-1)+k) = xdgelint(k); + phibar(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + phibar(1:nvar,:) = 1*mu(5)*phibar(1:nvar,:); % standard Sims and Zha prior + phibar(ndobs,:) = mu(6)*phibar(ndobs,:); + [phiq,phir]=qr(phibar,0); + xtxbar=phir'*phir; % phibar'*phibar. ncoef-by-ncoef. Reduced (not full) rank. See Forcast II, pp.69-69b. +end + + + + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<13 % <<>>1 Default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to the inverse to get inv(Sg(i)). + %sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + %=== Correlation in the MS equation to get a liquidity effect. + if (i==indxmsmdeqn(1)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + elseif (i==indxmsmdeqn(2)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + end + H0tdinv = inv(H0td); + %H0tdinv = diag(sg0bdinv); + % + H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + %--------------- + % The dummy observation prior affects only the prior covariance of A+|A0, + % but not the covariance of A0. See pp.69a-69b for the proof. + %--------------- + if indxDummy % Dummy observations as part of the explicit prior. + Hptdinv2 = Hptdinv + xtxbar; % Rename Hptdinv to Hptdinv2 because we want to keep Hptdinv diagonal in the next loop of i. + else + Hptdinv2 = Hptdinv; + end + Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv2/nStates))*Vi{i}; + %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? +end + + diff --git a/MatlabFiles/fn_rnrprior_covres_dobs_tv2.m b/MatlabFiles/fn_rnrprior_covres_dobs_tv2.m index 745f8adb678aaf4794771ad6a1351ddba9af9886..b1798897b442c3116c13bb6394b269c1a4a57b1c 100644 --- a/MatlabFiles/fn_rnrprior_covres_dobs_tv2.m +++ b/MatlabFiles/fn_rnrprior_covres_dobs_tv2.m @@ -1,325 +1,325 @@ -function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... - = fn_rnrprior_covres_dobs_tv2(nvar,nStates,indxScaleStates,q_m,lags,xdgel,mu,indxDummy,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) -% Differs from fn_rnrprior_covres_dobs(): linear restrictions (Ui and Vi) have been incorported in fn_rnrprior_covres_dobs_tv?(). -% Differs from fn_rnrprior_covres_dobs_tv(): allows an option to scale up the prior variance by nStates or not scale at all, -% so that the prior value is the same as the constant VAR when the parameters in all states are the same. -% -% Only works for the nexo=1 (constant term) case. To extend this to other exogenous variables, see fn_dataxy.m. 01/14/03. -% Differs from fn_rnrprior_covres_tv.m in that dummy observations are included as part of the explicit prior. See Forcast II, pp.68-69b. -% Exports random Bayesian prior of Sims and Zha with asymmetric rior with linear restrictions already applied -% and with dummy observations (i.e., mu(5) and mu(6)) used as part of an explicit prior. -% This function allows for prior covariances for the MS and MD equations to achieve liquidity effects. -% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES pp. 71k.0 and 50-61. -% -% nvar: number of endogenous variables -% nStates: Number of states. -% indxScaleStates: if 0, no scale adjustment in the prior variance for the number of states in the function fn_rnrprior_covres_dobs_tv2(); -% if 1: allows a scale adjustment, marking the prior variance bigger by the number of states. -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: T*nvar endogenous-variable matrix of raw or original data (no manipulation involved) with sample size including lags. -% Order of columns: (1) nvar endogenous variables; (2) constants will be automatically put in the last column. -% Used only to get variances of residuals for mu(1)-mu(5) and for dummy observations mu(5) and mu(6). -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% NOTE: for this function, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). -% indxDummy: 1: uses dummy observations to form part of an explicit prior; 0: no dummy observations as part of the prior. -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi*si orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters -% within the state and si is the number of free states. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state]. -% Vi: nvar-by-1 cell. In each cell, k-by-ri*ti orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters within the state and ti is the number of free states. -% With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. The ith equation is in the order of [nvar variables -% for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar -% variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on]. -% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. -% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. -% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. -% This will give us a liquidity effect. If hpmsmd=0, no such restrictions will be imposed. -% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. -% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. -% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% -------------------- -% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% qi*si-by-qi*si. The inverse of H0tld on p.60. -% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% ri*ti-by-ri*ti.The inverse of Hptld on p.60. -% -% Differs from fn_rnrprior_covres_dobs(): linear restrictions (Ui and Vi) have been incorported in fn_rnrprior_covres_dobs_tv?(). -% Differs from fn_rnrprior_covres_dobs_tv(): allows an option to scale up the prior variance by nStates or not scale at all. -% so that the prior value is the same as the constant VAR when the parameters in all states are the same. -% Tao Zha, February 2000. Revised, September 2000, 2001, February, May 2003, May 2004. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin<=12, nexo=1; end % <<>>1 -ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. -ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. - -H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. -Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. - -%*** Constructing Pi_bar for the ith equation under the random walk assumption -Pi_bar = zeros(ncoef,nvar); % same for all equations -Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% -if indxDummy % Dummy observations as part of the explicit prior. - ndobs=nvar+1; % Number of dummy observations: nvar unit roots and 1 cointegration prior. - phibar = zeros(ndobs,ncoef); - %* constant term - const = ones(nvar+1,1); - const(1:nvar) = 0.0; - phibar(:,ncoef) = const; % the first nvar periods: no or zero constant! - - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %* Dummies - for k=1:nvar - for m=1:lags - phibar(ndobs,nvar*(m-1)+k) = xdgelint(k); - phibar(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - phibar(1:nvar,:) = 1*mu(5)*phibar(1:nvar,:); % standard Sims and Zha prior - phibar(ndobs,:) = mu(6)*phibar(ndobs,:); - [phiq,phir]=qr(phibar,0); - xtxbar=phir'*phir; % phibar'*phibar. ncoef-by-ncoef. Reduced (not full) rank. See Forcast II, pp.69-69b. -end - - - - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<14 % <<>>1 Default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to the inverse to get inv(Sg(i)). - %sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - %=== Correlation in the MS equation to get a liquidity effect. - if (i==indxmsmdeqn(1)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - elseif (i==indxmsmdeqn(2)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - end - H0tdinv = inv(H0td); - %H0tdinv = diag(sg0bdinv); - % - if indxScaleStates - H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; - else - H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv))*Ui{i}; - end - - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - %--------------- - % The dummy observation prior affects only the prior covariance of A+|A0, - % but not the covariance of A0. See pp.69a-69b for the proof. - %--------------- - if indxDummy % Dummy observations as part of the explicit prior. - Hptdinv2 = Hptdinv + xtxbar; % Rename Hptdinv to Hptdinv2 because we want to keep Hptdinv diagonal in the next loop of i. - else - Hptdinv2 = Hptdinv; - end - if (indxScaleStates) - Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv2/nStates))*Vi{i}; - else - Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv2))*Vi{i}; - end - %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? -end - - +function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... + = fn_rnrprior_covres_dobs_tv2(nvar,nStates,indxScaleStates,q_m,lags,xdgel,mu,indxDummy,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) +% Differs from fn_rnrprior_covres_dobs(): linear restrictions (Ui and Vi) have been incorported in fn_rnrprior_covres_dobs_tv?(). +% Differs from fn_rnrprior_covres_dobs_tv(): allows an option to scale up the prior variance by nStates or not scale at all, +% so that the prior value is the same as the constant VAR when the parameters in all states are the same. +% +% Only works for the nexo=1 (constant term) case. To extend this to other exogenous variables, see fn_dataxy.m. 01/14/03. +% Differs from fn_rnrprior_covres_tv.m in that dummy observations are included as part of the explicit prior. See Forcast II, pp.68-69b. +% Exports random Bayesian prior of Sims and Zha with asymmetric rior with linear restrictions already applied +% and with dummy observations (i.e., mu(5) and mu(6)) used as part of an explicit prior. +% This function allows for prior covariances for the MS and MD equations to achieve liquidity effects. +% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES pp. 71k.0 and 50-61. +% +% nvar: number of endogenous variables +% nStates: Number of states. +% indxScaleStates: if 0, no scale adjustment in the prior variance for the number of states in the function fn_rnrprior_covres_dobs_tv2(); +% if 1: allows a scale adjustment, marking the prior variance bigger by the number of states. +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: T*nvar endogenous-variable matrix of raw or original data (no manipulation involved) with sample size including lags. +% Order of columns: (1) nvar endogenous variables; (2) constants will be automatically put in the last column. +% Used only to get variances of residuals for mu(1)-mu(5) and for dummy observations mu(5) and mu(6). +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% NOTE: for this function, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). +% indxDummy: 1: uses dummy observations to form part of an explicit prior; 0: no dummy observations as part of the prior. +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi*si orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters +% within the state and si is the number of free states. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state]. +% Vi: nvar-by-1 cell. In each cell, k-by-ri*ti orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters within the state and ti is the number of free states. +% With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. The ith equation is in the order of [nvar variables +% for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar +% variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on]. +% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. +% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. +% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. +% This will give us a liquidity effect. If hpmsmd=0, no such restrictions will be imposed. +% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. +% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. +% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% -------------------- +% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% qi*si-by-qi*si. The inverse of H0tld on p.60. +% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% ri*ti-by-ri*ti.The inverse of Hptld on p.60. +% +% Differs from fn_rnrprior_covres_dobs(): linear restrictions (Ui and Vi) have been incorported in fn_rnrprior_covres_dobs_tv?(). +% Differs from fn_rnrprior_covres_dobs_tv(): allows an option to scale up the prior variance by nStates or not scale at all. +% so that the prior value is the same as the constant VAR when the parameters in all states are the same. +% Tao Zha, February 2000. Revised, September 2000, 2001, February, May 2003, May 2004. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin<=12, nexo=1; end % <<>>1 +ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. +ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. + +H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. +Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. + +%*** Constructing Pi_bar for the ith equation under the random walk assumption +Pi_bar = zeros(ncoef,nvar); % same for all equations +Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% +if indxDummy % Dummy observations as part of the explicit prior. + ndobs=nvar+1; % Number of dummy observations: nvar unit roots and 1 cointegration prior. + phibar = zeros(ndobs,ncoef); + %* constant term + const = ones(nvar+1,1); + const(1:nvar) = 0.0; + phibar(:,ncoef) = const; % the first nvar periods: no or zero constant! + + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %* Dummies + for k=1:nvar + for m=1:lags + phibar(ndobs,nvar*(m-1)+k) = xdgelint(k); + phibar(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + phibar(1:nvar,:) = 1*mu(5)*phibar(1:nvar,:); % standard Sims and Zha prior + phibar(ndobs,:) = mu(6)*phibar(ndobs,:); + [phiq,phir]=qr(phibar,0); + xtxbar=phir'*phir; % phibar'*phibar. ncoef-by-ncoef. Reduced (not full) rank. See Forcast II, pp.69-69b. +end + + + + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<14 % <<>>1 Default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to the inverse to get inv(Sg(i)). + %sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + %=== Correlation in the MS equation to get a liquidity effect. + if (i==indxmsmdeqn(1)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + elseif (i==indxmsmdeqn(2)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + end + H0tdinv = inv(H0td); + %H0tdinv = diag(sg0bdinv); + % + if indxScaleStates + H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; + else + H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv))*Ui{i}; + end + + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + %--------------- + % The dummy observation prior affects only the prior covariance of A+|A0, + % but not the covariance of A0. See pp.69a-69b for the proof. + %--------------- + if indxDummy % Dummy observations as part of the explicit prior. + Hptdinv2 = Hptdinv + xtxbar; % Rename Hptdinv to Hptdinv2 because we want to keep Hptdinv diagonal in the next loop of i. + else + Hptdinv2 = Hptdinv; + end + if (indxScaleStates) + Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv2/nStates))*Vi{i}; + else + Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv2))*Vi{i}; + end + %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? +end + + diff --git a/MatlabFiles/fn_rnrprior_covres_tv.m b/MatlabFiles/fn_rnrprior_covres_tv.m index eb5935f9448e57de0c4361bd29c4e4c571579986..8082206b38d45482a81debe64b1380593fd42464 100644 --- a/MatlabFiles/fn_rnrprior_covres_tv.m +++ b/MatlabFiles/fn_rnrprior_covres_tv.m @@ -1,274 +1,274 @@ -function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... - = fn_rnrprior_covres_tv(nvar,nStates,q_m,lags,xdgel,mu,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) -% [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... -% = fn_rnrprior_covres_tv(nvar,nStates,q_m,lags,xdgel,mu,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) -% -% More general than fn_rnrprior_tv() because, when hpmsmd=0, fn_rnrprior_covres_tv() is the same as fn_rnrprior_tv(). -% Exports random Bayesian prior of Sims and Zha with asymmetric rior with linear restrictions already applied -% but without dummy observations (i.e., mu(5) and mu(6)) yet. -% This function allows for prior covariances for the MS and MD equations to achieve liquidity effects. -% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES pp. 71k.0 and 50-61. -% -% nvar: number of endogenous variables -% nStates: Number of states. -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags. Used only to get variances of residuals for -% the scaling purpose; NOT used for mu(5) and mu(6). -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% NOTE: for this function, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi*si orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters -% within the state and si is the number of free states. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state]. -% Vi: nvar-by-1 cell. In each cell, k-by-ri*ti orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters within the state and ti is the number of free states. -% With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. The ith equation is in the order of [nvar variables -% for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar -% variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on]. -% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. -% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. -% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. -% This will give us a liquidity effect. If hpmsmd=0, no such restrictions will be imposed. -% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. -% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. -% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% -------------------- -% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% qi*si-by-qi*si. The inverse of H0tld on p.60. -% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% ri*ti-by-ri*ti.The inverse of Hptld on p.60. -% -% Tao Zha, February 2000. Revised, September 2000, 2001, February, May 2003. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin==10, nexo=1; end % <<>>1 -ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. -ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. - -H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. -Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. - -%*** Constructing Pi_bar for the ith equation under the random walk assumption -Pi_bar = zeros(ncoef,nvar); % same for all equations -Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<12 % <<>>1 Default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to the inverse to get inv(Sg(i)). - %sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - %=== Correlation in the MS equation to get a liquidity effect. - if (i==indxmsmdeqn(1)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - elseif (i==indxmsmdeqn(2)) - H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); - end - H0tdinv = inv(H0td); - %H0tdinv = diag(sg0bdinv); - % - H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv/nStates))*Vi{i}; - %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? -end - - +function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... + = fn_rnrprior_covres_tv(nvar,nStates,q_m,lags,xdgel,mu,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) +% [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... +% = fn_rnrprior_covres_tv(nvar,nStates,q_m,lags,xdgel,mu,Ui,Vi,hpmsmd,indxmsmdeqn,nexo,asym0,asymp) +% +% More general than fn_rnrprior_tv() because, when hpmsmd=0, fn_rnrprior_covres_tv() is the same as fn_rnrprior_tv(). +% Exports random Bayesian prior of Sims and Zha with asymmetric rior with linear restrictions already applied +% but without dummy observations (i.e., mu(5) and mu(6)) yet. +% This function allows for prior covariances for the MS and MD equations to achieve liquidity effects. +% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES pp. 71k.0 and 50-61. +% +% nvar: number of endogenous variables +% nStates: Number of states. +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags. Used only to get variances of residuals for +% the scaling purpose; NOT used for mu(5) and mu(6). +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% NOTE: for this function, mu(5) and mu(6) are not used. See fn_dataxy.m for using mu(5) and mu(6). +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi*si orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters +% within the state and si is the number of free states. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state]. +% Vi: nvar-by-1 cell. In each cell, k-by-ri*ti orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters within the state and ti is the number of free states. +% With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. The ith equation is in the order of [nvar variables +% for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar +% variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on]. +% hpmsmd: 2-by-1 hyperparameters with -1<h1=hpmsmd(1)<=0 for the MS equation and 0<=h2=hpmsmd(2)<1 the MD equation. Consider a1*R + a2*M. +% The term h1*var(a1)*var(a2) is the prior covariance of a1 and a2 for MS, equivalent to penalizing the same sign of a1 and a2. +% The term h2*var(a1)*var(a2) is the prior covariance of a1 and a2 for MD, equivalent to penalizing opposite signs of a1 and a2. +% This will give us a liquidity effect. If hpmsmd=0, no such restrictions will be imposed. +% indxmsmdeqn: 4-by-1 index for the locations of the MS and MD equation and for the locations of M and R. +% indxmsmdeqn(1) for MS and indxmsmdeqn(2) for MD. +% indxmsmdeqn(3) for M and indxmsmdeqn(4) for R. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% -------------------- +% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% qi*si-by-qi*si. The inverse of H0tld on p.60. +% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% ri*ti-by-ri*ti.The inverse of Hptld on p.60. +% +% Tao Zha, February 2000. Revised, September 2000, 2001, February, May 2003. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin==10, nexo=1; end % <<>>1 +ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. +ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. + +H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. +Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. + +%*** Constructing Pi_bar for the ith equation under the random walk assumption +Pi_bar = zeros(ncoef,nvar); % same for all equations +Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<12 % <<>>1 Default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to the inverse to get inv(Sg(i)). + %sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + %=== Correlation in the MS equation to get a liquidity effect. + if (i==indxmsmdeqn(1)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(1)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + elseif (i==indxmsmdeqn(2)) + H0td(indxmsmdeqn(3),indxmsmdeqn(4)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + H0td(indxmsmdeqn(4),indxmsmdeqn(3)) = hpmsmd(2)*sqrt(sg0bida(indxmsmdeqn(3))*sg0bida(indxmsmdeqn(4))); + end + H0tdinv = inv(H0td); + %H0tdinv = diag(sg0bdinv); + % + H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv/nStates))*Vi{i}; + %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? +end + + diff --git a/MatlabFiles/fn_rnrprior_tv.m b/MatlabFiles/fn_rnrprior_tv.m index 3b7c4414a730fc8eca5e053b18c4c95cfdb4d4b4..d408bbf7d4b0c41199b8f5ed0ca3fe1c2d4fe6ea 100644 --- a/MatlabFiles/fn_rnrprior_tv.m +++ b/MatlabFiles/fn_rnrprior_tv.m @@ -1,252 +1,252 @@ -function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... - = fn_rnrprior_tv(nvar,nStates,q_m,lags,xdgel,mu,Ui,Vi,nexo,asym0,asymp) -% Exports random Bayesian prior of Sims and Zha with linear restrictions applied, allowing for -% possibly with asymmetric prior. -% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTE pp.50-61. -% -% nvar: number of endogenous variables -% nStates: Number of states. -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags. Used only to get variances of residuals for -% the scaling purpose; NOT used for mu(5) and mu(6). -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where -% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% NOTE: for this function, mu(5) and mu(6) are not used. -% Ui: nvar-by-1 cell. In each cell, nvar-by-(qi+si) orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters -% within the state and si is the number of free parameters across the states. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% Vi: nvar-by-1 cell. In each cell, k-by-(ri+ti) orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters within the state and ti is the number of free -% parameters across the states. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. The ith equation is in the order of [nvar for 1st lag, -% ..., nvar for last lag, const]. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. -% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. -% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. -% -------------------- -% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% (qi+si)-by-(qi+si). The inverse of H0tld on p.60. -% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is -% (ri+ti)-by-(ri+ti).The inverse of Hptld on p.60. -% -% Tao Zha, February 2000. Revised, September 2000, 2001. -% See fn_dataxy.m for using mu(5) and mu(6). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin==8, nexo=1; end % <<>>1 -ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. -ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. - -H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. -Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. - -%*** Constructing Pi_bar for the ith equation under the random walk assumption -Pi_bar = zeros(ncoef,nvar); % same for all equations -Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - - -if nargin<10 % <<>>1 Default is no asymmetric information - asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness - asymp = ones(ncoef-1,nvar); % for A+. Column -- equation -end - -%**** Asymmetric Information -%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. - sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - H0tdinv = diag(sg0bdinv); - % - H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv/nStates))*Vi{i}; - %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? -end - - +function [Pi_bar,H0tldcell_inv,Hptldcell_inv] ... + = fn_rnrprior_tv(nvar,nStates,q_m,lags,xdgel,mu,Ui,Vi,nexo,asym0,asymp) +% Exports random Bayesian prior of Sims and Zha with linear restrictions applied, allowing for +% possibly with asymmetric prior. +% See Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTE pp.50-61. +% +% nvar: number of endogenous variables +% nStates: Number of states. +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags. Used only to get variances of residuals for +% the scaling purpose; NOT used for mu(5) and mu(6). +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast), where +% mu(5) and mu(6) are NOT used here. See fn_dataxy.m for using mu(5) and mu(6). +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% NOTE: for this function, mu(5) and mu(6) are not used. +% Ui: nvar-by-1 cell. In each cell, nvar-by-(qi+si) orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters +% within the state and si is the number of free parameters across the states. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% Vi: nvar-by-1 cell. In each cell, k-by-(ri+ti) orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters within the state and ti is the number of free +% parameters across the states. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. The ith equation is in the order of [nvar for 1st lag, +% ..., nvar for last lag, const]. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation. +% If ones(nvar,nvar), symmetric prior; if not, relative (asymmetric) tightness on A0. +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation. +% If ones(ncoef-1,nvar), symmetric prior; if not, relative (asymmetric) tightness on A+. +% -------------------- +% Pi_bar: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0tldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% (qi+si)-by-(qi+si). The inverse of H0tld on p.60. +% Hptldcell_inv: cell(nvar,1). The ith cell represents the ith equation, where the dim is +% (ri+ti)-by-(ri+ti).The inverse of Hptld on p.60. +% +% Tao Zha, February 2000. Revised, September 2000, 2001. +% See fn_dataxy.m for using mu(5) and mu(6). +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin==8, nexo=1; end % <<>>1 +ncoef = nvar*lags+nexo; % Number of coefficients in *each* equation for each state, RHS coefficients only. +ncoefsts = nStates*ncoef; % Number of coefficients in *each* equation in all states, RHS coefficients only. + +H0tldcell_inv=cell(nvar,1); % inv(H0tilde) for different equations under asymmetric prior. +Hptldcell_inv=cell(nvar,1); % inv(H+tilde) for different equations under asymmetric prior. + +%*** Constructing Pi_bar for the ith equation under the random walk assumption +Pi_bar = zeros(ncoef,nvar); % same for all equations +Pi_bar(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + + +if nargin<10 % <<>>1 Default is no asymmetric information + asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness + asymp = ones(ncoef-1,nvar); % for A+. Column -- equation +end + +%**** Asymmetric Information +%asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +%asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. + sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + H0tdinv = diag(sg0bdinv); + % + H0tldcell_inv{i}=(Ui{i}'*kron(eye(nStates),H0tdinv/nStates))*Ui{i}; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + Hptldcell_inv{i}=(Vi{i}'*kron(eye(nStates),Hptdinv/nStates))*Vi{i}; + %Hptdinv_3 = kron(eye(nStates),Hptdinv); % ????? +end + + diff --git a/MatlabFiles/fn_seriesgraph.m b/MatlabFiles/fn_seriesgraph.m index 2a252e8d97e6ecd4b93df691ebff1688a49b2c52..53cd72d54bf076d9cd501bc483edb243504e8e38 100644 --- a/MatlabFiles/fn_seriesgraph.m +++ b/MatlabFiles/fn_seriesgraph.m @@ -1,65 +1,65 @@ -function fn_seriesgraph(ydate,keyindx,rnum,cnum,q_m,xlab,ylab,tlab) -% -% Graph actual series or point forecasts or both (annual or monthly or quarterly) -% -% ydate: series data with dates in the first 2 columns in the order of year and month (or quarter). -% Some elements are allowed to be NaN if no data are available. -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -% q_m: if 4 or 12, quarterly or monthly data -% xlab: x-axis label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -% ylab: string array for the length(keyindx)-by-1 variables -% tlab: title label for (e.g., as of time of forecast) -%------------- -% No output argument for this graph file -% See fn_foregraph.m, fn_forerrgraph.m. -% -% Tao Zha, September 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -vyrs = ydate(:,1); % vectorized -hornum = cell(length(vyrs),1); % horizontal year (number) -count=0; -for k=vyrs' - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - plot(ydate(:,1)+ydate(:,2)/q_m,ydate(:,2+i)) - - if (ydate(1,2)==0) % only for annual growth rates (not for, say, monthly annualized rates) - set(gca,'XLim',[vyrs(1) vyrs(end)]) - set(gca,'XTick',vyrs) - set(gca,'XTickLabel',char(hornum)) - end - - if i==keyindx(1) - title(tlab) - elseif i>=length(keyindx) %i>=length(keyindx)-1 - xlabel(xlab) - end - % - grid - ylabel(char(ylab(i))) -end +function fn_seriesgraph(ydate,keyindx,rnum,cnum,q_m,xlab,ylab,tlab) +% +% Graph actual series or point forecasts or both (annual or monthly or quarterly) +% +% ydate: series data with dates in the first 2 columns in the order of year and month (or quarter). +% Some elements are allowed to be NaN if no data are available. +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +% q_m: if 4 or 12, quarterly or monthly data +% xlab: x-axis label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +% ylab: string array for the length(keyindx)-by-1 variables +% tlab: title label for (e.g., as of time of forecast) +%------------- +% No output argument for this graph file +% See fn_foregraph.m, fn_forerrgraph.m. +% +% Tao Zha, September 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +vyrs = ydate(:,1); % vectorized +hornum = cell(length(vyrs),1); % horizontal year (number) +count=0; +for k=vyrs' + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + plot(ydate(:,1)+ydate(:,2)/q_m,ydate(:,2+i)) + + if (ydate(1,2)==0) % only for annual growth rates (not for, say, monthly annualized rates) + set(gca,'XLim',[vyrs(1) vyrs(end)]) + set(gca,'XTick',vyrs) + set(gca,'XTickLabel',char(hornum)) + end + + if i==keyindx(1) + title(tlab) + elseif i>=length(keyindx) %i>=length(keyindx)-1 + xlabel(xlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/fn_simul.m b/MatlabFiles/fn_simul.m index 9d3d8d83105c6e76a5e1d3fe854ff06c2c23fbd2..7a77db5a08a8bfd18a68f3dc8ba2cf4f0af56728 100644 --- a/MatlabFiles/fn_simul.m +++ b/MatlabFiles/fn_simul.m @@ -1,42 +1,42 @@ -function simul = fn_simul(G1, impact, nsim, shocks, x0); -% Inputs: -% G1: n-by-n; -% impact: n-by-r; -% nsim: length of time series for simulation. -% shocks: r-by-nsim, exogenous driving processes -% x0: n-by-1, initial values for the variables of interest -%--- -% Outputs: -% simul: nsim-by-n. -% -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -[n,r] = size(impact); - -[n1,n2] = size(G1); -if (n1 ~= n2) || (n1 ~= n) - error('fn_simul.m: make sure that (1) G1 is square and (2) size(G1,1) = size(impact,1)'); -end - -simul_tmp = zeros(n, nsim); - -simul_tmp(:, 1) = x0; -for ti = 2:nsim; - simul_tmp(:, ti) = G1*simul_tmp(:, ti-1) + impact*shocks(:, ti); -end; -simul = simul_tmp'; +function simul = fn_simul(G1, impact, nsim, shocks, x0); +% Inputs: +% G1: n-by-n; +% impact: n-by-r; +% nsim: length of time series for simulation. +% shocks: r-by-nsim, exogenous driving processes +% x0: n-by-1, initial values for the variables of interest +%--- +% Outputs: +% simul: nsim-by-n. +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +[n,r] = size(impact); + +[n1,n2] = size(G1); +if (n1 ~= n2) || (n1 ~= n) + error('fn_simul.m: make sure that (1) G1 is square and (2) size(G1,1) = size(impact,1)'); +end + +simul_tmp = zeros(n, nsim); + +simul_tmp(:, 1) = x0; +for ti = 2:nsim; + simul_tmp(:, ti) = G1*simul_tmp(:, ti-1) + impact*shocks(:, ti); +end; +simul = simul_tmp'; diff --git a/MatlabFiles/fn_tran_a2b.m b/MatlabFiles/fn_tran_a2b.m index b8ca8ddd690073a0d76ba7ccd26e08351e2a6110..51fe994b07abafbb61309e66c478126e5d7cdf61 100644 --- a/MatlabFiles/fn_tran_a2b.m +++ b/MatlabFiles/fn_tran_a2b.m @@ -1,41 +1,41 @@ -function b = fn_tran_a2b(A0,Ui,nvar,n0) -% b = fn_tran_a2b(A0,Ui,nvar,n0) -% Transform A0 to free parameters b's. Note: columns correspond to equations -% See Waggoner and Zha's ``A Gibbs sampler for structural VARs'' -% -% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -%---------------- -% b: sum(n0)-by-1 vector of A0 free parameters -% -% Tao Zha, February 2000. Revised, August 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -n0=n0(:); -n0cum = [0; cumsum(n0)]; -b=zeros(n0cum(end),1); -for kj = 1:nvar - b(n0cum(kj)+1:n0cum(kj+1))=Ui{kj}'*A0(:,kj); -end +function b = fn_tran_a2b(A0,Ui,nvar,n0) +% b = fn_tran_a2b(A0,Ui,nvar,n0) +% Transform A0 to free parameters b's. Note: columns correspond to equations +% See Waggoner and Zha's ``A Gibbs sampler for structural VARs'' +% +% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +%---------------- +% b: sum(n0)-by-1 vector of A0 free parameters +% +% Tao Zha, February 2000. Revised, August 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +n0=n0(:); +n0cum = [0; cumsum(n0)]; +b=zeros(n0cum(end),1); +for kj = 1:nvar + b(n0cum(kj)+1:n0cum(kj+1))=Ui{kj}'*A0(:,kj); +end diff --git a/MatlabFiles/fn_tran_b2a.m b/MatlabFiles/fn_tran_b2a.m index 4cc95b6623c7d4f49d1f17f7a99c549dc052a4da..00645e957ff59fc7f64dbee8d3f3c82a37889085 100644 --- a/MatlabFiles/fn_tran_b2a.m +++ b/MatlabFiles/fn_tran_b2a.m @@ -1,40 +1,40 @@ -function A0 = fn_tran_b2a(b,Ui,nvar,n0) -% A0 = fn_tran_b2a(b,Ui,nvar,n0) -% Transform free parameters b's to A0. Note: columns correspond to equations -% -% b: sum(n0)-by-1 vector of A0 free parameters -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -%---------------- -% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) -% -% Tao Zha, February 2000. Revised, August 2000. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -b=b(:); n0=n0(:); -A0 = zeros(nvar); -n0cum = [0; cumsum(n0)]; -for kj = 1:nvar - A0(:,kj) = Ui{kj}*b(n0cum(kj)+1:n0cum(kj+1)); -end +function A0 = fn_tran_b2a(b,Ui,nvar,n0) +% A0 = fn_tran_b2a(b,Ui,nvar,n0) +% Transform free parameters b's to A0. Note: columns correspond to equations +% +% b: sum(n0)-by-1 vector of A0 free parameters +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +%---------------- +% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) +% +% Tao Zha, February 2000. Revised, August 2000. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +b=b(:); n0=n0(:); +A0 = zeros(nvar); +n0cum = [0; cumsum(n0)]; +for kj = 1:nvar + A0(:,kj) = Ui{kj}*b(n0cum(kj)+1:n0cum(kj+1)); +end diff --git a/MatlabFiles/fn_tran_f2g.m b/MatlabFiles/fn_tran_f2g.m index 6bc2a6b3647cdb31d44fe008c8f79c345e099b03..a2c455596d0e487f8c717bbe789e26818ea93ae0 100644 --- a/MatlabFiles/fn_tran_f2g.m +++ b/MatlabFiles/fn_tran_f2g.m @@ -1,42 +1,42 @@ -function g = fn_tran_f2g(F,Vi,nvar,np) -% g = fn_tran_f2g(F,Vi,nvar,np) -% Transform F (A+) to free parameters g's. Note: columns correspond to equations -% See Waggoner and Zha's ``A Gibbs sampler for structural VARs'' -% -% F: ncoef-by-nvar matrix of original lagged parameters A+. Column corresponding to equation. -% Note that ncoef is the number of original lagged variables per equation -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. -% nvar: number of endogeous variables -% np: nvar-element vector, ith element represents the number of free A+ parameters in ith equation -%--------------- -% g: sum(np)-by-1 stacked vector of all free lagged parameters A+. -% -% August 2000, Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -np=np(:); -npcum = [0;cumsum(np)]; -g = zeros(npcum(end),1); -for kj=1:nvar - g(npcum(kj)+1:npcum(kj+1)) = Vi{kj}'*F(:,kj); -end +function g = fn_tran_f2g(F,Vi,nvar,np) +% g = fn_tran_f2g(F,Vi,nvar,np) +% Transform F (A+) to free parameters g's. Note: columns correspond to equations +% See Waggoner and Zha's ``A Gibbs sampler for structural VARs'' +% +% F: ncoef-by-nvar matrix of original lagged parameters A+. Column corresponding to equation. +% Note that ncoef is the number of original lagged variables per equation +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. +% nvar: number of endogeous variables +% np: nvar-element vector, ith element represents the number of free A+ parameters in ith equation +%--------------- +% g: sum(np)-by-1 stacked vector of all free lagged parameters A+. +% +% August 2000, Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +np=np(:); +npcum = [0;cumsum(np)]; +g = zeros(npcum(end),1); +for kj=1:nvar + g(npcum(kj)+1:npcum(kj+1)) = Vi{kj}'*F(:,kj); +end diff --git a/MatlabFiles/fn_tran_g2f.m b/MatlabFiles/fn_tran_g2f.m index 2e6a2cd28f9851b9fbc4fab9ab74c547268e341e..6bfd51f0da94b0da925d67c8db869e1e391c8eb5 100644 --- a/MatlabFiles/fn_tran_g2f.m +++ b/MatlabFiles/fn_tran_g2f.m @@ -1,41 +1,41 @@ -function F = fn_tran_g2f(g,Vi,nvar,ncoef,np) -% Transform free parameters g's to F (A+). Note: columns correspond to equations -% See Waggoner and Zha's ``A Gibbs sampler for structural VARs'' -% -% g: sum(np)-by-1 stacked vector of all free lagged parameters A+. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. -% nvar: number of endogeous variables -% ncoef: number of original lagged variables per equation -% np: nvar-element vector, ith element represents the number of free A+ parameters in ith equation -%--------------- -% F: ncoef-by-nvar matrix of original lagged parameters A+. Column corresponding to equation. -% -% August 2000, Tao Zha. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -g=g(:); np=np(:); -npcum = [0;cumsum(np)]; -F = zeros(ncoef,nvar); % ncoef: maximum original lagged parameters per equation -for kj=1:nvar - F(:,kj) = Vi{kj}*g(npcum(kj)+1:npcum(kj+1)); -end +function F = fn_tran_g2f(g,Vi,nvar,ncoef,np) +% Transform free parameters g's to F (A+). Note: columns correspond to equations +% See Waggoner and Zha's ``A Gibbs sampler for structural VARs'' +% +% g: sum(np)-by-1 stacked vector of all free lagged parameters A+. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. +% nvar: number of endogeous variables +% ncoef: number of original lagged variables per equation +% np: nvar-element vector, ith element represents the number of free A+ parameters in ith equation +%--------------- +% F: ncoef-by-nvar matrix of original lagged parameters A+. Column corresponding to equation. +% +% August 2000, Tao Zha. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +g=g(:); np=np(:); +npcum = [0;cumsum(np)]; +F = zeros(ncoef,nvar); % ncoef: maximum original lagged parameters per equation +for kj=1:nvar + F(:,kj) = Vi{kj}*g(npcum(kj)+1:npcum(kj+1)); +end diff --git a/MatlabFiles/fn_uncondfcst_var1.m b/MatlabFiles/fn_uncondfcst_var1.m index 7aab8e0d5a68569b9a310ffc0a0bc1095821b745..9fb5e5e46836b2f654b58d749cc8cb01aeb33b23 100644 --- a/MatlabFiles/fn_uncondfcst_var1.m +++ b/MatlabFiles/fn_uncondfcst_var1.m @@ -1,44 +1,44 @@ -function y = fn_uncondfcst_var1(G1, y0, nsteps); -%y = fn_irf_var1(G1,y0,nsteps); -% Inputs: -% G1: n-by-n; -% y0: n-by-1, initial condition; -% nsteps: number of forecasts steps. -%--- -% Outputs: -% y: nsteps-by-n unconditional forecasts. -% -% See fn_vds.m, fn_irf_var1.m. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -n = length(y0); - -[n1,n2] = size(G1); -if (n1 ~= n2) || (n1 ~= n) - error('fn_uncondfcst_var1.m: make sure that (1) G1 is square and (2) size(G1,1) = length(y0)'); -end - -y = zeros(nsteps,n); - - -%---- Forecast at the first step. -y(1,:) = (G1*y0)'; - -for ti = 2:nsteps - y(ti,:) = (G1*y(ti-1,:)')'; -end +function y = fn_uncondfcst_var1(G1, y0, nsteps); +%y = fn_irf_var1(G1,y0,nsteps); +% Inputs: +% G1: n-by-n; +% y0: n-by-1, initial condition; +% nsteps: number of forecasts steps. +%--- +% Outputs: +% y: nsteps-by-n unconditional forecasts. +% +% See fn_vds.m, fn_irf_var1.m. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +n = length(y0); + +[n1,n2] = size(G1); +if (n1 ~= n2) || (n1 ~= n) + error('fn_uncondfcst_var1.m: make sure that (1) G1 is square and (2) size(G1,1) = length(y0)'); +end + +y = zeros(nsteps,n); + + +%---- Forecast at the first step. +y(1,:) = (G1*y0)'; + +for ti = 2:nsteps + y(ti,:) = (G1*y(ti-1,:)')'; +end diff --git a/MatlabFiles/fn_varoots.m b/MatlabFiles/fn_varoots.m index 2c342bc37b5d58be4705637108e076fc47144302..9fdf8df86626a1092c0b67806860e6abeeb0b90f 100644 --- a/MatlabFiles/fn_varoots.m +++ b/MatlabFiles/fn_varoots.m @@ -1,46 +1,46 @@ -function rootsinv = fn_varoots(Bhat,nvar,lags) -% -% Using eigenvalues to find the inverse of all roots associated with the VAR proceess: -% y_t' = C + y_{t-1}'*B_1 + ... + Y_{t-p}'*B_p + u_t'. -% where columns correspond to equations. See also Judge (1), pp.753-755 where rows correspond to equations. -% Bhat: ncoef-by-nvar where ncoef=nvar*lags+nexo and nvar is the number of endogenous variables. -% Columns corresponds to equations with -% ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] -% ..., nvar coef in the last lag, and nexo coefficients. -% Note that entries in the rows of Bhat that > nvar*lags are irrelevant. -% nvar: number of endogenous variables. -% lags: number of lags. -%------- -% rootsinv: a vector of nvar*lags inverse roots. When > 1, explosive. When all < 1, stationary. -% -% Tao Zha, September 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if size(Bhat,1)<nvar*lags - disp(' ') - warning('Make sure that Bhat has at least nvar*lags rows') - return -end - -%--------- Strack the VAR(p) to the VAR(1) with z_t = Az_{t-1}. -% -A1 = diag(ones(nvar*(lags-1),1)); -A2 = [A1 zeros(nvar*(lags-1),nvar)]; -A = [Bhat(1:nvar*lags,:)'; A2]; -rootsinv=eig(A); +function rootsinv = fn_varoots(Bhat,nvar,lags) +% +% Using eigenvalues to find the inverse of all roots associated with the VAR proceess: +% y_t' = C + y_{t-1}'*B_1 + ... + Y_{t-p}'*B_p + u_t'. +% where columns correspond to equations. See also Judge (1), pp.753-755 where rows correspond to equations. +% Bhat: ncoef-by-nvar where ncoef=nvar*lags+nexo and nvar is the number of endogenous variables. +% Columns corresponds to equations with +% ncoef=[nvar for 1st lag, ..., nvar for last lag, other exogenous terms, const term] +% ..., nvar coef in the last lag, and nexo coefficients. +% Note that entries in the rows of Bhat that > nvar*lags are irrelevant. +% nvar: number of endogenous variables. +% lags: number of lags. +%------- +% rootsinv: a vector of nvar*lags inverse roots. When > 1, explosive. When all < 1, stationary. +% +% Tao Zha, September 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if size(Bhat,1)<nvar*lags + disp(' ') + warning('Make sure that Bhat has at least nvar*lags rows') + return +end + +%--------- Strack the VAR(p) to the VAR(1) with z_t = Az_{t-1}. +% +A1 = diag(ones(nvar*(lags-1),1)); +A2 = [A1 zeros(nvar*(lags-1),nvar)]; +A = [Bhat(1:nvar*lags,:)'; A2]; +rootsinv=eig(A); diff --git a/MatlabFiles/fn_vds.m b/MatlabFiles/fn_vds.m index cf5b64ea80a8d86e10d528da59c6ab0b4f89e61a..7128eb3c95da89a5d42f6aff28388194657ea895 100644 --- a/MatlabFiles/fn_vds.m +++ b/MatlabFiles/fn_vds.m @@ -1,33 +1,33 @@ -function vds = fn_vds(irfs); -%vds = fn_vds(irfs) -% -% Inputs: -% irfs: nsteps-by-n-by-r. For each shock of r shocks, impulse responses are nsteps-by-n. -%--- -% Outputs: -% vds: nsteps-by-n-by-r. For each shock of r shocks, variance decompositions (%) are nsteps-by-n. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -[nsteps, n,r] = size(irfs); - -vds = zeros(nsteps,n,r); - -vds_square_cum = cumsum(irfs.^2,1); -vds_square_sum = repmat(sum(vds_square_cum,3),[1 1 r]); -vds = (vds_square_cum ./ vds_square_sum) .* 100; - +function vds = fn_vds(irfs); +%vds = fn_vds(irfs) +% +% Inputs: +% irfs: nsteps-by-n-by-r. For each shock of r shocks, impulse responses are nsteps-by-n. +%--- +% Outputs: +% vds: nsteps-by-n-by-r. For each shock of r shocks, variance decompositions (%) are nsteps-by-n. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +[nsteps, n,r] = size(irfs); + +vds = zeros(nsteps,n,r); + +vds_square_cum = cumsum(irfs.^2,1); +vds_square_sum = repmat(sum(vds_square_cum,3),[1 1 r]); +vds = (vds_square_cum ./ vds_square_sum) .* 100; + diff --git a/MatlabFiles/fn_vds_abs.m b/MatlabFiles/fn_vds_abs.m index d6ede7c5b7c398a3b0388d908359f8ef1d917634..49e36e7b9412c925abeaba6e0529de9cf534409c 100644 --- a/MatlabFiles/fn_vds_abs.m +++ b/MatlabFiles/fn_vds_abs.m @@ -1,33 +1,33 @@ -function vds = fn_vds_abs(irfs); -%vds = fn_vds(irfs) -% -% Inputs: -% irfs: nsteps-by-n-by-r. For each shock of r shocks, impulse responses are nsteps-by-n. -%--- -% Outputs: -% vds: nsteps-by-n-by-r. For each shock of r shocks, variance decompositions (%) are nsteps-by-n. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -[nsteps, n,r] = size(irfs); - -vds = zeros(nsteps,n,r); - -vds_square_cum = cumsum(abs(irfs),1); -vds_square_sum = repmat(sum(vds_square_cum,3),[1 1 r]); -vds = (vds_square_cum ./ vds_square_sum) .* 100; - +function vds = fn_vds_abs(irfs); +%vds = fn_vds(irfs) +% +% Inputs: +% irfs: nsteps-by-n-by-r. For each shock of r shocks, impulse responses are nsteps-by-n. +%--- +% Outputs: +% vds: nsteps-by-n-by-r. For each shock of r shocks, variance decompositions (%) are nsteps-by-n. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +[nsteps, n,r] = size(irfs); + +vds = zeros(nsteps,n,r); + +vds_square_cum = cumsum(abs(irfs),1); +vds_square_sum = repmat(sum(vds_square_cum,3),[1 1 r]); +vds = (vds_square_cum ./ vds_square_sum) .* 100; + diff --git a/MatlabFiles/fore_cal.m b/MatlabFiles/fore_cal.m index 0dc5b147a3f970c65844cfdc288f8647168029ab..0b877b66f93d2fd4e4b6a90fb0c2244adf142633 100644 --- a/MatlabFiles/fore_cal.m +++ b/MatlabFiles/fore_cal.m @@ -1,267 +1,267 @@ -function [yforelml,yforemgml,yforeqgml,yforeCalygml] = fore_cal(yfore,xdata,nvar,... - nSample,nSampleCal,forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,... - vlistper,lmqyIndx) -% Converting oringinal forecast "yfore" to series by calendar years and series -% with growth rates (annualized for monthly and quarterly series). -% -%function [yforelml,yforemgml,yforeqgml,yforeCalygml] = fore_cal(yfore,xdata,nvar,... -% nSample,nSampleCal,forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,... -% vlistper,mqyIndx) -% -% yfore: oringal forecast series, all logged except R, U, etc. -% xdata: oringal data set beyond the sample into forecast horizon -% until yrFin:qmFin, all logged except R, U, etc. -% nvar: number of variables -% nSample: sample size (including lags or initial periods) -% nSampleCal: sample size in terms of calendar years -% forep: forecast periods (monthly) -% forepq: forecast periods (quarterly) -% forepy: forecast periods (yearly) -% q_m: quarterly or monthly for the underlying model -% qmEnd: last q_m before out-of-sample forecasting -% vlist: a list of variables -% vlistlog: sub list of variables that are in log -% vlistper: sub list of variables that are in percent -% lmyqIndx: 4-by-1 1 or 0's. Index for level, mg, qg, and yg; 1: yes; 0: no -%---------------- -% yforelml: monthly level forecast (in percent for R, U, etc.) with the same size as "yfore" in log -% yforemgml: monthly growth (at annual rates), in percent -% yforeqgml: ML forecast: quarterly growth (at annual rates), in percent -% yforeCalygml: ML forecast: annual growth (by calendar years), in percent -% forepy-by-nvar -% -% Copyright (c) March 1998 by Tao Zha -% Revision, October 1998. Added lmyqIndx so previous programs may not be compatible. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%================================================= -% Making everything presentable at FOMC -%================================================= -% -%%%% -%$$$ Monthly, prior quarter, and year-over-year change -%$$$ Out-of-sample forecasts -%%%% - - -if length(lmqyIndx)~=4 - warning('lmqyIndx must be a 4-by-1 vector containing 1 or 0') - return -end - - - -%--------------------- -% Actual data -%--------------------- -yact = xdata(nSample-q_m+1:nSample,:); % the latest (not calender) year -yactCal = xdata(nSampleCal-q_m+1:nSampleCal,:); % the lastest calendar year - - - -%----------------------------------------- -% Converted to monthly level -%----------------------------------------- -if lmqyIndx(1) - yforelml=yfore; - yforelml(:,vlistlog)=exp(yfore(:,vlistlog)); % mode, all levels - yforelml(:,vlistper)=100*yfore(:,vlistper); % mode, all levels -else - yforelml = NaN; -end - - - -%----------------------------------------- -% Converted to monthly growth -%----------------------------------------- -if lmqyIndx(2) - yactm = zeros(1,length(vlist)); % the latest month prior to forecasting - yforem = zeros(1+forep,length(vlist)); % including the 1 month prior to forecasting - % - yactm = yact(length(yact(:,1)),:); % last month prior to forecasting - yforem(1,:) = yactm; % last month prior to forecasting - yforem(2:forep+1,:) = yfore(1:forep,:); % monthly forecasts, all logged. - % - %@@ monthly growth rate (annualized) - yforemg = yforem(2:forep+1,:); - yforemg(:,vlistlog) = ... - ( yforem(2:forep+1,vlistlog) - yforem(1:forep,vlistlog) ) .* q_m; - % monthly change (annualized), 12*log(1+growth rate) - yforemgml=yforemg; - yforemgml(:,vlistlog) = 100*(exp(yforemg(:,vlistlog))-1); - % monthly growth rate (annualized) - yforemgml(:,vlistper) = 100*yforemg(:,vlistper); % monthly growth rate (annualized) -else - yforemgml=NaN; -end - - - -%----------------------------------------- -% Converted to quarterly -%----------------------------------------- -if lmqyIndx(3) - yactQ = xdata(nSample-mod(qmEnd,3)-q_m+1:nSample-mod(qmEnd,3),:); - % the latest actual quarter - yactq = zeros(4,length(vlist)); % the latest 4 quarters prior to forecasting - yforeq = zeros(4+forepq,length(vlist)); - % including the 4 quarters prior to forecasting - % - qT1 = length(yactQ(:,1))/3; - if qT1 ~= 4 - error('Must hae 4 actual quarters to compute quarterly change for forecasting!') - end - for i = 1:qT1 - i1 = 1+3*(i-1); - i2 = 3*i; - yactq(i,:) = sum(yact(i1:i2,:)) ./ 3; - end - yforeq(1:4,:) = yactq; - % - yforeq_1 = sum(xdata( nSample-mod(qmEnd,3)+1:nSample,:),1); - yforeq(5,:) = ( yforeq_1 + sum(yfore(1:3-mod(qmEnd,3),:),1) ) ./ 3; - % 1st quarterly forecast which may contain actual data within quarter - % note, dimension "1" in sum(ytem,1) is necessary because when - % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this - % is not what we want. - for i = 2:forepq - i1 = 3-mod(qmEnd,3) + 1+3*(i-2); - i2 = 3-mod(qmEnd,3) + 3*(i-1); - yforeq(4+i,:) = sum(yfore(i1:i2,:)) ./ 3; - end - % - %@@ prior quarter growth rate (annualized) - yforeqg = yforeq(5:forepq+4,:); - %yforeqg(:,vlistlog) = (100*(yforeq(5:qT2+4,vlistlog)-yforeq(1:qT2,vlistlog))) ... - % ./ yforeq(1:qT2,vlistlog); % year-over-year - %yforeqg(:,vlistlog) = 100*((yforeq(5:qT2+4,vlistlog)./yforeq(4:qT2+3,vlistlog)).^4 - 1 ); - % prior quarter - yforeqg(:,vlistlog) = ... - ( yforeq(5:forepq+4,vlistlog) - yforeq(4:forepq+3,vlistlog) ) .* 4; - % prior quarter, 4*log(1+growth rate) - yforeqgml=yforeqg; - yforeqgml(:,vlistlog) = 100*(exp(yforeqg(:,vlistlog))-1); - % quarterly growth rate (annualized) - yforeqgml(:,vlistper) = 100*yforeqg(:,vlistper); - % quarterly growth rate (annualized) -else - yforeqgml = NaN; -end - - - -%----------------------------------------- -% Converted to calendar years -%----------------------------------------- -if lmqyIndx(4) - yactCaly = zeros(1,length(vlist)); % the latest calendar year - yforeCaly = zeros(1+forepy,length(vlist)); - % including the calendar year prior to forecasting - % - yT1 = length(yactCal(:,1))/q_m; - if yT1 ~= 1 - error('yT1 Beginings or ends of monthly and calendar series are not the same!') - end - for i = 1:yT1 - i1 = 1+q_m*(i-1); - i2 = q_m*i; - yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; - end - yforeCaly(1,:) = yactCaly; - % - %@@ initial monthly actual data for calendar years - if qmEnd == q_m - yforeCaly_1 = 0; - else - ytem = xdata(nSampleCal+1:nSampleCal+qmEnd,:); - %ytem(:,vlistlog) = exp(ytem(:,vlistlog)); - yforeCaly_1 = sum(ytem,1); - % note, dimension "1" in sum(ytem,1) is necessary because when - % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this - % is not what we want. - end - % - if qmEnd == q_m - for i = 1:forepy - i1 = 1+q_m*(i-1); - i2 = q_m*i; - yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; - end - else - yforeCaly(2,:) = (yforeCaly_1+sum(yfore(1:q_m-qmEnd,:),1)) ./ q_m; - % note, dimension "1" in sum(yfore,1) is necessary because when - % q_m-qmEnd=1, sum(yfore) will give us a number, not a vector. But this - % is not what we want. - for i = 2:forepy - i1 = q_m-qmEnd+1+q_m*(i-2); - i2 = q_m-qmEnd+q_m*(i-1); - yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; - end - end - % - %@@ year-over-year growth rate - yforeCalyg = yforeCaly(2:forepy+1,:); - yforeCalyg(:,vlistlog) = ... - yforeCaly(2:forepy+1,vlistlog) - yforeCaly(1:forepy,vlistlog); - % year-over-year, log(1+growth rate) - yforeCalygml=yforeCalyg; - yforeCalygml(:,vlistlog) = 100*(exp(yforeCalyg(:,vlistlog))-1); - % annaul growth rate - yforeCalygml(:,vlistper) = 100*yforeCalyg(:,vlistper); % annaul growth rate -else - yforeCalygml = NaN; -end - - - -%ndraws -% -% posterior mean of out-of-sample forecasts -%yfore1 = (1.0/ndraws)*yfore1; % mean -%yforeqg1 = (1.0/ndraws)*yforeqg1; % mean -%yforeCalyg1 = (1.0/ndraws)*yforeCalyg1; % mean -% -%@@@ correlation of inflation and U -%IUcov = zeros(forepq,1); % forepq quarters -%IUbeta = zeros(forepq,2); % forepq quarters -%for i = 1:forepq -% indI = 4*forepq+i; -% indU = 5*forepq+i; -% %junk = corrcoef(yforeqgw(:,indI),yforeqgw(:,indU)); -% %IUcov(i,1) = junk(1,2); -% xjnk = [100*yforeqgw(:,indU) ones(ndraws,1)]; -% yjnk = yforeqgw(:,indI); -% junk = (xjnk'*xjnk)\(xjnk'*yjnk); -% IUbeta(i,:) = junk'; -%end - - -%% -% *** .68 and .90 probability bands of out-of-sample forecasts -%yforel = zeros(forep*nvar,1); % preallocating -%yforeh = zeros(forep*nvar,1); % preallocating -%yforeqgl = zeros(forepq*nvar,1); % preallocating -%yforeqgh = zeros(forepq*nvar,1); % preallocating - -%clear yfores yforepgs yforeCalygs -%*** write out final results -%yforeml = reshape(yforeml,forep,nvar); -%yforeqgml = reshape(yforeqgml,forepq,nvar); -%yforeCalygml = reshape(yforeCalygml,forepy,nvar); \ No newline at end of file +function [yforelml,yforemgml,yforeqgml,yforeCalygml] = fore_cal(yfore,xdata,nvar,... + nSample,nSampleCal,forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,... + vlistper,lmqyIndx) +% Converting oringinal forecast "yfore" to series by calendar years and series +% with growth rates (annualized for monthly and quarterly series). +% +%function [yforelml,yforemgml,yforeqgml,yforeCalygml] = fore_cal(yfore,xdata,nvar,... +% nSample,nSampleCal,forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,... +% vlistper,mqyIndx) +% +% yfore: oringal forecast series, all logged except R, U, etc. +% xdata: oringal data set beyond the sample into forecast horizon +% until yrFin:qmFin, all logged except R, U, etc. +% nvar: number of variables +% nSample: sample size (including lags or initial periods) +% nSampleCal: sample size in terms of calendar years +% forep: forecast periods (monthly) +% forepq: forecast periods (quarterly) +% forepy: forecast periods (yearly) +% q_m: quarterly or monthly for the underlying model +% qmEnd: last q_m before out-of-sample forecasting +% vlist: a list of variables +% vlistlog: sub list of variables that are in log +% vlistper: sub list of variables that are in percent +% lmyqIndx: 4-by-1 1 or 0's. Index for level, mg, qg, and yg; 1: yes; 0: no +%---------------- +% yforelml: monthly level forecast (in percent for R, U, etc.) with the same size as "yfore" in log +% yforemgml: monthly growth (at annual rates), in percent +% yforeqgml: ML forecast: quarterly growth (at annual rates), in percent +% yforeCalygml: ML forecast: annual growth (by calendar years), in percent +% forepy-by-nvar +% +% Written by Tao Zha March 1998 +% Revision, October 1998. Added lmyqIndx so previous programs may not be compatible. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%================================================= +% Making everything presentable at FOMC +%================================================= +% +%%%% +%$$$ Monthly, prior quarter, and year-over-year change +%$$$ Out-of-sample forecasts +%%%% + + +if length(lmqyIndx)~=4 + warning('lmqyIndx must be a 4-by-1 vector containing 1 or 0') + return +end + + + +%--------------------- +% Actual data +%--------------------- +yact = xdata(nSample-q_m+1:nSample,:); % the latest (not calender) year +yactCal = xdata(nSampleCal-q_m+1:nSampleCal,:); % the lastest calendar year + + + +%----------------------------------------- +% Converted to monthly level +%----------------------------------------- +if lmqyIndx(1) + yforelml=yfore; + yforelml(:,vlistlog)=exp(yfore(:,vlistlog)); % mode, all levels + yforelml(:,vlistper)=100*yfore(:,vlistper); % mode, all levels +else + yforelml = NaN; +end + + + +%----------------------------------------- +% Converted to monthly growth +%----------------------------------------- +if lmqyIndx(2) + yactm = zeros(1,length(vlist)); % the latest month prior to forecasting + yforem = zeros(1+forep,length(vlist)); % including the 1 month prior to forecasting + % + yactm = yact(length(yact(:,1)),:); % last month prior to forecasting + yforem(1,:) = yactm; % last month prior to forecasting + yforem(2:forep+1,:) = yfore(1:forep,:); % monthly forecasts, all logged. + % + %@@ monthly growth rate (annualized) + yforemg = yforem(2:forep+1,:); + yforemg(:,vlistlog) = ... + ( yforem(2:forep+1,vlistlog) - yforem(1:forep,vlistlog) ) .* q_m; + % monthly change (annualized), 12*log(1+growth rate) + yforemgml=yforemg; + yforemgml(:,vlistlog) = 100*(exp(yforemg(:,vlistlog))-1); + % monthly growth rate (annualized) + yforemgml(:,vlistper) = 100*yforemg(:,vlistper); % monthly growth rate (annualized) +else + yforemgml=NaN; +end + + + +%----------------------------------------- +% Converted to quarterly +%----------------------------------------- +if lmqyIndx(3) + yactQ = xdata(nSample-mod(qmEnd,3)-q_m+1:nSample-mod(qmEnd,3),:); + % the latest actual quarter + yactq = zeros(4,length(vlist)); % the latest 4 quarters prior to forecasting + yforeq = zeros(4+forepq,length(vlist)); + % including the 4 quarters prior to forecasting + % + qT1 = length(yactQ(:,1))/3; + if qT1 ~= 4 + error('Must hae 4 actual quarters to compute quarterly change for forecasting!') + end + for i = 1:qT1 + i1 = 1+3*(i-1); + i2 = 3*i; + yactq(i,:) = sum(yact(i1:i2,:)) ./ 3; + end + yforeq(1:4,:) = yactq; + % + yforeq_1 = sum(xdata( nSample-mod(qmEnd,3)+1:nSample,:),1); + yforeq(5,:) = ( yforeq_1 + sum(yfore(1:3-mod(qmEnd,3),:),1) ) ./ 3; + % 1st quarterly forecast which may contain actual data within quarter + % note, dimension "1" in sum(ytem,1) is necessary because when + % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this + % is not what we want. + for i = 2:forepq + i1 = 3-mod(qmEnd,3) + 1+3*(i-2); + i2 = 3-mod(qmEnd,3) + 3*(i-1); + yforeq(4+i,:) = sum(yfore(i1:i2,:)) ./ 3; + end + % + %@@ prior quarter growth rate (annualized) + yforeqg = yforeq(5:forepq+4,:); + %yforeqg(:,vlistlog) = (100*(yforeq(5:qT2+4,vlistlog)-yforeq(1:qT2,vlistlog))) ... + % ./ yforeq(1:qT2,vlistlog); % year-over-year + %yforeqg(:,vlistlog) = 100*((yforeq(5:qT2+4,vlistlog)./yforeq(4:qT2+3,vlistlog)).^4 - 1 ); + % prior quarter + yforeqg(:,vlistlog) = ... + ( yforeq(5:forepq+4,vlistlog) - yforeq(4:forepq+3,vlistlog) ) .* 4; + % prior quarter, 4*log(1+growth rate) + yforeqgml=yforeqg; + yforeqgml(:,vlistlog) = 100*(exp(yforeqg(:,vlistlog))-1); + % quarterly growth rate (annualized) + yforeqgml(:,vlistper) = 100*yforeqg(:,vlistper); + % quarterly growth rate (annualized) +else + yforeqgml = NaN; +end + + + +%----------------------------------------- +% Converted to calendar years +%----------------------------------------- +if lmqyIndx(4) + yactCaly = zeros(1,length(vlist)); % the latest calendar year + yforeCaly = zeros(1+forepy,length(vlist)); + % including the calendar year prior to forecasting + % + yT1 = length(yactCal(:,1))/q_m; + if yT1 ~= 1 + error('yT1 Beginings or ends of monthly and calendar series are not the same!') + end + for i = 1:yT1 + i1 = 1+q_m*(i-1); + i2 = q_m*i; + yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; + end + yforeCaly(1,:) = yactCaly; + % + %@@ initial monthly actual data for calendar years + if qmEnd == q_m + yforeCaly_1 = 0; + else + ytem = xdata(nSampleCal+1:nSampleCal+qmEnd,:); + %ytem(:,vlistlog) = exp(ytem(:,vlistlog)); + yforeCaly_1 = sum(ytem,1); + % note, dimension "1" in sum(ytem,1) is necessary because when + % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this + % is not what we want. + end + % + if qmEnd == q_m + for i = 1:forepy + i1 = 1+q_m*(i-1); + i2 = q_m*i; + yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; + end + else + yforeCaly(2,:) = (yforeCaly_1+sum(yfore(1:q_m-qmEnd,:),1)) ./ q_m; + % note, dimension "1" in sum(yfore,1) is necessary because when + % q_m-qmEnd=1, sum(yfore) will give us a number, not a vector. But this + % is not what we want. + for i = 2:forepy + i1 = q_m-qmEnd+1+q_m*(i-2); + i2 = q_m-qmEnd+q_m*(i-1); + yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; + end + end + % + %@@ year-over-year growth rate + yforeCalyg = yforeCaly(2:forepy+1,:); + yforeCalyg(:,vlistlog) = ... + yforeCaly(2:forepy+1,vlistlog) - yforeCaly(1:forepy,vlistlog); + % year-over-year, log(1+growth rate) + yforeCalygml=yforeCalyg; + yforeCalygml(:,vlistlog) = 100*(exp(yforeCalyg(:,vlistlog))-1); + % annaul growth rate + yforeCalygml(:,vlistper) = 100*yforeCalyg(:,vlistper); % annaul growth rate +else + yforeCalygml = NaN; +end + + + +%ndraws +% +% posterior mean of out-of-sample forecasts +%yfore1 = (1.0/ndraws)*yfore1; % mean +%yforeqg1 = (1.0/ndraws)*yforeqg1; % mean +%yforeCalyg1 = (1.0/ndraws)*yforeCalyg1; % mean +% +%@@@ correlation of inflation and U +%IUcov = zeros(forepq,1); % forepq quarters +%IUbeta = zeros(forepq,2); % forepq quarters +%for i = 1:forepq +% indI = 4*forepq+i; +% indU = 5*forepq+i; +% %junk = corrcoef(yforeqgw(:,indI),yforeqgw(:,indU)); +% %IUcov(i,1) = junk(1,2); +% xjnk = [100*yforeqgw(:,indU) ones(ndraws,1)]; +% yjnk = yforeqgw(:,indI); +% junk = (xjnk'*xjnk)\(xjnk'*yjnk); +% IUbeta(i,:) = junk'; +%end + + +%% +% *** .68 and .90 probability bands of out-of-sample forecasts +%yforel = zeros(forep*nvar,1); % preallocating +%yforeh = zeros(forep*nvar,1); % preallocating +%yforeqgl = zeros(forepq*nvar,1); % preallocating +%yforeqgh = zeros(forepq*nvar,1); % preallocating + +%clear yfores yforepgs yforeCalygs +%*** write out final results +%yforeml = reshape(yforeml,forep,nvar); +%yforeqgml = reshape(yforeqgml,forepq,nvar); +%yforeCalygml = reshape(yforeCalygml,forepy,nvar); diff --git a/MatlabFiles/fore_gh.m b/MatlabFiles/fore_gh.m index daec61bdeb6669efba0f57d27cd382d2d6d47b5c..4d7268cde0ca7019d3e960cbc94daba7ebed2734 100644 --- a/MatlabFiles/fore_gh.m +++ b/MatlabFiles/fore_gh.m @@ -1,257 +1,256 @@ -function [yactCalyg,yforeCalygml,yAg,yFg,yactqg,yforeqgml,qAg,qFg,... - yactmg,yforemgml,mAg,mFg,yact,yactCal] = fore_gh(xinput) -% Plot graphics -% [yactCalyg,yforeCalygml,yAg,yFg,yactqg,yforeqgml,qAg,qFg,... -% yactmg,yforemgml,mAg,mFg,yact,yactCal] = fore_gh(xinput) -% -% xdata=xinput{1}: data, all logged except R, U, etc. -% nvar=xinput{2}: number of variables -% nSample=xinput{3}: sample size (including lags or initial periods) -% nSampleCal=xinput{4}: converting nSample of calendar years; -% yforelml=xinput{5}: monthly ML forecast, all in level, in percent -% yforemgml=xinput{6}: monthly growth -- annualized rate, in percent -% yforeqgml=xinput{7}: prior-quarter growth -- annualized rate, in percent -% yforeCalygml=xinput{8}: annual rate, expressed in percentage point, in percent -% actup=xinput{9}: periods for actual data (monthly) -% actupq=xinput{10}: periods for actual data (quarterly) -% actupy=xinput{11}: periods for actual data (calendar yearly) -% vlist=xinput{12}: list of variables -% vlistlog=xinput{13}: sub list of variables that are in log -% vlistper=xinput{14}: sub list of variables that are in percent -% q_m=xinput{15}: month or quarter in the model -% forep=xinput{16}: forecast periods (monthly) -% ylab=xinput{17}: labels for the y-axis -% forepq=xinput{18}: quarters in the forecast period -% forepy=xinput{19}: calendar years in the forecast period -% Psuedo=xinput{20}: 1: Psuedo out-of-sample; 0: real time out-of-sample -% Graphfore=xinput{21}: 1: graphics in this file; 0: no graphics in the execution. -% yearsCal=xinput{22}: calendar years matching output "yactCalyg" -% qmEnd=xinput{23}: last month (or quarter) of the sample -%------------- -% yactCalyg: annual growth for actual data -% yforeCalygml: annaul growth for ML forecasts, expressed in percent -% yAg: length of yactCalyg (actual data) -% yFg: lenght of yforeCalyg (forecasts) -% -% yactqg: prior-quarter annualized growth for actual data -% yforeqgml: prior-quarter annaulized growth for ML forecasts, expressed in percent -% qAg: length of yactqg (actual data) -% qFg: lenght of yforeqg (forecasts) -% -% yactmg: month-to-month annualized growth for actual data -% yforemgml: month-to-month annaulized growth for ML forecasts, expressed in percent -% mAg: length of yactqg (actual data) -% mFg: lenght of yforeqg (forecasts) -% -% yact: log(y) except R, ect. (monthly). If Psuedo, yact includes "forep" months. -% i.e., (actup+forep)-by-nvar -% yactCal: same as yact but ends at the end of the last calendar year. If Psuedo, -% (actup+forep)-by-nvar, which include some actual data in the 1st calendar year. -% -% Copyright (c) March 1998 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -xdata=xinput{1}; nvar=xinput{2}; nSample=xinput{3}; nSampleCal=xinput{4}; -yforelml=xinput{5}; yforemgml=xinput{6}; yforeqgml=xinput{7}; yforeCalygml=xinput{8}; -actup=xinput{9}; actupq=xinput{10}; actupy=xinput{11}; vlist=xinput{12}; -vlistlog=xinput{13}; vlistper=xinput{14}; q_m=xinput{15}; forep=xinput{16}; -ylab=xinput{17}; forepq=xinput{18}; forepy=xinput{19}; Psuedo=xinput{20}; -Graphfore=xinput{21}; yearsCal=xinput{22}; qmEnd=xinput{23}; - -% ========= plot the graphics with actural vs forecast vs Full Bayesian ========= -% -%*** actual data -if Psuedo - yact = xdata(nSample-actup+1:nSample+forep,:); % actup (not calendar) months + forep - yactCal = xdata(nSampleCal-actupy*q_m+1:nSampleCal+forepy*q_m,:); % calendar years -else - yact = xdata(nSample-actup+1:nSample,:); % actup (not calendar) months - yactCal = xdata(nSampleCal-actupy*q_m+1:nSampleCal,:); % caledar years -end -% - - - -%%%%--------------------------------------------------------------- -%$$$ Actual monthly growth rate, Prior quarter, and year-over-year change -%%%%--------------------------------------------------------------- - -% -%@@@ Monthly change (annaluized rate) -% -yactm = yact; -mT1 = length(yact(:,1)); -% -yactmg = yactm(2:mT1,:); % start at second month to get growth rate -yactmg(:,vlistlog) = (yactm(2:mT1,vlistlog) - yactm(1:mT1-1,vlistlog)) .* 12; - % monthly, 12*log(1+growth rate), annualized growth rate -yactmg(:,vlistlog) = 100*(exp(yactmg(:,vlistlog))-1); -yactmg(:,vlistper) = 100*yactmg(:,vlistper); -mAg = length(yactmg(:,1)); - - -% -%@@@ Prior Quarter change (annaluized rate) -% -if Psuedo - yactQ = xdata(nSample-mod(qmEnd,3)-actupq*3+1:nSample-mod(qmEnd,3)+forepq*3,:); - yactq = zeros(actupq+forepq,length(vlist)); -else - yactQ = xdata(nSample-mod(qmEnd,3)-actupq*3+1:nSample-mod(qmEnd,3),:); - yactq = zeros(actupq,length(vlist)); -end -% -qT1 = length(yactQ(:,1))/3; -qT1a = length(yactq(:,1)); -if qT1 ~= qT1a - warning('line #') - error('qT1: Beginings or ends of monthly and quarterly series do not match!') -end -% -for i = 1:qT1 - i1 = 1+3*(i-1); - i2 = 3*i; - yactq(i,:) = sum(yactQ(i1:i2,:)) ./ 3; -end -% -yactqg = yactq(5:qT1,:); % 4+1=5 where 4 means 4 quarters -yactqg(:,vlistlog) = (yactq(5:qT1,vlistlog) - yactq(4:qT1-1,vlistlog)) .* 4; - % quarterly, 4*log(1+growth rate), annualized growth rate -yactqg(:,vlistlog) = 100*(exp(yactqg(:,vlistlog))-1); -yactqg(:,vlistper) = 100*yactqg(:,vlistper); -qAg = length(yactqg(:,1)); - - -% -%@@@ Calendar year-over-year change -% -if Psuedo - yactCaly = zeros(actupy+forepy,length(vlist)); % past "actupy" calendar years + forepy -else - yactCaly = zeros(actupy,length(vlist)); % past "actupy" calendar years -end -yT1 = length(yactCal(:,1))/q_m; -yT1a = length(yactCaly(:,1)); -if yT1 ~= yT1a - error('yT1: Beginings or ends of monthly and quarterly series are not the same!') -end -% -for i = 1:yT1 - i1 = 1+q_m*(i-1); - i2 = q_m*i; - yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; -end -% -yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year -yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); - % annual rate: log(1+growth rate) -yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); -yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); -yAg = length(yactCalyg(:,1)); - - -%---------------------------------------------------------------------- -%================= Graphics of actual vs forecast =================== -%---------------------------------------------------------------------- -yactl(:,vlistlog)=exp(yact(:,vlistlog)); -yactl(:,vlistper)=100*yact(:,vlistper); % convert to levels, in percent -% -mFg = length(yforemgml(:,1)); -qFg = length(yforeqgml(:,1)); -yFg = length(yforeCalygml(:,1)); - -if Psuedo - t1=1:actup+forep; -else - t1=1:actup; -end -t2=actup+1:actup+forep; -% -if Graphfore - figure % The graphics below are expressed in level (monthly) - for i = 1:nvar - subplot(nvar/2,2,i) - plot(t1,yactl(:,i),t2,yforelml(:,i),'--') - %title('solid-actual, dotted-forecast'); - %title(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) - end -end - -t1 = 1:mAg; -if Psuedo - t2 = mAg-mFg+1:mAg; -else - t2 = mAg+1:mAg+mFg; -end -% -if Graphfore - figure % The graphics below are monthly growth rates except R and U, at annualized rates - for i = 1:nvar - subplot(nvar/2,2,i) - plot(t1,yactmg(:,i),t2,yforemgml(:,i),'--') - %title('solid-actual, dotted-forecast'); - %xlabel(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) - end -end - -t1 = 1:qAg; -if Psuedo - t2 = qAg-qFg+1:qAg; -else - t2 = qAg+1:qAg+qFg; -end -% -if Graphfore - figure % The graphics below are prior quarter growth rate except R and U, at annualized rates - for i = 1:nvar - subplot(nvar/2,2,i) - plot(t1,yactqg(:,i),t2,yforeqgml(:,i),'--') - %title('quarterly growth, unconditional'); - %xlabel(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) - end -end - - -%t1 = 1:yAg; -t1 = yearsCal; -yAgCal=yearsCal(length(yearsCal)); -if Psuedo - t2 = yAgCal-yFg+1:yAgCal; -else - t2 = yAgCal+1:yAgCal+yFg; -end -% -if Graphfore - figure - % The graphics below are over-the-year growth rate except R and U, annually - for i = 1:nvar - subplot(nvar/2,2,i) - plot(t1,yactCalyg(:,i),t2,yforeCalygml(:,i),'--') - %title('solid-actual, dotted-forecast'); - %xlabel(eval(['forelabel'])); - %ylabel(eval(['x' int2str(i)])); - ylabel(char(ylab(i))) - end -end \ No newline at end of file +function [yactCalyg,yforeCalygml,yAg,yFg,yactqg,yforeqgml,qAg,qFg,... + yactmg,yforemgml,mAg,mFg,yact,yactCal] = fore_gh(xinput) +% Plot graphics +% [yactCalyg,yforeCalygml,yAg,yFg,yactqg,yforeqgml,qAg,qFg,... +% yactmg,yforemgml,mAg,mFg,yact,yactCal] = fore_gh(xinput) +% +% xdata=xinput{1}: data, all logged except R, U, etc. +% nvar=xinput{2}: number of variables +% nSample=xinput{3}: sample size (including lags or initial periods) +% nSampleCal=xinput{4}: converting nSample of calendar years; +% yforelml=xinput{5}: monthly ML forecast, all in level, in percent +% yforemgml=xinput{6}: monthly growth -- annualized rate, in percent +% yforeqgml=xinput{7}: prior-quarter growth -- annualized rate, in percent +% yforeCalygml=xinput{8}: annual rate, expressed in percentage point, in percent +% actup=xinput{9}: periods for actual data (monthly) +% actupq=xinput{10}: periods for actual data (quarterly) +% actupy=xinput{11}: periods for actual data (calendar yearly) +% vlist=xinput{12}: list of variables +% vlistlog=xinput{13}: sub list of variables that are in log +% vlistper=xinput{14}: sub list of variables that are in percent +% q_m=xinput{15}: month or quarter in the model +% forep=xinput{16}: forecast periods (monthly) +% ylab=xinput{17}: labels for the y-axis +% forepq=xinput{18}: quarters in the forecast period +% forepy=xinput{19}: calendar years in the forecast period +% Psuedo=xinput{20}: 1: Psuedo out-of-sample; 0: real time out-of-sample +% Graphfore=xinput{21}: 1: graphics in this file; 0: no graphics in the execution. +% yearsCal=xinput{22}: calendar years matching output "yactCalyg" +% qmEnd=xinput{23}: last month (or quarter) of the sample +%------------- +% yactCalyg: annual growth for actual data +% yforeCalygml: annaul growth for ML forecasts, expressed in percent +% yAg: length of yactCalyg (actual data) +% yFg: lenght of yforeCalyg (forecasts) +% +% yactqg: prior-quarter annualized growth for actual data +% yforeqgml: prior-quarter annaulized growth for ML forecasts, expressed in percent +% qAg: length of yactqg (actual data) +% qFg: lenght of yforeqg (forecasts) +% +% yactmg: month-to-month annualized growth for actual data +% yforemgml: month-to-month annaulized growth for ML forecasts, expressed in percent +% mAg: length of yactqg (actual data) +% mFg: lenght of yforeqg (forecasts) +% +% yact: log(y) except R, ect. (monthly). If Psuedo, yact includes "forep" months. +% i.e., (actup+forep)-by-nvar +% yactCal: same as yact but ends at the end of the last calendar year. If Psuedo, +% (actup+forep)-by-nvar, which include some actual data in the 1st calendar year. +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +xdata=xinput{1}; nvar=xinput{2}; nSample=xinput{3}; nSampleCal=xinput{4}; +yforelml=xinput{5}; yforemgml=xinput{6}; yforeqgml=xinput{7}; yforeCalygml=xinput{8}; +actup=xinput{9}; actupq=xinput{10}; actupy=xinput{11}; vlist=xinput{12}; +vlistlog=xinput{13}; vlistper=xinput{14}; q_m=xinput{15}; forep=xinput{16}; +ylab=xinput{17}; forepq=xinput{18}; forepy=xinput{19}; Psuedo=xinput{20}; +Graphfore=xinput{21}; yearsCal=xinput{22}; qmEnd=xinput{23}; + +% ========= plot the graphics with actural vs forecast vs Full Bayesian ========= +% +%*** actual data +if Psuedo + yact = xdata(nSample-actup+1:nSample+forep,:); % actup (not calendar) months + forep + yactCal = xdata(nSampleCal-actupy*q_m+1:nSampleCal+forepy*q_m,:); % calendar years +else + yact = xdata(nSample-actup+1:nSample,:); % actup (not calendar) months + yactCal = xdata(nSampleCal-actupy*q_m+1:nSampleCal,:); % caledar years +end +% + + + +%%%%--------------------------------------------------------------- +%$$$ Actual monthly growth rate, Prior quarter, and year-over-year change +%%%%--------------------------------------------------------------- + +% +%@@@ Monthly change (annaluized rate) +% +yactm = yact; +mT1 = length(yact(:,1)); +% +yactmg = yactm(2:mT1,:); % start at second month to get growth rate +yactmg(:,vlistlog) = (yactm(2:mT1,vlistlog) - yactm(1:mT1-1,vlistlog)) .* 12; + % monthly, 12*log(1+growth rate), annualized growth rate +yactmg(:,vlistlog) = 100*(exp(yactmg(:,vlistlog))-1); +yactmg(:,vlistper) = 100*yactmg(:,vlistper); +mAg = length(yactmg(:,1)); + + +% +%@@@ Prior Quarter change (annaluized rate) +% +if Psuedo + yactQ = xdata(nSample-mod(qmEnd,3)-actupq*3+1:nSample-mod(qmEnd,3)+forepq*3,:); + yactq = zeros(actupq+forepq,length(vlist)); +else + yactQ = xdata(nSample-mod(qmEnd,3)-actupq*3+1:nSample-mod(qmEnd,3),:); + yactq = zeros(actupq,length(vlist)); +end +% +qT1 = length(yactQ(:,1))/3; +qT1a = length(yactq(:,1)); +if qT1 ~= qT1a + warning('line #') + error('qT1: Beginings or ends of monthly and quarterly series do not match!') +end +% +for i = 1:qT1 + i1 = 1+3*(i-1); + i2 = 3*i; + yactq(i,:) = sum(yactQ(i1:i2,:)) ./ 3; +end +% +yactqg = yactq(5:qT1,:); % 4+1=5 where 4 means 4 quarters +yactqg(:,vlistlog) = (yactq(5:qT1,vlistlog) - yactq(4:qT1-1,vlistlog)) .* 4; + % quarterly, 4*log(1+growth rate), annualized growth rate +yactqg(:,vlistlog) = 100*(exp(yactqg(:,vlistlog))-1); +yactqg(:,vlistper) = 100*yactqg(:,vlistper); +qAg = length(yactqg(:,1)); + + +% +%@@@ Calendar year-over-year change +% +if Psuedo + yactCaly = zeros(actupy+forepy,length(vlist)); % past "actupy" calendar years + forepy +else + yactCaly = zeros(actupy,length(vlist)); % past "actupy" calendar years +end +yT1 = length(yactCal(:,1))/q_m; +yT1a = length(yactCaly(:,1)); +if yT1 ~= yT1a + error('yT1: Beginings or ends of monthly and quarterly series are not the same!') +end +% +for i = 1:yT1 + i1 = 1+q_m*(i-1); + i2 = q_m*i; + yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; +end +% +yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year +yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); + % annual rate: log(1+growth rate) +yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); +yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); +yAg = length(yactCalyg(:,1)); + + +%---------------------------------------------------------------------- +%================= Graphics of actual vs forecast =================== +%---------------------------------------------------------------------- +yactl(:,vlistlog)=exp(yact(:,vlistlog)); +yactl(:,vlistper)=100*yact(:,vlistper); % convert to levels, in percent +% +mFg = length(yforemgml(:,1)); +qFg = length(yforeqgml(:,1)); +yFg = length(yforeCalygml(:,1)); + +if Psuedo + t1=1:actup+forep; +else + t1=1:actup; +end +t2=actup+1:actup+forep; +% +if Graphfore + figure % The graphics below are expressed in level (monthly) + for i = 1:nvar + subplot(nvar/2,2,i) + plot(t1,yactl(:,i),t2,yforelml(:,i),'--') + %title('solid-actual, dotted-forecast'); + %title(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) + end +end + +t1 = 1:mAg; +if Psuedo + t2 = mAg-mFg+1:mAg; +else + t2 = mAg+1:mAg+mFg; +end +% +if Graphfore + figure % The graphics below are monthly growth rates except R and U, at annualized rates + for i = 1:nvar + subplot(nvar/2,2,i) + plot(t1,yactmg(:,i),t2,yforemgml(:,i),'--') + %title('solid-actual, dotted-forecast'); + %xlabel(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) + end +end + +t1 = 1:qAg; +if Psuedo + t2 = qAg-qFg+1:qAg; +else + t2 = qAg+1:qAg+qFg; +end +% +if Graphfore + figure % The graphics below are prior quarter growth rate except R and U, at annualized rates + for i = 1:nvar + subplot(nvar/2,2,i) + plot(t1,yactqg(:,i),t2,yforeqgml(:,i),'--') + %title('quarterly growth, unconditional'); + %xlabel(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) + end +end + + +%t1 = 1:yAg; +t1 = yearsCal; +yAgCal=yearsCal(length(yearsCal)); +if Psuedo + t2 = yAgCal-yFg+1:yAgCal; +else + t2 = yAgCal+1:yAgCal+yFg; +end +% +if Graphfore + figure + % The graphics below are over-the-year growth rate except R and U, annually + for i = 1:nvar + subplot(nvar/2,2,i) + plot(t1,yactCalyg(:,i),t2,yforeCalygml(:,i),'--') + %title('solid-actual, dotted-forecast'); + %xlabel(eval(['forelabel'])); + %ylabel(eval(['x' int2str(i)])); + ylabel(char(ylab(i))) + end +end diff --git a/MatlabFiles/fore_mqy.m b/MatlabFiles/fore_mqy.m index 6759e1be280d636ee5932ef8276593bd8a8eff06..3bb4394999bb1390a2d052579435ca3bfec3f014 100644 --- a/MatlabFiles/fore_mqy.m +++ b/MatlabFiles/fore_mqy.m @@ -1,338 +1,338 @@ -function [yforelml,yforemgml,yforeqgml,yforeCalygml,yactl,yactmg,yactqg,yactCalyg,yactlog] = ... - fore_mqy(yfore,xdata,nvar,nSample,nSampleCal,... - forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,... - lmqyIndx,indxCal) -% [yforelml,yforemgml,yforeqgml,yforeCalygml,yactl,yactmg,yactqg,yactCalyg,yactlog] = ... -% fore_mqy(yfore,xdata,nvar,nSample,nSampleCal,... -% forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,... -% lmqyIndx,indxCal) -% -% Converting oringinal forecast "yfore" to series by calendar years and series -% with growth rates (annualized for monthly and quarterly series) and -% with corresponding actual data (ONLY valid when we have actual data. -% Later should add an index to allow an option out 3/23/99). -% 3/23/99 I guess that this program is more general than fore_cal because it allows -% for non-Calendar annual growth rate calculation if nSample before "forep" and -% and q_m before "vlist" are used. -% -% yfore: oringal forecast series, all logged except R, U, etc. -% xdata: oringal data set, up to the period before (peudo-) out-of-sample forecasting, -% all logged except R, U, etc. -% nvar: number of variables -% nSample: sample size (including lags or initial periods) -% nSampleCal: sample size in terms of calendar years -% forep: forecast periods (monthly) -% forepq: forecast periods (quarterly) -% forepy: forecast periods (yearly) -% q_m: quarterly or monthly for the underlying model -% qmEnd: last q_m before out-of-sample forecasting -% vlist: a list of variables -% vlistlog: sub list of variables that are in log -% vlistper: sub list of variables that are in percent -% lmyqIndx: 4-by-1 1 or 0's. Index for level, mg, qg, and yg; 1: yes; 0: no -% indxCal: 1: calendar years; 0: (NOT calendar) years -%---------------- -% yforelml: forep-by-nvar, ymonthly ML forecast, all at level, in percent -% yforemgml: ML forecasts, monthly growth (at annual rates), in percent -% yforeqgml: ML forecast: quarterly growth (at annual rates), in percent -% yforeCalygml: forepq-by-nvar ML forecast: annual growth, in percent -% yactl: forep-by-nvar, actual, all at level, in percent -% yactmg: -% yactqg: -% yactCalyg: forepq-by-nvar, actual, annual growth, in percent -% yactlog: forep-by-nvar, actual, all log except R and U. -% -% Copyright (c) March 1998 by Tao Zha -% Revised, 3/23/99. Added "lmqyIndx" so that previous programs may not be compatible. -% Revised, 4/27/99. Added "indxCal" so that previous programs may not be compatible. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -%================================================= -% Making everything presentable at FOMC -%================================================= -% -%%%% -%$$$ Monthly, prior quarter, and year-over-year change -%$$$ Out-of-sample forecasts -%%%% -% - -if length(lmqyIndx)~=4 - warning('lmqyIndx must be a 4-by-1 vector containing 1 or 0') - return -end - - - -%--------------------- -% Actual data -%--------------------- -yact = xdata(nSample-q_m+1:nSample,:); % the latest (not calender) year -yactCal = xdata(nSampleCal-q_m+1:nSampleCal,:); - % the lastest calendar year (always earlier than the lastest (not calendar) year - - - -%----------------------------------------- -% Converted to monthly level -%----------------------------------------- -if lmqyIndx(1) - yforelml=yfore; - yforelml(:,vlistlog)=exp(yfore(:,vlistlog)); % mode, all levels - yforelml(:,vlistper)=100*yfore(:,vlistper); % mode, all levels -else - yforelml = NaN; -end - - -%----------------------------------------- -% Converted to monthly growth -%----------------------------------------- -if lmqyIndx(2) - yactm = zeros(1,length(vlist)); % the latest month prior to forecasting - yforem = zeros(1+forep,length(vlist)); % including the 1 month prior to forecasting - % - yactm = yact(length(yact(:,1)),:); % last month prior to forecasting - yforem(1,:) = yactm; % last month prior to forecasting - yforem(2:forep+1,:) = yfore(1:forep,:); % monthly forecasts, all logged. - % - %@@ monthly growth rate (annualized) - yforemg = yforem(2:forep+1,:); - yforemg(:,vlistlog) = ( yforem(2:forep+1,vlistlog) - yforem(1:forep,vlistlog) ) .* q_m; - % monthly change (annualized), 12*log(1+growth rate) - yforemgml=yforemg; - yforemgml(:,vlistlog) = 100*(exp(yforemg(:,vlistlog))-1); % monthly growth rate (annualized) - yforemgml(:,vlistper) = 100*yforemg(:,vlistper); % monthly growth rate (annualized) -else - yforemgml=NaN; -end - - - -%----------------------------------------- -% Converted to quarterly -%----------------------------------------- -if lmqyIndx(3) - yactQ = xdata(nSample-mod(qmEnd,3)-q_m+1:nSample-mod(qmEnd,3),:); % the latest actual quarter - yactq = zeros(4,length(vlist)); % the latest 4 quarters prior to forecasting - yforeq = zeros(4+forepq,length(vlist)); % including the 4 quarters prior to forecasting - % - qT1 = length(yactQ(:,1))/3; - if qT1 ~= 4 - error('Must hae 4 actual quarters to compute quarterly change for forecasting!') - end - for i = 1:qT1 - i1 = 1+3*(i-1); - i2 = 3*i; - yactq(i,:) = sum(yact(i1:i2,:)) ./ 3; - end - yforeq(1:4,:) = yactq; - % - yforeq_1 = sum(xdata( nSample-mod(qmEnd,3)+1:nSample,:),1); - yforeq(5,:) = ( yforeq_1 + sum(yfore(1:3-mod(qmEnd,3),:),1) ) ./ 3; - % 1st quarterly forecast which may contain actual data within quarter - % note, dimension "1" in sum(ytem,1) is necessary because when - % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this - % is not what we want. - for i = 2:forepq - i1 = 3-mod(qmEnd,3) + 1+3*(i-2); - i2 = 3-mod(qmEnd,3) + 3*(i-1); - yforeq(4+i,:) = sum(yfore(i1:i2,:)) ./ 3; - end - % - %@@ prior quarter growth rate (annualized) - yforeqg = yforeq(5:forepq+4,:); - %yforeqg(:,vlistlog) = (100*(yforeq(5:qT2+4,vlistlog)-yforeq(1:qT2,vlistlog))) ... - % ./ yforeq(1:qT2,vlistlog); % year-over-year - %yforeqg(:,vlistlog) = 100*((yforeq(5:qT2+4,vlistlog)./yforeq(4:qT2+3,vlistlog)).^4 - 1 ); - % prior quarter - yforeqg(:,vlistlog) = ( yforeq(5:forepq+4,vlistlog) - yforeq(4:forepq+3,vlistlog) ) .* 4; - % prior quarter, 4*log(1+growth rate) - yforeqgml=yforeqg; - yforeqgml(:,vlistlog) = 100*(exp(yforeqg(:,vlistlog))-1); % quarterly growth rate (annualized) - yforeqgml(:,vlistper) = 100*yforeqg(:,vlistper); % quarterly growth rate (annualized) -else - yforeqgml = NaN; -end - - -%----------------------------------------- -% Converted to annual years (may not be calendar) -%----------------------------------------- -if lmqyIndx(4) - yactCaly = zeros(1,length(vlist)); % the latest calendar year - yforeCaly = zeros(1+forepy,length(vlist)); % including the calendar year prior to forecasting - % - yT1 = length(yactCal(:,1))/q_m; - if yT1 ~= 1 - error('yT1 Beginings or ends of monthly and calendar series are not the same!') - end - for i = 1:yT1 - i1 = 1+q_m*(i-1); - i2 = q_m*i; - yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; - end - yforeCaly(1,:) = yactCaly; - % - %@@ initial monthly actual data for calendar years - if qmEnd == q_m - yforeCaly_1 = 0; - else - ytem = xdata(nSampleCal+1:nSampleCal+qmEnd,:); - %ytem(:,vlistlog) = exp(ytem(:,vlistlog)); - yforeCaly_1 = sum(ytem,1); - % note, dimension "1" in sum(ytem,1) is necessary because when - % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this - % is not what we want. - end - % - if qmEnd == q_m - for i = 1:forepy - i1 = 1+q_m*(i-1); - i2 = q_m*i; - yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; - end - else - yforeCaly(2,:) = (yforeCaly_1+sum(yfore(1:q_m-qmEnd,:),1)) ./ q_m; - % note, dimension "1" in sum(yfore,1) is necessary because when - % q_m-qmEnd=1, sum(yfore) will give us a number, not a vector. But this - % is not what we want. - for i = 2:forepy - i1 = q_m-qmEnd+1+q_m*(i-2); - i2 = q_m-qmEnd+q_m*(i-1); - yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; - end - end - % - %@@ year-over-year growth rate - yforeCalyg = yforeCaly(2:forepy+1,:); - yforeCalyg(:,vlistlog) = yforeCaly(2:forepy+1,vlistlog) - yforeCaly(1:forepy,vlistlog); - % year-over-year, log(1+growth rate) - yforeCalygml=yforeCalyg; - yforeCalygml(:,vlistlog) = 100*(exp(yforeCalyg(:,vlistlog))-1); % annaul growth rate - yforeCalygml(:,vlistper) = 100*yforeCalyg(:,vlistper); % annaul growth rate -else - yforeCalygml = NaN; -end - - - -%---------------------------------------------------------------------- -% --------------------- Actual ----------------------------------------- -%---------------------------------------------------------------------- -if indxCal - Rem_qm = q_m-qmEnd; % remaining months within the first calendar year - Rem_y = floor((forep-Rem_qm)/q_m); % remaining calendar years after the first one - yact = xdata(nSample-2*q_m+1:nSample+Rem_qm+Rem_y*q_m,:); - % 2*q_m (not calendar) months + months ended at last calendar year -else - yact = xdata(nSample-q_m+1:nSample+forep,:); % q_m (not calendar) months + forep -end -mT1 = length(yact(:,1)); -yactlog = yact(q_m+1:mT1,:); - - -%----------------------------------------- -% Converted to monthly level -%----------------------------------------- -if lmqyIndx(1) - yactl=yactlog; - yactl(:,vlistlog)=exp(yactlog(:,vlistlog)); % mode, all levels - yactl(:,vlistper)=100*yactlog(:,vlistper); % mode, all levels -else - yactl=NaN; -end - -%----------------------------------------- -% Converted to monthly growth -%----------------------------------------- -if lmqyIndx(2) - yactmg = yactl; - yactmg(:,vlistlog) = (yact(q_m+1:mT1,vlistlog) - yact(q_m:mT1-1,vlistlog)) .* 12; - % monthly, 12*log(1+growth rate), annualized growth rate - yactmg(:,vlistlog) = 100*(exp(yactmg(:,vlistlog))-1); - yactmg(:,vlistper) = 100*yactmg(:,vlistper); -else - yactmg=NaN; -end - -%----------------------------------------- -% Converted to quarterly -%----------------------------------------- -if lmqyIndx(3) - warning(' ') - disp('Not worked out yet. 4/27/99') - disp('Press ctrl-c to abort!') - pause - - yactQ = yact(10:mT1,:); % October: beginning of the 4th quarter - yactq = zeros(1+forepq,length(vlist)); - qT1 = 1+forepq; - % - for i = 1:qT1 - i1 = 1+3*(i-1); - i2 = 3*i; - yactq(i,:) = sum(yactQ(i1:i2,:)) ./ 3; - end - % - yactqg = yactq(2:qT1,:); % 4+1=5 where 4 means 4 quarters - yactqg(:,vlistlog) = (yactq(2:qT1,vlistlog) - yactq(1:qT1-1,vlistlog)) .* 4; - % quarterly, 4*log(1+growth rate), annualized growth rate - yactqg(:,vlistlog) = 100*(exp(yactqg(:,vlistlog))-1); - yactqg(:,vlistper) = 100*yactqg(:,vlistper); -else - yactqg=NaN; -end - - -%----------------------------------------- -% Converted to annual years (may not be calendar) -%----------------------------------------- -if lmqyIndx(4) - if indxCal - yT1 = 1+forepy; - yactCaly = zeros(yT1,length(vlist)); % the latest 1+forepy calendar years - for i = 1:yT1 - i1 = ( Rem_qm+q_m*(qmEnd==q_m) ) + 1+q_m*(i-1); - i2 = ( Rem_qm+q_m*(qmEnd==q_m) ) + q_m*i; - yactCaly(i,:) = sum(yact(i1:i2,:)) ./ q_m; - end - % - yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year - yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); - % annual rate: log(1+growth rate) - yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); - yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); - else - yT1 = 1+forepy; - for i = 1:yT1 - i1 = 1+q_m*(i-1); - i2 = q_m*i; - yactCaly(i,:) = sum(yact(i1:i2,:)) ./ q_m; - end - % - yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year - yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); - % annual rate: log(1+growth rate) - yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); - yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); - end -else - yactCalyg=NaN; -end \ No newline at end of file +function [yforelml,yforemgml,yforeqgml,yforeCalygml,yactl,yactmg,yactqg,yactCalyg,yactlog] = ... + fore_mqy(yfore,xdata,nvar,nSample,nSampleCal,... + forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,... + lmqyIndx,indxCal) +% [yforelml,yforemgml,yforeqgml,yforeCalygml,yactl,yactmg,yactqg,yactCalyg,yactlog] = ... +% fore_mqy(yfore,xdata,nvar,nSample,nSampleCal,... +% forep,forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,... +% lmqyIndx,indxCal) +% +% Converting oringinal forecast "yfore" to series by calendar years and series +% with growth rates (annualized for monthly and quarterly series) and +% with corresponding actual data (ONLY valid when we have actual data. +% Later should add an index to allow an option out 3/23/99). +% 3/23/99 I guess that this program is more general than fore_cal because it allows +% for non-Calendar annual growth rate calculation if nSample before "forep" and +% and q_m before "vlist" are used. +% +% yfore: oringal forecast series, all logged except R, U, etc. +% xdata: oringal data set, up to the period before (peudo-) out-of-sample forecasting, +% all logged except R, U, etc. +% nvar: number of variables +% nSample: sample size (including lags or initial periods) +% nSampleCal: sample size in terms of calendar years +% forep: forecast periods (monthly) +% forepq: forecast periods (quarterly) +% forepy: forecast periods (yearly) +% q_m: quarterly or monthly for the underlying model +% qmEnd: last q_m before out-of-sample forecasting +% vlist: a list of variables +% vlistlog: sub list of variables that are in log +% vlistper: sub list of variables that are in percent +% lmyqIndx: 4-by-1 1 or 0's. Index for level, mg, qg, and yg; 1: yes; 0: no +% indxCal: 1: calendar years; 0: (NOT calendar) years +%---------------- +% yforelml: forep-by-nvar, ymonthly ML forecast, all at level, in percent +% yforemgml: ML forecasts, monthly growth (at annual rates), in percent +% yforeqgml: ML forecast: quarterly growth (at annual rates), in percent +% yforeCalygml: forepq-by-nvar ML forecast: annual growth, in percent +% yactl: forep-by-nvar, actual, all at level, in percent +% yactmg: +% yactqg: +% yactCalyg: forepq-by-nvar, actual, annual growth, in percent +% yactlog: forep-by-nvar, actual, all log except R and U. +% +% Written by Tao Zha March 1998 +% Revised, 3/23/99. Added "lmqyIndx" so that previous programs may not be compatible. +% Revised, 4/27/99. Added "indxCal" so that previous programs may not be compatible. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +%================================================= +% Making everything presentable at FOMC +%================================================= +% +%%%% +%$$$ Monthly, prior quarter, and year-over-year change +%$$$ Out-of-sample forecasts +%%%% +% + +if length(lmqyIndx)~=4 + warning('lmqyIndx must be a 4-by-1 vector containing 1 or 0') + return +end + + + +%--------------------- +% Actual data +%--------------------- +yact = xdata(nSample-q_m+1:nSample,:); % the latest (not calender) year +yactCal = xdata(nSampleCal-q_m+1:nSampleCal,:); + % the lastest calendar year (always earlier than the lastest (not calendar) year + + + +%----------------------------------------- +% Converted to monthly level +%----------------------------------------- +if lmqyIndx(1) + yforelml=yfore; + yforelml(:,vlistlog)=exp(yfore(:,vlistlog)); % mode, all levels + yforelml(:,vlistper)=100*yfore(:,vlistper); % mode, all levels +else + yforelml = NaN; +end + + +%----------------------------------------- +% Converted to monthly growth +%----------------------------------------- +if lmqyIndx(2) + yactm = zeros(1,length(vlist)); % the latest month prior to forecasting + yforem = zeros(1+forep,length(vlist)); % including the 1 month prior to forecasting + % + yactm = yact(length(yact(:,1)),:); % last month prior to forecasting + yforem(1,:) = yactm; % last month prior to forecasting + yforem(2:forep+1,:) = yfore(1:forep,:); % monthly forecasts, all logged. + % + %@@ monthly growth rate (annualized) + yforemg = yforem(2:forep+1,:); + yforemg(:,vlistlog) = ( yforem(2:forep+1,vlistlog) - yforem(1:forep,vlistlog) ) .* q_m; + % monthly change (annualized), 12*log(1+growth rate) + yforemgml=yforemg; + yforemgml(:,vlistlog) = 100*(exp(yforemg(:,vlistlog))-1); % monthly growth rate (annualized) + yforemgml(:,vlistper) = 100*yforemg(:,vlistper); % monthly growth rate (annualized) +else + yforemgml=NaN; +end + + + +%----------------------------------------- +% Converted to quarterly +%----------------------------------------- +if lmqyIndx(3) + yactQ = xdata(nSample-mod(qmEnd,3)-q_m+1:nSample-mod(qmEnd,3),:); % the latest actual quarter + yactq = zeros(4,length(vlist)); % the latest 4 quarters prior to forecasting + yforeq = zeros(4+forepq,length(vlist)); % including the 4 quarters prior to forecasting + % + qT1 = length(yactQ(:,1))/3; + if qT1 ~= 4 + error('Must hae 4 actual quarters to compute quarterly change for forecasting!') + end + for i = 1:qT1 + i1 = 1+3*(i-1); + i2 = 3*i; + yactq(i,:) = sum(yact(i1:i2,:)) ./ 3; + end + yforeq(1:4,:) = yactq; + % + yforeq_1 = sum(xdata( nSample-mod(qmEnd,3)+1:nSample,:),1); + yforeq(5,:) = ( yforeq_1 + sum(yfore(1:3-mod(qmEnd,3),:),1) ) ./ 3; + % 1st quarterly forecast which may contain actual data within quarter + % note, dimension "1" in sum(ytem,1) is necessary because when + % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this + % is not what we want. + for i = 2:forepq + i1 = 3-mod(qmEnd,3) + 1+3*(i-2); + i2 = 3-mod(qmEnd,3) + 3*(i-1); + yforeq(4+i,:) = sum(yfore(i1:i2,:)) ./ 3; + end + % + %@@ prior quarter growth rate (annualized) + yforeqg = yforeq(5:forepq+4,:); + %yforeqg(:,vlistlog) = (100*(yforeq(5:qT2+4,vlistlog)-yforeq(1:qT2,vlistlog))) ... + % ./ yforeq(1:qT2,vlistlog); % year-over-year + %yforeqg(:,vlistlog) = 100*((yforeq(5:qT2+4,vlistlog)./yforeq(4:qT2+3,vlistlog)).^4 - 1 ); + % prior quarter + yforeqg(:,vlistlog) = ( yforeq(5:forepq+4,vlistlog) - yforeq(4:forepq+3,vlistlog) ) .* 4; + % prior quarter, 4*log(1+growth rate) + yforeqgml=yforeqg; + yforeqgml(:,vlistlog) = 100*(exp(yforeqg(:,vlistlog))-1); % quarterly growth rate (annualized) + yforeqgml(:,vlistper) = 100*yforeqg(:,vlistper); % quarterly growth rate (annualized) +else + yforeqgml = NaN; +end + + +%----------------------------------------- +% Converted to annual years (may not be calendar) +%----------------------------------------- +if lmqyIndx(4) + yactCaly = zeros(1,length(vlist)); % the latest calendar year + yforeCaly = zeros(1+forepy,length(vlist)); % including the calendar year prior to forecasting + % + yT1 = length(yactCal(:,1))/q_m; + if yT1 ~= 1 + error('yT1 Beginings or ends of monthly and calendar series are not the same!') + end + for i = 1:yT1 + i1 = 1+q_m*(i-1); + i2 = q_m*i; + yactCaly(i,:) = sum(yactCal(i1:i2,:)) ./ q_m; + end + yforeCaly(1,:) = yactCaly; + % + %@@ initial monthly actual data for calendar years + if qmEnd == q_m + yforeCaly_1 = 0; + else + ytem = xdata(nSampleCal+1:nSampleCal+qmEnd,:); + %ytem(:,vlistlog) = exp(ytem(:,vlistlog)); + yforeCaly_1 = sum(ytem,1); + % note, dimension "1" in sum(ytem,1) is necessary because when + % qmEnd=1, sum(ytem,1) will give us a nomber, not a vector. But this + % is not what we want. + end + % + if qmEnd == q_m + for i = 1:forepy + i1 = 1+q_m*(i-1); + i2 = q_m*i; + yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; + end + else + yforeCaly(2,:) = (yforeCaly_1+sum(yfore(1:q_m-qmEnd,:),1)) ./ q_m; + % note, dimension "1" in sum(yfore,1) is necessary because when + % q_m-qmEnd=1, sum(yfore) will give us a number, not a vector. But this + % is not what we want. + for i = 2:forepy + i1 = q_m-qmEnd+1+q_m*(i-2); + i2 = q_m-qmEnd+q_m*(i-1); + yforeCaly(1+i,:) = sum(yfore(i1:i2,:)) ./ q_m; + end + end + % + %@@ year-over-year growth rate + yforeCalyg = yforeCaly(2:forepy+1,:); + yforeCalyg(:,vlistlog) = yforeCaly(2:forepy+1,vlistlog) - yforeCaly(1:forepy,vlistlog); + % year-over-year, log(1+growth rate) + yforeCalygml=yforeCalyg; + yforeCalygml(:,vlistlog) = 100*(exp(yforeCalyg(:,vlistlog))-1); % annaul growth rate + yforeCalygml(:,vlistper) = 100*yforeCalyg(:,vlistper); % annaul growth rate +else + yforeCalygml = NaN; +end + + + +%---------------------------------------------------------------------- +% --------------------- Actual ----------------------------------------- +%---------------------------------------------------------------------- +if indxCal + Rem_qm = q_m-qmEnd; % remaining months within the first calendar year + Rem_y = floor((forep-Rem_qm)/q_m); % remaining calendar years after the first one + yact = xdata(nSample-2*q_m+1:nSample+Rem_qm+Rem_y*q_m,:); + % 2*q_m (not calendar) months + months ended at last calendar year +else + yact = xdata(nSample-q_m+1:nSample+forep,:); % q_m (not calendar) months + forep +end +mT1 = length(yact(:,1)); +yactlog = yact(q_m+1:mT1,:); + + +%----------------------------------------- +% Converted to monthly level +%----------------------------------------- +if lmqyIndx(1) + yactl=yactlog; + yactl(:,vlistlog)=exp(yactlog(:,vlistlog)); % mode, all levels + yactl(:,vlistper)=100*yactlog(:,vlistper); % mode, all levels +else + yactl=NaN; +end + +%----------------------------------------- +% Converted to monthly growth +%----------------------------------------- +if lmqyIndx(2) + yactmg = yactl; + yactmg(:,vlistlog) = (yact(q_m+1:mT1,vlistlog) - yact(q_m:mT1-1,vlistlog)) .* 12; + % monthly, 12*log(1+growth rate), annualized growth rate + yactmg(:,vlistlog) = 100*(exp(yactmg(:,vlistlog))-1); + yactmg(:,vlistper) = 100*yactmg(:,vlistper); +else + yactmg=NaN; +end + +%----------------------------------------- +% Converted to quarterly +%----------------------------------------- +if lmqyIndx(3) + warning(' ') + disp('Not worked out yet. 4/27/99') + disp('Press ctrl-c to abort!') + pause + + yactQ = yact(10:mT1,:); % October: beginning of the 4th quarter + yactq = zeros(1+forepq,length(vlist)); + qT1 = 1+forepq; + % + for i = 1:qT1 + i1 = 1+3*(i-1); + i2 = 3*i; + yactq(i,:) = sum(yactQ(i1:i2,:)) ./ 3; + end + % + yactqg = yactq(2:qT1,:); % 4+1=5 where 4 means 4 quarters + yactqg(:,vlistlog) = (yactq(2:qT1,vlistlog) - yactq(1:qT1-1,vlistlog)) .* 4; + % quarterly, 4*log(1+growth rate), annualized growth rate + yactqg(:,vlistlog) = 100*(exp(yactqg(:,vlistlog))-1); + yactqg(:,vlistper) = 100*yactqg(:,vlistper); +else + yactqg=NaN; +end + + +%----------------------------------------- +% Converted to annual years (may not be calendar) +%----------------------------------------- +if lmqyIndx(4) + if indxCal + yT1 = 1+forepy; + yactCaly = zeros(yT1,length(vlist)); % the latest 1+forepy calendar years + for i = 1:yT1 + i1 = ( Rem_qm+q_m*(qmEnd==q_m) ) + 1+q_m*(i-1); + i2 = ( Rem_qm+q_m*(qmEnd==q_m) ) + q_m*i; + yactCaly(i,:) = sum(yact(i1:i2,:)) ./ q_m; + end + % + yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year + yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); + % annual rate: log(1+growth rate) + yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); + yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); + else + yT1 = 1+forepy; + for i = 1:yT1 + i1 = 1+q_m*(i-1); + i2 = q_m*i; + yactCaly(i,:) = sum(yact(i1:i2,:)) ./ q_m; + end + % + yactCalyg = yactCaly(2:yT1,:); % 1+1=2 where 1 means 1 year + yactCalyg(:,vlistlog) = (yactCaly(2:yT1,vlistlog) - yactCaly(1:yT1-1,vlistlog)); + % annual rate: log(1+growth rate) + yactCalyg(:,vlistlog) = 100*(exp(yactCalyg(:,vlistlog))-1); + yactCalyg(:,vlistper) = 100*yactCalyg(:,vlistper); + end +else + yactCalyg=NaN; +end diff --git a/MatlabFiles/forecast.m b/MatlabFiles/forecast.m index e39d8e43a6c5e683423bcd2907cc8ef0fe1e69fc..54d7a93eb1c18bb1796d0b043d2d66db43ced614 100644 --- a/MatlabFiles/forecast.m +++ b/MatlabFiles/forecast.m @@ -1,41 +1,41 @@ -function yhat = forecast(Bh,phi,nn) -% yhat = forecast(Bh,phi,nn) -% -% Forecast: unconditional forecating: yhat = forecast(Bh,phi,nn) -% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar -% where Bh: the (posterior) estimate of B; -% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast); -% nn: [nvar,lags,forep], forep: forecast periods; -% yhat: forep*nvar. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup -nvar = nn(1); -lags = nn(2); -forep = nn(3); -tcwc = nvar*lags; % total coefficients without constant - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -yhat = zeros(forep,nvar); -for k=1:forep - yhat(k,:) = phi*Bh; - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); -end +function yhat = forecast(Bh,phi,nn) +% yhat = forecast(Bh,phi,nn) +% +% Forecast: unconditional forecating: yhat = forecast(Bh,phi,nn) +% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar +% where Bh: the (posterior) estimate of B; +% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast); +% nn: [nvar,lags,forep], forep: forecast periods; +% yhat: forep*nvar. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup +nvar = nn(1); +lags = nn(2); +forep = nn(3); +tcwc = nvar*lags; % total coefficients without constant + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +yhat = zeros(forep,nvar); +for k=1:forep + yhat(k,:) = phi*Bh; + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); +end diff --git a/MatlabFiles/forecasterr.m b/MatlabFiles/forecasterr.m index 7ee0e2b6198e4b8c65f7d1fc0fd5a997d7d64ef7..fc2c980453d2137c4c7b96c36895b15eca7eaf82 100644 --- a/MatlabFiles/forecasterr.m +++ b/MatlabFiles/forecasterr.m @@ -1,44 +1,44 @@ -function yhat = forecasterr(A0hin,Bh,phi,nn) -% forecast: unconditional forecating: yhat = forecast(Bh,phi,nn) -% y_hat(t+h) = x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar -% where A0hin: inv(A0h) where columns correspond to equations -% Bh: the (posterior) estimate of B; -% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast); -% nn: [nvar,lags,forep], forep: forecast periods; -% yhat: forep*nvar. -% -% See fsim.m when A0h (rather than A0hin) is used. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup -nvar = nn(1); -lags = nn(2); -forep = nn(3); -tcwc = nvar*lags; % total coefficients without constant - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -Estr = randn(forep,nvar); -Ures = Estr*A0hin; -yhat = zeros(forep,nvar); -for k=1:forep - yhat(k,:) = phi*Bh + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); -end +function yhat = forecasterr(A0hin,Bh,phi,nn) +% forecast: unconditional forecating: yhat = forecast(Bh,phi,nn) +% y_hat(t+h) = x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar +% where A0hin: inv(A0h) where columns correspond to equations +% Bh: the (posterior) estimate of B; +% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast); +% nn: [nvar,lags,forep], forep: forecast periods; +% yhat: forep*nvar. +% +% See fsim.m when A0h (rather than A0hin) is used. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup +nvar = nn(1); +lags = nn(2); +forep = nn(3); +tcwc = nvar*lags; % total coefficients without constant + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +Estr = randn(forep,nvar); +Ures = Estr*A0hin; +yhat = zeros(forep,nvar); +for k=1:forep + yhat(k,:) = phi*Bh + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); +end diff --git a/MatlabFiles/forefixe.m b/MatlabFiles/forefixe.m index 60834432d9014e8d74e1f20959573e3ce98147f1..3ef25bb66b71556332197b431fadabbfb464d0e7 100644 --- a/MatlabFiles/forefixe.m +++ b/MatlabFiles/forefixe.m @@ -1,46 +1,46 @@ -function yhat = forefixe(A0h,Bh,phi,nn,Estr) -% yhat = forefixe(A0h,Bh,phi,nn,Estr) -% Forecat conditional on particular structural shocks -% -% where A0h: column means equation -% Bh: the (posterior) estimate of B; -% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast); -% nn: [nvar,lags,forep], forep: forecast periods; -% Estr: forep-by-nvar, each column corresponds to shocks from a particular -% source such as MS; -% yhat: forep*nvar; -% -% For reduced-form shocks, see fshock.m -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup -nvar = nn(1); -lags = nn(2); -forep = nn(3); -tcwc = nvar*lags; % total coefficients without constant - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -Ures = Estr/A0h; -yhat = zeros(forep,nvar); -for k=1:forep - yhat(k,:) = phi*Bh + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); -end +function yhat = forefixe(A0h,Bh,phi,nn,Estr) +% yhat = forefixe(A0h,Bh,phi,nn,Estr) +% Forecat conditional on particular structural shocks +% +% where A0h: column means equation +% Bh: the (posterior) estimate of B; +% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast); +% nn: [nvar,lags,forep], forep: forecast periods; +% Estr: forep-by-nvar, each column corresponds to shocks from a particular +% source such as MS; +% yhat: forep*nvar; +% +% For reduced-form shocks, see fshock.m +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup +nvar = nn(1); +lags = nn(2); +forep = nn(3); +tcwc = nvar*lags; % total coefficients without constant + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +Ures = Estr/A0h; +yhat = zeros(forep,nvar); +for k=1:forep + yhat(k,:) = phi*Bh + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); +end diff --git a/MatlabFiles/fshock.m b/MatlabFiles/fshock.m index a5799576862a1b5307e41e0bd42fe56bd2ac3645..715cf5fb3710266320c3352895aef55c2b871101 100644 --- a/MatlabFiles/fshock.m +++ b/MatlabFiles/fshock.m @@ -1,44 +1,44 @@ -function yhat = fshock(Bh,phi,shock,nn) -% fshock: unconditionally forecasts supplied with reduced-form shocks -% yhat = fshock(Bh,phi,shock,nn) -% -% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar -% where Bh: the (posterior) estimate of B; -% phi: the 1-by-(nvar*lags+1) initial data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast); -% shock: forep-by-nvar reduced-form residuals, where forep: forecast periods; -% nn: [nvar,lags,forep]; -% yhat: forep-by-nvar. -% -% For structural shocks, see forefixe.m -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup -nvar = nn(1); -lags = nn(2); -forep = nn(3); -tcwc = nvar*lags; % total coefficients without constant - -% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B -% ** where phi = x(t+h-1) with last column being constant -yhat = zeros(forep,nvar); -for k=1:forep - yhat(k,:) = phi*Bh + shock(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); -end +function yhat = fshock(Bh,phi,shock,nn) +% fshock: unconditionally forecasts supplied with reduced-form shocks +% yhat = fshock(Bh,phi,shock,nn) +% +% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar +% where Bh: the (posterior) estimate of B; +% phi: the 1-by-(nvar*lags+1) initial data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast); +% shock: forep-by-nvar reduced-form residuals, where forep: forecast periods; +% nn: [nvar,lags,forep]; +% yhat: forep-by-nvar. +% +% For structural shocks, see forefixe.m +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup +nvar = nn(1); +lags = nn(2); +forep = nn(3); +tcwc = nvar*lags; % total coefficients without constant + +% ** reconstruct x(t) for y(t+h) = x(t+h-1)*B +% ** where phi = x(t+h-1) with last column being constant +yhat = zeros(forep,nvar); +for k=1:forep + yhat(k,:) = phi*Bh + shock(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); +end diff --git a/MatlabFiles/fsim.m b/MatlabFiles/fsim.m index e01da891c1df8693522654ac5bd3f2b12cbe06cf..14a9fdc3ca0ce32b85b1c48695c006e88c376735 100644 --- a/MatlabFiles/fsim.m +++ b/MatlabFiles/fsim.m @@ -1,49 +1,49 @@ -function yhat = fsim(Bh,A0h,phi,nn) -% yhat = fsim(Bh,A0h,phi,nn) -% Unconditional forecasts with simulated shocks (which do not depend on reduced-form or structural shocks). -% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar -% where Bh: the (posterior) estimate of B; -% A0h: has columns correpond to equations -% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast); -% nn: [nvar,lags,forep], forep: forecast periods; -% yhat: forep*nvar. -% -% 3/22/99. Revised so that A0h has columns corr. to equations. Previous -% may use A0h' (papers before Sims and Zha IER paper). So please double -% check. -% -% See forecasterr.m when A0h_in (instead of A0h) is used. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup -nvar = nn(1); -lags = nn(2); -forep = nn(3); -tcwc = nvar*lags; % total coefficients without constant - -Ures = randn(forep,nvar)/A0h; % Unconditional forecast - % Now, forep-by-nvar -- ready for forecasts - % Ures: reduced-form residuals. Row--steps; Column--n shocks - -yhat = zeros(forep,nvar); -for k=1:forep - yhat(k,:) = phi*Bh + Ures(k,:); - phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); - phi(1,1:nvar) = yhat(k,:); -end +function yhat = fsim(Bh,A0h,phi,nn) +% yhat = fsim(Bh,A0h,phi,nn) +% Unconditional forecasts with simulated shocks (which do not depend on reduced-form or structural shocks). +% y_hat(t+h) = c + x_hat(t+h-1)*Bh, X: 1*k; Bh: k*nvar; y_hat: 1*nvar +% where Bh: the (posterior) estimate of B; +% A0h: has columns correpond to equations +% phi: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast); +% nn: [nvar,lags,forep], forep: forecast periods; +% yhat: forep*nvar. +% +% 3/22/99. Revised so that A0h has columns corr. to equations. Previous +% may use A0h' (papers before Sims and Zha IER paper). So please double +% check. +% +% See forecasterr.m when A0h_in (instead of A0h) is used. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup +nvar = nn(1); +lags = nn(2); +forep = nn(3); +tcwc = nvar*lags; % total coefficients without constant + +Ures = randn(forep,nvar)/A0h; % Unconditional forecast + % Now, forep-by-nvar -- ready for forecasts + % Ures: reduced-form residuals. Row--steps; Column--n shocks + +yhat = zeros(forep,nvar); +for k=1:forep + yhat(k,:) = phi*Bh + Ures(k,:); + phi(1,nvar+1:tcwc) = phi(1,1:tcwc-nvar); + phi(1,1:nvar) = yhat(k,:); +end diff --git a/MatlabFiles/gactual.m b/MatlabFiles/gactual.m index 0765333594b5fcda8a5f79279bee6119a920498c..8d5b65a313af2829b1017b33d98891f4ebd986af 100644 --- a/MatlabFiles/gactual.m +++ b/MatlabFiles/gactual.m @@ -1,197 +1,197 @@ -function actual = gactual(begy,begm,begq,finy,finm,finq,ylab,mqyIndx,idfile) -% -% actual = gactual(begy,begm,begq,finy,finm,finq,ylab,mqyIndx,idfile) -% Actual data according to mqyIndx; graph if no output argument is specified. -% -% begy: the beginning year for the graph -% begm: the begiining month for the graph -% begq: the begiining quarter for the graph -% finy: the end year for the graph -% finm: the end month for the graph -% finq: the end quarter for the graph -% ylab: label for each variable -% mqyIndx: 1-by-3 index of monthly log, qg, and calendar yg. 1: yes; 0: no. -% Only one at a time -% idfile: import xinample.mat in the LZ paper under \condz -%-------------- -% actual: T-by-nvar+1; 1st column is the dates; 2nd-7th columns: actual data of -% of nvar variables with mlog, qg, or calendar yg, one at a time, -% depending on mqyIndx -% graph if no output argument is specified. -% -% -% When insampleg.m is run, xinsample.mat is loaded for a long -% history (e.g.,1960-1998) -% When mspoint.m is run, outxshock.mat from msstart is loaded, which varies -% with parac.m. -% -% October 1998 by Tao A. Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -eval(['load ' idfile '.mat']); -% - -if length(find(mqyIndx))>1 - warning('To get the number (not graph) out, only one at a time') - disp('Make sure that mqyIndx has only 1 in a vector of 1 and 0s') - disp(' ') - disp('Press Enter to continue or Ctrl to abort') - pause -end - -if mqyIndx(1)==1 % monthly log - ibegy = find(myears==begy); - ifiny = find(myears==finy); - - ibegy1 = find(myears==begy+1); - % - if isempty(ibegy) & isempty(ibegy1) - warning('Either ibegy or begm is out of the range of myears in xinsample.mat') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - disp('Press ctrl-c to abort now') - pause - elseif isempty(ibegy) & (begm<myears(1)) - warning('Either ibegy or begm is out of the range of myears in xinample.mat') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - disp('Press ctrl-c to abort now') - pause - elseif isempty(ibegy) - ibegy = -myears(1)+2; % +2 is needed for the following -1 in - % bar(Estrexa(ibegy+begm-1:ifiny+finm-1,i)) - %so that it 2-1=1 so that +1 is what we want - end - % - if isempty(ifiny) - warning('Either ifiny or finm is out of the range of myears') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - elseif (ifiny+finm-1>size(myears,1)) - warning('Either ifiny or finm is out of the range of myears') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - end - - - if nargout==0 - t=length(yact(ibegy+begm-1:ifiny+finm-1,1)); - for i=1:size(yact,2) - figure - plot(1:t, yact(ibegy+begm-1:ifiny+finm-1,i),'*:'); - %bar(yact(ibegy+begm-1:ifiny+finm-1,i)) - title('Monthly Log') - ylabel(char(ylab(i))) - xlabel([ 'From ' num2str(begy) ':' num2str(begm) ' to ' ... - num2str(finy) ':' num2str(finm) ]) - grid - end - end - - actual = [myears(ibegy+begm-1:ifiny+finm-1) yact(ibegy+begm-1:ifiny+finm-1,:)]; -end - - -if mqyIndx(2)==1 % quarterly - ibegy = find(qyears==begy); - ifiny = find(qyears==finy); - - ibegy1 = find(qyears==begy+1); - % - if isempty(ibegy) & isempty(ibegy1) - warning('Either ibegy or begq is out of the range of qyears') - disp('Print qyears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - elseif isempty(ibegy) & (begq<qyears(1)) - warning('Either ibegy or begq is out of the range of qyears') - disp('Print qyears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - elseif isempty(ibegy) - ibegy = -qyears(1)+2; % +2 is needed for the following -1 in - % bar(Estrexa(ibegy+begq-1:ifiny+finm-1,i)) - %so that it 2-1=1 so that +1 is what we want - end - % - if isempty(ifiny) - warning('Either ifiny or finq is out of the range of qyears') - disp('Print qyears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - elseif (ifiny+finq-1>size(qyears,1)) - warning('Either ifiny or finq is out of the range of qyears') - disp('Print qyears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - end - - - if nargout==0 - t=length(yactqg(ibegy+begq-1:ifiny+finq-1,1)); - for i=1:size(yactqg,2) - figure - plot(1:t, yactqg(ibegy+begq-1:ifiny+finq-1,i),'*:'); - title('Quarter-to-quarter Growth Rate') - ylabel(char(ylab(i))) - xlabel([ 'From ' num2str(begy) ':' num2str(begq) ' to ' ... - num2str(finy) ':' num2str(finq) ]) - grid - end - end - - actual = [qyears(ibegy+begq-1:ifiny+finq-1) yactqg(ibegy+begq-1:ifiny+finq-1,:)]; -end - - -if mqyIndx(3)==1 % calendar year - ibegy = find(yearsCal==begy); - ifiny = find(yearsCal==finy); - % - if isempty(ibegy) - warning('Either ibegy or begq is out of the range of yearsCal') - disp('Print yearsCal to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - end - % - if isempty(ifiny) - warning('Either ifiny or finq is out of the range of yearsCal') - disp('Print yearsCal to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - return - end - - if nargout==0 - t=length(yactCalyg(ibegy:ifiny,1)); - for i=1:size(yactCalyg,2) - figure - plot(1:t, yactCalyg(ibegy:ifiny,i),'*:'); - title('Calendar Annual Average Growth Rate') - ylabel(char(ylab(i))) - xlabel([ 'From 19' num2str(begy) ' to 19' ... - num2str(finy) ]) - grid - end - end - - actual = [yearsCal(ibegy:ifiny) yactCalyg(ibegy:ifiny,:)]; -end +function actual = gactual(begy,begm,begq,finy,finm,finq,ylab,mqyIndx,idfile) +% +% actual = gactual(begy,begm,begq,finy,finm,finq,ylab,mqyIndx,idfile) +% Actual data according to mqyIndx; graph if no output argument is specified. +% +% begy: the beginning year for the graph +% begm: the begiining month for the graph +% begq: the begiining quarter for the graph +% finy: the end year for the graph +% finm: the end month for the graph +% finq: the end quarter for the graph +% ylab: label for each variable +% mqyIndx: 1-by-3 index of monthly log, qg, and calendar yg. 1: yes; 0: no. +% Only one at a time +% idfile: import xinample.mat in the LZ paper under \condz +%-------------- +% actual: T-by-nvar+1; 1st column is the dates; 2nd-7th columns: actual data of +% of nvar variables with mlog, qg, or calendar yg, one at a time, +% depending on mqyIndx +% graph if no output argument is specified. +% +% +% When insampleg.m is run, xinsample.mat is loaded for a long +% history (e.g.,1960-1998) +% When mspoint.m is run, outxshock.mat from msstart is loaded, which varies +% with parac.m. +% +% October 1998 by Tao A. Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +eval(['load ' idfile '.mat']); +% + +if length(find(mqyIndx))>1 + warning('To get the number (not graph) out, only one at a time') + disp('Make sure that mqyIndx has only 1 in a vector of 1 and 0s') + disp(' ') + disp('Press Enter to continue or Ctrl to abort') + pause +end + +if mqyIndx(1)==1 % monthly log + ibegy = find(myears==begy); + ifiny = find(myears==finy); + + ibegy1 = find(myears==begy+1); + % + if isempty(ibegy) & isempty(ibegy1) + warning('Either ibegy or begm is out of the range of myears in xinsample.mat') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + disp('Press ctrl-c to abort now') + pause + elseif isempty(ibegy) & (begm<myears(1)) + warning('Either ibegy or begm is out of the range of myears in xinample.mat') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + disp('Press ctrl-c to abort now') + pause + elseif isempty(ibegy) + ibegy = -myears(1)+2; % +2 is needed for the following -1 in + % bar(Estrexa(ibegy+begm-1:ifiny+finm-1,i)) + %so that it 2-1=1 so that +1 is what we want + end + % + if isempty(ifiny) + warning('Either ifiny or finm is out of the range of myears') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + elseif (ifiny+finm-1>size(myears,1)) + warning('Either ifiny or finm is out of the range of myears') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + end + + + if nargout==0 + t=length(yact(ibegy+begm-1:ifiny+finm-1,1)); + for i=1:size(yact,2) + figure + plot(1:t, yact(ibegy+begm-1:ifiny+finm-1,i),'*:'); + %bar(yact(ibegy+begm-1:ifiny+finm-1,i)) + title('Monthly Log') + ylabel(char(ylab(i))) + xlabel([ 'From ' num2str(begy) ':' num2str(begm) ' to ' ... + num2str(finy) ':' num2str(finm) ]) + grid + end + end + + actual = [myears(ibegy+begm-1:ifiny+finm-1) yact(ibegy+begm-1:ifiny+finm-1,:)]; +end + + +if mqyIndx(2)==1 % quarterly + ibegy = find(qyears==begy); + ifiny = find(qyears==finy); + + ibegy1 = find(qyears==begy+1); + % + if isempty(ibegy) & isempty(ibegy1) + warning('Either ibegy or begq is out of the range of qyears') + disp('Print qyears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + elseif isempty(ibegy) & (begq<qyears(1)) + warning('Either ibegy or begq is out of the range of qyears') + disp('Print qyears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + elseif isempty(ibegy) + ibegy = -qyears(1)+2; % +2 is needed for the following -1 in + % bar(Estrexa(ibegy+begq-1:ifiny+finm-1,i)) + %so that it 2-1=1 so that +1 is what we want + end + % + if isempty(ifiny) + warning('Either ifiny or finq is out of the range of qyears') + disp('Print qyears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + elseif (ifiny+finq-1>size(qyears,1)) + warning('Either ifiny or finq is out of the range of qyears') + disp('Print qyears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + end + + + if nargout==0 + t=length(yactqg(ibegy+begq-1:ifiny+finq-1,1)); + for i=1:size(yactqg,2) + figure + plot(1:t, yactqg(ibegy+begq-1:ifiny+finq-1,i),'*:'); + title('Quarter-to-quarter Growth Rate') + ylabel(char(ylab(i))) + xlabel([ 'From ' num2str(begy) ':' num2str(begq) ' to ' ... + num2str(finy) ':' num2str(finq) ]) + grid + end + end + + actual = [qyears(ibegy+begq-1:ifiny+finq-1) yactqg(ibegy+begq-1:ifiny+finq-1,:)]; +end + + +if mqyIndx(3)==1 % calendar year + ibegy = find(yearsCal==begy); + ifiny = find(yearsCal==finy); + % + if isempty(ibegy) + warning('Either ibegy or begq is out of the range of yearsCal') + disp('Print yearsCal to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + end + % + if isempty(ifiny) + warning('Either ifiny or finq is out of the range of yearsCal') + disp('Print yearsCal to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + return + end + + if nargout==0 + t=length(yactCalyg(ibegy:ifiny,1)); + for i=1:size(yactCalyg,2) + figure + plot(1:t, yactCalyg(ibegy:ifiny,i),'*:'); + title('Calendar Annual Average Growth Rate') + ylabel(char(ylab(i))) + xlabel([ 'From 19' num2str(begy) ' to 19' ... + num2str(finy) ]) + grid + end + end + + actual = [yearsCal(ibegy:ifiny) yactCalyg(ibegy:ifiny,:)]; +end diff --git a/MatlabFiles/gaf.m b/MatlabFiles/gaf.m index 83cdc906d0dc6f7704cc859049afb364bb262d2d..b4be1e0f4f285eafba2c5d280217d0fd890654a3 100644 --- a/MatlabFiles/gaf.m +++ b/MatlabFiles/gaf.m @@ -1,104 +1,104 @@ -function gaf(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... - yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) -% gaf(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... -% yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) -% Graph (calendar year) forecasts vs actual (actual from "msstart.m") -% Make sure that actup in "msstart.m" is set at the length for visual graphs -% -% yrEnd: the end year for the sample -% qmEnd: last q_m before out-of-sample forecasting -% q_m: quarterly or monthly for the underlying model -% yearsCal: calendar years including actual and forecast data -% yactCalyg: actual calendar annual growth data -% yhatCalygml: conditional (calendar annual) forecasts on particular shocks -% forepy: forecast periods (yearly) -% xlab: label for structural equations -% ylab: label for the variables -% forelabel: title label for as of time of forecast -% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -%------------- -% No output argument for this graph file -% -% October 1998 Tao Zha; revised, 03/20/99 - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -%*** Begining forecast (actual) period -fbegm = qmEnd+1; % +1 because the first month out of sample -if fbegm > q_m % the first forecast month into the next year - fbegm = 1; - fbegy = yrEnd+1; % the first forecast year for the graph -else - fbegy = yrEnd; % the first forecast year for the graph -end -abegy = min(yearsCal); % the actual beginning year for the graph, NOT the same as - % the first forecast year -%abegm = 1; -ifbegy = find(yearsCal==fbegy-1); % index for the actual year in "yactCalyg" - % before the first forecast year - -%*** Final forecast (and actual) period -ffiny = fbegy+forepy-1; % the forecast final year -afiny = max(yearsCal); % the actual final year for the graph, coinciding with - - - -figure - -nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U -%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U -%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 - -hornum = cell(length(abegy:ffiny),1); % horizontal number -count=0; -for k=abegy:ffiny - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -cnum = 2; -% -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - % - if abegy>fbegy-1 - plot(abegy:afiny,yactCalyg(:,i),fbegy:ffiny,yhatCalygml(:,i),'-.') - set(gca,'XTick',abegy:ffiny) - else - plot(abegy:afiny,yactCalyg(:,i),... - fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygml(:,i)],'-.') - set(gca,'XTick',abegy:ffiny) - end - set(gca,'XTickLabel',char(hornum)) - if i<=cnum - title(forelabel) - elseif i>=nvar-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end \ No newline at end of file +function gaf(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... + yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) +% gaf(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... +% yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) +% Graph (calendar year) forecasts vs actual (actual from "msstart.m") +% Make sure that actup in "msstart.m" is set at the length for visual graphs +% +% yrEnd: the end year for the sample +% qmEnd: last q_m before out-of-sample forecasting +% q_m: quarterly or monthly for the underlying model +% yearsCal: calendar years including actual and forecast data +% yactCalyg: actual calendar annual growth data +% yhatCalygml: conditional (calendar annual) forecasts on particular shocks +% forepy: forecast periods (yearly) +% xlab: label for structural equations +% ylab: label for the variables +% forelabel: title label for as of time of forecast +% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +%------------- +% No output argument for this graph file +% +% October 1998 Tao Zha; revised, 03/20/99 + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +%*** Begining forecast (actual) period +fbegm = qmEnd+1; % +1 because the first month out of sample +if fbegm > q_m % the first forecast month into the next year + fbegm = 1; + fbegy = yrEnd+1; % the first forecast year for the graph +else + fbegy = yrEnd; % the first forecast year for the graph +end +abegy = min(yearsCal); % the actual beginning year for the graph, NOT the same as + % the first forecast year +%abegm = 1; +ifbegy = find(yearsCal==fbegy-1); % index for the actual year in "yactCalyg" + % before the first forecast year + +%*** Final forecast (and actual) period +ffiny = fbegy+forepy-1; % the forecast final year +afiny = max(yearsCal); % the actual final year for the graph, coinciding with + + + +figure + +nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U +%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U +%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 + +hornum = cell(length(abegy:ffiny),1); % horizontal number +count=0; +for k=abegy:ffiny + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +cnum = 2; +% +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + % + if abegy>fbegy-1 + plot(abegy:afiny,yactCalyg(:,i),fbegy:ffiny,yhatCalygml(:,i),'-.') + set(gca,'XTick',abegy:ffiny) + else + plot(abegy:afiny,yactCalyg(:,i),... + fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygml(:,i)],'-.') + set(gca,'XTick',abegy:ffiny) + end + set(gca,'XTickLabel',char(hornum)) + if i<=cnum + title(forelabel) + elseif i>=nvar-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/gaferr1.m b/MatlabFiles/gaferr1.m index d9730c1ea148630e8e70f6310c1f9e8c77978f6e..ec919ebbb0b2214b6c761131189fd32b60eeb4f2 100644 --- a/MatlabFiles/gaferr1.m +++ b/MatlabFiles/gaferr1.m @@ -1,106 +1,106 @@ -function gaferr1(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,yhatCalygml,yhatCalygl1,... - yhatCalygh1,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) - -% -% One (.68) error band: (calendar year) forecasts vs actual (actual from "msstart.m") -% Make sure that actup in "msstart.m" is set at the length for visual graphs -% -% yrEnd: the end year for the sample -% qmEnd: last q_m before out-of-sample forecasting -% q_m: quarterly or monthly for the underlying model -% yearsCal: calendar years including actual and forecast data -% yactCalyg: actual calendar annual growth data -% yhatCalygml: conditional (calendar annual) forecasts on particular shocks -% yhatCalygl1: 0.68 lower band -% yhatCalygh1: 0.68 upper band -% forepy: forecast periods (yearly) -% xlab: label for structural equations -% ylab: label for the variables -% forelabel: title label for as of time of forecast -% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -%------------- -% No output argument for this graph file -% -% 03/19/99 - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%*** Begining period -fbegm = qmEnd+1; % +1 because the first month out of sample -if fbegm > q_m % the first forecast month into the next year - fbegm = 1; - fbegy = yrEnd+1; % the first forecast year for the graph -else - fbegy = yrEnd; % the first forecast year for the graph -end -abegy = min(yearsCal); % the actual beginning year for the graph -abegm = 1; -ifbegy = find(yearsCal==fbegy-1); % index for the year before the first - % forecast first year in actual data "yactCalyg" - -%*** Final period -ffiny = fbegy+forepy-1; % the forecast final year -afiny = max(yearsCal); % the actual final year - - - -figure - -nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U -%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U -%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 - -hornum = cell(length(abegy:ffiny),1); % horizontal number -count=0; -for k=abegy:ffiny - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -% -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - % - if abegy>fbegy-1 - plot(abegy:afiny,yactCalyg(:,i),fbegy:ffiny,yhatCalygml(:,i),'-.',... - fbegy:ffiny,yhatCalygl1,'--',fbegy:ffiny,yhatCalygh1,'--' ) - set(gca,'XTick',abegy:ffiny) - else - plot(abegy:afiny,yactCalyg(:,i),... - fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygml(:,i)],'-.',... - fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygl1(:,i)],'--',... - fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygh1(:,i)],'--') - set(gca,'XTick',abegy:ffiny) - end - set(gca,'XTickLabel',char(hornum)) - if i<=cnum - title(forelabel) - elseif i>=nvar-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end +function gaferr1(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,yhatCalygml,yhatCalygl1,... + yhatCalygh1,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) + +% +% One (.68) error band: (calendar year) forecasts vs actual (actual from "msstart.m") +% Make sure that actup in "msstart.m" is set at the length for visual graphs +% +% yrEnd: the end year for the sample +% qmEnd: last q_m before out-of-sample forecasting +% q_m: quarterly or monthly for the underlying model +% yearsCal: calendar years including actual and forecast data +% yactCalyg: actual calendar annual growth data +% yhatCalygml: conditional (calendar annual) forecasts on particular shocks +% yhatCalygl1: 0.68 lower band +% yhatCalygh1: 0.68 upper band +% forepy: forecast periods (yearly) +% xlab: label for structural equations +% ylab: label for the variables +% forelabel: title label for as of time of forecast +% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +%------------- +% No output argument for this graph file +% +% 03/19/99 + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%*** Begining period +fbegm = qmEnd+1; % +1 because the first month out of sample +if fbegm > q_m % the first forecast month into the next year + fbegm = 1; + fbegy = yrEnd+1; % the first forecast year for the graph +else + fbegy = yrEnd; % the first forecast year for the graph +end +abegy = min(yearsCal); % the actual beginning year for the graph +abegm = 1; +ifbegy = find(yearsCal==fbegy-1); % index for the year before the first + % forecast first year in actual data "yactCalyg" + +%*** Final period +ffiny = fbegy+forepy-1; % the forecast final year +afiny = max(yearsCal); % the actual final year + + + +figure + +nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U +%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U +%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 + +hornum = cell(length(abegy:ffiny),1); % horizontal number +count=0; +for k=abegy:ffiny + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +% +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + % + if abegy>fbegy-1 + plot(abegy:afiny,yactCalyg(:,i),fbegy:ffiny,yhatCalygml(:,i),'-.',... + fbegy:ffiny,yhatCalygl1,'--',fbegy:ffiny,yhatCalygh1,'--' ) + set(gca,'XTick',abegy:ffiny) + else + plot(abegy:afiny,yactCalyg(:,i),... + fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygml(:,i)],'-.',... + fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygl1(:,i)],'--',... + fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygh1(:,i)],'--') + set(gca,'XTick',abegy:ffiny) + end + set(gca,'XTickLabel',char(hornum)) + if i<=cnum + title(forelabel) + elseif i>=nvar-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/gampar.m b/MatlabFiles/gampar.m index e80d80b8e081ec4842f4db80c71c3bc49e46dc84..e103b059279c02b8addcf68b3da8f14e52af327b 100644 --- a/MatlabFiles/gampar.m +++ b/MatlabFiles/gampar.m @@ -1,31 +1,31 @@ -function f = gampar(ab, XLO, XUP, PLO, PUP); - -% The function takes as inputs the parameters ab=[a, b] of the gamma -% distribution, the bounds of the support [XLO, XUP], the the corresponding -% probability of the bounds [PLO, PUP] and returns the residual value f. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -a = abs(ab(1)); b = abs(ab(2)); % abs() is used to allow continuous search for the fsolve function find_gampar.m. -f1 = PLO - gamcdf(XLO, a, 1/b); %Note that in Matlab, it is 1/b, NOT b. -f2 = PUP - gamcdf(XUP, a, 1/b); %Note that in Matlab, it is 1/b, NOT b. -% Equivalently, one can use the gaminv function to define the zero -% conditions: -% f1 = XLO - gaminv(PLO, a, b); -% f2 = XUP - gaminv(PUP, a, b); - -f = [f1, f2]; +function f = gampar(ab, XLO, XUP, PLO, PUP); + +% The function takes as inputs the parameters ab=[a, b] of the gamma +% distribution, the bounds of the support [XLO, XUP], the the corresponding +% probability of the bounds [PLO, PUP] and returns the residual value f. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +a = abs(ab(1)); b = abs(ab(2)); % abs() is used to allow continuous search for the fsolve function find_gampar.m. +f1 = PLO - gamcdf(XLO, a, 1/b); %Note that in Matlab, it is 1/b, NOT b. +f2 = PUP - gamcdf(XUP, a, 1/b); %Note that in Matlab, it is 1/b, NOT b. +% Equivalently, one can use the gaminv function to define the zero +% conditions: +% f1 = XLO - gaminv(PLO, a, b); +% f2 = XUP - gaminv(PUP, a, b); + +f = [f1, f2]; diff --git a/MatlabFiles/gensys.m b/MatlabFiles/gensys.m index 2914a55d42967a35a5b423e6610d630ad9fc273f..671b228b24f2751bed248235e4daf45d7d92e2a9 100644 --- a/MatlabFiles/gensys.m +++ b/MatlabFiles/gensys.m @@ -11,22 +11,22 @@ function [G1,C,impact,fmat,fwt,ywt,gev,eu]=gensys(g0,g1,c,psi,pi,div) % existence only with not-s.c. z; eu=[-2,-2] for coincident zeros. % By Christopher A. Sims % Corrected 10/28/96 by CAS -% Copyright (C) 1996-2012 Christopher A. Sims % -% This file is part of Dynare. +% Copyright (C) 1996-2012 Christopher A. Sims % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% eu=[0;0]; realsmall=1e-6; diff --git a/MatlabFiles/gensys_z2.m b/MatlabFiles/gensys_z2.m index 7a47757d209435df05ade14f06ca14439a752fb1..95b5b4530005b1cbe260797151eb80a53fd02973 100644 --- a/MatlabFiles/gensys_z2.m +++ b/MatlabFiles/gensys_z2.m @@ -14,22 +14,22 @@ function [z2,eu2]=gensys_z2(g0,g1,c,psi,gpi,div) % eu2 = [-2,-2] for coincident zeros. % By Christopher A. Sims % Corrected 10/28/96 by CAS -% Copyright (C) 1997-2012 Christopher A. Sims % -% This file is part of Dynare. +% Copyright (C) 1997-2012 Christopher A. Sims % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% eu2=NaN*ones(2,1); realsmall=1e-6; diff --git a/MatlabFiles/gensys_z2new.m b/MatlabFiles/gensys_z2new.m index 599b3ade6121435454fc119d09e226dd9685bd8d..ccb2fcfab699385c76b47fce14349f748b78c515 100644 --- a/MatlabFiles/gensys_z2new.m +++ b/MatlabFiles/gensys_z2new.m @@ -14,22 +14,22 @@ function [z2,eu2,div]=gensys_z2new(g0,g1,c,psi,gpi) % eu2 = [-2,-2] for coincident zeros. % By Christopher A. Sims % Corrected 10/28/96 by CAS -% Copyright (C) 1997-2012 Christopher A. Sims % -% This file is part of Dynare. +% Copyright (C) 1997-2012 Christopher A. Sims % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% eu2=NaN*ones(2,1); n2 = size(gpi,2); %number of expectational errors. diff --git a/MatlabFiles/gensysct.m b/MatlabFiles/gensysct.m index 13c053c15d45694e06a7fdfe0ac62ece83a685dc..079a79b2deb096825ca695d0c11663346ea11dac 100644 --- a/MatlabFiles/gensysct.m +++ b/MatlabFiles/gensysct.m @@ -1,197 +1,197 @@ -function [G1,C,impact,q,a,b,z,eu]=gensysct(g0,g1,c,psi,pi,div) -%function [G1,C,impact,q,a,b,z,eu]=gensysct(g0,g1,c,psi,pi,div) -%System given as -% g0*Dy(t)=g1*y(t)+c+psi*epsilon(t)+pi*eta(t), -%with epsilon an exogenous variable process and eta being endogenously determined -%white noise expectational errors. Returned system is -% Dy(t)=G1*y(t)+C+impact*epsilon(t). -% epsilon(t) is assumed to be white noise. -% If div is omitted from argument list, a div>0 is calculated. -% Also returned is the qz decomposition, q'az'=g0, q'bz'=g1, with a and b -% upper triangular and the system ordered so that all zeros on the diagonal of b are in -% the lower right corner, all cases where the real part of bii/aii is greater than or -% equal to div appear in the next block above the zeros, and the remaining bii/aii's -% all have bii/aii<div . These elements can be used to construct the full backward and -% forward solution. See the paper "Solving Linear Rational Expectations Models", -% http://eco-072399b.princeton.edu/yftp/gensys . Note that if one simply wants the backward -% and forward projection of y on epsilon, ignoring existence and uniqueness questions, the -% projection can be computed by Fourier methods. -% eu(1)=(existence); eu(2)=(uniqueness). Else eu=[-2,2] => indeterminacy via singularity -% in the equation system. Else eu(1)=-1 => existence only for white noise epsilon. -% realsmall=sqrt(eps)*10; -% Copyright (C) 1997-2012 C. A. Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -realsmall=sqrt(eps)*10; -%realsmall=1e-3; -eu=[0;0]; -fixdiv=(nargin==6) -n=size(g0,1); -[a b q z v]=qz(g0,g1); -if ~fixdiv, div=.001; end -nunstab=0; -nzero=0; -zxz=0; -for i=1:n - %------------------div calc------------ - if ~fixdiv - if abs(a(i,i)) > realsmall - divhat=real(b(i,i)/a(i,i)); - if realsmall<divhat & divhat<div - div=.5*divhat; - end - end - end - %---------------------------------------- - if abs(a(i,i))<realsmall - nzero=nzero+1; - nunstab=nunstab+1; - if abs(b(i,i))<realsmall - zxz=1; - end - else - nunstab=nunstab+ (real(b(i,i)/a(i,i))>div); - end -end -div -nunstab -nzero -% Note that qzdivct first puts all singularities in a in lower right, then puts unstable -% roots on top of those. -[a b q z]=qzdivct(div,a,b,q,z); -gev=[diag(a) diag(b)]; -if zxz - %disp('Coincident zeros. Indeterminacy and/or nonexistence.') - eu=[-2;-2]; - return -end -q1=q(1:n-nunstab,:); -q2=q(n-nunstab+1:n,:); -z1=z(:,1:n-nunstab)'; -z2=z(:,n-nunstab+1:n)'; -a2=a(n-nunstab+1:n,n-nunstab+1:n); -b2=b(n-nunstab+1:n,n-nunstab+1:n); -etawt=q2*pi; -zwt=q2*psi; -[ueta,deta,veta]=svd(etawt); -md=min(size(deta)); -bigev=find(diag(deta(1:md,1:md))>realsmall); -ueta=ueta(:,bigev); -veta=veta(:,bigev); -deta=deta(bigev,bigev); -[uz,dz,vz]=svd(zwt); -md=min(size(dz)); -bigev=find(diag(dz(1:md,1:md))>realsmall); -uz=uz(:,bigev); -vz=vz(:,bigev); -dz=dz(bigev,bigev); -if isempty(bigev) - exist=1; -else - exist=norm(uz-ueta*ueta'*uz,'fro') < realsmall*n; -end -if ~isempty(bigev) - zwtx0=b2\zwt; - zwtx=zwtx0; - M=b2\a2; - M=M/norm(M); - for i=2:nunstab - zwtx=[M*zwtx zwtx0]; - end - zwtx=b2*zwtx; - [ux,dx,vx]=svd(zwtx); - md=min(size(dx)); - bigev=find(diag(dx(1:md,1:md))>realsmall); - ux=ux(:,bigev); - vx=vx(:,bigev); - dx=dx(bigev,bigev); - existx=norm(ux-ueta*ueta'*ux,'fro') < realsmall*n; -else - existx=1; -end -%---------------------------------------------------- -% Note that existence and uniqueness are not just matters of comparing -% numbers of roots and numbers of endogenous errors. These counts are -% reported below because usually they point to the source of the problem. -%------------------------------------------------------ -[ueta1,deta1,veta1]=svd(q1*pi); -md=min(size(deta1)); -bigev=find(diag(deta1(1:md,1:md))>realsmall); -ueta1=ueta1(:,bigev); -veta1=veta1(:,bigev); -deta1=deta1(bigev,bigev); -if existx | nunstab==0 - %disp('solution exists'); - eu(1)=1; -else - if exist - %disp('solution exists for unforecastable z only'); - eu(1)=-1; - %else - %fprintf(1,'No solution. %d unstable roots. %d endog errors.\n',nunstab,size(ueta1,2)); - end - %disp('Generalized eigenvalues') - %disp(gev); - %md=abs(diag(a))>realsmall; - %ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; - %disp(ev) -% return; -end -%disp('Generalized eigenvalues') -%disp(gev); -%md=abs(diag(a))>realsmall; -%ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; -%disp(ev) -% return; -if isempty(veta1) - unique=1; -else - unique=norm(veta1-veta*veta'*veta1,'fro')<realsmall*n; -end -if unique - %disp('solution unique'); - eu(2)=1; -%else - %fprintf(1,'Indeterminacy. %d loose endog errors.\n',size(veta1,2)-size(veta,2)); - %disp('Generalized eigenvalues') - %disp(gev); - %disp(ev) -% return; -end -tmat = [eye(n-nunstab) -ueta1*deta1*veta1'*veta*(deta\ueta')]; -G0= [tmat*a; zeros(nunstab,n-nunstab) eye(nunstab)]; -G1= [tmat*b; zeros(nunstab,n)]; -%---------------------- -% G0 is always non-singular because by construction there are no zeros on -% the diagonal of a(1:n-nunstab,1:n-nunstab), which forms G0's ul corner. -%----------------------- -G0I=inv(G0); -G1=G0I*G1; -usix=n-nunstab+1:n; -C=G0I*[tmat*q*c;(a(usix,usix)-b(usix,usix))\q2*c]; -impact=G0I*[tmat*q*psi;zeros(nunstab,size(psi,2))]; -%-------------------- above are output for system in terms of z'y ------- -G1=z*G1*z'; -if max(max(abs(imag(G1))))>100*realsmall - disp('Inaccuracy in G1:') - s1=svd(G1); - s2=svd(real(G1)); - disp(max((s1-s2)./(1/12+s1))) % this is reasonable scaling for monthly time unit -end -G1=real(G1); -C=real(z*C); -impact=real(z*impact); +function [G1,C,impact,q,a,b,z,eu]=gensysct(g0,g1,c,psi,pi,div) +%function [G1,C,impact,q,a,b,z,eu]=gensysct(g0,g1,c,psi,pi,div) +%System given as +% g0*Dy(t)=g1*y(t)+c+psi*epsilon(t)+pi*eta(t), +%with epsilon an exogenous variable process and eta being endogenously determined +%white noise expectational errors. Returned system is +% Dy(t)=G1*y(t)+C+impact*epsilon(t). +% epsilon(t) is assumed to be white noise. +% If div is omitted from argument list, a div>0 is calculated. +% Also returned is the qz decomposition, q'az'=g0, q'bz'=g1, with a and b +% upper triangular and the system ordered so that all zeros on the diagonal of b are in +% the lower right corner, all cases where the real part of bii/aii is greater than or +% equal to div appear in the next block above the zeros, and the remaining bii/aii's +% all have bii/aii<div . These elements can be used to construct the full backward and +% forward solution. See the paper "Solving Linear Rational Expectations Models", +% http://eco-072399b.princeton.edu/yftp/gensys . Note that if one simply wants the backward +% and forward projection of y on epsilon, ignoring existence and uniqueness questions, the +% projection can be computed by Fourier methods. +% eu(1)=(existence); eu(2)=(uniqueness). Else eu=[-2,2] => indeterminacy via singularity +% in the equation system. Else eu(1)=-1 => existence only for white noise epsilon. +% realsmall=sqrt(eps)*10; +% +% Copyright (C) 1997-2012 C. A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +realsmall=sqrt(eps)*10; +%realsmall=1e-3; +eu=[0;0]; +fixdiv=(nargin==6) +n=size(g0,1); +[a b q z v]=qz(g0,g1); +if ~fixdiv, div=.001; end +nunstab=0; +nzero=0; +zxz=0; +for i=1:n + %------------------div calc------------ + if ~fixdiv + if abs(a(i,i)) > realsmall + divhat=real(b(i,i)/a(i,i)); + if realsmall<divhat & divhat<div + div=.5*divhat; + end + end + end + %---------------------------------------- + if abs(a(i,i))<realsmall + nzero=nzero+1; + nunstab=nunstab+1; + if abs(b(i,i))<realsmall + zxz=1; + end + else + nunstab=nunstab+ (real(b(i,i)/a(i,i))>div); + end +end +div +nunstab +nzero +% Note that qzdivct first puts all singularities in a in lower right, then puts unstable +% roots on top of those. +[a b q z]=qzdivct(div,a,b,q,z); +gev=[diag(a) diag(b)]; +if zxz + %disp('Coincident zeros. Indeterminacy and/or nonexistence.') + eu=[-2;-2]; + return +end +q1=q(1:n-nunstab,:); +q2=q(n-nunstab+1:n,:); +z1=z(:,1:n-nunstab)'; +z2=z(:,n-nunstab+1:n)'; +a2=a(n-nunstab+1:n,n-nunstab+1:n); +b2=b(n-nunstab+1:n,n-nunstab+1:n); +etawt=q2*pi; +zwt=q2*psi; +[ueta,deta,veta]=svd(etawt); +md=min(size(deta)); +bigev=find(diag(deta(1:md,1:md))>realsmall); +ueta=ueta(:,bigev); +veta=veta(:,bigev); +deta=deta(bigev,bigev); +[uz,dz,vz]=svd(zwt); +md=min(size(dz)); +bigev=find(diag(dz(1:md,1:md))>realsmall); +uz=uz(:,bigev); +vz=vz(:,bigev); +dz=dz(bigev,bigev); +if isempty(bigev) + exist=1; +else + exist=norm(uz-ueta*ueta'*uz,'fro') < realsmall*n; +end +if ~isempty(bigev) + zwtx0=b2\zwt; + zwtx=zwtx0; + M=b2\a2; + M=M/norm(M); + for i=2:nunstab + zwtx=[M*zwtx zwtx0]; + end + zwtx=b2*zwtx; + [ux,dx,vx]=svd(zwtx); + md=min(size(dx)); + bigev=find(diag(dx(1:md,1:md))>realsmall); + ux=ux(:,bigev); + vx=vx(:,bigev); + dx=dx(bigev,bigev); + existx=norm(ux-ueta*ueta'*ux,'fro') < realsmall*n; +else + existx=1; +end +%---------------------------------------------------- +% Note that existence and uniqueness are not just matters of comparing +% numbers of roots and numbers of endogenous errors. These counts are +% reported below because usually they point to the source of the problem. +%------------------------------------------------------ +[ueta1,deta1,veta1]=svd(q1*pi); +md=min(size(deta1)); +bigev=find(diag(deta1(1:md,1:md))>realsmall); +ueta1=ueta1(:,bigev); +veta1=veta1(:,bigev); +deta1=deta1(bigev,bigev); +if existx | nunstab==0 + %disp('solution exists'); + eu(1)=1; +else + if exist + %disp('solution exists for unforecastable z only'); + eu(1)=-1; + %else + %fprintf(1,'No solution. %d unstable roots. %d endog errors.\n',nunstab,size(ueta1,2)); + end + %disp('Generalized eigenvalues') + %disp(gev); + %md=abs(diag(a))>realsmall; + %ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; + %disp(ev) +% return; +end +%disp('Generalized eigenvalues') +%disp(gev); +%md=abs(diag(a))>realsmall; +%ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; +%disp(ev) +% return; +if isempty(veta1) + unique=1; +else + unique=norm(veta1-veta*veta'*veta1,'fro')<realsmall*n; +end +if unique + %disp('solution unique'); + eu(2)=1; +%else + %fprintf(1,'Indeterminacy. %d loose endog errors.\n',size(veta1,2)-size(veta,2)); + %disp('Generalized eigenvalues') + %disp(gev); + %disp(ev) +% return; +end +tmat = [eye(n-nunstab) -ueta1*deta1*veta1'*veta*(deta\ueta')]; +G0= [tmat*a; zeros(nunstab,n-nunstab) eye(nunstab)]; +G1= [tmat*b; zeros(nunstab,n)]; +%---------------------- +% G0 is always non-singular because by construction there are no zeros on +% the diagonal of a(1:n-nunstab,1:n-nunstab), which forms G0's ul corner. +%----------------------- +G0I=inv(G0); +G1=G0I*G1; +usix=n-nunstab+1:n; +C=G0I*[tmat*q*c;(a(usix,usix)-b(usix,usix))\q2*c]; +impact=G0I*[tmat*q*psi;zeros(nunstab,size(psi,2))]; +%-------------------- above are output for system in terms of z'y ------- +G1=z*G1*z'; +if max(max(abs(imag(G1))))>100*realsmall + disp('Inaccuracy in G1:') + s1=svd(G1); + s2=svd(real(G1)); + disp(max((s1-s2)./(1/12+s1))) % this is reasonable scaling for monthly time unit +end +G1=real(G1); +C=real(z*C); +impact=real(z*impact); diff --git a/MatlabFiles/gensysoldversion.m b/MatlabFiles/gensysoldversion.m index 66cdc49907d0436df6101a8ca30e971d52d9f753..f723571db88fc380d981c0ab6d64e4abff0a4d19 100644 --- a/MatlabFiles/gensysoldversion.m +++ b/MatlabFiles/gensysoldversion.m @@ -1,168 +1,168 @@ -function [G1,C,impact,fmat,fwt,ywt,gev,eu]=gensys(g0,g1,c,psi,pi,div) -%function [G1,C,impact,fmat,fwt,ywt,gev,eu]=gensys(g0,g1,c,psi,pi,div) -%System given as -% g0*y(t)=g1*y(t-1)+c+psi*z(t)+pi*eta(t), -%with z an exogenous variable process and eta being endogenously determined -%one-step-ahead expectational errors. Returned system is -% y(t)=G1*y(t-1)+C+impact*z(t)+ywt*inv(I-fmat*inv(L))*fwt*z(t+1) . -% If z(t) is i.i.d., the last term drops out. -% If div is omitted from argument list, a div>1 is calculated. -% eu(1)=1 for existence, eu(2)=1 for uniqueness. eu(1)=-1 for -% existence only with not-s.c. z; eu=[-2,-2] for coincident zeros. -% By Christopher A. Sims -% Corrected 10/28/96 by CAS -% Copyright (C) 1997-2012 Christopher A. Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -eu=[0;0]; -realsmall=1e-6; -fixdiv=(nargin==6); -n=size(g0,1); -[a b q z]=qz(g0,g1); -if ~fixdiv, div=1.01; end -nunstab=0; -zxz=0; -for i=1:n -%------------------div calc------------ - if ~fixdiv - if abs(a(i,i)) > 0 - divhat=abs(b(i,i))/abs(a(i,i)); - if 1+realsmall<divhat & divhat<div - div=.5*(1+divhat); - end - end - end -%---------------------------------------- - nunstab=nunstab+(abs(b(i,i))>div*abs(a(i,i))); - if abs(a(i,i))<realsmall & abs(b(i,i))<realsmall - zxz=1; - end -end -if ~zxz - [a b q z]=qzdiv(div,a,b,q,z); -end -save d:\mex\gensysmkl\abqz.mat a b q z div -gev=[diag(a) diag(b)]; -if zxz - %disp('Coincident zeros. Indeterminacy and/or nonexistence.') - eu=[-2;-2]; - return -end -q1=q(1:n-nunstab,:); -q2=q(n-nunstab+1:n,:); -a2=a(n-nunstab+1:n,n-nunstab+1:n); -b2=b(n-nunstab+1:n,n-nunstab+1:n); -etawt=q2*pi; -zwt=q2*psi; -[ueta,deta,veta]=svd(etawt); -md=min(size(deta)); -bigev=find(diag(deta(1:md,1:md))>realsmall); -ueta=ueta(:,bigev); -veta=veta(:,bigev); -deta=deta(bigev,bigev); -[uz,dz,vz]=svd(zwt); -md=min(size(dz)); -bigev=find(diag(dz(1:md,1:md))>realsmall); -uz=uz(:,bigev); -vz=vz(:,bigev); -dz=dz(bigev,bigev); -if isempty(bigev) - exist=1; - existx=1; -else - exist=norm(uz-ueta*ueta'*uz) < realsmall*n; - zwtx0=b2\zwt; - zwtx=zwtx0; - M=b2\a2; - for i=2:nunstab - zwtx=[M*zwtx zwtx0]; - end - zwtx=b2*zwtx; - [ux,dx,vx]=svd(zwtx); - md=min(size(dx)); - bigev=find(diag(dx(1:md,1:md))>realsmall); - ux=ux(:,bigev); - vx=vx(:,bigev); - dx=dx(bigev,bigev); - existx=norm(ux-ueta*ueta'*ux) < realsmall*n; -end -%---------------------------------------------------- -% Note that existence and uniqueness are not just matters of comparing -% numbers of roots and numbers of endogenous errors. These counts are -% reported below because usually they point to the source of the problem. -%------------------------------------------------------ -[ueta1,deta1,veta1]=svd(q1*pi); -md=min(size(deta1)); -bigev=find(diag(deta1(1:md,1:md))>realsmall); -ueta1=ueta1(:,bigev); -veta1=veta1(:,bigev); -deta1=deta1(bigev,bigev); -if existx | nunstab==0 - %disp('solution exists'); - eu(1)=1; -else - if exist - %disp('solution exists for unforecastable z only'); - eu(1)=-1; - %else - %fprintf(1,'No solution. %d unstable roots. %d endog errors.\n',nunstab,size(ueta1,2)); - end - %disp('Generalized eigenvalues') - %disp(gev); - %md=abs(diag(a))>realsmall; - %ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; - %disp(ev) -% return; -end -if isempty(veta1) - unique=1; -else - unique=norm(veta1-veta*veta'*veta1)<realsmall*n; -end -if unique - %disp('solution unique'); - eu(2)=1; -else - fprintf(1,'Indeterminacy. %d loose endog errors.\n',size(veta1,2)-size(veta,2)); - %disp('Generalized eigenvalues') - %disp(gev); - %md=abs(diag(a))>realsmall; - %ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; - %disp(ev) -% return; -end -tmat = [eye(n-nunstab) -(ueta*(deta\veta')*veta1*deta1*ueta1')']; -G0= [tmat*a; zeros(nunstab,n-nunstab) eye(nunstab)]; -G1= [tmat*b; zeros(nunstab,n)]; -%---------------------- -% G0 is always non-singular because by construction there are no zeros on -% the diagonal of a(1:n-nunstab,1:n-nunstab), which forms G0's ul corner. -%----------------------- -G0I=inv(G0); -G1=G0I*G1; -usix=n-nunstab+1:n; -C=G0I*[tmat*q*c;(a(usix,usix)-b(usix,usix))\q2*c]; -impact=G0I*[tmat*q*psi;zeros(nunstab,size(psi,2))]; -fmat=b(usix,usix)\a(usix,usix); -fwt=-b(usix,usix)\q2*psi; -ywt=G0I(:,usix); -%-------------------- above are output for system in terms of z'y ------- -G1=real(z*G1*z'); -C=real(z*C); -impact=real(z*impact); -% Correction 10/28/96: formerly line below had real(z*ywt) on rhs, an error. -ywt=z*ywt; \ No newline at end of file +function [G1,C,impact,fmat,fwt,ywt,gev,eu]=gensys(g0,g1,c,psi,pi,div) +%function [G1,C,impact,fmat,fwt,ywt,gev,eu]=gensys(g0,g1,c,psi,pi,div) +%System given as +% g0*y(t)=g1*y(t-1)+c+psi*z(t)+pi*eta(t), +%with z an exogenous variable process and eta being endogenously determined +%one-step-ahead expectational errors. Returned system is +% y(t)=G1*y(t-1)+C+impact*z(t)+ywt*inv(I-fmat*inv(L))*fwt*z(t+1) . +% If z(t) is i.i.d., the last term drops out. +% If div is omitted from argument list, a div>1 is calculated. +% eu(1)=1 for existence, eu(2)=1 for uniqueness. eu(1)=-1 for +% existence only with not-s.c. z; eu=[-2,-2] for coincident zeros. +% By Christopher A. Sims +% Corrected 10/28/96 by CAS +% +% Copyright (C) 1997-2012 Christopher A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +eu=[0;0]; +realsmall=1e-6; +fixdiv=(nargin==6); +n=size(g0,1); +[a b q z]=qz(g0,g1); +if ~fixdiv, div=1.01; end +nunstab=0; +zxz=0; +for i=1:n +%------------------div calc------------ + if ~fixdiv + if abs(a(i,i)) > 0 + divhat=abs(b(i,i))/abs(a(i,i)); + if 1+realsmall<divhat & divhat<div + div=.5*(1+divhat); + end + end + end +%---------------------------------------- + nunstab=nunstab+(abs(b(i,i))>div*abs(a(i,i))); + if abs(a(i,i))<realsmall & abs(b(i,i))<realsmall + zxz=1; + end +end +if ~zxz + [a b q z]=qzdiv(div,a,b,q,z); +end +save d:\mex\gensysmkl\abqz.mat a b q z div +gev=[diag(a) diag(b)]; +if zxz + %disp('Coincident zeros. Indeterminacy and/or nonexistence.') + eu=[-2;-2]; + return +end +q1=q(1:n-nunstab,:); +q2=q(n-nunstab+1:n,:); +a2=a(n-nunstab+1:n,n-nunstab+1:n); +b2=b(n-nunstab+1:n,n-nunstab+1:n); +etawt=q2*pi; +zwt=q2*psi; +[ueta,deta,veta]=svd(etawt); +md=min(size(deta)); +bigev=find(diag(deta(1:md,1:md))>realsmall); +ueta=ueta(:,bigev); +veta=veta(:,bigev); +deta=deta(bigev,bigev); +[uz,dz,vz]=svd(zwt); +md=min(size(dz)); +bigev=find(diag(dz(1:md,1:md))>realsmall); +uz=uz(:,bigev); +vz=vz(:,bigev); +dz=dz(bigev,bigev); +if isempty(bigev) + exist=1; + existx=1; +else + exist=norm(uz-ueta*ueta'*uz) < realsmall*n; + zwtx0=b2\zwt; + zwtx=zwtx0; + M=b2\a2; + for i=2:nunstab + zwtx=[M*zwtx zwtx0]; + end + zwtx=b2*zwtx; + [ux,dx,vx]=svd(zwtx); + md=min(size(dx)); + bigev=find(diag(dx(1:md,1:md))>realsmall); + ux=ux(:,bigev); + vx=vx(:,bigev); + dx=dx(bigev,bigev); + existx=norm(ux-ueta*ueta'*ux) < realsmall*n; +end +%---------------------------------------------------- +% Note that existence and uniqueness are not just matters of comparing +% numbers of roots and numbers of endogenous errors. These counts are +% reported below because usually they point to the source of the problem. +%------------------------------------------------------ +[ueta1,deta1,veta1]=svd(q1*pi); +md=min(size(deta1)); +bigev=find(diag(deta1(1:md,1:md))>realsmall); +ueta1=ueta1(:,bigev); +veta1=veta1(:,bigev); +deta1=deta1(bigev,bigev); +if existx | nunstab==0 + %disp('solution exists'); + eu(1)=1; +else + if exist + %disp('solution exists for unforecastable z only'); + eu(1)=-1; + %else + %fprintf(1,'No solution. %d unstable roots. %d endog errors.\n',nunstab,size(ueta1,2)); + end + %disp('Generalized eigenvalues') + %disp(gev); + %md=abs(diag(a))>realsmall; + %ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; + %disp(ev) +% return; +end +if isempty(veta1) + unique=1; +else + unique=norm(veta1-veta*veta'*veta1)<realsmall*n; +end +if unique + %disp('solution unique'); + eu(2)=1; +else + fprintf(1,'Indeterminacy. %d loose endog errors.\n',size(veta1,2)-size(veta,2)); + %disp('Generalized eigenvalues') + %disp(gev); + %md=abs(diag(a))>realsmall; + %ev=diag(md.*diag(a)+(1-md).*diag(b))\ev; + %disp(ev) +% return; +end +tmat = [eye(n-nunstab) -(ueta*(deta\veta')*veta1*deta1*ueta1')']; +G0= [tmat*a; zeros(nunstab,n-nunstab) eye(nunstab)]; +G1= [tmat*b; zeros(nunstab,n)]; +%---------------------- +% G0 is always non-singular because by construction there are no zeros on +% the diagonal of a(1:n-nunstab,1:n-nunstab), which forms G0's ul corner. +%----------------------- +G0I=inv(G0); +G1=G0I*G1; +usix=n-nunstab+1:n; +C=G0I*[tmat*q*c;(a(usix,usix)-b(usix,usix))\q2*c]; +impact=G0I*[tmat*q*psi;zeros(nunstab,size(psi,2))]; +fmat=b(usix,usix)\a(usix,usix); +fwt=-b(usix,usix)\q2*psi; +ywt=G0I(:,usix); +%-------------------- above are output for system in terms of z'y ------- +G1=real(z*G1*z'); +C=real(z*C); +impact=real(z*impact); +% Correction 10/28/96: formerly line below had real(z*ywt) on rhs, an error. +ywt=z*ywt; diff --git a/MatlabFiles/gfmean.m b/MatlabFiles/gfmean.m index 360bb29ad82cf38da1a8500f7faf8aa0324f2909..5a77b71b9c8d4bd716c858a67d6a59e0e7e25618 100644 --- a/MatlabFiles/gfmean.m +++ b/MatlabFiles/gfmean.m @@ -1,66 +1,66 @@ -function [Fmat,gvec] = gfmean(b,P,Vi,nvar,ncoef,n0,np) -% [Fmat,gvec] = gfmean(b,P,Vi,nvar,ncoef,n0,np) -% -% Mean of free lagged parameters g and original lagged parameters F, conditional on comtemporaneous b's -% See Waggoner and Zha's Gibbs sampling -% -% b: sum(n0)-by-1 vector of A0 free parameters -% P: cell(nvar,1). In each cell, posterior linear transformation for random walk prior for the ith equation % tld: tilda -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k is a total of exogenous variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. -% nvar: number of endogeous variables -% ncoef: number of original lagged variables per equation -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation -%--------------- -% Fmat: 0, the value that is used in csminwel.m -% gvec: sum(n0)-by-1 analytical gradient for a0freefun.m -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -b=b(:); - - -n0cum = cumsum(n0); -npcum = cumsum(np); -gvec = zeros(npcum(end),1); -Fmat = zeros(ncoef,nvar); % ncoef: maximum original lagged parameters per equation - -if ~(length(b)==n0cum(end)) - error('Make inputs n0 and length(b) match exactly') -end - -for kj=1:nvar - if kj==1 - bj = b(1:n0(kj)); - gj = P{kj}*bj; - gvec(1:np(kj)) = gj; - Fmat(:,kj) = Vi{kj}*gj; - else - bj = b(n0cum(kj-1)+1:n0cum(kj)); - gj = P{kj}*bj; - gvec(npcum(kj-1)+1:npcum(kj)) = gj; - Fmat(:,kj) = Vi{kj}*gj; - end -end +function [Fmat,gvec] = gfmean(b,P,Vi,nvar,ncoef,n0,np) +% [Fmat,gvec] = gfmean(b,P,Vi,nvar,ncoef,n0,np) +% +% Mean of free lagged parameters g and original lagged parameters F, conditional on comtemporaneous b's +% See Waggoner and Zha's Gibbs sampling +% +% b: sum(n0)-by-1 vector of A0 free parameters +% P: cell(nvar,1). In each cell, posterior linear transformation for random walk prior for the ith equation % tld: tilda +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k is a total of exogenous variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. +% nvar: number of endogeous variables +% ncoef: number of original lagged variables per equation +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation +%--------------- +% Fmat: 0, the value that is used in csminwel.m +% gvec: sum(n0)-by-1 analytical gradient for a0freefun.m +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +b=b(:); + + +n0cum = cumsum(n0); +npcum = cumsum(np); +gvec = zeros(npcum(end),1); +Fmat = zeros(ncoef,nvar); % ncoef: maximum original lagged parameters per equation + +if ~(length(b)==n0cum(end)) + error('Make inputs n0 and length(b) match exactly') +end + +for kj=1:nvar + if kj==1 + bj = b(1:n0(kj)); + gj = P{kj}*bj; + gvec(1:np(kj)) = gj; + Fmat(:,kj) = Vi{kj}*gj; + else + bj = b(n0cum(kj-1)+1:n0cum(kj)); + gj = P{kj}*bj; + gvec(npcum(kj-1)+1:npcum(kj)) = gj; + Fmat(:,kj) = Vi{kj}*gj; + end +end diff --git a/MatlabFiles/gfore.m b/MatlabFiles/gfore.m index 298b5e505ec264f1346feccf18440b4f5ce8cf8f..98baba6da65996443656f8d62d4362af6964bd20 100644 --- a/MatlabFiles/gfore.m +++ b/MatlabFiles/gfore.m @@ -1,102 +1,102 @@ -function gfore(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... - yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) -% gfore(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... -% yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) -% Graph (calendar year) forecasts vs actual (actual from "msstart.m") -% Make sure that actup in "msstart.m" is set at the length for visual graphs -% -% yrEnd: the end year for the sample -% qmEnd: last q_m before out-of-sample forecasting -% q_m: quarterly or monthly for the underlying model -% yearsCal: calendar years including actual and forecast data -% yactCalyg: actual calendar annual growth data -% yhatCalygml: conditional (calendar annual) forecasts on particular shocks -% forepy: forecast periods (yearly) -% xlab: label for structural equations -% ylab: label for the variables -% forelabel: title label for as of time of forecast -% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -%------------- -% No output argument for this graph file -% -% October 1998 Tao Zha; revised, 03/17/99 -- May not be compatible with previous programs -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -%*** Begining period -fbegm = qmEnd+1; % +1 because the first month out of sample -if fbegm > q_m % the first forecast month into the next year - fbegm = 1; - fbegy = yrEnd+1; % the first forecast year for the graph -else - fbegy = yrEnd; % the first forecast year for the graph -end -abegy = min(yearsCal); % the actual beginning year for the graph -abegm = 1; -ifbegy = find(yearsCal==fbegy-1); % index for the year before the first - % forecast first year in actual data "yactCalyg" - -%*** Final period -ffiny = fbegy+forepy-1; % the forecast final year -afiny = max(yearsCal); % the actual final year - - - -figure - -nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U -%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U -%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 - -hornum = cell(length(abegy:ffiny),1); % horizontal number -count=0; -for k=abegy:ffiny - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -cnum = 2; -% -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - % - if abegy>fbegy-1 - plot(abegy:afiny,yactCalyg(:,i),fbegy:ffiny,yhatCalygml(:,i),'-.') - set(gca,'XTick',abegy:ffiny) - else - plot(abegy:afiny,yactCalyg(:,i),... - fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygml(:,i)],'-.') - set(gca,'XTick',abegy:ffiny) - end - set(gca,'XTickLabel',char(hornum)) - if i<=cnum - title(forelabel) - elseif i>=nvar-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end +function gfore(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... + yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) +% gfore(yrEnd,qmEnd,q_m,yearsCal,yactCalyg,forepy,... +% yhatCalygml,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) +% Graph (calendar year) forecasts vs actual (actual from "msstart.m") +% Make sure that actup in "msstart.m" is set at the length for visual graphs +% +% yrEnd: the end year for the sample +% qmEnd: last q_m before out-of-sample forecasting +% q_m: quarterly or monthly for the underlying model +% yearsCal: calendar years including actual and forecast data +% yactCalyg: actual calendar annual growth data +% yhatCalygml: conditional (calendar annual) forecasts on particular shocks +% forepy: forecast periods (yearly) +% xlab: label for structural equations +% ylab: label for the variables +% forelabel: title label for as of time of forecast +% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +%------------- +% No output argument for this graph file +% +% October 1998 Tao Zha; revised, 03/17/99 -- May not be compatible with previous programs +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +%*** Begining period +fbegm = qmEnd+1; % +1 because the first month out of sample +if fbegm > q_m % the first forecast month into the next year + fbegm = 1; + fbegy = yrEnd+1; % the first forecast year for the graph +else + fbegy = yrEnd; % the first forecast year for the graph +end +abegy = min(yearsCal); % the actual beginning year for the graph +abegm = 1; +ifbegy = find(yearsCal==fbegy-1); % index for the year before the first + % forecast first year in actual data "yactCalyg" + +%*** Final period +ffiny = fbegy+forepy-1; % the forecast final year +afiny = max(yearsCal); % the actual final year + + + +figure + +nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U +%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U +%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 + +hornum = cell(length(abegy:ffiny),1); % horizontal number +count=0; +for k=abegy:ffiny + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +cnum = 2; +% +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + % + if abegy>fbegy-1 + plot(abegy:afiny,yactCalyg(:,i),fbegy:ffiny,yhatCalygml(:,i),'-.') + set(gca,'XTick',abegy:ffiny) + else + plot(abegy:afiny,yactCalyg(:,i),... + fbegy-1:ffiny,[yactCalyg(ifbegy,i);yhatCalygml(:,i)],'-.') + set(gca,'XTick',abegy:ffiny) + end + set(gca,'XTickLabel',char(hornum)) + if i<=cnum + title(forelabel) + elseif i>=nvar-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/gforerr1.m b/MatlabFiles/gforerr1.m index db05b11d110e6586f3533ec7d9859fa16beac274..4122d36f3320323135453eb95b6b911a782d01ba 100644 --- a/MatlabFiles/gforerr1.m +++ b/MatlabFiles/gforerr1.m @@ -1,98 +1,98 @@ -function gforerr1(yrEnd,qmEnd,q_m,forepy,yhatCalygml,yhatCalygl1,... - yhatCalygh1,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) - -% -% One (.68) error band: (calendar year) forecasts only (no actual) -% -% yrEnd: the end year for the sample -% qmEnd: last q_m before out-of-sample forecasting -% q_m: quarterly or monthly for the underlying model -% yearsCal: calendar years including actual and forecast data -% yactCalyg: actual calendar annual growth data -% yhatCalygml: conditional (calendar annual) forecasts on particular shocks -% yhatCalygl1: 0.68 lower band -% yhatCalygh1: 0.68 upper band -% forepy: forecast periods (yearly) -% xlab: label for structural equations -% ylab: label for the variables -% forelabel: title label for as of time of forecast -% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -%------------- -% No output argument for this graph file -% -% 03/19/99 - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -%*** Begining period -fbegm = qmEnd+1; % +1 because the first month out of sample -if fbegm > q_m % the first forecast month into the next year - fbegm = 1; - fbegy = yrEnd+1; % the first forecast year for the graph -else - fbegy = yrEnd; % the first forecast year for the graph -end -% -% abegy = min(yearsCal); % the actual beginning year for the graph -% abegm = 1; -% ifbegy = find(yearsCal==fbegy-1); % index for the year before the first -% % forecast first year in actual data "yactCalyg" - -%*** Final period -ffiny = fbegy+forepy-1; % the forecast final year -%afiny = max(yearsCal); % the actual final year - - - -figure - -nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U -%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U -%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 - -hornum = cell(length(fbegy:ffiny),1); % horizontal number -count=0; -for k=fbegy:ffiny - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -% -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - % - plot(fbegy:ffiny,yhatCalygml(:,i),'-',... - fbegy:ffiny,yhatCalygl1(:,i),'--',fbegy:ffiny,yhatCalygh1(:,i),'--' ) - set(gca,'XTick',fbegy:ffiny) - set(gca,'XTickLabel',char(hornum)) - if i<=cnum - title(forelabel) - elseif i>=nvar-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end \ No newline at end of file +function gforerr1(yrEnd,qmEnd,q_m,forepy,yhatCalygml,yhatCalygl1,... + yhatCalygh1,xlab,ylab,forelabel,conlab,keyindx,rnum,cnum) + +% +% One (.68) error band: (calendar year) forecasts only (no actual) +% +% yrEnd: the end year for the sample +% qmEnd: last q_m before out-of-sample forecasting +% q_m: quarterly or monthly for the underlying model +% yearsCal: calendar years including actual and forecast data +% yactCalyg: actual calendar annual growth data +% yhatCalygml: conditional (calendar annual) forecasts on particular shocks +% yhatCalygl1: 0.68 lower band +% yhatCalygh1: 0.68 upper band +% forepy: forecast periods (yearly) +% xlab: label for structural equations +% ylab: label for the variables +% forelabel: title label for as of time of forecast +% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +%------------- +% No output argument for this graph file +% +% 03/19/99 + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +%*** Begining period +fbegm = qmEnd+1; % +1 because the first month out of sample +if fbegm > q_m % the first forecast month into the next year + fbegm = 1; + fbegy = yrEnd+1; % the first forecast year for the graph +else + fbegy = yrEnd; % the first forecast year for the graph +end +% +% abegy = min(yearsCal); % the actual beginning year for the graph +% abegm = 1; +% ifbegy = find(yearsCal==fbegy-1); % index for the year before the first +% % forecast first year in actual data "yactCalyg" + +%*** Final period +ffiny = fbegy+forepy-1; % the forecast final year +%afiny = max(yearsCal); % the actual final year + + + +figure + +nvar = size(yhatCalygml,2); % Pcm,M2,FFR,GdP, CPI, U +%keyindx = 1:nvar; % Pcm,M2,FFR,GdP, CPI, U +%keyindx = [4:nvar 3 2]; % GdP, CPI, U, FFR, M2 + +hornum = cell(length(fbegy:ffiny),1); % horizontal number +count=0; +for k=fbegy:ffiny + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +% +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + % + plot(fbegy:ffiny,yhatCalygml(:,i),'-',... + fbegy:ffiny,yhatCalygl1(:,i),'--',fbegy:ffiny,yhatCalygh1(:,i),'--' ) + set(gca,'XTick',fbegy:ffiny) + set(gca,'XTickLabel',char(hornum)) + if i<=cnum + title(forelabel) + elseif i>=nvar-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/ghistd.m b/MatlabFiles/ghistd.m index d5b0f68e5b3e7223fbe36eb061ce3ba4924b2758..0d062675ecca68e1ae4da6ed827a38c12f9f07af 100644 --- a/MatlabFiles/ghistd.m +++ b/MatlabFiles/ghistd.m @@ -1,93 +1,93 @@ -function noargout = ghistd(qmEnd,yrEnd,forepy,q_m,HDv,lendlab,titlab,ylab,timelab,rnum,cnum) -% -% Plot historical decompositions (annually at this time), no argument out -% -% qmEnd: the end month before the forecast -% yrEnd: the end year before the forecast -% forepy: the number of forecast calendar years -% q_m: 12 or 4 (monthly or quarterly) -% HDv: nHD-by-1 cell where nHD is number of decompositions; -% each cell is forepy-by-nvar -% lendlab: label for the lengend -% titlab: label for the title -% ylab: label for the variables -% timelab: label for the time of forecast and indication of insample or out-of-sample -% rnum: row number for the subplot (e.g., 3) -% cnum: column number for the subplot (e.g., 2) -%--------------- -% no argument out -% -% October 1998 Tao Zha -%% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% To be done: -% lengend does not work well -% colormap should be replaced by some non-color shading -% title: need to have only one. - -fbegm = qmEnd+1; % +1 because the first month out of sample -if fbegm > q_m % the first forecast month into the next year - fbegm = 1; % reset - fbegy = yrEnd+1; % the first forecast year for the graph -else - fbegy = yrEnd; % the first forecast year for the graph -end -ffiny = fbegy+forepy-1; % the forecast final year - -figure -%cnum = 2; -nvar = size(HDv{1},2); -rnum = nvar/cnum; -if ~(rnum==fix(rnum)) - warning('Make that subplot is divided properly') - disp('Check rnum as well as cnum') - return -end - -hornum = cell(length(fbegy:ffiny),1); % horizontal number -count=0; -for k=fbegy:ffiny - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - - -for k=1:nvar - bardata = []; - for n=1:size(HDv,1) - bardata = [bardata HDv{n}(:,k)]; - end - - subplot(rnum,cnum,k) - bar(fbegy:ffiny,bardata,0.75,'group') - set(gca,'XTickLabel',char(hornum)) - if k==1 - legend(char(lendlab),1) - end - colormatrix = [0.2 0.2 0.2;0.8 0.8 0.8]; - colormap(colormatrix) - if k<=cnum - title(char(titlab)) - end - if k>((rnum-1)*cnum) - xlabel(timelab) - end - grid - ylabel(char(ylab{k})) -end \ No newline at end of file +function noargout = ghistd(qmEnd,yrEnd,forepy,q_m,HDv,lendlab,titlab,ylab,timelab,rnum,cnum) +% +% Plot historical decompositions (annually at this time), no argument out +% +% qmEnd: the end month before the forecast +% yrEnd: the end year before the forecast +% forepy: the number of forecast calendar years +% q_m: 12 or 4 (monthly or quarterly) +% HDv: nHD-by-1 cell where nHD is number of decompositions; +% each cell is forepy-by-nvar +% lendlab: label for the lengend +% titlab: label for the title +% ylab: label for the variables +% timelab: label for the time of forecast and indication of insample or out-of-sample +% rnum: row number for the subplot (e.g., 3) +% cnum: column number for the subplot (e.g., 2) +%--------------- +% no argument out +% +% October 1998 Tao Zha +% +%% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% To be done: +% lengend does not work well +% colormap should be replaced by some non-color shading +% title: need to have only one. + +fbegm = qmEnd+1; % +1 because the first month out of sample +if fbegm > q_m % the first forecast month into the next year + fbegm = 1; % reset + fbegy = yrEnd+1; % the first forecast year for the graph +else + fbegy = yrEnd; % the first forecast year for the graph +end +ffiny = fbegy+forepy-1; % the forecast final year + +figure +%cnum = 2; +nvar = size(HDv{1},2); +rnum = nvar/cnum; +if ~(rnum==fix(rnum)) + warning('Make that subplot is divided properly') + disp('Check rnum as well as cnum') + return +end + +hornum = cell(length(fbegy:ffiny),1); % horizontal number +count=0; +for k=fbegy:ffiny + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + + +for k=1:nvar + bardata = []; + for n=1:size(HDv,1) + bardata = [bardata HDv{n}(:,k)]; + end + + subplot(rnum,cnum,k) + bar(fbegy:ffiny,bardata,0.75,'group') + set(gca,'XTickLabel',char(hornum)) + if k==1 + legend(char(lendlab),1) + end + colormatrix = [0.2 0.2 0.2;0.8 0.8 0.8]; + colormap(colormatrix) + if k<=cnum + title(char(titlab)) + end + if k>((rnum-1)*cnum) + xlabel(timelab) + end + grid + ylabel(char(ylab{k})) +end diff --git a/MatlabFiles/gibbsglb.m b/MatlabFiles/gibbsglb.m index 88f0a86954dada0a4f3edb200d747c34d2d520ac..25325bdfa39804c6fc6b05088ec541a15a9a08c5 100644 --- a/MatlabFiles/gibbsglb.m +++ b/MatlabFiles/gibbsglb.m @@ -1,73 +1,74 @@ -function [cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss) -% [cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss) -% Global setup outside the Gibbs loop -- c.f. gibbsvar -% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" -% See Note Forecast (2) pp. 44-51 -% -% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the -% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. -% Note,"bd" stands for block diagonal. -% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. -% nvar: rank of A0 or # of variables -% fss: effective sample size (in the exponential term) -- -% # of observations + # of dummy observations -% (or nSample - lags + # of dummy observations) -%------------- -% cT{i}: nvar-by-nvar where T'*T=Sbd{i} which is kind of covariance martrix -% divided by fss already -% vR{i}: nvar-by-q{i} -- orthonormral basis for T*R, which is obtained through -% single value decomposition of Q*inv(T) -% kdf: the polynomial power in the Gamma or 1d Wishart distribution, used in -% "gibbsvar.m" -% -% Written by Tao Zha; Copyright (c) 1999 by Waggoner and Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -kdf = fss; %2; %fss; - -cT = cell(nvar,1); -for k=1:nvar - cT{k} = chol(Sbd{k}); % upper triangular but lower triangular Choleski -end - -Q = cell(nvar,1); - % Q{i}: nvar-by-nvar with rank nvar-q(i) with ith equation a and - % q(i) which is # of non-zero elements in a. Note: Q*a=0. - -vR = cell(nvar,1); -for k=1:nvar - Q{k} = diag(idmat0(:,k)==0); % constructing Q{k} - % - [jnk1,d1,v1] = svd(Q{k}/cT{k}); - d1max=max(diag(d1)); - if d1max==0 - Idxk=1:nvar; - else - Idxk = find(diag(d1)<eps*d1max); - end - lenk = length(find(idmat0(:,k))); - if ( length(Idxk)<lenk ) - warning('Dimension of non-zero A0(:,k) is different from svd(Q*inv(T))') - disp('Press ctrl-c to abort') - pause - else - jnk1 = v1(:,Idxk); - vR{k} = jnk1(:,1:lenk); % orthonormal basis for T*R - end -end +function [cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss) +% [cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss) +% Global setup outside the Gibbs loop -- c.f. gibbsvar +% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" +% See Note Forecast (2) pp. 44-51 +% +% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the +% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. +% Note,"bd" stands for block diagonal. +% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. +% nvar: rank of A0 or # of variables +% fss: effective sample size (in the exponential term) -- +% # of observations + # of dummy observations +% (or nSample - lags + # of dummy observations) +%------------- +% cT{i}: nvar-by-nvar where T'*T=Sbd{i} which is kind of covariance martrix +% divided by fss already +% vR{i}: nvar-by-q{i} -- orthonormral basis for T*R, which is obtained through +% single value decomposition of Q*inv(T) +% kdf: the polynomial power in the Gamma or 1d Wishart distribution, used in +% "gibbsvar.m" +% +% Written by Tao Zha; +% +% +% Copyright (C) 1997-2012 Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +kdf = fss; %2; %fss; + +cT = cell(nvar,1); +for k=1:nvar + cT{k} = chol(Sbd{k}); % upper triangular but lower triangular Choleski +end + +Q = cell(nvar,1); + % Q{i}: nvar-by-nvar with rank nvar-q(i) with ith equation a and + % q(i) which is # of non-zero elements in a. Note: Q*a=0. + +vR = cell(nvar,1); +for k=1:nvar + Q{k} = diag(idmat0(:,k)==0); % constructing Q{k} + % + [jnk1,d1,v1] = svd(Q{k}/cT{k}); + d1max=max(diag(d1)); + if d1max==0 + Idxk=1:nvar; + else + Idxk = find(diag(d1)<eps*d1max); + end + lenk = length(find(idmat0(:,k))); + if ( length(Idxk)<lenk ) + warning('Dimension of non-zero A0(:,k) is different from svd(Q*inv(T))') + disp('Press ctrl-c to abort') + pause + else + jnk1 = v1(:,Idxk); + vR{k} = jnk1(:,1:lenk); % orthonormal basis for T*R + end +end diff --git a/MatlabFiles/gibbsvar.m b/MatlabFiles/gibbsvar.m index 5d12d432c174e66fc648f42d6ac824ef9e5dcdd8..4f3e3619085023785c8fd7e37695b480cb3bf398 100644 --- a/MatlabFiles/gibbsvar.m +++ b/MatlabFiles/gibbsvar.m @@ -1,93 +1,93 @@ -function A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf,Indxcol) -% A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf) -% One-step Gibbs sampler for structural VARs -- simultaneous equations approach -% Ref.: D.F. Waggoner and T. Zha: "Does Normalization Matter for Inference?" -% See Note Forecast (2) pp. 44-51 -% -% A0gbs: the last draw of A0 matrix -% cT{i}: nvar-by-nvar where T'*T=Sbd{i} which is kind of covariance martrix -% divided by fss already -% vR{i}: nvar-by-q{i} -- orthonormral basis for T*R, which is obtained through -% single value decomposition of Q*inv(T). See gibbsglb.m -% nvar: rank of A0 or # of variables -% fss: effective sample size == nSample (T)-lags+# of dummy observations -% kdf: polynomial power in the Gamma or 1d Wishart distribution -% Indxcol: a vector of random columns this Gibbs draws. -% When this input is not supplied, the Gibbs draws all columns -%------------------ -% A0bgs: new draw of A0 matrix in this Gibbs step -% -% Written by Tao Zha; Copyright (c) 1999 by Waggoner and Zha -% NOTE: Added Indxcol on 2/13/00 so that previous programs may not be compatible. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (nargin==6), Indxcol=[1:nvar]; end - -%---------------- Local loop for Gibbs given last A0gbs ---------- -%* uR{i}: nvar-by-q{i} -- orthonormal with first q(i)-1 vectors lies in the -% span(T*a(j)|j~=i) -%*** Constructing u(1),...,u(q{i}) at each Gibbs step -% -sw0 = zeros(nvar,1); -for k=Indxcol % given last A0gbs and general new A0bgs - X = cT{k}*A0gbs; % given the latest updated A0gbs - X(:,k) = 0; % want to find non-zero sw s.t., X'*sw=0 - [jL,Ux] = lu(X'); - jIx0 = min(find(abs(diag(Ux))<eps)); % if isempty(jIx0), then something is wrong here - % - sw0(jIx0+1:end) = 0; - sw0(jIx0) = 1; - jA = Ux(1:jIx0-1,1:jIx0-1); - jb = Ux(1:jIx0-1,jIx0); - jy = -jA\jb; - sw0(1:jIx0-1) = jy; - sw = sw0/sqrt(sum(sw0.^2)); - % - lenk = length(vR{k}(1,:)); - gkb = zeros(lenk,1); % greek beta's - uR = zeros(nvar,lenk); - sx = zeros(nvar,lenk); - sx(:,1) = vR{k}(:,1); - for ki = 1:lenk-1 - wxv = [sw'*sx(:,ki);sw'*vR{k}(:,ki+1)]; % w'*x and w'*v(+1) - dwxv = sqrt(sum(wxv.^2)); - if (dwxv<eps) - uR(:,ki)=sx(:,ki); sx(:,ki+1)=vR{k}(:,ki+1); - else - wxv = wxv/dwxv; - uR(:,ki) = wxv(1)*vR{k}(:,ki+1) - wxv(2)*sx(:,ki); - sx(:,ki+1) = wxv(2)*vR{k}(:,ki+1) + wxv(1)*sx(:,ki); - end - end - uR(:,lenk) = sx(:,lenk); % uR now constructed - % - %--------- Gibbs loop ---------- - %*** draw independently beta's that combine uR to form a's (columns of A0) - jcon = sqrt(1/fss); - gkb(1:lenk-1) = jcon*randn(lenk-1,1); - %* gamma or 1-d Wishart draw - jnk = jcon*randn(kdf+1,1); - if rand(1)<0.5 - gkb(lenk) = sqrt(jnk'*jnk); - else - gkb(lenk) = -sqrt(jnk'*jnk); - end - % - %*** form new a(i) - ith column of A0 - A0gbs(:,k) = (cT{k}\uR)*gkb; -end +function A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf,Indxcol) +% A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf) +% One-step Gibbs sampler for structural VARs -- simultaneous equations approach +% Ref.: D.F. Waggoner and T. Zha: "Does Normalization Matter for Inference?" +% See Note Forecast (2) pp. 44-51 +% +% A0gbs: the last draw of A0 matrix +% cT{i}: nvar-by-nvar where T'*T=Sbd{i} which is kind of covariance martrix +% divided by fss already +% vR{i}: nvar-by-q{i} -- orthonormral basis for T*R, which is obtained through +% single value decomposition of Q*inv(T). See gibbsglb.m +% nvar: rank of A0 or # of variables +% fss: effective sample size == nSample (T)-lags+# of dummy observations +% kdf: polynomial power in the Gamma or 1d Wishart distribution +% Indxcol: a vector of random columns this Gibbs draws. +% When this input is not supplied, the Gibbs draws all columns +%------------------ +% A0bgs: new draw of A0 matrix in this Gibbs step +% +% NOTE: Added Indxcol on 2/13/00 so that previous programs may not be compatible. +% +% +% Copyright (C) 1997-2012 Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (nargin==6), Indxcol=[1:nvar]; end + +%---------------- Local loop for Gibbs given last A0gbs ---------- +%* uR{i}: nvar-by-q{i} -- orthonormal with first q(i)-1 vectors lies in the +% span(T*a(j)|j~=i) +%*** Constructing u(1),...,u(q{i}) at each Gibbs step +% +sw0 = zeros(nvar,1); +for k=Indxcol % given last A0gbs and general new A0bgs + X = cT{k}*A0gbs; % given the latest updated A0gbs + X(:,k) = 0; % want to find non-zero sw s.t., X'*sw=0 + [jL,Ux] = lu(X'); + jIx0 = min(find(abs(diag(Ux))<eps)); % if isempty(jIx0), then something is wrong here + % + sw0(jIx0+1:end) = 0; + sw0(jIx0) = 1; + jA = Ux(1:jIx0-1,1:jIx0-1); + jb = Ux(1:jIx0-1,jIx0); + jy = -jA\jb; + sw0(1:jIx0-1) = jy; + sw = sw0/sqrt(sum(sw0.^2)); + % + lenk = length(vR{k}(1,:)); + gkb = zeros(lenk,1); % greek beta's + uR = zeros(nvar,lenk); + sx = zeros(nvar,lenk); + sx(:,1) = vR{k}(:,1); + for ki = 1:lenk-1 + wxv = [sw'*sx(:,ki);sw'*vR{k}(:,ki+1)]; % w'*x and w'*v(+1) + dwxv = sqrt(sum(wxv.^2)); + if (dwxv<eps) + uR(:,ki)=sx(:,ki); sx(:,ki+1)=vR{k}(:,ki+1); + else + wxv = wxv/dwxv; + uR(:,ki) = wxv(1)*vR{k}(:,ki+1) - wxv(2)*sx(:,ki); + sx(:,ki+1) = wxv(2)*vR{k}(:,ki+1) + wxv(1)*sx(:,ki); + end + end + uR(:,lenk) = sx(:,lenk); % uR now constructed + % + %--------- Gibbs loop ---------- + %*** draw independently beta's that combine uR to form a's (columns of A0) + jcon = sqrt(1/fss); + gkb(1:lenk-1) = jcon*randn(lenk-1,1); + %* gamma or 1-d Wishart draw + jnk = jcon*randn(kdf+1,1); + if rand(1)<0.5 + gkb(lenk) = sqrt(jnk'*jnk); + else + gkb(lenk) = -sqrt(jnk'*jnk); + end + % + %*** form new a(i) - ith column of A0 + A0gbs(:,k) = (cT{k}\uR)*gkb; +end diff --git a/MatlabFiles/gradcd.m b/MatlabFiles/gradcd.m index 1655d01ed0b89811a8665f152b072b3371a80fda..73da507d7fd9e2d07b393f58f60d0fef4d0b7829 100644 --- a/MatlabFiles/gradcd.m +++ b/MatlabFiles/gradcd.m @@ -1,83 +1,83 @@ -function grdd = gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... - P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -%function grdd = gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... -% P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -% computes numerical gradient of a single-valued function or Jacobian -% matrix of a vector-valued function using a central difference with -% function grdd = gradcd(fcn,x0,grdh) -% -% fcn: a string naming a vector-valued function (f:n*1 -> k*1). -% x0: a column vector n*1, at which point the hessian is evaluated. -% grdh: step size, n*1. Set as follows -% step = eps^(1/3); -% %step = 1e-04; -% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); -% grdd: Jacobian matrix, k*n. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -stps = eps^(1/3); -% eps: floating point relative accuracy or machine precision: 2.22e-16 -% stps: step size recommended by Dennis and Schnabel: 6.006e-6 - -x0 = x0(:); -tailstr = ')'; -for i=nargin-3:-1:1 - tailstr=[ ',P' num2str(i) tailstr]; -end -f0 = eval([fcn '(x0' tailstr]); - -% ** initializations -n = length(x0); -k = length(f0); % dimension of "fcn" - -% ** Computation of stepsize (dh) -if all(grdh) - dh = grdh; -else - ax0 = abs(x0); - if all(x0) - dax0 = x0 ./ ax0; - else - dax0 = 1; - end - dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; -end - -xdh = x0 + dh; -dh = xdh - x0; % This increases precision slightly -% -argplus = x0(:,ones(n,1)); -argminus = argplus; -dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). -argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". -argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". - -grdd = zeros(k,n); % preallocate to speed the loop. -i = 0; -while i ~= n - i = i+1; - fp = eval([fcn '(argplus(:,i)' tailstr]); - fm = eval([fcn '(argminus(:,i)' tailstr]); - grdd(:,i) = fp - fm; -end -dhm = dh(:,ones(k,1)); -dhm = dhm'; % k*n -grdd = grdd ./ (2*dhm); - - +function grdd = gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... + P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +%function grdd = gradcd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... +% P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +% computes numerical gradient of a single-valued function or Jacobian +% matrix of a vector-valued function using a central difference with +% function grdd = gradcd(fcn,x0,grdh) +% +% fcn: a string naming a vector-valued function (f:n*1 -> k*1). +% x0: a column vector n*1, at which point the hessian is evaluated. +% grdh: step size, n*1. Set as follows +% step = eps^(1/3); +% %step = 1e-04; +% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); +% grdd: Jacobian matrix, k*n. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +stps = eps^(1/3); +% eps: floating point relative accuracy or machine precision: 2.22e-16 +% stps: step size recommended by Dennis and Schnabel: 6.006e-6 + +x0 = x0(:); +tailstr = ')'; +for i=nargin-3:-1:1 + tailstr=[ ',P' num2str(i) tailstr]; +end +f0 = eval([fcn '(x0' tailstr]); + +% ** initializations +n = length(x0); +k = length(f0); % dimension of "fcn" + +% ** Computation of stepsize (dh) +if all(grdh) + dh = grdh; +else + ax0 = abs(x0); + if all(x0) + dax0 = x0 ./ ax0; + else + dax0 = 1; + end + dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; +end + +xdh = x0 + dh; +dh = xdh - x0; % This increases precision slightly +% +argplus = x0(:,ones(n,1)); +argminus = argplus; +dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). +argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". +argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". + +grdd = zeros(k,n); % preallocate to speed the loop. +i = 0; +while i ~= n + i = i+1; + fp = eval([fcn '(argplus(:,i)' tailstr]); + fm = eval([fcn '(argminus(:,i)' tailstr]); + grdd(:,i) = fp - fm; +end +dhm = dh(:,ones(k,1)); +dhm = dhm'; % k*n +grdd = grdd ./ (2*dhm); + + diff --git a/MatlabFiles/gshock.m b/MatlabFiles/gshock.m index 492188355e740279fecc808d073dc31624f7688e..33f614cee56e064563c7e3986bba452a0e129626 100644 --- a/MatlabFiles/gshock.m +++ b/MatlabFiles/gshock.m @@ -1,87 +1,87 @@ -function ExactSmyear = gshock(begy,begm,finy,finm,xlab,idfile,tlinput) -% ExactSmyear = gshock(begy,begm,finy,finm,xlab) -% Plot the structural shocks for the range given by the inputs -% -% begy: the beginning year for the graph -% begm: the begiining month for the graph -% finy: the end year for the graph -% finm: the end month for the graph -% xlab: label for each structural equation -%----------- -% ExactSmyear: time (myears) and all structural shocks -% if no nargout, plot graphics. -% -% October 1998 by Tao A. Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -eval(['load ' idfile '.mat']); - -% -ibegy = find(myears==begy); -ifiny = find(myears==finy); - -ibegy1 = find(myears==begy+1); - -% -if isempty(ibegy) & isempty(ibegy1) - warning('Either ibegy or begm is out of the range of myears') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - pause -elseif isempty(ibegy) & (begm<myears(1)) - warning('Either ibegy or begm is out of the range of myears') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - pause -elseif isempty(ibegy) - ibegy = -myears(1)+2; % +2 is needed for the following -1 in - % bar(Estrexa(ibegy+begm-1:ifiny+finm-1,i)) - %so that it 2-1=1 so that +1 is what we want -end - -% -if isempty(ifiny) - warning('Either ifiny or finm is out of the range of myears') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - pause -elseif (ifiny+finm-1>size(myears,1)) - warning('Either ifiny or finm is out of the range of myears') - disp('Print myears to see the range') - disp('Or change actuap to make the range longer and save new results to Xshock.mat') - pause -end - - -if nargout==0 - t=length(Estrexa(ibegy+begm-1:ifiny+finm-1,1)); - for i=1:size(Estrexa,2) - figure - %plot(1:t, Estrexa(ibegy+begm-1:ifiny+finm-1,i)); - bar(Estrexa(ibegy+begm-1:ifiny+finm-1,i)) - title([ tlinput ' Monthly Structural Shocks' ]) - ylabel(char(xlab(i))) - xlabel([ 'From ' num2str(begy) ':' num2str(begm) ' to ' ... - num2str(finy) ':' num2str(finm) ]) - grid - end -else - ExactSmyear = [myears(ibegy+begm-1:ifiny+finm-1) Estrexa(ibegy+begm-1:ifiny+finm-1,:)]; -end +function ExactSmyear = gshock(begy,begm,finy,finm,xlab,idfile,tlinput) +% ExactSmyear = gshock(begy,begm,finy,finm,xlab) +% Plot the structural shocks for the range given by the inputs +% +% begy: the beginning year for the graph +% begm: the begiining month for the graph +% finy: the end year for the graph +% finm: the end month for the graph +% xlab: label for each structural equation +%----------- +% ExactSmyear: time (myears) and all structural shocks +% if no nargout, plot graphics. +% +% October 1998 by Tao A. Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +eval(['load ' idfile '.mat']); + +% +ibegy = find(myears==begy); +ifiny = find(myears==finy); + +ibegy1 = find(myears==begy+1); + +% +if isempty(ibegy) & isempty(ibegy1) + warning('Either ibegy or begm is out of the range of myears') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + pause +elseif isempty(ibegy) & (begm<myears(1)) + warning('Either ibegy or begm is out of the range of myears') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + pause +elseif isempty(ibegy) + ibegy = -myears(1)+2; % +2 is needed for the following -1 in + % bar(Estrexa(ibegy+begm-1:ifiny+finm-1,i)) + %so that it 2-1=1 so that +1 is what we want +end + +% +if isempty(ifiny) + warning('Either ifiny or finm is out of the range of myears') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + pause +elseif (ifiny+finm-1>size(myears,1)) + warning('Either ifiny or finm is out of the range of myears') + disp('Print myears to see the range') + disp('Or change actuap to make the range longer and save new results to Xshock.mat') + pause +end + + +if nargout==0 + t=length(Estrexa(ibegy+begm-1:ifiny+finm-1,1)); + for i=1:size(Estrexa,2) + figure + %plot(1:t, Estrexa(ibegy+begm-1:ifiny+finm-1,i)); + bar(Estrexa(ibegy+begm-1:ifiny+finm-1,i)) + title([ tlinput ' Monthly Structural Shocks' ]) + ylabel(char(xlab(i))) + xlabel([ 'From ' num2str(begy) ':' num2str(begm) ' to ' ... + num2str(finy) ':' num2str(finm) ]) + grid + end +else + ExactSmyear = [myears(ibegy+begm-1:ifiny+finm-1) Estrexa(ibegy+begm-1:ifiny+finm-1,:)]; +end diff --git a/MatlabFiles/gstate.m b/MatlabFiles/gstate.m index b076e5d017797062a720f5013e538ff2e3552806..c693576439dd9a7a9b59c178e2f2a953a8ea6916 100644 --- a/MatlabFiles/gstate.m +++ b/MatlabFiles/gstate.m @@ -1,114 +1,114 @@ -function [GS,pickn,ok,uis,uiu,vs]=gstate(G1,impact,pick) -%function [GS,pickn,ok,uis,vs]=gstate(G1,impact,pick) -% G1: the coefficient on lagged y from the output of gensys.m. -% impact:the coefficient on exogenous shocks from the output of gensys.m -% pick: an optional guess at a matrix of coefficients that extracts -% the state vector from y -% ok: 0 if pick matrix is just no good. -% 1 if pick matrix is usable forward, but loses initial date information -% 2 if pick matrix is not usable forward, is part of a correct state vector, but is not complete -% 3 if pick matrix is usable forward, is part of a correct state vector, but is not complete -% 4 if pick matrix is not usable forward, summarizes past, but is redundant -% 5 if pick matrix is usable forward, summarizes past, but is redundant -% 6 if pick matrix summarizes past and is not redundant, but is not usable forward -% 7 if pick matrix is perfect, both forward and as history summary -% pickn: a matrix of coefficients that extracts the state vector from y. Equal -% to pick if pick is supplied and ok=1; otherwise, an ok-maximizing pick matrix that -% is somewhat similar to pick. -% GS: the matrix of coefficients on the lagged state variable -% uis,vs: If uis'*vs is square and full rank, ok=7 is possible, otherwise not. If ok<2, an ok>2 can be found by trying -% a pick in the row space of vs'. Any pick with pick*uis full column rank will provide a foward state -% (i.e. ok an odd number). -% uiu: uiu'y(t)=0, and this is interpretable as the decision rule setting controls as functions of the states. -% The solution was in the form y(t)=G1*y(t-1)+impact*z(t). Now it's in the form y(t)=GS*pickn*y(t-1)+impact*z(t). -% In general, pickn is mxn with m<n. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -REALSMALL=1e-9; -[nr,nc]=size(G1); -%if nr<nc -% G1=[G1;zeros(nc-nr,nc)]; -%end -[u d v]=svd(G1); -top=find(diag(d)>REALSMALL); -nd=top(end); -us=u(:,top); -uu=u(:,top+1:end); -d=d(top,top); -vs=v(:,top); -if nargin<=2 - pick=vs'; - vp=v; - vps=vs; - dp=eye(nd); - ups=eye(nr,nd); - ndp=nd; -else - [up dp vp]=svd(pick); - topp=find(diag(dp)>REALSMALL); - ndp=topp(end); - vps=vp(:,topp); - dp=dp(topp,topp); - ups=up(:,topp); -end - % If we were worried about efficiency, we'd skip some of this when pick=vs. - %Does pick summarize history? (pick in v' row space, v in vp' row space). - pinv=all(all((pick'-vs*vs'*pick').^2<REALSMALL)); - vinp=all(all((vs-vps*vps'*vs).^2<REALSMALL)); - okpast=pinv+vinp; - % Does pick summarize all current info? (impact in us column space, pick*uu full rank) - [ui,di,vi]=svd([impact us]); - topi=find(diag(di)>REALSMALL); - ndi=length(topi); - uis=ui(:,topi); - uiu=ui(:,ndi+1:size(ui,2)); - if ndi<size(G1,1) - if(size(pick,1)<size(uis,2)) - oknow=0; - else - [ut,dt,vt]=svd(pick*uis); - toppu=find(diag(dt)>REALSMALL); - if length(toppu)<size(us,2) - oknow=0; - else - oknow=1; - end - end - else - oknow=0; - end - if vinp - GS=G1/pick; - pickn=pick; - elseif pinv - r=vs-vps*vps'*vs; - [ur,dr,vr]=svd(r); - topr=find(dr>REALSMALL); - p2=ur(:,topr); - pickn=[pick;p2']; - GS=G1/pickn; - elseif oknow - GS=G1/[pick;uiu']; - GS=GS(:,1:size(pick,1)); - pickn=pick; - else - pickn=vs'; - GS=us*d; - end -ok=oknow+2*pinv+4*vinp; +function [GS,pickn,ok,uis,uiu,vs]=gstate(G1,impact,pick) +%function [GS,pickn,ok,uis,vs]=gstate(G1,impact,pick) +% G1: the coefficient on lagged y from the output of gensys.m. +% impact:the coefficient on exogenous shocks from the output of gensys.m +% pick: an optional guess at a matrix of coefficients that extracts +% the state vector from y +% ok: 0 if pick matrix is just no good. +% 1 if pick matrix is usable forward, but loses initial date information +% 2 if pick matrix is not usable forward, is part of a correct state vector, but is not complete +% 3 if pick matrix is usable forward, is part of a correct state vector, but is not complete +% 4 if pick matrix is not usable forward, summarizes past, but is redundant +% 5 if pick matrix is usable forward, summarizes past, but is redundant +% 6 if pick matrix summarizes past and is not redundant, but is not usable forward +% 7 if pick matrix is perfect, both forward and as history summary +% pickn: a matrix of coefficients that extracts the state vector from y. Equal +% to pick if pick is supplied and ok=1; otherwise, an ok-maximizing pick matrix that +% is somewhat similar to pick. +% GS: the matrix of coefficients on the lagged state variable +% uis,vs: If uis'*vs is square and full rank, ok=7 is possible, otherwise not. If ok<2, an ok>2 can be found by trying +% a pick in the row space of vs'. Any pick with pick*uis full column rank will provide a foward state +% (i.e. ok an odd number). +% uiu: uiu'y(t)=0, and this is interpretable as the decision rule setting controls as functions of the states. +% The solution was in the form y(t)=G1*y(t-1)+impact*z(t). Now it's in the form y(t)=GS*pickn*y(t-1)+impact*z(t). +% In general, pickn is mxn with m<n. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +REALSMALL=1e-9; +[nr,nc]=size(G1); +%if nr<nc +% G1=[G1;zeros(nc-nr,nc)]; +%end +[u d v]=svd(G1); +top=find(diag(d)>REALSMALL); +nd=top(end); +us=u(:,top); +uu=u(:,top+1:end); +d=d(top,top); +vs=v(:,top); +if nargin<=2 + pick=vs'; + vp=v; + vps=vs; + dp=eye(nd); + ups=eye(nr,nd); + ndp=nd; +else + [up dp vp]=svd(pick); + topp=find(diag(dp)>REALSMALL); + ndp=topp(end); + vps=vp(:,topp); + dp=dp(topp,topp); + ups=up(:,topp); +end + % If we were worried about efficiency, we'd skip some of this when pick=vs. + %Does pick summarize history? (pick in v' row space, v in vp' row space). + pinv=all(all((pick'-vs*vs'*pick').^2<REALSMALL)); + vinp=all(all((vs-vps*vps'*vs).^2<REALSMALL)); + okpast=pinv+vinp; + % Does pick summarize all current info? (impact in us column space, pick*uu full rank) + [ui,di,vi]=svd([impact us]); + topi=find(diag(di)>REALSMALL); + ndi=length(topi); + uis=ui(:,topi); + uiu=ui(:,ndi+1:size(ui,2)); + if ndi<size(G1,1) + if(size(pick,1)<size(uis,2)) + oknow=0; + else + [ut,dt,vt]=svd(pick*uis); + toppu=find(diag(dt)>REALSMALL); + if length(toppu)<size(us,2) + oknow=0; + else + oknow=1; + end + end + else + oknow=0; + end + if vinp + GS=G1/pick; + pickn=pick; + elseif pinv + r=vs-vps*vps'*vs; + [ur,dr,vr]=svd(r); + topr=find(dr>REALSMALL); + p2=ur(:,topr); + pickn=[pick;p2']; + GS=G1/pickn; + elseif oknow + GS=G1/[pick;uiu']; + GS=GS(:,1:size(pick,1)); + pickn=pick; + else + pickn=vs'; + GS=us*d; + end +ok=oknow+2*pinv+4*vinp; diff --git a/MatlabFiles/gyrfore.m b/MatlabFiles/gyrfore.m index 7bee2d62b5737a8622c4b8101358c1ee69ed6be9..2ab6c7b1a283e3169326fe28fd4cc2062f9dc392 100644 --- a/MatlabFiles/gyrfore.m +++ b/MatlabFiles/gyrfore.m @@ -1,60 +1,60 @@ -function gyrfore(yfore,yacte,keyindx,rnum,cnum,ylab,forelabel,conlab) -% -% Graph annual (or calendar year) forecasts vs actual (all data from "msstart.m") -% -% yfore: actual and forecast annual growth data with dates. -% yacte: actual annual growth data with dates. -% keyindx: index for the variables to be graphed -% rnum: number of rows in subplot -% cnum: number of columns in subplot -% ylab: label for the variables -% forelabel: title label for as of time of forecast -% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' -%------------- -% No output argument for this graph file -% -% Tao Zha, March 2000 - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -vyrs = yfore(:,1); -hornum = cell(length(vyrs),1); % horizontal year (number) -count=0; -for k=vyrs' - count=count+1; - jnk=num2str(k); - hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' -end - -count=0; -for i = keyindx - count = count+1; - subplot(rnum,cnum,count) - % - plot(yacte(:,1),yacte(:,2+i),vyrs,yfore(:,2+i),'--') - set(gca,'XTick',vyrs) - set(gca,'XTickLabel',char(hornum)) - if i==keyindx(1) - title(forelabel) - elseif i>=length(keyindx)-1 - xlabel(conlab) - end - % - grid - ylabel(char(ylab(i))) -end +function gyrfore(yfore,yacte,keyindx,rnum,cnum,ylab,forelabel,conlab) +% +% Graph annual (or calendar year) forecasts vs actual (all data from "msstart.m") +% +% yfore: actual and forecast annual growth data with dates. +% yacte: actual annual growth data with dates. +% keyindx: index for the variables to be graphed +% rnum: number of rows in subplot +% cnum: number of columns in subplot +% ylab: label for the variables +% forelabel: title label for as of time of forecast +% conlab: label for what conditions imposed; e.g., conlab = 'All bar MS shocks inspl' +%------------- +% No output argument for this graph file +% +% Tao Zha, March 2000 + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +vyrs = yfore(:,1); +hornum = cell(length(vyrs),1); % horizontal year (number) +count=0; +for k=vyrs' + count=count+1; + jnk=num2str(k); + hornum{count}=jnk(3:4); % e.g., with '1990', we have '90' +end + +count=0; +for i = keyindx + count = count+1; + subplot(rnum,cnum,count) + % + plot(yacte(:,1),yacte(:,2+i),vyrs,yfore(:,2+i),'--') + set(gca,'XTick',vyrs) + set(gca,'XTickLabel',char(hornum)) + if i==keyindx(1) + title(forelabel) + elseif i>=length(keyindx)-1 + xlabel(conlab) + end + % + grid + ylabel(char(ylab(i))) +end diff --git a/MatlabFiles/hesscd.m b/MatlabFiles/hesscd.m index 99ee783c73ee01f25e5cd4e6e0df4c29b7de1073..a52a388f3b776420028e5990f9b5a5efbfaa94d7 100644 --- a/MatlabFiles/hesscd.m +++ b/MatlabFiles/hesscd.m @@ -1,79 +1,79 @@ -function grdd = hesscd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... - P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) -% computing numerical hessian using a central difference with -% function grdd = hesscd(fcn,x0,grdh,Passed variables1) -% -% fcn: a string naming the objective function. -% x0: a column vector n*1, at which point the hessian is evaluated. -% grdh: step size. -% grdd: hessian matrix (second derivative), n*n. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -stps = eps^(1/3); -% eps: floating point relative accuracy or machine precision: 2.22e-16 -% stps: step size recommended by Dennis and Schnabel: 6.006e-6 - -x0 = x0(:); -tailstr = ')'; -for i=nargin-3:-1:1 - tailstr=[ ',P' num2str(i) tailstr]; -end -f0 = eval([fcn '(x0' tailstr]); - -% ** initializations -k = length(x0); -grdd = zeros(k); - -% ** Computation of stepsize (dh) -if all(grdh) - dh = grdh; -else - ax0 = abs(x0); - if all(x0) - dax0 = x0 ./ ax0; - else - dax0 = 1; - end - dh = stps * (max([ax0 (1e-2)*ones(k,1)]'))' .* dax0; -end - -xdh = x0 + dh; -dh = xdh - x0; % This increases precision slightly -dhm = dh(:,ones(k,1)); -ee = eye(k) .* dhm; - -i = 1; -while i <= k - j = i; - while j <= k - - fune1 = eval([fcn '(x0 + ee(:,i) + ee(:,j)' tailstr]); - fune2 = eval([fcn '(x0 - ee(:,i) + ee(:,j)' tailstr]); - fune3 = eval([fcn '(x0 + ee(:,i) - ee(:,j)' tailstr]); - fune4 = eval([fcn '(x0 - ee(:,i) - ee(:,j)' tailstr]); - grdd(i,j) = (fune1 - fune2 - fune3 + fune4) / (4 * dh(i) * dh(j)); - - if i ~= j - grdd(j,i) = grdd(i,j); - end - - j = j+1; - end - i = i+1; -end - +function grdd = hesscd(fcn,x0,grdh,P1,P2,P3,P4,P5,P6,P7,P8,P9,... + P10,P11,P12,P13,P14,P15,P16,P17,P18,P19,P20) +% computing numerical hessian using a central difference with +% function grdd = hesscd(fcn,x0,grdh,Passed variables1) +% +% fcn: a string naming the objective function. +% x0: a column vector n*1, at which point the hessian is evaluated. +% grdh: step size. +% grdd: hessian matrix (second derivative), n*n. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +stps = eps^(1/3); +% eps: floating point relative accuracy or machine precision: 2.22e-16 +% stps: step size recommended by Dennis and Schnabel: 6.006e-6 + +x0 = x0(:); +tailstr = ')'; +for i=nargin-3:-1:1 + tailstr=[ ',P' num2str(i) tailstr]; +end +f0 = eval([fcn '(x0' tailstr]); + +% ** initializations +k = length(x0); +grdd = zeros(k); + +% ** Computation of stepsize (dh) +if all(grdh) + dh = grdh; +else + ax0 = abs(x0); + if all(x0) + dax0 = x0 ./ ax0; + else + dax0 = 1; + end + dh = stps * (max([ax0 (1e-2)*ones(k,1)]'))' .* dax0; +end + +xdh = x0 + dh; +dh = xdh - x0; % This increases precision slightly +dhm = dh(:,ones(k,1)); +ee = eye(k) .* dhm; + +i = 1; +while i <= k + j = i; + while j <= k + + fune1 = eval([fcn '(x0 + ee(:,i) + ee(:,j)' tailstr]); + fune2 = eval([fcn '(x0 - ee(:,i) + ee(:,j)' tailstr]); + fune3 = eval([fcn '(x0 + ee(:,i) - ee(:,j)' tailstr]); + fune4 = eval([fcn '(x0 - ee(:,i) - ee(:,j)' tailstr]); + grdd(i,j) = (fune1 - fune2 - fune3 + fune4) / (4 * dh(i) * dh(j)); + + if i ~= j + grdd(j,i) = grdd(i,j); + end + + j = j+1; + end + i = i+1; +end + diff --git a/MatlabFiles/hist2.m b/MatlabFiles/hist2.m deleted file mode 100644 index 37bea11bc62ea965ac05ed723ceb489f840cd438..0000000000000000000000000000000000000000 --- a/MatlabFiles/hist2.m +++ /dev/null @@ -1,85 +0,0 @@ -function [no,xo,binwidth] = hist2(y,x) -%HIST2 Histogram. -% N = HIST2(Y) bins the elements of Y into 10 equally spaced containers -% and returns the number of elements in each container. If Y is a -% matrix, HIST2 works down the columns. -% -% N = HIST2(Y,M), where M is a scalar, uses M bins. -% -% N = HIST2(Y,X), where X is a vector, returns the distribution of Y -% among bins with centers specified by X. -% -% [N,X] = HIST2(...) also returns the position of the bin centers in X. -% -% [N,X,BW] = HIST2(...) also returns the position of the bin centers in X and the width of the bin. -% -% HIST2(...) without output arguments produces a histogram bar plot of -% the results. - -% J.N. Little 2-06-86 -% Revised 10-29-87, 12-29-88 LS -% Revised 8-13-91 by cmt, 2-3-92 by ls. -% Copyright (c) 1984-97 by The MathWorks, Inc. -% $Revision: 5.10 $ $Date: 1997/04/08 05:22:50 $ - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if nargin == 0 - error('Requires one or two input arguments.') -end -if nargin == 1 - x = 10; -end -if min(size(y))==1, y = y(:); end -if isstr(x) | isstr(y) - error('Input arguments must be numeric.') -end -[m,n] = size(y); -if length(x) == 1 - miny = min(min(y)); - maxy = max(max(y)); - binwidth = (maxy - miny) ./ x; - xx = miny + binwidth*(0:x); - xx(length(xx)) = maxy; - x = xx(1:length(xx)-1) + binwidth/2; -else - xx = x(:)'; - miny = min(min(y)); - maxy = max(max(y)); - binwidth = [diff(xx) 0]; - xx = [xx(1)-binwidth(1)/2 xx+binwidth/2]; - xx(1) = miny; - xx(length(xx)) = maxy; -end -nbin = length(xx); -nn = zeros(nbin,n); -for i=2:nbin - nn(i,:) = sum(y <= xx(i)); -end -nn = nn(2:nbin,:) - nn(1:nbin-1,:); -if nargout == 0 - bar(x,nn,'hist'); -else - if min(size(y))==1, % Return row vectors if possible. - no = nn'; - xo = x; - else - no = nn; - xo = x'; - end -end \ No newline at end of file diff --git a/MatlabFiles/history.m b/MatlabFiles/history.m index 4f224f32ad23ec922840cdeac9d05ed63c8e4a1a..b1f14487e3f6b034f6001000bcce8cdf8cfdaaed 100644 --- a/MatlabFiles/history.m +++ b/MatlabFiles/history.m @@ -1,124 +1,124 @@ -function [hd,ehat] = history(uhat,Bh,A0,nn) -% Computing historical decompositions with -% [hd,ehat] = history(uhat,Bh,A0,nn) -% where hd: historical decompositions, dstp-by-nvar^2 matrix. -% Column: 1st variable decompositions attributed to nvar -% (cumulative) shocks, 2nd variable decompositions -% attributed to nvar (cumulative) shocks, and so on. -% Row: steps of decompositions "dstp". -% ehat: structural one-step forecast errors -% of each variable, dstp-by-nvar. -% uhat: dstp-by-nvar reduced form one-step forecast errors -% begining with the decomposition period. -% Bh: the estimated reduced form coefficient in the form -% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix -% form or dimension is the same as "Bh" from the function "sye". -% A0: comtemporaneous A in the structural model A(L)y(t) = e(t). -% nn: # of inputs -- [nvar,lags,dstp (steps of decompositions)]. -% ===== Note: this function can be easily modified to get variance -% ===== decompositions and impulse responses. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nvar = nn(1); -lags = nn(2); -dstp = nn(3); % number of steps for decompositions -imstep = dstp; % steps of impulse responses -tcwc = nvar*lags; % total coefficients without constant -swish = inv(A0); - - -Ah = Bh'; -% Row: nvar equations -% Column: 1st lag (with nvar variables) to -% lags (with nvar variables) + const = k. -ehat = uhat*A0'; -% dstp-by-nvar matrix: structural one-step forecast errors. - -hd = zeros(dstp,nvar*nvar); -% Column: 1st varaible to nvar shocks, 2nd variables to nvar shock, and so on. -% Row: steps of decompositions. -imf = zeros(dstp,nvar*nvar); % impulse responses -% different format from "hd", i.e., nvar variables to 1st shock, -% nvar variables to 2nd shock, etc. To make the format the same -% as "hd", just change Mtem to Mtem' right before stacking "imf". -% See also "impulseo.m" in \toolbox\cstz -M = zeros(nvar*(lags+1),nvar); % stacked matrices for impulse responses -% Stack M0;M1;M2;...;Mlags -MH = zeros(nvar*dstp,nvar); -% same as M, but stacked in a different fashion after t > lags so that -% all the cumulations are recorded for historical decompositions. -M(1:nvar,:) = swish; -Mtem = M(1:nvar,:); % temporary M -- impulse responses. -% -Hdc = M(1:nvar,:)*diag(ehat(1,:)); -% first period historical decompositions. -% * put in the form of "hd", as well as "imf" -Hdc = Hdc'; -hd(1,:) = Hdc(:)'; -imf(1,:) = Mtem(:)'; - - -% -% ** beginning with the second period. Note, 1st period is t=0 -% -t = 1; -ims1 = min([dstp-1 lags]); -while t <= ims1 - % ** impulse response functions - Mtem = zeros(nvar,nvar); - for k = 1:t - Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(t-k)+1:nvar*(t-k+1),:) + Mtem; - % Row: nvar equations, each for the nvar variables at tth lag - end - M(nvar*t+1:nvar*(t+1),:) = Mtem; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. - % ** historical decompositions - Hdc = M(1:nvar,:)*diag(ehat(t+1,:)); - for k = 1:t - Hdc = Hdc + M(nvar*k+1:nvar*(k+1),:)*diag(ehat(t+1-k,:)); - % Row: nvar variables; Column: nvar shocks - end - Hdc = Hdc'; - hd(t+1,:) = Hdc(:)'; - t= t+1; -end - -MH(1:nvar*(lags+1),:) = M; -for t = lags+1:imstep-1 - % ** impulse response functions - M(1:nvar*lags,:) = M(nvar+1:nvar*(lags+1),:); - Mtem = zeros(nvar,nvar); - for k = 1:lags - Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(lags-k)+1:nvar*(lags-k+1),:) + Mtem; - % Row: nvar equations, each for the nvar variables at tth lag - end - M(nvar*lags+1:nvar*(lags+1),:) = Mtem; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. - % ** historical decompositions - MH(nvar*t+1:nvar*(t+1),:) = Mtem; - Hdc = MH(1:nvar,:)*diag(ehat(t+1,:)); - for k = 1:t - Hdc = Hdc + MH(nvar*k+1:nvar*(k+1),:)*diag(ehat(t+1-k,:)); - % Row: nvar variables; Column: nvar shocks - end - Hdc = Hdc'; - hd(t+1,:) = Hdc(:)'; -end - \ No newline at end of file +function [hd,ehat] = history(uhat,Bh,A0,nn) +% Computing historical decompositions with +% [hd,ehat] = history(uhat,Bh,A0,nn) +% where hd: historical decompositions, dstp-by-nvar^2 matrix. +% Column: 1st variable decompositions attributed to nvar +% (cumulative) shocks, 2nd variable decompositions +% attributed to nvar (cumulative) shocks, and so on. +% Row: steps of decompositions "dstp". +% ehat: structural one-step forecast errors +% of each variable, dstp-by-nvar. +% uhat: dstp-by-nvar reduced form one-step forecast errors +% begining with the decomposition period. +% Bh: the estimated reduced form coefficient in the form +% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix +% form or dimension is the same as "Bh" from the function "sye". +% A0: comtemporaneous A in the structural model A(L)y(t) = e(t). +% nn: # of inputs -- [nvar,lags,dstp (steps of decompositions)]. +% ===== Note: this function can be easily modified to get variance +% ===== decompositions and impulse responses. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nvar = nn(1); +lags = nn(2); +dstp = nn(3); % number of steps for decompositions +imstep = dstp; % steps of impulse responses +tcwc = nvar*lags; % total coefficients without constant +swish = inv(A0); + + +Ah = Bh'; +% Row: nvar equations +% Column: 1st lag (with nvar variables) to +% lags (with nvar variables) + const = k. +ehat = uhat*A0'; +% dstp-by-nvar matrix: structural one-step forecast errors. + +hd = zeros(dstp,nvar*nvar); +% Column: 1st varaible to nvar shocks, 2nd variables to nvar shock, and so on. +% Row: steps of decompositions. +imf = zeros(dstp,nvar*nvar); % impulse responses +% different format from "hd", i.e., nvar variables to 1st shock, +% nvar variables to 2nd shock, etc. To make the format the same +% as "hd", just change Mtem to Mtem' right before stacking "imf". +% See also "impulseo.m" in \toolbox\cstz +M = zeros(nvar*(lags+1),nvar); % stacked matrices for impulse responses +% Stack M0;M1;M2;...;Mlags +MH = zeros(nvar*dstp,nvar); +% same as M, but stacked in a different fashion after t > lags so that +% all the cumulations are recorded for historical decompositions. +M(1:nvar,:) = swish; +Mtem = M(1:nvar,:); % temporary M -- impulse responses. +% +Hdc = M(1:nvar,:)*diag(ehat(1,:)); +% first period historical decompositions. +% * put in the form of "hd", as well as "imf" +Hdc = Hdc'; +hd(1,:) = Hdc(:)'; +imf(1,:) = Mtem(:)'; + + +% +% ** beginning with the second period. Note, 1st period is t=0 +% +t = 1; +ims1 = min([dstp-1 lags]); +while t <= ims1 + % ** impulse response functions + Mtem = zeros(nvar,nvar); + for k = 1:t + Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(t-k)+1:nvar*(t-k+1),:) + Mtem; + % Row: nvar equations, each for the nvar variables at tth lag + end + M(nvar*t+1:nvar*(t+1),:) = Mtem; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. + % ** historical decompositions + Hdc = M(1:nvar,:)*diag(ehat(t+1,:)); + for k = 1:t + Hdc = Hdc + M(nvar*k+1:nvar*(k+1),:)*diag(ehat(t+1-k,:)); + % Row: nvar variables; Column: nvar shocks + end + Hdc = Hdc'; + hd(t+1,:) = Hdc(:)'; + t= t+1; +end + +MH(1:nvar*(lags+1),:) = M; +for t = lags+1:imstep-1 + % ** impulse response functions + M(1:nvar*lags,:) = M(nvar+1:nvar*(lags+1),:); + Mtem = zeros(nvar,nvar); + for k = 1:lags + Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(lags-k)+1:nvar*(lags-k+1),:) + Mtem; + % Row: nvar equations, each for the nvar variables at tth lag + end + M(nvar*lags+1:nvar*(lags+1),:) = Mtem; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. + % ** historical decompositions + MH(nvar*t+1:nvar*(t+1),:) = Mtem; + Hdc = MH(1:nvar,:)*diag(ehat(t+1,:)); + for k = 1:t + Hdc = Hdc + MH(nvar*k+1:nvar*(k+1),:)*diag(ehat(t+1-k,:)); + % Row: nvar variables; Column: nvar shocks + end + Hdc = Hdc'; + hd(t+1,:) = Hdc(:)'; +end + diff --git a/MatlabFiles/history2.m b/MatlabFiles/history2.m index 07a7287f8c600dc58ad368d78cf53994a3572896..d2ceaf6e27d0d0f8a41c9c33df8772592d91de6c 100644 --- a/MatlabFiles/history2.m +++ b/MatlabFiles/history2.m @@ -1,160 +1,160 @@ -function [HDratio,HDvalue,yhatn,yforen] = history2(HDindx,A0,Bhml,phil,nn,... - actup,Estrexa,xdata,nvar,nSample,nSampleCal,forep,forepq,forepy,q_m,... - qmEnd,vlist,vlistlog,vlistper,lmqyIndx) -% [HDratio,HDvalue,yhatn,yforen] = history2(HDindx,A0,Bhml,phil,nn,actup,... -% xdata,nvar,nSample,nSampleCal,forep,forepq,forepy,q_m,... -% qmEnd,vlist,vlistlog,vlistper,lmqyIndx) -% -% (Out-of-sample) historical decompostions: alternative approach to history.m in 3 aspects -% (1) compute the percentage (not the value itself) -% (2) NOT cumulative HD (THIS is NOT correct, TAZ, 03/17/99) -% (3) conditional on time t (not time 0). -% (4) condtional and uncondtional forecasts -% -% HDindx: k-by-1 cell where k groups of shocks; index number for particular shocks -% A0h: nvar-by-nvar for y(t)A0 = X*A+ + E, where column means equation -% Bh: the (posterior) estimate of B for y(t) = X*Bh + E*inv(A0) -% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 -% (last period plus lags before the beginning of forecast) -% nn: [nvar,lags,forep], forep: forecast periods (monthly) -% actup: actual data periods (monthly) before the beginning of forecasts -% xdata: oringal data set, up to the period before (peudo-) out-of-sample forecasting, -% all logged except R, U, etc. -% Estrexa: forep-by-nvar -- backed out structural shocks for out-of-sample forecast -% nvar: number of variables -% nSample: sample size (including lags or initial periods) -% nSampleCal: sample size in terms of calendar years -% forep: forecast periods (monthly) -% forepq: forecast periods (quarterly) -% forepy: forecast periods (yearly) -% q_m: quarterly or monthly for the underlying model -% qmEnd: last q_m before out-of-sample forecasting -% vlist: a list of variables -% vlistlog: sub list of variables that are in log -% vlistper: sub list of variables that are in percent -% lmyqIndx: 4-by-1 1 or 0's. Index for m log, m level, qg, and yg; 1: yes; 0: no; -% if lmyqIndx(1)==1, both monthly log and monthly level are returned -%-------------- -% HDratio: 5-by-k cells, where k groups (see HDindx) of shocks associated with decomposition; -% 5: monthly log, monthly level, mg, qg, and calendar yg in this order; -% each cell is forep(q)(y)-by-nvar -% HDvalue: same dimension as HDratio but with the values (differences between -% conditional and unconditional forecasts -% yhatn: same dimension as HDratio but with conditional forecasts -% yforen: 5-by-1 cells and each cell is forep(q)(y)-by-nvar unconditional forecasts -% -% October 1998 by Tao Zha. -% Last change 3/19/99 on the dimension of "Estrexa" so that previous programs may not be -% compatible. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nyout = 1+nargout('fore_cal'); - % +1 because we want the original logged variables as well. -[nHD,jnk] = size(HDindx); -yhat=cell(nHD,1); -yhatn = cell(nyout,nHD); - % row: output such as l, mg, qg, or yg; column: how many decomps - - - -%-------------------------------------------------------------------------- -% Unconditional point forecasts for log, monthly levle, mg, qg, and yg. -%-------------------------------------------------------------------------- -yforeml = forecast(Bhml,phil,nn); -yforen = cell(nyout,1); -yforen{1} = yforeml; -oputstr = '['; % output string -for n=2:nyout - if n<nyout - oputstr = [oputstr 'yforen{' num2str(n) '},']; - else - oputstr = [oputstr 'yforen{' num2str(n) '}']; - end -end -oputstr =[oputstr ']']; -% -eval([oputstr ' = fore_cal(yforeml,xdata,nvar,nSample,nSampleCal,forep,'... - 'forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,lmqyIndx);']); - - - -%-------------------------------------------------------------------------- -% Conditional forecasts on specified paths of shocks -% for log, monthly levle, mg, qg, and yg. -%-------------------------------------------------------------------------- -for k=1:nHD - Estr = zeros(forep,nvar); % out of sample - Estr(:,HDindx{k}) = Estrexa(:,HDindx{k}); % out of sample, MS - yhat{k} = forefixe(A0,Bhml,phil,nn,Estr); - yhatn{1,k} = yhat{k}; % original logged variables - % - oputstr = '['; % output string - for n=2:nyout - if n<nyout - oputstr = [oputstr 'yhatn{' num2str(n) ',k},']; - else - oputstr = [oputstr 'yhatn{' num2str(n) ',k}']; - end - end - oputstr =[oputstr ']']; - % - eval([oputstr ' = fore_cal(yhat{k},xdata,nvar,nSample,nSampleCal,forep,'... - 'forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,lmqyIndx);']); -end - - - -%-------------------------------------------------------------------------- -% Historical decompositions: both values and raitos (%) -%-------------------------------------------------------------------------- -HDratio=cell(nyout,nHD); -HDvalue=HDratio; -for n=2:nyout - if lmqyIndx(n-1) - if (n-1==1) - yhatotal = zeros(size(yhatn{1,k})); - for k=1:nHD - HDvalue{1,k} = yhatn{1,k}-yforen{1}; - yhatotal = yhatotal + abs(HDvalue{1,k}); - % a sum of absolute values. One can also use square - end - % - for k=1:nHD - HDratio{1,k} = abs(HDvalue{1,k})*100 ./ yhatotal; - end - end - % - yhatotal = zeros(size(yhatn{n,k})); - for k=1:nHD - HDvalue{n,k} = yhatn{n,k}-yforen{n}; - yhatotal = yhatotal + abs(HDvalue{n,k}); - % a sum of absolute values. One can also use square - end - % - for k=1:nHD - HDratio{n,k} = abs(HDvalue{n,k})*100 ./ yhatotal; - end - end -end - - -%** check. This first may not be zeros, but the second (monthly log) must be zeros. -%HDvalue{5,1}+HDvalue{5,2}-... -% (yactCalyg(size(yactCalyg,1)-3:size(yactCalyg,1),:)-yforeCalygml) -%HDvalue{1,1}+HDvalue{1,2}-... -% (yact(size(yact,1)-forep+1:size(yact,1),:)-yforen{1,1}) \ No newline at end of file +function [HDratio,HDvalue,yhatn,yforen] = history2(HDindx,A0,Bhml,phil,nn,... + actup,Estrexa,xdata,nvar,nSample,nSampleCal,forep,forepq,forepy,q_m,... + qmEnd,vlist,vlistlog,vlistper,lmqyIndx) +% [HDratio,HDvalue,yhatn,yforen] = history2(HDindx,A0,Bhml,phil,nn,actup,... +% xdata,nvar,nSample,nSampleCal,forep,forepq,forepy,q_m,... +% qmEnd,vlist,vlistlog,vlistper,lmqyIndx) +% +% (Out-of-sample) historical decompostions: alternative approach to history.m in 3 aspects +% (1) compute the percentage (not the value itself) +% (2) NOT cumulative HD (THIS is NOT correct, TAZ, 03/17/99) +% (3) conditional on time t (not time 0). +% (4) condtional and uncondtional forecasts +% +% HDindx: k-by-1 cell where k groups of shocks; index number for particular shocks +% A0h: nvar-by-nvar for y(t)A0 = X*A+ + E, where column means equation +% Bh: the (posterior) estimate of B for y(t) = X*Bh + E*inv(A0) +% phil: the 1-by-(nvar*lags+1) data matrix where k=nvar*lags+1 +% (last period plus lags before the beginning of forecast) +% nn: [nvar,lags,forep], forep: forecast periods (monthly) +% actup: actual data periods (monthly) before the beginning of forecasts +% xdata: oringal data set, up to the period before (peudo-) out-of-sample forecasting, +% all logged except R, U, etc. +% Estrexa: forep-by-nvar -- backed out structural shocks for out-of-sample forecast +% nvar: number of variables +% nSample: sample size (including lags or initial periods) +% nSampleCal: sample size in terms of calendar years +% forep: forecast periods (monthly) +% forepq: forecast periods (quarterly) +% forepy: forecast periods (yearly) +% q_m: quarterly or monthly for the underlying model +% qmEnd: last q_m before out-of-sample forecasting +% vlist: a list of variables +% vlistlog: sub list of variables that are in log +% vlistper: sub list of variables that are in percent +% lmyqIndx: 4-by-1 1 or 0's. Index for m log, m level, qg, and yg; 1: yes; 0: no; +% if lmyqIndx(1)==1, both monthly log and monthly level are returned +%-------------- +% HDratio: 5-by-k cells, where k groups (see HDindx) of shocks associated with decomposition; +% 5: monthly log, monthly level, mg, qg, and calendar yg in this order; +% each cell is forep(q)(y)-by-nvar +% HDvalue: same dimension as HDratio but with the values (differences between +% conditional and unconditional forecasts +% yhatn: same dimension as HDratio but with conditional forecasts +% yforen: 5-by-1 cells and each cell is forep(q)(y)-by-nvar unconditional forecasts +% +% October 1998 by Tao Zha. +% Last change 3/19/99 on the dimension of "Estrexa" so that previous programs may not be +% compatible. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nyout = 1+nargout('fore_cal'); + % +1 because we want the original logged variables as well. +[nHD,jnk] = size(HDindx); +yhat=cell(nHD,1); +yhatn = cell(nyout,nHD); + % row: output such as l, mg, qg, or yg; column: how many decomps + + + +%-------------------------------------------------------------------------- +% Unconditional point forecasts for log, monthly levle, mg, qg, and yg. +%-------------------------------------------------------------------------- +yforeml = forecast(Bhml,phil,nn); +yforen = cell(nyout,1); +yforen{1} = yforeml; +oputstr = '['; % output string +for n=2:nyout + if n<nyout + oputstr = [oputstr 'yforen{' num2str(n) '},']; + else + oputstr = [oputstr 'yforen{' num2str(n) '}']; + end +end +oputstr =[oputstr ']']; +% +eval([oputstr ' = fore_cal(yforeml,xdata,nvar,nSample,nSampleCal,forep,'... + 'forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,lmqyIndx);']); + + + +%-------------------------------------------------------------------------- +% Conditional forecasts on specified paths of shocks +% for log, monthly levle, mg, qg, and yg. +%-------------------------------------------------------------------------- +for k=1:nHD + Estr = zeros(forep,nvar); % out of sample + Estr(:,HDindx{k}) = Estrexa(:,HDindx{k}); % out of sample, MS + yhat{k} = forefixe(A0,Bhml,phil,nn,Estr); + yhatn{1,k} = yhat{k}; % original logged variables + % + oputstr = '['; % output string + for n=2:nyout + if n<nyout + oputstr = [oputstr 'yhatn{' num2str(n) ',k},']; + else + oputstr = [oputstr 'yhatn{' num2str(n) ',k}']; + end + end + oputstr =[oputstr ']']; + % + eval([oputstr ' = fore_cal(yhat{k},xdata,nvar,nSample,nSampleCal,forep,'... + 'forepq,forepy,q_m,qmEnd,vlist,vlistlog,vlistper,lmqyIndx);']); +end + + + +%-------------------------------------------------------------------------- +% Historical decompositions: both values and raitos (%) +%-------------------------------------------------------------------------- +HDratio=cell(nyout,nHD); +HDvalue=HDratio; +for n=2:nyout + if lmqyIndx(n-1) + if (n-1==1) + yhatotal = zeros(size(yhatn{1,k})); + for k=1:nHD + HDvalue{1,k} = yhatn{1,k}-yforen{1}; + yhatotal = yhatotal + abs(HDvalue{1,k}); + % a sum of absolute values. One can also use square + end + % + for k=1:nHD + HDratio{1,k} = abs(HDvalue{1,k})*100 ./ yhatotal; + end + end + % + yhatotal = zeros(size(yhatn{n,k})); + for k=1:nHD + HDvalue{n,k} = yhatn{n,k}-yforen{n}; + yhatotal = yhatotal + abs(HDvalue{n,k}); + % a sum of absolute values. One can also use square + end + % + for k=1:nHD + HDratio{n,k} = abs(HDvalue{n,k})*100 ./ yhatotal; + end + end +end + + +%** check. This first may not be zeros, but the second (monthly log) must be zeros. +%HDvalue{5,1}+HDvalue{5,2}-... +% (yactCalyg(size(yactCalyg,1)-3:size(yactCalyg,1),:)-yforeCalygml) +%HDvalue{1,1}+HDvalue{1,2}-... +% (yact(size(yact,1)-forep+1:size(yact,1),:)-yforen{1,1}) diff --git a/MatlabFiles/histpdfcnt.m b/MatlabFiles/histpdfcnt.m index cffb0567556223e61b385a986e93bb47577259d8..6e50618a67acb9d3b9b73f9cb75f9c2fbd643fbf 100644 --- a/MatlabFiles/histpdfcnt.m +++ b/MatlabFiles/histpdfcnt.m @@ -1,134 +1,134 @@ -function [imfpdf,imfpo,imfprob] = histpdfcnt(imfcnt,ndrawscnt,forep,shockp,nvar,ninv,invc,Am,... - ixdeng,findex,sindex,vindex,idxuniscl,lval,hval,ncom,gIndx) -% [imfpdf,imfpo,imfprob] = histpdfcnt(imfcnt,ndrawscnt,forep,shockp,nvar,ninv,invc,Am,... -% ixdeng,findex,sindex,vindex,idxuniscl,lval,hval,ncom,gIndx) -% From already ordered and binned (cnt: count) series (not pdf yet). -% Produce (1) the dataset for generating p.d.f., (2) the dataset for -% probability (NOT density) at each bin, (3) with option ixdeng=1, -% graphs of density functions -% -% imfcnt: 2+ninv-by-forep*shockp*nvar. Counted logcnt, yhatqgcnt, or yhatCalygcnt. -% In the case of impulse responses, forep=imstp and shockp=nvar. -% In case of of A0(Avhx), forep=1, shockp=1, nvar=nfp -% In case of forecasts, shockp=1 -% ndrawscnt: a total number of draws used in imfcnt -% forep: forecast periods -- 1st dim (must be compatible with findex) -% shockp: number of shocks -- 2nd dim (must be compatible with sindex) -% nvar: number of responses (variables) -- 3rd dim (must be compatible with vindex) -% ninv: the number of small interior intervals for sorting. -% invc: 1-by-forep*shockp*nvar. Whole inverval lenghth from min to max for one of -% (yhat, yhatqg, or yhatCalyg) -% Am: 1-by-forep*shockp*nvar. Range5{i}(:,:,1) is lowest range for for one of -% (yhat, yhatqg, or yhatCalyg) -% ixdeng: index for density graphs. 1: enable; 0: disenable -% findex: index for selected forecast periods, 1st dim (c.f., forep) -% sindex: index for selected shocks, 2nd dim (c.f., shockp) -% vindex: variable index, 3rd dim (c.f., nvar) -% idxuniscl: 1: scale on each graph by using lval and hval; 0: disenable this -% lval: (length(findex),length(sindex),length(vindex)); lowest point on the axis; -% The number matches a total of findex, sindex, and vindex -% hval: (length(findex),length(sindex),length(vindex)); highest point on the axis; -% The number matches a total of findex, sindex, and vindex -% ncom: number of combined intervals. Large ncom implies large size of the bin. -% Must set ncom so that ninv can be divided -% gIndx: 1: plot graphs of pdf's; 0: no plot -%----------------- -% imfpdf: 2+ninv-by-forep*shockp*nvar. Density -% imfpo: 2+ninv-by-forep*shockp*nvar. Bin position (x-axis) in relation to imfs3 -% imfprob: 2+ninv-by-forep*shockp*nvar. Probability (NOT density) at each bin -% -% 27 August 1998 Tao Zha -% Revised, October 1998, March 1999 -% 3/24/99, added gIndx so that the previous programs may not be compatible. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -invlength = invc ./ ninv; -invlengthM = repmat(invlength,[2+ninv,1]); -invlengthM([1 2+ninv],:) = 1; - % first (-inf, low bound) and last (high bound, +inf), the interval is set - % to be 1. Of course, theoretically, the interval length should be set - % to infinity, but 1 is large enough compared with invlength. -imfprob = imfcnt ./ ndrawscnt; % probability (NOT density) -imfpdf = imfprob ./ invlengthM; % density - -imfpo = [1:2+ninv]'; % positions for each forecast -imfpo = imfpo - 2; % the first step to put back to original form -imfpo = repmat(imfpo,[1,forep*shockp*nvar]); -invcM = repmat(invc,[2+ninv,1]); -AmM = repmat(Am,[2+ninv,1]); -imfpo = ((imfpo .* invcM) ./ ninv) + AmM; % 2+ninv-by-forep*shockp*nvar - % the final step to put back to original form of impulse responses - - -if mod(ninv,ncom) - warning('Set ncom so that ninv can be divided') - return -end -% -ninv2=ninv/ncom; -imfpdfn=zeros(2+ninv2,forep*shockp*nvar); %<<>> -imfpon=imfpdfn; -% -for ik=1:ninv2 % from 2 to 1+ninv2 for imfpdfn and imfpon - imfpdfn(1+ik,:) = sum(imfpdf(1+(ik-1)*ncom+1:1+ik*ncom,:))/ncom; - imfpon(1+ik,:) = mean(imfpo(1+(ik-1)*ncom+1:1+ik*ncom,:)); -end - -imfpdf4 = reshape(imfpdfn,2+ninv2,forep,nvar,shockp); -% imfpdf3: row--bin numbers, column--steps, 3rd dim--variables(responses), 4rd dime--shocks -imfpdf4s = permute(imfpdf4,[1 2 4 3]); - % imf3pdfs: permuted so that - % row--bin numbers, column--steps, 3rd dim--shocks, 4rd dime--variables (responses) -imfpo4 = reshape(imfpon,2+ninv2,forep,nvar,shockp); -imfpo4s = permute(imfpo4,[1 2 4 3]); - - -if gIndx - ck1=0; - for k1=findex - ck1=ck1+1; - ck2=0; - for k2=sindex - ck2=ck2+1; - ck3=0; - for k3=vindex - ck3=ck3+1; - %figure - if idxuniscl - lpos = min(find(imfpo4s(2:1+ninv2,k1,k2,k3)>lval(ck1,ck2,ck3))); % low position - hpos = max(find(imfpo4s(2:1+ninv2,k1,k2,k3)<hval(ck1,ck2,ck3))); % high position - plot(imfpo4s(lpos+1:hpos+1,k1,k2,k3),imfpdf4s(lpos+1:hpos+1,k1,k2,k3)) % - % push everything forward by 1 because lpos and hpos start at 2 - set(gca,'XLim',[lval(ck1,ck2,ck3) hval(ck1,ck2,ck3)]) - grid - else - plot(imfpo4s(2:1+ninv2,k1,k2,k3),imfpdf4s(2:1+ninv2,k1,k2,k3)) % - grid - end - end - end - end -end - -%xlabel('The 1984 U Forecast') %The 1982 GDP Growth Forecast') -%set(gca,'XLim',[lval hval]) -%xact = [7.508 7.508]; %[-2.13 -2.13]; -%yact = [0 0.5]; %[0 0.5]; -%set(line(xact,yact),'Linestyle','-') -%title('Figure 8') -%line([-2 -2],[0 400]) \ No newline at end of file +function [imfpdf,imfpo,imfprob] = histpdfcnt(imfcnt,ndrawscnt,forep,shockp,nvar,ninv,invc,Am,... + ixdeng,findex,sindex,vindex,idxuniscl,lval,hval,ncom,gIndx) +% [imfpdf,imfpo,imfprob] = histpdfcnt(imfcnt,ndrawscnt,forep,shockp,nvar,ninv,invc,Am,... +% ixdeng,findex,sindex,vindex,idxuniscl,lval,hval,ncom,gIndx) +% From already ordered and binned (cnt: count) series (not pdf yet). +% Produce (1) the dataset for generating p.d.f., (2) the dataset for +% probability (NOT density) at each bin, (3) with option ixdeng=1, +% graphs of density functions +% +% imfcnt: 2+ninv-by-forep*shockp*nvar. Counted logcnt, yhatqgcnt, or yhatCalygcnt. +% In the case of impulse responses, forep=imstp and shockp=nvar. +% In case of of A0(Avhx), forep=1, shockp=1, nvar=nfp +% In case of forecasts, shockp=1 +% ndrawscnt: a total number of draws used in imfcnt +% forep: forecast periods -- 1st dim (must be compatible with findex) +% shockp: number of shocks -- 2nd dim (must be compatible with sindex) +% nvar: number of responses (variables) -- 3rd dim (must be compatible with vindex) +% ninv: the number of small interior intervals for sorting. +% invc: 1-by-forep*shockp*nvar. Whole inverval lenghth from min to max for one of +% (yhat, yhatqg, or yhatCalyg) +% Am: 1-by-forep*shockp*nvar. Range5{i}(:,:,1) is lowest range for for one of +% (yhat, yhatqg, or yhatCalyg) +% ixdeng: index for density graphs. 1: enable; 0: disenable +% findex: index for selected forecast periods, 1st dim (c.f., forep) +% sindex: index for selected shocks, 2nd dim (c.f., shockp) +% vindex: variable index, 3rd dim (c.f., nvar) +% idxuniscl: 1: scale on each graph by using lval and hval; 0: disenable this +% lval: (length(findex),length(sindex),length(vindex)); lowest point on the axis; +% The number matches a total of findex, sindex, and vindex +% hval: (length(findex),length(sindex),length(vindex)); highest point on the axis; +% The number matches a total of findex, sindex, and vindex +% ncom: number of combined intervals. Large ncom implies large size of the bin. +% Must set ncom so that ninv can be divided +% gIndx: 1: plot graphs of pdf's; 0: no plot +%----------------- +% imfpdf: 2+ninv-by-forep*shockp*nvar. Density +% imfpo: 2+ninv-by-forep*shockp*nvar. Bin position (x-axis) in relation to imfs3 +% imfprob: 2+ninv-by-forep*shockp*nvar. Probability (NOT density) at each bin +% +% 27 August 1998 Tao Zha +% Revised, October 1998, March 1999 +% 3/24/99, added gIndx so that the previous programs may not be compatible. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +invlength = invc ./ ninv; +invlengthM = repmat(invlength,[2+ninv,1]); +invlengthM([1 2+ninv],:) = 1; + % first (-inf, low bound) and last (high bound, +inf), the interval is set + % to be 1. Of course, theoretically, the interval length should be set + % to infinity, but 1 is large enough compared with invlength. +imfprob = imfcnt ./ ndrawscnt; % probability (NOT density) +imfpdf = imfprob ./ invlengthM; % density + +imfpo = [1:2+ninv]'; % positions for each forecast +imfpo = imfpo - 2; % the first step to put back to original form +imfpo = repmat(imfpo,[1,forep*shockp*nvar]); +invcM = repmat(invc,[2+ninv,1]); +AmM = repmat(Am,[2+ninv,1]); +imfpo = ((imfpo .* invcM) ./ ninv) + AmM; % 2+ninv-by-forep*shockp*nvar + % the final step to put back to original form of impulse responses + + +if mod(ninv,ncom) + warning('Set ncom so that ninv can be divided') + return +end +% +ninv2=ninv/ncom; +imfpdfn=zeros(2+ninv2,forep*shockp*nvar); %<<>> +imfpon=imfpdfn; +% +for ik=1:ninv2 % from 2 to 1+ninv2 for imfpdfn and imfpon + imfpdfn(1+ik,:) = sum(imfpdf(1+(ik-1)*ncom+1:1+ik*ncom,:))/ncom; + imfpon(1+ik,:) = mean(imfpo(1+(ik-1)*ncom+1:1+ik*ncom,:)); +end + +imfpdf4 = reshape(imfpdfn,2+ninv2,forep,nvar,shockp); +% imfpdf3: row--bin numbers, column--steps, 3rd dim--variables(responses), 4rd dime--shocks +imfpdf4s = permute(imfpdf4,[1 2 4 3]); + % imf3pdfs: permuted so that + % row--bin numbers, column--steps, 3rd dim--shocks, 4rd dime--variables (responses) +imfpo4 = reshape(imfpon,2+ninv2,forep,nvar,shockp); +imfpo4s = permute(imfpo4,[1 2 4 3]); + + +if gIndx + ck1=0; + for k1=findex + ck1=ck1+1; + ck2=0; + for k2=sindex + ck2=ck2+1; + ck3=0; + for k3=vindex + ck3=ck3+1; + %figure + if idxuniscl + lpos = min(find(imfpo4s(2:1+ninv2,k1,k2,k3)>lval(ck1,ck2,ck3))); % low position + hpos = max(find(imfpo4s(2:1+ninv2,k1,k2,k3)<hval(ck1,ck2,ck3))); % high position + plot(imfpo4s(lpos+1:hpos+1,k1,k2,k3),imfpdf4s(lpos+1:hpos+1,k1,k2,k3)) % + % push everything forward by 1 because lpos and hpos start at 2 + set(gca,'XLim',[lval(ck1,ck2,ck3) hval(ck1,ck2,ck3)]) + grid + else + plot(imfpo4s(2:1+ninv2,k1,k2,k3),imfpdf4s(2:1+ninv2,k1,k2,k3)) % + grid + end + end + end + end +end + +%xlabel('The 1984 U Forecast') %The 1982 GDP Growth Forecast') +%set(gca,'XLim',[lval hval]) +%xact = [7.508 7.508]; %[-2.13 -2.13]; +%yact = [0 0.5]; %[0 0.5]; +%set(line(xact,yact),'Linestyle','-') +%title('Figure 8') +%line([-2 -2],[0 400]) diff --git a/MatlabFiles/histpdfg.m b/MatlabFiles/histpdfg.m index 8fd378c4686613e181d97d1b3038a91bf5061078..b7859e69c69975c0fcdee5a0c656731239f8cf86 100644 --- a/MatlabFiles/histpdfg.m +++ b/MatlabFiles/histpdfg.m @@ -1,48 +1,48 @@ -function [n,z] = histpdfg(seqdraws,binnum,titstr,xlabstr,ylabstr) -% [n,z] = histpdfg(seqdraws,binnum,titstr,xlabstr,ylabstr) -% Plot (if no nargout) and export (if nargout) pdf by scaling histogram -% of an unsorted sequence of draws -% -% seqdraws: an unordered sequence of draws -% binnum: the total number of bins in histogram, with 10 being a starting value -% titstr: title string; if [], no title -% xlabstr: xlabel string; if [], no xlab -% ylabstr: ylabel string; if [], no ylab -%-------- -% n: a vector of the number of elements in each bin or container -% z: a vector of the position of the center of the bin -% plot p.d.f. graph if no nargout -% -% October 1998 Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (nargin==2), titstr=[]; xlabstr=[]; ylabstr=[]; end - -[n,z,bw]=hist2(seqdraws,binnum); -n=(n/length(seqdraws))/bw; % make it p.d.f. -%bar(z,n) -if nargout - z=z'; - n=n'; -else - %figure - plot(z,n) - title(titstr) - xlabel(xlabstr) - ylabel(ylabstr) -end +function [n,z] = histpdfg(seqdraws,binnum,titstr,xlabstr,ylabstr) +% [n,z] = histpdfg(seqdraws,binnum,titstr,xlabstr,ylabstr) +% Plot (if no nargout) and export (if nargout) pdf by scaling histogram +% of an unsorted sequence of draws +% +% seqdraws: an unordered sequence of draws +% binnum: the total number of bins in histogram, with 10 being a starting value +% titstr: title string; if [], no title +% xlabstr: xlabel string; if [], no xlab +% ylabstr: ylabel string; if [], no ylab +%-------- +% n: a vector of the number of elements in each bin or container +% z: a vector of the position of the center of the bin +% plot p.d.f. graph if no nargout +% +% October 1998 Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (nargin==2), titstr=[]; xlabstr=[]; ylabstr=[]; end + +[n,z,bw]=hist2(seqdraws,binnum); +n=(n/length(seqdraws))/bw; % make it p.d.f. +%bar(z,n) +if nargout + z=z'; + n=n'; +else + %figure + plot(z,n) + title(titstr) + xlabel(xlabstr) + ylabel(ylabstr) +end diff --git a/MatlabFiles/histpdfg2d.m b/MatlabFiles/histpdfg2d.m index ed24a8e5277c4bf374e926398d64e41699832f82..4386708222135b077cae1294546e4f70c28eb81c 100644 --- a/MatlabFiles/histpdfg2d.m +++ b/MatlabFiles/histpdfg2d.m @@ -1,124 +1,124 @@ -function [xc,yc,z,zn] = histpdfg2D(w,n,ditp,xlabstr,ylabstr) -% histpdfg2D(w,n,ditp,xlabstr,ylabstr) -% Given 2D draws, generate 2D pdf by scaling 2D histogram -% -% w: ndraws-by-2 matrix where ndraws is # of draws and 2 variables -% n: 1-by-2 vector -- # of bins (integers in general) for both x-axis and y-axis -% ditp: number -- degrees of bicubic interpolation -% xlabstr: xlabel string; if [], no xlab -% ylabstr: ylabel string; if [], no ylab -%--------------------------------- -% xc: the position of centered bin on x-axis, from left to right. All rows are identical -% yc: the position of centered bin on y-axis, from top to bottom. All columns are identical -% z: size(xc,2)-by-size(yc,1) -- the pdf value in each rectangular cell -% zn: size(xc,2)-by-size(yc,1) -- the probability value in each rectangular cell -% if nargout==0, plot 2D p.d.f. graphics -% -% January 1999 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (size(w,2)~=2) - error('The size of 1st argument must be *-by-2 (i.e., 2 columns)') -end - -if (nargin==3), xlabstr=[]; ylabstr=[]; end - -if (length(n(:))~=2) - error('2nd argument must have exactly 2 elements') -end - -if (min(n)<3) - error('2nd argument -- bin size -- must have at least 3 for each axis') -end - -ndraws=size(w,1); - -%*** x-axis -minx = min(min(w(:,1))); -maxx = max(max(w(:,1))); -h1 = (maxx-minx)/n(1); % binwidth for x-axis -x = minx + h1*(0:n(1)); -xlen = length(x); % n(1)+1 -x(xlen) = maxx; % in case n(1) is not an integer -xc = x(1:xlen-1) + h1/2; % the position of the center of the x-bin - % 1-by-n(1) row vector: from left to right -xc = repmat(xc,[n(2) 1]); - -%*** y-axis -miny = min(min(w(:,2))); -maxy = max(max(w(:,2))); -h2 = (maxy-miny)/n(2); % binwidth for y-axis -y = miny + h2*(0:n(2)); -ylen = length(y); -y(ylen) = maxy; % in case n(2) is not an integer -yc = y(1:ylen-1) + h2/2; % the position of the center of the y-bin -yc = yc(:); % n(2)-by-1 column vector: from top to bottom -yc = repmat(yc,[1 n(1)]); - - -zn = zeros(n(2),n(1)); % the reverse of x and y is designed for mesh. - % see meshgrid to understand this. -tic -for draws=1:ndraws - k1 = floor((w(draws,1)-minx)/h1)+1; - k2 = floor((w(draws,2)-miny)/h2)+1; - % - % if k1==0 - % k1=1; - % end - % if k2==0; - % k2=1; - % end - % - if k1>n(1) - k1=n(1); - end - if k2>n(2) - k2=n(2) - end - zn(k2,k1) = zn(k2,k1)+1; -end -timeloop=toc; -disp(['Loop time -- minutes ' num2str(timeloop/60)]) - -zn = zn/ndraws; % probability in each rectangular cell - -z=zn/(h1*h2); % converted to the height of the p.d.f. - - -%*** scaled 2D histogram or p.d.f. -if (nargout==0) - %figure(1) - colormap(zeros(1,3)); % set color to black - mesh(xc,yc,z) - title('Scaled histogram or p.d.f.') - xlabel(xlabstr) - ylabel(ylabstr) -end - -%*** interpolation -if (ditp & nargout==0) - [xi,yi]=meshgrid(minx:h1/ditp:maxx,miny:h2/ditp:maxy); - zi = interp2(xc,yc,z,xi,yi,'bicubic'); - figure(30) - colormap(zeros(1,3)); % set color to black - mesh(xi,yi,zi) - title('Interpolated p.d.f.') - xlabel(xlabstr) - ylabel(ylabstr) -end \ No newline at end of file +function [xc,yc,z,zn] = histpdfg2D(w,n,ditp,xlabstr,ylabstr) +% histpdfg2D(w,n,ditp,xlabstr,ylabstr) +% Given 2D draws, generate 2D pdf by scaling 2D histogram +% +% w: ndraws-by-2 matrix where ndraws is # of draws and 2 variables +% n: 1-by-2 vector -- # of bins (integers in general) for both x-axis and y-axis +% ditp: number -- degrees of bicubic interpolation +% xlabstr: xlabel string; if [], no xlab +% ylabstr: ylabel string; if [], no ylab +%--------------------------------- +% xc: the position of centered bin on x-axis, from left to right. All rows are identical +% yc: the position of centered bin on y-axis, from top to bottom. All columns are identical +% z: size(xc,2)-by-size(yc,1) -- the pdf value in each rectangular cell +% zn: size(xc,2)-by-size(yc,1) -- the probability value in each rectangular cell +% if nargout==0, plot 2D p.d.f. graphics +% +% January 1999 by Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (size(w,2)~=2) + error('The size of 1st argument must be *-by-2 (i.e., 2 columns)') +end + +if (nargin==3), xlabstr=[]; ylabstr=[]; end + +if (length(n(:))~=2) + error('2nd argument must have exactly 2 elements') +end + +if (min(n)<3) + error('2nd argument -- bin size -- must have at least 3 for each axis') +end + +ndraws=size(w,1); + +%*** x-axis +minx = min(min(w(:,1))); +maxx = max(max(w(:,1))); +h1 = (maxx-minx)/n(1); % binwidth for x-axis +x = minx + h1*(0:n(1)); +xlen = length(x); % n(1)+1 +x(xlen) = maxx; % in case n(1) is not an integer +xc = x(1:xlen-1) + h1/2; % the position of the center of the x-bin + % 1-by-n(1) row vector: from left to right +xc = repmat(xc,[n(2) 1]); + +%*** y-axis +miny = min(min(w(:,2))); +maxy = max(max(w(:,2))); +h2 = (maxy-miny)/n(2); % binwidth for y-axis +y = miny + h2*(0:n(2)); +ylen = length(y); +y(ylen) = maxy; % in case n(2) is not an integer +yc = y(1:ylen-1) + h2/2; % the position of the center of the y-bin +yc = yc(:); % n(2)-by-1 column vector: from top to bottom +yc = repmat(yc,[1 n(1)]); + + +zn = zeros(n(2),n(1)); % the reverse of x and y is designed for mesh. + % see meshgrid to understand this. +tic +for draws=1:ndraws + k1 = floor((w(draws,1)-minx)/h1)+1; + k2 = floor((w(draws,2)-miny)/h2)+1; + % + % if k1==0 + % k1=1; + % end + % if k2==0; + % k2=1; + % end + % + if k1>n(1) + k1=n(1); + end + if k2>n(2) + k2=n(2) + end + zn(k2,k1) = zn(k2,k1)+1; +end +timeloop=toc; +disp(['Loop time -- minutes ' num2str(timeloop/60)]) + +zn = zn/ndraws; % probability in each rectangular cell + +z=zn/(h1*h2); % converted to the height of the p.d.f. + + +%*** scaled 2D histogram or p.d.f. +if (nargout==0) + %figure(1) + colormap(zeros(1,3)); % set color to black + mesh(xc,yc,z) + title('Scaled histogram or p.d.f.') + xlabel(xlabstr) + ylabel(ylabstr) +end + +%*** interpolation +if (ditp & nargout==0) + [xi,yi]=meshgrid(minx:h1/ditp:maxx,miny:h2/ditp:maxy); + zi = interp2(xc,yc,z,xi,yi,'bicubic'); + figure(30) + colormap(zeros(1,3)); % set color to black + mesh(xi,yi,zi) + title('Interpolated p.d.f.') + xlabel(xlabstr) + ylabel(ylabstr) +end diff --git a/MatlabFiles/histwpdfg.m b/MatlabFiles/histwpdfg.m index 1daa8e555fbc5bf54d2a8a2a54c8dc10a9abe60c..8cb8a2f3e005419ecb4b7729aaa2545dbf2b8a56 100644 --- a/MatlabFiles/histwpdfg.m +++ b/MatlabFiles/histwpdfg.m @@ -1,78 +1,78 @@ -function [xp,xpd,xc,w,bw] = histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) -% [xp,xpd,xc,w,bw] = histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) -% Generate probabilities and plot scaled densitys, given the unsorted draws and weights -% -% s: ndraws-by-n draws where ndraws is # of draws and n is # of series -% nbin: the number of bins (the maximum is ndraws) -% gIdx: 1 if plotting the pdf; 0 if no graph -% w (optional): ndraws-by-n (unscaled) weights where ndraws is # of draws and n is # of series -% xlabstr (optional): xlabel string -% ylabstr (optional): ylabel string -% titstr (optional): title string -%------------- -% xp: nbin-by-n: probability (not density) in the centered bin on x-axis. -% NOTE: sum(xp) must be 1 for each column -% xpd: nbin-by-n: density (not probability) in the centered bin on x-axis. -% xc: nbin-by-n: the position of centered bin on x-axis, from top to bottom. -% All columns are identical -% w: ndraws-by-n scaled weights so that sum(w)=1 for each column -% bw: bandwidth -% -% August 1999 by Tao Zha -% July 18 2000. Place w after gIdx so that previous programs need modifications accordingly. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (nargin<=4), titstr=[]; xlabstr=[]; ylabstr=[]; end -[m,n] = size(s); -if (nargin<=3) - w=ones(m,n)/m; -else - %** normalized to 1 for the probability - wsum = repmat(sum(w), [m 1]); - w = w ./ wsum; -end - -%if min(size(s))==1, s=s(:); w=w(:); end % making sure they are column vectors - -%*** the position of the center of the bin on the x-axis -mins = min(min(s)); -maxs = max(max(s)); -bw = (maxs-mins)/nbin; % binwidth for x-axis -x = mins + bw*(0:nbin); -x(end) = maxs; % in case nbin is not an integer -xc = x(1:end-1) + bw/2; % the position of the center of the x-bin -xc = xc'; % nbin-by-1 row vector: from top to bottom -xc = repmat(xc,[1 n]); % nbin-by-n, same for each column - - -%*** the probability at each bin on the x-axis -nbin = nbin+1; % + 1 to get the difference for getting probability xp -nn = zeros(nbin,n); -for i=2:nbin - for k=1:n - xidx = find(s(:,k) <= x(i)); % index for the positions - nn(i,k) = sum(w(xidx,k)); - end -end -xp = nn(2:nbin,:) - nn(1:nbin-1,:); -xpd = xp/bw; % the density, NOT the probability as xp - -if gIdx - plot(xc,xpd) - title(titstr), xlabel(xlabstr), ylabel(ylabstr); -end +function [xp,xpd,xc,w,bw] = histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) +% [xp,xpd,xc,w,bw] = histwpdfg(s,nbin,gIdx,w,xlabstr,ylabstr,titstr) +% Generate probabilities and plot scaled densitys, given the unsorted draws and weights +% +% s: ndraws-by-n draws where ndraws is # of draws and n is # of series +% nbin: the number of bins (the maximum is ndraws) +% gIdx: 1 if plotting the pdf; 0 if no graph +% w (optional): ndraws-by-n (unscaled) weights where ndraws is # of draws and n is # of series +% xlabstr (optional): xlabel string +% ylabstr (optional): ylabel string +% titstr (optional): title string +%------------- +% xp: nbin-by-n: probability (not density) in the centered bin on x-axis. +% NOTE: sum(xp) must be 1 for each column +% xpd: nbin-by-n: density (not probability) in the centered bin on x-axis. +% xc: nbin-by-n: the position of centered bin on x-axis, from top to bottom. +% All columns are identical +% w: ndraws-by-n scaled weights so that sum(w)=1 for each column +% bw: bandwidth +% +% August 1999 by Tao Zha +% July 18 2000. Place w after gIdx so that previous programs need modifications accordingly. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (nargin<=4), titstr=[]; xlabstr=[]; ylabstr=[]; end +[m,n] = size(s); +if (nargin<=3) + w=ones(m,n)/m; +else + %** normalized to 1 for the probability + wsum = repmat(sum(w), [m 1]); + w = w ./ wsum; +end + +%if min(size(s))==1, s=s(:); w=w(:); end % making sure they are column vectors + +%*** the position of the center of the bin on the x-axis +mins = min(min(s)); +maxs = max(max(s)); +bw = (maxs-mins)/nbin; % binwidth for x-axis +x = mins + bw*(0:nbin); +x(end) = maxs; % in case nbin is not an integer +xc = x(1:end-1) + bw/2; % the position of the center of the x-bin +xc = xc'; % nbin-by-1 row vector: from top to bottom +xc = repmat(xc,[1 n]); % nbin-by-n, same for each column + + +%*** the probability at each bin on the x-axis +nbin = nbin+1; % + 1 to get the difference for getting probability xp +nn = zeros(nbin,n); +for i=2:nbin + for k=1:n + xidx = find(s(:,k) <= x(i)); % index for the positions + nn(i,k) = sum(w(xidx,k)); + end +end +xp = nn(2:nbin,:) - nn(1:nbin-1,:); +xpd = xp/bw; % the density, NOT the probability as xp + +if gIdx + plot(xc,xpd) + title(titstr), xlabel(xlabstr), ylabel(ylabstr); +end diff --git a/MatlabFiles/histwpdfg2d.m b/MatlabFiles/histwpdfg2d.m index 8362c7d196324350c7b75f39d47948860f1c617b..3ad73c7ba86dc03ba214f140315c0babc5d47380 100644 --- a/MatlabFiles/histwpdfg2d.m +++ b/MatlabFiles/histwpdfg2d.m @@ -1,127 +1,127 @@ -function [xc,yc,z,zn] = histwpdfg2D(s,w,n,ditp,xlabstr,ylabstr) -% [xc,yc,z,zn] = histwpdfg2D(s,w,n,ditp,xlabstr,ylabstr) -% Given uneven weights and 2D draws, generate 2D pdf and probabilites by scaling 2D histogram -% -% s: ndraws-by-2 matrix where ndraws is # of draws and 2 variables -% w: ndraws-by-1 vector of (uneven) weights -% n: 1-by-2 vector -- # of bins (integers in general) for both x-axis and y-axis -% ditp: number -- degrees of bicubic interpolation -% xlabstr: xlabel string; if [], no xlab -% ylabstr: ylabel string; if [], no ylab -%--------------------------------- -% xc: the position of centered bin on x-axis, from left to right. All rows are identical -% yc: the position of centered bin on y-axis, from top to bottom. All columns are identical -% z: size(xc,2)-by-size(yc,1) -- the pdf value in each rectangular cell -% zn: size(xc,2)-by-size(yc,1) -- the probability value in each rectangular cell -% if nargout==0, plot 2D p.d.f. graphics -% -% January 1999 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if (size(s,2)~=2) - error('The size of 1st argument must be *-by-2 (i.e., 2 columns)') -end - -if (nargin==3), xlabstr=[]; ylabstr=[]; end - -if (length(n(:))~=2) - error('2nd argument must have exactly 2 elements') -end - -if (min(n)<3) - error('2nd argument -- bin size -- must have at least 3 for each axis') -end - -ndraws=size(s,1); - -%** normalized to 1 for the probability -w=w(:); % make sure it's a column vector -w = w/sum(w); - -%*** x-axis -minx = min(min(s(:,1))); -maxx = max(max(s(:,1))); -h1 = (maxx-minx)/n(1); % binwidth for x-axis -x = minx + h1*(0:n(1)); -xlen = length(x); % n(1)+1 -x(xlen) = maxx; % in case n(1) is not an integer -xc = x(1:xlen-1) + h1/2; % the position of the center of the x-bin - % 1-by-n(1) row vector: from left to right -xc = repmat(xc,[n(2) 1]); - -%*** y-axis -miny = min(min(s(:,2))); -maxy = max(max(s(:,2))); -h2 = (maxy-miny)/n(2); % binwidth for y-axis -y = miny + h2*(0:n(2)); -ylen = length(y); -y(ylen) = maxy; % in case n(2) is not an integer -yc = y(1:ylen-1) + h2/2; % the position of the center of the y-bin -yc = yc(:); % n(2)-by-1 column vector: from top to bottom -yc = repmat(yc,[1 n(1)]); - - -zn = zeros(n(2),n(1)); % the reverse of x and y is designed for mesh. - % see meshgrid to understand this. -tic -for draws=1:ndraws - k1 = floor((s(draws,1)-minx)/h1)+1; - k2 = floor((s(draws,2)-miny)/h2)+1; - % - % if k1==0 - % k1=1; - % end - % if k2==0; - % k2=1; - % end - % - if k1>n(1) - k1=n(1); - end - if k2>n(2) - k2=n(2) - end - zn(k2,k1) = zn(k2,k1)+w(draws); % probability in each rectangular cell -end -timeloop=toc; -disp(['Loop time -- minutes ' num2str(timeloop/60)]) - -z=zn/(h1*h2); % converted to the height of the p.d.f. - - -%*** scaled 2D histogram or p.d.f. -if (nargout==0) - %figure(1) - colormap(zeros(1,3)); % set color to black - mesh(xc,yc,z) - title('Scaled histogram or p.d.f.') - xlabel(xlabstr) - ylabel(ylabstr) -end - -%*** interpolation -if (ditp & nargout==0) - [xi,yi]=meshgrid(minx:h1/ditp:maxx,miny:h2/ditp:maxy); - zi = interp2(xc,yc,z,xi,yi,'bicubic'); - figure(30) - colormap(zeros(1,3)); % set color to black - mesh(xi,yi,zi) % or mesh - title('Interpolated p.d.f.') - xlabel(xlabstr) - ylabel(ylabstr) -end \ No newline at end of file +function [xc,yc,z,zn] = histwpdfg2D(s,w,n,ditp,xlabstr,ylabstr) +% [xc,yc,z,zn] = histwpdfg2D(s,w,n,ditp,xlabstr,ylabstr) +% Given uneven weights and 2D draws, generate 2D pdf and probabilites by scaling 2D histogram +% +% s: ndraws-by-2 matrix where ndraws is # of draws and 2 variables +% w: ndraws-by-1 vector of (uneven) weights +% n: 1-by-2 vector -- # of bins (integers in general) for both x-axis and y-axis +% ditp: number -- degrees of bicubic interpolation +% xlabstr: xlabel string; if [], no xlab +% ylabstr: ylabel string; if [], no ylab +%--------------------------------- +% xc: the position of centered bin on x-axis, from left to right. All rows are identical +% yc: the position of centered bin on y-axis, from top to bottom. All columns are identical +% z: size(xc,2)-by-size(yc,1) -- the pdf value in each rectangular cell +% zn: size(xc,2)-by-size(yc,1) -- the probability value in each rectangular cell +% if nargout==0, plot 2D p.d.f. graphics +% +% January 1999 by Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if (size(s,2)~=2) + error('The size of 1st argument must be *-by-2 (i.e., 2 columns)') +end + +if (nargin==3), xlabstr=[]; ylabstr=[]; end + +if (length(n(:))~=2) + error('2nd argument must have exactly 2 elements') +end + +if (min(n)<3) + error('2nd argument -- bin size -- must have at least 3 for each axis') +end + +ndraws=size(s,1); + +%** normalized to 1 for the probability +w=w(:); % make sure it's a column vector +w = w/sum(w); + +%*** x-axis +minx = min(min(s(:,1))); +maxx = max(max(s(:,1))); +h1 = (maxx-minx)/n(1); % binwidth for x-axis +x = minx + h1*(0:n(1)); +xlen = length(x); % n(1)+1 +x(xlen) = maxx; % in case n(1) is not an integer +xc = x(1:xlen-1) + h1/2; % the position of the center of the x-bin + % 1-by-n(1) row vector: from left to right +xc = repmat(xc,[n(2) 1]); + +%*** y-axis +miny = min(min(s(:,2))); +maxy = max(max(s(:,2))); +h2 = (maxy-miny)/n(2); % binwidth for y-axis +y = miny + h2*(0:n(2)); +ylen = length(y); +y(ylen) = maxy; % in case n(2) is not an integer +yc = y(1:ylen-1) + h2/2; % the position of the center of the y-bin +yc = yc(:); % n(2)-by-1 column vector: from top to bottom +yc = repmat(yc,[1 n(1)]); + + +zn = zeros(n(2),n(1)); % the reverse of x and y is designed for mesh. + % see meshgrid to understand this. +tic +for draws=1:ndraws + k1 = floor((s(draws,1)-minx)/h1)+1; + k2 = floor((s(draws,2)-miny)/h2)+1; + % + % if k1==0 + % k1=1; + % end + % if k2==0; + % k2=1; + % end + % + if k1>n(1) + k1=n(1); + end + if k2>n(2) + k2=n(2) + end + zn(k2,k1) = zn(k2,k1)+w(draws); % probability in each rectangular cell +end +timeloop=toc; +disp(['Loop time -- minutes ' num2str(timeloop/60)]) + +z=zn/(h1*h2); % converted to the height of the p.d.f. + + +%*** scaled 2D histogram or p.d.f. +if (nargout==0) + %figure(1) + colormap(zeros(1,3)); % set color to black + mesh(xc,yc,z) + title('Scaled histogram or p.d.f.') + xlabel(xlabstr) + ylabel(ylabstr) +end + +%*** interpolation +if (ditp & nargout==0) + [xi,yi]=meshgrid(minx:h1/ditp:maxx,miny:h2/ditp:maxy); + zi = interp2(xc,yc,z,xi,yi,'bicubic'); + figure(30) + colormap(zeros(1,3)); % set color to black + mesh(xi,yi,zi) % or mesh + title('Interpolated p.d.f.') + xlabel(xlabstr) + ylabel(ylabstr) +end diff --git a/MatlabFiles/imc2errgraph.m b/MatlabFiles/imc2errgraph.m index 82b19c11944731c18d06bfbb6105a4b8de509f4b..c87fc0b350d37954a41b70ea23a2f7003f4e5b54 100644 --- a/MatlabFiles/imc2errgraph.m +++ b/MatlabFiles/imc2errgraph.m @@ -1,120 +1,120 @@ -function scaleout = imc2errgraph(imf,firstl1,firsth1,... - firstl,firsth,nvar,imstp,xlab,ylab,XTick) -% scaleout = imc2errgraph(imf,firstl1,firsth1,... -% firstl,firsth,nvar,imstp,xlab,ylab,XTick) -% imc2errgraph: impulse, c (column: shock 1 to N), 2 error bands, graph -% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock -% etc), row (impusle steps), -% firstl1: lower band, .68 -% highth1: high band, .68 -% firstl: lower band, .90 -% highth: high band, .90 -% nvar: number of variables -% imstp: step of impulse responses -% xlab,ylab: labels -% Xtick: tick on x-axis; e.g., [1 12 36]; if [], no ticks -%----------------------- -% scaleout: gives out max and min for each row of graphs -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -maxval=zeros(nvar,1); -minval=zeros(nvar,1); -for i = 1:nvar - for j = 1:nvar - jnk1=max(firsth(:,(j-1)*nvar+i)); - jnk2=max(firstl(:,(j-1)*nvar+i)); - jnk3=max(firsth1(:,(j-1)*nvar+i)); - jnk4=max(firstl1(:,(j-1)*nvar+i)); - jnk5=max(imf(:,(j-1)*nvar+i)); - - temp1(j)=max([jnk1 jnk2 jnk3 jnk4 jnk5]); - % - jnk1=min(firstl(:,(j-1)*nvar+i)); - jnk2=min(firsth(:,(j-1)*nvar+i)); - jnk3=min(firstl1(:,(j-1)*nvar+i)); - jnk4=min(firsth1(:,(j-1)*nvar+i)); - jnk5=min(imf(:,(j-1)*nvar+i)); - - temp2(j)=min([jnk1 jnk2 jnk3 jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -%figure -rowlabel = 1; -for i = 1:nvar - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - scale=[1 imstp minval(i) maxval(i)]; - for j = 1:nvar - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,[firstl1(:,k2) firsth1(:,k2)],'--',... - t,[firstl(:,k2) firsth(:,k2)],'-.',t,zeros(length(imf(:,k2)),1),'-'); - grid; - axis(scale); - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - set(gca,'YTick',yt) - if i<nvar - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if j>1 - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; -end \ No newline at end of file +function scaleout = imc2errgraph(imf,firstl1,firsth1,... + firstl,firsth,nvar,imstp,xlab,ylab,XTick) +% scaleout = imc2errgraph(imf,firstl1,firsth1,... +% firstl,firsth,nvar,imstp,xlab,ylab,XTick) +% imc2errgraph: impulse, c (column: shock 1 to N), 2 error bands, graph +% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock +% etc), row (impusle steps), +% firstl1: lower band, .68 +% highth1: high band, .68 +% firstl: lower band, .90 +% highth: high band, .90 +% nvar: number of variables +% imstp: step of impulse responses +% xlab,ylab: labels +% Xtick: tick on x-axis; e.g., [1 12 36]; if [], no ticks +%----------------------- +% scaleout: gives out max and min for each row of graphs +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +maxval=zeros(nvar,1); +minval=zeros(nvar,1); +for i = 1:nvar + for j = 1:nvar + jnk1=max(firsth(:,(j-1)*nvar+i)); + jnk2=max(firstl(:,(j-1)*nvar+i)); + jnk3=max(firsth1(:,(j-1)*nvar+i)); + jnk4=max(firstl1(:,(j-1)*nvar+i)); + jnk5=max(imf(:,(j-1)*nvar+i)); + + temp1(j)=max([jnk1 jnk2 jnk3 jnk4 jnk5]); + % + jnk1=min(firstl(:,(j-1)*nvar+i)); + jnk2=min(firsth(:,(j-1)*nvar+i)); + jnk3=min(firstl1(:,(j-1)*nvar+i)); + jnk4=min(firsth1(:,(j-1)*nvar+i)); + jnk5=min(imf(:,(j-1)*nvar+i)); + + temp2(j)=min([jnk1 jnk2 jnk3 jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +%figure +rowlabel = 1; +for i = 1:nvar + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + scale=[1 imstp minval(i) maxval(i)]; + for j = 1:nvar + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,[firstl1(:,k2) firsth1(:,k2)],'--',... + t,[firstl(:,k2) firsth(:,k2)],'-.',t,zeros(length(imf(:,k2)),1),'-'); + grid; + axis(scale); + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + set(gca,'YTick',yt) + if i<nvar + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if j>1 + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/imcerrgraph.m b/MatlabFiles/imcerrgraph.m index 2e3b620d35e5b1ca665af38f7572b58dfdbe9dc1..607f50ad18ad9581d0f9b587dd2c328d17cb24b8 100644 --- a/MatlabFiles/imcerrgraph.m +++ b/MatlabFiles/imcerrgraph.m @@ -1,75 +1,75 @@ -function scaleout = imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab) -% function scaleout = imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab) -% imcerrgraph: impulse, c (column: shock 1 to N), error bands, graph -% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock -% etc), row (impusle steps), -% firstl: lower band -% highth: high band -% nvar: number of variables -% imstp: step of impulse responses -% xlab,ylab: labels -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -maxval=zeros(nvar,1); -minval=zeros(nvar,1); -for i = 1:nvar - for j = 1:nvar - temp1(j)=max(firsth(:,(j-1)*nvar+i)); - temp2(j)=min(firstl(:,(j-1)*nvar+i)); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -figure -rowlabel = 1; -for i = 1:nvar - columnlabel = 1; - for j = 1:nvar - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,[firstl(:,k2) firsth(:,k2)],':',... - t,zeros(length(imf(:,k2)),1),'-'); - set(gca,'YLim',[minval(i) maxval(i)]) - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; -end \ No newline at end of file +function scaleout = imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab) +% function scaleout = imcerrgraph(imf,firstl,firsth,nvar,imstp,xlab,ylab) +% imcerrgraph: impulse, c (column: shock 1 to N), error bands, graph +% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock +% etc), row (impusle steps), +% firstl: lower band +% highth: high band +% nvar: number of variables +% imstp: step of impulse responses +% xlab,ylab: labels +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +maxval=zeros(nvar,1); +minval=zeros(nvar,1); +for i = 1:nvar + for j = 1:nvar + temp1(j)=max(firsth(:,(j-1)*nvar+i)); + temp2(j)=min(firstl(:,(j-1)*nvar+i)); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +figure +rowlabel = 1; +for i = 1:nvar + columnlabel = 1; + for j = 1:nvar + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,[firstl(:,k2) firsth(:,k2)],':',... + t,zeros(length(imf(:,k2)),1),'-'); + set(gca,'YLim',[minval(i) maxval(i)]) + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/imcgraph.m b/MatlabFiles/imcgraph.m index 568daae11a27943e54dc67a38e604ab42a9e7dbd..3e3dfb8f93868d8664d8bbb4b2cd529f5439def2 100644 --- a/MatlabFiles/imcgraph.m +++ b/MatlabFiles/imcgraph.m @@ -1,80 +1,80 @@ -function scaleout = imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml) -% scaleout = imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml) -% imcgraph: impulse, c (column: shock 1 to N), graph -% Graph the ML point impulse response -% -% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock -% etc), row (impusle steps), -% nvar: number of variables -% imstp: step of impulse responses -% xlab,ylab: labels -% indxGimfml: 1, graph; 0, no graph -% -% NOTE: I added "indxGimfml" so this function may not be compatible with programs -% older than 03/06/99, TZ -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -maxval=zeros(nvar,1); -minval=zeros(nvar,1); -for i = 1:nvar - for j = 1:nvar - temp1(j)=max(imf(:,(j-1)*nvar+i)); - temp2(j)=min(imf(:,(j-1)*nvar+i)); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -if indxGimfml - figure(1) - rowlabel = 1; - for i = 1:nvar - columnlabel = 1; - for j = 1:nvar - k1=(i-1)*nvar+j; - k2=(j-1)*nvar+i; - subplot(nvar,nvar,k1) - plot(t,imf(:,k2),t,zeros(length(imf(:,k2)),1),':'); - set(gca,'YLim',[minval(i) maxval(i)]) - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; - end -end \ No newline at end of file +function scaleout = imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml) +% scaleout = imcgraph(imf,nvar,imstp,xlab,ylab,indxGimfml) +% imcgraph: impulse, c (column: shock 1 to N), graph +% Graph the ML point impulse response +% +% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock +% etc), row (impusle steps), +% nvar: number of variables +% imstp: step of impulse responses +% xlab,ylab: labels +% indxGimfml: 1, graph; 0, no graph +% +% NOTE: I added "indxGimfml" so this function may not be compatible with programs +% older than 03/06/99, TZ +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +maxval=zeros(nvar,1); +minval=zeros(nvar,1); +for i = 1:nvar + for j = 1:nvar + temp1(j)=max(imf(:,(j-1)*nvar+i)); + temp2(j)=min(imf(:,(j-1)*nvar+i)); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +if indxGimfml + figure(1) + rowlabel = 1; + for i = 1:nvar + columnlabel = 1; + for j = 1:nvar + k1=(i-1)*nvar+j; + k2=(j-1)*nvar+i; + subplot(nvar,nvar,k1) + plot(t,imf(:,k2),t,zeros(length(imf(:,k2)),1),':'); + set(gca,'YLim',[minval(i) maxval(i)]) + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; + end +end diff --git a/MatlabFiles/imfsim.m b/MatlabFiles/imfsim.m index 600cfc073fef56a9a1aa6196358abd6a04a4d5a1..e0ceea08ca458b74c78ddba9001e8cbb6a96425f 100644 --- a/MatlabFiles/imfsim.m +++ b/MatlabFiles/imfsim.m @@ -1,346 +1,346 @@ -function imfsim(xinput) -% imfsim(xinput) -% Save the simulated pdfs of impulse responses; -% Print and save Gelman's measures of B and W for A0's, -% only when nstarts (# of starting points) >1. -% Ref: Waggoner and Zha "Does Normalization Matter for Inference" -% See note Forecast (2) -% -% xinput{1}: nfp -- total number of free parameters -% xinput{2}: nvar -- number of variables -% xinput{3}: xhat -- ML estimate of free parameters in A0 -% xinput{4}: hess -- Hessian of -logLH -% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest -% to select variables, always check idmat0 to make sure -% it plots: (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, -% (2) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences -% (5) scattered plot of 1st and 2nd for al sequences. -% xinput{6}: IndxGraph - 1: plot graphs; 0: no graphs -% xinput{7}: idmat0 -- Index for non-zero elements in A0 with column to equation -% xinput{8}: nstarts -- # of starting points in Gibbs sampling -% xinput{9}: ndraws1 -- # of 1st loop to be discarded -% xinput{10}: ndraws2 -- # of 2nd loop for saving A0 draws -% xinput{11}: imndraws=nstarts*ndraws2 -% xinput{12}: a0indx -- index number for non-zero elements in A0 -% xinput{13}: tdf -- degrees of freedom for t-distribution -% xinput{14}: nbuffer -- interval for printing, plotting, and saving -% xinput{15}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation -% Already divided by "fss." -% xinput{16}: nSample -- the original sample size including lags -% xinput{17}: IndxNmlr -- index for which normalization rule to choose -% xinput{18}: IndxGibbs -- index for WZ Gibbs; 1; Gibbs; 0: Metropolis -% xinput{19}: scf -- reduction scale factor for Metropolis jumping kernel -% xinput{20}: H_sr -- square root of the inverse of the covariance matrix -% for free elements in A0 (nfp-by-nfp) -% xinput{21}: fss -- effective sample size == nSample-lags+# of dummy observations -% xinput{22}: idfile1 -- calls "iden6std." Save stds. of both data and impulse responses in idfile1 -% xinput{23}: xxhpc -- chol(X'X+inv(H_p_tilde)): upper triangular but its transpose -% is lower triagular Choleski -% xinput{24}: ImfErr -- if 1, impulse response simulation; if 0, disable this simulation -% xinput{25}: ninv -- number of bins pre-specified to put each draw of impulse response -% into a proper bin (or small interval) -% xinput{26}: imstp -- # of steps for impulse responses -% xinput{27}: forep -- forecast periods (# of steps) -% xinput{28}: yact -- actual data (in log except R, U, etc.) -% xinput{29}: yactqg -- quarterly annualized growth in actual data -% xinput{30}: yactCalyg -- calendar annual growth in actual data -% xinput{31}: imfml -- imstp-by-nvar^2 ML impulse responses -% xinput{32}: forepq -- forecast periods for quarterly growth -% xinput{33}: forepy -- forecast periods for annual growth -% xinput{34}: ncoef -- k: # of coeffients per equation -% xinput{35}: Bhml -- ML reduced form parameter B (nvar-by-k) -% xinput{36}: lags -- # of lags -%------------------ -% imfcntmulti: (ninv+2,imstp*nvar^2,nstarts) matrix -% cnt: count; for impulse responses; multi (nstarts) sequences -% All output is saved in outB_W, including Range5, invc, ninv, and imfcntmulti -% -% Written by T. Zha 1999 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess=xinput{4}; Indxv=xinput{5}; -IndxGraph=xinput{6}; idmat0=xinput{7}; nstarts=xinput{8}; ndraws1=xinput{9}; ndraws2=xinput{10}; -imndraws=xinput{11}; a0indx=xinput{12}; tdf=xinput{13}; nbuffer=xinput{14}; Sbd=xinput{15}; -nSample = xinput{16}; IndxNmlr=xinput{17}; IndxGibbs=xinput{18}; scf=xinput{19}; H_sr=xinput{20}; -fss=xinput{21}; idfile1=xinput{22}; xxhpc=xinput{23}; ImfErr=xinput{24}; ninv=xinput{25}; -imstp=xinput{26}; forep=xinput{27}; yact=xinput{28}; yactqg=xinput{29}; yactCalyg=xinput{30}; -imfml=xinput{31}; forepq=xinput{32}; forepy=xinput{33}; ncoef=xinput{34}; Bhml=xinput{35}; -lags=xinput{36}; - -Avhx_bs = zeros(nfp,1); -Avhx_bm = zeros(nfp,1); -Avhx_bj = zeros(nfp,1); -Avhx_cj = zeros(nfp,1); -Avhx_cm = zeros(nfp,1); -A0_h = zeros(nvar); -A0gbs = A0_h; % drawn A0 in Gibbs sampling -Avhxm = zeros(nfp,1); -Avhxs = Avhxm; -A0xhat = zeros(nvar); -A0xhat(a0indx) = xhat; -% A0hatw = zeros(nvar^2,nbuffer); - -countJump = zeros(nstarts,1); - -imfmean = zeros(imstp,nvar^2); -imfcntmulti = zeros(ninv+2,imstp*nvar^2,nstarts); - % cnt: count; for impulse responses; multi (nstarts) sequences - - -%--------------------------------------------------- -% Specify the range for counting the empirical distribution -% -%** load the standard deviations of 6 variables, one for log(y), one for gq, and -%** the third one for yg -eval(['load ' idfile1 '.prn -ascii']); -eval(['ABstd=' idfile1 ';']); -Range5 = cell(4,1); % 4: log, qg, yg, and imf - -%@@@ Tony's trick to expand the matrix -% -%** In order of log(y), qg, and yg for Range5{i} for i=1:3 -Range5{1} =zeros(forep,nvar,2); % 2: min and max -Range5{1}(:,:,1) = repmat(yact(length(yact(:,1)),:)-10*ABstd(1,:),[forep 1]); % min, 30 std. -Range5{1}(:,:,2) = repmat(yact(length(yact(:,1)),:)+10*ABstd(1,:),[forep 1]); % max, 30 std. -% -Range5{2} =zeros(forepq,nvar,2); % 2: min and max -Range5{2}(:,:,1) = repmat(yactqg(length(yactqg(:,1)),:)-10*ABstd(2,:),[forepq 1]); % min, 30 std. -Range5{2}(:,:,2) = repmat(yactqg(length(yactqg(:,1)),:)+10*ABstd(2,:),[forepq 1]); % max, 30 std. -% -Range5{3} =zeros(forepy,nvar,2); % 2: min and max -Range5{3}(:,:,1) = repmat(yactCalyg(length(yactCalyg(:,1)),:)-10*ABstd(3,:),[forepy 1]); % min, 30 std. -Range5{3}(:,:,2) = repmat(yactCalyg(length(yactCalyg(:,1)),:)+10*ABstd(3,:),[forepy 1]); % max, 30 std. -% -Range5{4} =zeros(imstp,nvar^2,2); % 2: min and max -imfscale = repmat(ABstd(4,:),[1 nvar]); % because nvar variables to 1, ..., nvar shocks -Range5{4}(:,:,1) = repmat(imfml(1,:)-5*imfscale,[imstp 1]); % min, 5 std. -Range5{4}(:,:,2) = repmat(imfml(1,:)+5*imfscale,[imstp 1]); % max, 5 std. - % Range5(4)(:,:,1): imstp-by-nvar^2. Column: nvar responses to 1st shock, - % nvar responses to 2nd shock, ... -%** -invc = cell(4,1); % interval length (used for counting later). 1st 3 cells have each - % forep-by-nvar, and 4th has imstp-by-nvar^2. -for i=1:4 - invc{i} = Range5{i}(:,:,2) - Range5{i}(:,:,1); -end -hbin = invc{4} ./ ninv; % bin size for each point of impulse responses kkdf -imfloor = Range5{4}(:,:,1); - - - -%=================================== -% Here begins with the big loop -%=================================== -H1 = chol(hess); % upper triangular so that H1' is a lower triangular decomp -baseW = H_sr; %inv(H1); %H_sr; % covariance matrix without scaling -nswitch=0; %<<>> total number of sign switches -A0inxhat = inv(A0xhat); % inverse of ML estimate -a0indx0 = find(idmat0==0); % index for all zero's in A0; -nn=[nvar lags imstp]; - -[cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss); - -tic -for starts = 1:nstarts - starts - if starts == 1 - A0gbs(a0indx) = xhat; % from "load ..." - if ~IndxGibbs % Metropolist - Avhx = xhat; - hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); - hAvhx = -hAvhx; % converted to logLH - end - else - Avhx = baseW*randn(nfp,1); %H_sr*randn(nfp,1); % D: discarded sequence - csq=randn(tdf,1); - csq=sum(csq .* csq); - Avhx = xhat+Avhx/sqrt(csq/tdf); - %** Normalization by the choice of IndxNmlr - A0gbs(a0indx) = Avhx; - if ~IndxNmlr(5) - [A0gbs,jnk] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); - else - A0ingbs = inv(A0gbs); - [A0gbs,jnk,jnk1] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); - end - % - if ~IndxGibbs % Metropolist - Avhx = A0gbs(a0indx); - hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); - hAvhx = -hAvhx; % converted to logLH - end - end - % - Avhxmm = zeros(nfp,1); - Avhxss = zeros(nfp,1); - cJump = 0; - imfcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count; for impulse responses - - for draws = 1:ndraws1 - if IndxGibbs - A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); - else % Metropolis - [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... - baseW,nfp,Sbd,fss,nvar,a0indx); - end - end - - wdraws=(starts-1)*ndraws2+0; - for draws = 1:ndraws2 - drawsc = (starts-1)*ndraws2+draws; - if IndxGibbs - A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); - A0gbs(a0indx0) = 0; % set all zeros in A0gbs clean to avoid possible cumulative round-off errors - else % Metropolis - [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... - baseW,nfp,Sbd,fss,nvar,a0indx); - A0gbs(a0indx) = Avhx; - end - - %*** call normalization so that A0_h is normalized - if ~IndxNmlr(5) - [A0_h,nswitch] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); - A0_hin = inv(A0_h); - else - A0ingbs = inv(A0gbs); - [A0_h,nswitch,A0_hin] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); - end - Avhx_norm = A0_h(a0indx); - - % - % *** normal draws for posterior Aplus conditional on A0h - % - %** the mean is Aplushm, and the covariance is inv(xxhp)=Lxxhpc*Lxxhpc' - Apindm = randn(ncoef,nvar); - % - if ~all(all(finite(Bhml))) - Aplushm=zeros(ncoef,nvar); - for i=1:nvar - Aplushm(:,i)=Gb{i}*A0_h(:,i); % see Zha's forecast (1) p.9 - % Here, Gb is used to compute A+ where A+(i) = Gb(i)*a0(i) - end - Bh_h = (Aplushm + xxhpc\Apindm)*A0_hin; - else - Bh_h = Bhml + (xxhpc\Apindm)*A0_hin; - end - - if ImfErr - swish_h = A0_hin'; % Switching back to the form A0*y(t) = e(t) - imf_h = zimpulse(Bh_h,swish_h,nn); % in the form that is congenial to RATS - % imf3_h=reshape(imf_h,size(imf_h,1),nvar,nvar); - % % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks - imfmean = imfmean + imf_h; % posterior mean - imfcnt = empdfsort(imfcnt,imf_h,imfloor,hbin,ninv); - % sorted counts (prob.) in bins - end - - Avhxm = Avhxm + Avhx_norm; % 1st step to overall mean of parameter - Avhxs = Avhxs + Avhx_norm.^2; % 1st step to overall 2nd moment of parameter - - %* compute the mean and 2nd moment - %** Getting average of variances W and variance of means B/n -- B_n - %* see Gelman, p.331, my Shock(0), 12-13, and my Forecast (2), 28-31 - if (nstarts>1) - Avhxmm = Avhxmm + Avhx_norm; % n*(phi_.j) - Avhxss = Avhxss + Avhx_norm.^2; % 1st step to (phi_ij) for fixed j - end - - % A0hatw(:,drawsc-wdraws) = A0_h(:); - if ~mod(draws,nbuffer) - starts - draws - wdraws=drawsc - % fwriteid = fopen('outA0.bin','a'); - % count = fwrite(fwriteid,A0hatw,'double'); - % status = fclose('all'); - end - end - % - imfcntmulti(:,:,starts) = imfcnt; - - if ~IndxGibbs - countJump(starts,1) = cJump; - end - % - %** Getting average of variances W and variance of means B/n -- B_n - %** see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 - if (nstarts>1) - Avhx_aj = Avhxmm/ndraws2; % (phi_.j) - Avhx_bs = Avhx_bs + Avhx_aj.^2; % 1st step to 2nd moment of (phi_.j) - Avhx_bm = Avhx_bm + Avhx_aj; % 1st step to (phi_..) - % - Avhx_bj = Avhxss/ndraws2; % 2nd moment of (phi_ij) for fixed j - Avhx_cj = Avhx_bj - Avhx_aj.^2; % ((n-1)/n)*S^2_j - Avhx_cm = Avhx_cm + Avhx_cj; % sum of ((n-1)/n)*S^2_j across j - end -end -timend = toc -timeminutes=timend/60 - -if ~IndxGibbs - countJump = countJump/ndraws2 -end - -Avhxm = Avhxm/(imndraws); -Avhxs = Avhxs/(imndraws); -Avhxv = Avhxs - Avhxm.^2; -Avhxs = sqrt(Avhxv); % stardard deviation -A0hm = zeros(nvar); -A0hm(a0indx) = Avhxm % mean -A0hv = zeros(nvar); -A0hv(a0indx) = Avhxv; % varaince matrix -A0hs = zeros(nvar); -A0hs(a0indx) = Avhxs; % standar deviation - -imfmean = imfmean/(imndraws); - -%**** Getting Within-Sequence W and Between-Sequence B_n -% see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 -if (nstarts>1) - AvhxW = (ndraws2/(ndraws2-1))*Avhx_cm/nstarts; - % W: average of j within-sequence variances - AvhxB_n = (nstarts/(nstarts-1)) * ( Avhx_bs/nstarts - (Avhx_bm/nstarts).^2 ); - % B/n: variance of J within-sequence means - AvhxB = ndraws2*AvhxB_n; % B - % - B_W1 = AvhxB ./ AvhxW; - B1 = AvhxB; - W1 = AvhxW; - GR1 = sqrt((ndraws2-1)/ndraws2 + B_W1/ndraws2); - % measure of Gelman reduction; need not be 1 to be accurate, - % contrary to what Gelman claims - save outB_W B_W1 B1 W1 GR1 nstarts ndraws2 imndraws timeminutes Avhxs ... - A0xhat A0hm A0hs A0hv IndxGibbs countJump - if ImfErr - save outB_W nswitch imfml imfmean imfcntmulti Range5 ninv invc imstp nvar -append - end - - titstr = ['J ' num2str(nstarts) ' n1 ' num2str(ndraws1) ... - ' n2 ' num2str(ndraws2) ' timend minutes ' num2str(timend/60)]; - disp(' ') - disp(titstr) - disp('B/W sqrt(B) sqrt(W) Std(A0) GR') - format short g - [B_W1 sqrt(B1) sqrt(W1) Avhxs GR1] -else - save outB_W nstarts ndraws1 ndraws2 imndraws timeminutes Avhxs ... - A0xhat A0hm A0hs A0hv IndxGibbs countJump - if ImfErr - save outB_W nswitch imfml imfmean imfcntmulti Range5 ninv invc imstp nvar -append - end -end +function imfsim(xinput) +% imfsim(xinput) +% Save the simulated pdfs of impulse responses; +% Print and save Gelman's measures of B and W for A0's, +% only when nstarts (# of starting points) >1. +% Ref: Waggoner and Zha "Does Normalization Matter for Inference" +% See note Forecast (2) +% +% xinput{1}: nfp -- total number of free parameters +% xinput{2}: nvar -- number of variables +% xinput{3}: xhat -- ML estimate of free parameters in A0 +% xinput{4}: hess -- Hessian of -logLH +% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest +% to select variables, always check idmat0 to make sure +% it plots: (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, +% (2) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences +% (5) scattered plot of 1st and 2nd for al sequences. +% xinput{6}: IndxGraph - 1: plot graphs; 0: no graphs +% xinput{7}: idmat0 -- Index for non-zero elements in A0 with column to equation +% xinput{8}: nstarts -- # of starting points in Gibbs sampling +% xinput{9}: ndraws1 -- # of 1st loop to be discarded +% xinput{10}: ndraws2 -- # of 2nd loop for saving A0 draws +% xinput{11}: imndraws=nstarts*ndraws2 +% xinput{12}: a0indx -- index number for non-zero elements in A0 +% xinput{13}: tdf -- degrees of freedom for t-distribution +% xinput{14}: nbuffer -- interval for printing, plotting, and saving +% xinput{15}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation +% Already divided by "fss." +% xinput{16}: nSample -- the original sample size including lags +% xinput{17}: IndxNmlr -- index for which normalization rule to choose +% xinput{18}: IndxGibbs -- index for WZ Gibbs; 1; Gibbs; 0: Metropolis +% xinput{19}: scf -- reduction scale factor for Metropolis jumping kernel +% xinput{20}: H_sr -- square root of the inverse of the covariance matrix +% for free elements in A0 (nfp-by-nfp) +% xinput{21}: fss -- effective sample size == nSample-lags+# of dummy observations +% xinput{22}: idfile1 -- calls "iden6std." Save stds. of both data and impulse responses in idfile1 +% xinput{23}: xxhpc -- chol(X'X+inv(H_p_tilde)): upper triangular but its transpose +% is lower triagular Choleski +% xinput{24}: ImfErr -- if 1, impulse response simulation; if 0, disable this simulation +% xinput{25}: ninv -- number of bins pre-specified to put each draw of impulse response +% into a proper bin (or small interval) +% xinput{26}: imstp -- # of steps for impulse responses +% xinput{27}: forep -- forecast periods (# of steps) +% xinput{28}: yact -- actual data (in log except R, U, etc.) +% xinput{29}: yactqg -- quarterly annualized growth in actual data +% xinput{30}: yactCalyg -- calendar annual growth in actual data +% xinput{31}: imfml -- imstp-by-nvar^2 ML impulse responses +% xinput{32}: forepq -- forecast periods for quarterly growth +% xinput{33}: forepy -- forecast periods for annual growth +% xinput{34}: ncoef -- k: # of coeffients per equation +% xinput{35}: Bhml -- ML reduced form parameter B (nvar-by-k) +% xinput{36}: lags -- # of lags +%------------------ +% imfcntmulti: (ninv+2,imstp*nvar^2,nstarts) matrix +% cnt: count; for impulse responses; multi (nstarts) sequences +% All output is saved in outB_W, including Range5, invc, ninv, and imfcntmulti +% +% Written by T. Zha 1999 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess=xinput{4}; Indxv=xinput{5}; +IndxGraph=xinput{6}; idmat0=xinput{7}; nstarts=xinput{8}; ndraws1=xinput{9}; ndraws2=xinput{10}; +imndraws=xinput{11}; a0indx=xinput{12}; tdf=xinput{13}; nbuffer=xinput{14}; Sbd=xinput{15}; +nSample = xinput{16}; IndxNmlr=xinput{17}; IndxGibbs=xinput{18}; scf=xinput{19}; H_sr=xinput{20}; +fss=xinput{21}; idfile1=xinput{22}; xxhpc=xinput{23}; ImfErr=xinput{24}; ninv=xinput{25}; +imstp=xinput{26}; forep=xinput{27}; yact=xinput{28}; yactqg=xinput{29}; yactCalyg=xinput{30}; +imfml=xinput{31}; forepq=xinput{32}; forepy=xinput{33}; ncoef=xinput{34}; Bhml=xinput{35}; +lags=xinput{36}; + +Avhx_bs = zeros(nfp,1); +Avhx_bm = zeros(nfp,1); +Avhx_bj = zeros(nfp,1); +Avhx_cj = zeros(nfp,1); +Avhx_cm = zeros(nfp,1); +A0_h = zeros(nvar); +A0gbs = A0_h; % drawn A0 in Gibbs sampling +Avhxm = zeros(nfp,1); +Avhxs = Avhxm; +A0xhat = zeros(nvar); +A0xhat(a0indx) = xhat; +% A0hatw = zeros(nvar^2,nbuffer); + +countJump = zeros(nstarts,1); + +imfmean = zeros(imstp,nvar^2); +imfcntmulti = zeros(ninv+2,imstp*nvar^2,nstarts); + % cnt: count; for impulse responses; multi (nstarts) sequences + + +%--------------------------------------------------- +% Specify the range for counting the empirical distribution +% +%** load the standard deviations of 6 variables, one for log(y), one for gq, and +%** the third one for yg +eval(['load ' idfile1 '.prn -ascii']); +eval(['ABstd=' idfile1 ';']); +Range5 = cell(4,1); % 4: log, qg, yg, and imf + +%@@@ Tony's trick to expand the matrix +% +%** In order of log(y), qg, and yg for Range5{i} for i=1:3 +Range5{1} =zeros(forep,nvar,2); % 2: min and max +Range5{1}(:,:,1) = repmat(yact(length(yact(:,1)),:)-10*ABstd(1,:),[forep 1]); % min, 30 std. +Range5{1}(:,:,2) = repmat(yact(length(yact(:,1)),:)+10*ABstd(1,:),[forep 1]); % max, 30 std. +% +Range5{2} =zeros(forepq,nvar,2); % 2: min and max +Range5{2}(:,:,1) = repmat(yactqg(length(yactqg(:,1)),:)-10*ABstd(2,:),[forepq 1]); % min, 30 std. +Range5{2}(:,:,2) = repmat(yactqg(length(yactqg(:,1)),:)+10*ABstd(2,:),[forepq 1]); % max, 30 std. +% +Range5{3} =zeros(forepy,nvar,2); % 2: min and max +Range5{3}(:,:,1) = repmat(yactCalyg(length(yactCalyg(:,1)),:)-10*ABstd(3,:),[forepy 1]); % min, 30 std. +Range5{3}(:,:,2) = repmat(yactCalyg(length(yactCalyg(:,1)),:)+10*ABstd(3,:),[forepy 1]); % max, 30 std. +% +Range5{4} =zeros(imstp,nvar^2,2); % 2: min and max +imfscale = repmat(ABstd(4,:),[1 nvar]); % because nvar variables to 1, ..., nvar shocks +Range5{4}(:,:,1) = repmat(imfml(1,:)-5*imfscale,[imstp 1]); % min, 5 std. +Range5{4}(:,:,2) = repmat(imfml(1,:)+5*imfscale,[imstp 1]); % max, 5 std. + % Range5(4)(:,:,1): imstp-by-nvar^2. Column: nvar responses to 1st shock, + % nvar responses to 2nd shock, ... +%** +invc = cell(4,1); % interval length (used for counting later). 1st 3 cells have each + % forep-by-nvar, and 4th has imstp-by-nvar^2. +for i=1:4 + invc{i} = Range5{i}(:,:,2) - Range5{i}(:,:,1); +end +hbin = invc{4} ./ ninv; % bin size for each point of impulse responses kkdf +imfloor = Range5{4}(:,:,1); + + + +%=================================== +% Here begins with the big loop +%=================================== +H1 = chol(hess); % upper triangular so that H1' is a lower triangular decomp +baseW = H_sr; %inv(H1); %H_sr; % covariance matrix without scaling +nswitch=0; %<<>> total number of sign switches +A0inxhat = inv(A0xhat); % inverse of ML estimate +a0indx0 = find(idmat0==0); % index for all zero's in A0; +nn=[nvar lags imstp]; + +[cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss); + +tic +for starts = 1:nstarts + starts + if starts == 1 + A0gbs(a0indx) = xhat; % from "load ..." + if ~IndxGibbs % Metropolist + Avhx = xhat; + hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); + hAvhx = -hAvhx; % converted to logLH + end + else + Avhx = baseW*randn(nfp,1); %H_sr*randn(nfp,1); % D: discarded sequence + csq=randn(tdf,1); + csq=sum(csq .* csq); + Avhx = xhat+Avhx/sqrt(csq/tdf); + %** Normalization by the choice of IndxNmlr + A0gbs(a0indx) = Avhx; + if ~IndxNmlr(5) + [A0gbs,jnk] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); + else + A0ingbs = inv(A0gbs); + [A0gbs,jnk,jnk1] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); + end + % + if ~IndxGibbs % Metropolist + Avhx = A0gbs(a0indx); + hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); + hAvhx = -hAvhx; % converted to logLH + end + end + % + Avhxmm = zeros(nfp,1); + Avhxss = zeros(nfp,1); + cJump = 0; + imfcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count; for impulse responses + + for draws = 1:ndraws1 + if IndxGibbs + A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); + else % Metropolis + [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... + baseW,nfp,Sbd,fss,nvar,a0indx); + end + end + + wdraws=(starts-1)*ndraws2+0; + for draws = 1:ndraws2 + drawsc = (starts-1)*ndraws2+draws; + if IndxGibbs + A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); + A0gbs(a0indx0) = 0; % set all zeros in A0gbs clean to avoid possible cumulative round-off errors + else % Metropolis + [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... + baseW,nfp,Sbd,fss,nvar,a0indx); + A0gbs(a0indx) = Avhx; + end + + %*** call normalization so that A0_h is normalized + if ~IndxNmlr(5) + [A0_h,nswitch] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); + A0_hin = inv(A0_h); + else + A0ingbs = inv(A0gbs); + [A0_h,nswitch,A0_hin] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); + end + Avhx_norm = A0_h(a0indx); + + % + % *** normal draws for posterior Aplus conditional on A0h + % + %** the mean is Aplushm, and the covariance is inv(xxhp)=Lxxhpc*Lxxhpc' + Apindm = randn(ncoef,nvar); + % + if ~all(all(finite(Bhml))) + Aplushm=zeros(ncoef,nvar); + for i=1:nvar + Aplushm(:,i)=Gb{i}*A0_h(:,i); % see Zha's forecast (1) p.9 + % Here, Gb is used to compute A+ where A+(i) = Gb(i)*a0(i) + end + Bh_h = (Aplushm + xxhpc\Apindm)*A0_hin; + else + Bh_h = Bhml + (xxhpc\Apindm)*A0_hin; + end + + if ImfErr + swish_h = A0_hin'; % Switching back to the form A0*y(t) = e(t) + imf_h = zimpulse(Bh_h,swish_h,nn); % in the form that is congenial to RATS + % imf3_h=reshape(imf_h,size(imf_h,1),nvar,nvar); + % % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks + imfmean = imfmean + imf_h; % posterior mean + imfcnt = empdfsort(imfcnt,imf_h,imfloor,hbin,ninv); + % sorted counts (prob.) in bins + end + + Avhxm = Avhxm + Avhx_norm; % 1st step to overall mean of parameter + Avhxs = Avhxs + Avhx_norm.^2; % 1st step to overall 2nd moment of parameter + + %* compute the mean and 2nd moment + %** Getting average of variances W and variance of means B/n -- B_n + %* see Gelman, p.331, my Shock(0), 12-13, and my Forecast (2), 28-31 + if (nstarts>1) + Avhxmm = Avhxmm + Avhx_norm; % n*(phi_.j) + Avhxss = Avhxss + Avhx_norm.^2; % 1st step to (phi_ij) for fixed j + end + + % A0hatw(:,drawsc-wdraws) = A0_h(:); + if ~mod(draws,nbuffer) + starts + draws + wdraws=drawsc + % fwriteid = fopen('outA0.bin','a'); + % count = fwrite(fwriteid,A0hatw,'double'); + % status = fclose('all'); + end + end + % + imfcntmulti(:,:,starts) = imfcnt; + + if ~IndxGibbs + countJump(starts,1) = cJump; + end + % + %** Getting average of variances W and variance of means B/n -- B_n + %** see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 + if (nstarts>1) + Avhx_aj = Avhxmm/ndraws2; % (phi_.j) + Avhx_bs = Avhx_bs + Avhx_aj.^2; % 1st step to 2nd moment of (phi_.j) + Avhx_bm = Avhx_bm + Avhx_aj; % 1st step to (phi_..) + % + Avhx_bj = Avhxss/ndraws2; % 2nd moment of (phi_ij) for fixed j + Avhx_cj = Avhx_bj - Avhx_aj.^2; % ((n-1)/n)*S^2_j + Avhx_cm = Avhx_cm + Avhx_cj; % sum of ((n-1)/n)*S^2_j across j + end +end +timend = toc +timeminutes=timend/60 + +if ~IndxGibbs + countJump = countJump/ndraws2 +end + +Avhxm = Avhxm/(imndraws); +Avhxs = Avhxs/(imndraws); +Avhxv = Avhxs - Avhxm.^2; +Avhxs = sqrt(Avhxv); % stardard deviation +A0hm = zeros(nvar); +A0hm(a0indx) = Avhxm % mean +A0hv = zeros(nvar); +A0hv(a0indx) = Avhxv; % varaince matrix +A0hs = zeros(nvar); +A0hs(a0indx) = Avhxs; % standar deviation + +imfmean = imfmean/(imndraws); + +%**** Getting Within-Sequence W and Between-Sequence B_n +% see Gelman, p.331, my Shock(0), pp.12-13, and my Forecast (2), pp.28-31 +if (nstarts>1) + AvhxW = (ndraws2/(ndraws2-1))*Avhx_cm/nstarts; + % W: average of j within-sequence variances + AvhxB_n = (nstarts/(nstarts-1)) * ( Avhx_bs/nstarts - (Avhx_bm/nstarts).^2 ); + % B/n: variance of J within-sequence means + AvhxB = ndraws2*AvhxB_n; % B + % + B_W1 = AvhxB ./ AvhxW; + B1 = AvhxB; + W1 = AvhxW; + GR1 = sqrt((ndraws2-1)/ndraws2 + B_W1/ndraws2); + % measure of Gelman reduction; need not be 1 to be accurate, + % contrary to what Gelman claims + save outB_W B_W1 B1 W1 GR1 nstarts ndraws2 imndraws timeminutes Avhxs ... + A0xhat A0hm A0hs A0hv IndxGibbs countJump + if ImfErr + save outB_W nswitch imfml imfmean imfcntmulti Range5 ninv invc imstp nvar -append + end + + titstr = ['J ' num2str(nstarts) ' n1 ' num2str(ndraws1) ... + ' n2 ' num2str(ndraws2) ' timend minutes ' num2str(timend/60)]; + disp(' ') + disp(titstr) + disp('B/W sqrt(B) sqrt(W) Std(A0) GR') + format short g + [B_W1 sqrt(B1) sqrt(W1) Avhxs GR1] +else + save outB_W nstarts ndraws1 ndraws2 imndraws timeminutes Avhxs ... + A0xhat A0hm A0hs A0hv IndxGibbs countJump + if ImfErr + save outB_W nswitch imfml imfmean imfcntmulti Range5 ninv invc imstp nvar -append + end +end diff --git a/MatlabFiles/imfvdscksim.m b/MatlabFiles/imfvdscksim.m index 1d9d0df52aa4c7616d8f28a9da41e71708c3d71c..2e49e4aafdeccc7b7ac549c36897a109b9e947db 100644 --- a/MatlabFiles/imfvdscksim.m +++ b/MatlabFiles/imfvdscksim.m @@ -1,553 +1,553 @@ -function imfvdscksim(xinput,sa0indx,simfindx) -% imfvdscksim(xinput,sa0indx,simfindx) -% Save the simulated pdfs of impulse responses, vd, shocks, and A0's; -% Ref: Waggoner and Zha "Does Normalization Matter for Inference" -% See note Forecast (2) -% -% xinput{1}: nfp -- total number of free parameters -% xinput{2}: nvar -- number of variables -% xinput{3}: xhat -- ML estimate of free parameters in A0 -% xinput{4}: hess -- Hessian of -logLH -% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest -% to select variables, always check idmat0 to make sure -% it plots: (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, -% (2) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences -% (5) scattered plot of 1st and 2nd for al sequences. -% xinput{6}: IndxGraph - 1: plot graphs; 0: no graphs -% xinput{7}: idmat0 -- Index for non-zero elements in A0 with column to equation -% xinput{8}: nstarts -- # of starting points in Gibbs sampling -% xinput{9}: ndraws1 -- # of 1st loop to be discarded -% xinput{10}: ndraws2 -- # of 2nd loop for saving A0 draws -% xinput{11}: imndraws=nstarts*ndraws2 -% xinput{12}: a0indx -- index number for non-zero elements in A0 -% xinput{13}: tdf -- degrees of freedom for t-distribution -% xinput{14}: nbuffer -- interval for printing, plotting, and saving -% xinput{15}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation -% xinput{16}: nSample -- the original sample size including lags -% xinput{17}: IndxNmlr -- index for which normalization rule to choose -% xinput{18}: IndxGibbs -- index for WZ Gibbs; 1; Gibbs; 0: Metropolis -% xinput{19}: scf -- reduction scale factor for Metropolis jumping kernel -% xinput{20}: H_sr -- covariance matrix for free elements in A0 (nfp-by-nfp) -% xinput{21}: fss -- effective sample size == nSample-lags+# of dummy observations -% xinput{22}: idfile1 -- calls "iden6std." Save stds. of both data and impulse responses in idfile1 -% xinput{23}: xxhpc -- chol(X'X+inv(H_p_tilde)): upper triangular but its transpose -% is lower triagular Choleski -% xinput{24}: ImfErr -- if 1, impulse response simulation; if 0, disable this simulation -% xinput{25}: ninv -- number of bins pre-specified to put each draw of impulse response -% into a proper bin (or small interval) -% xinput{26}: imstp -- # of steps for impulse responses -% xinput{27}: forep -- forecast periods (# of steps) -% xinput{28}: yact -- actual data (in log except R, U, etc.) -% xinput{29}: yactqg -- quarterly annualized growth in actual data -% xinput{30}: yactCalyg -- calendar annual growth in actual data -% xinput{31}: imfml -- imstp-by-nvar^2 ML impulse responses -% xinput{32}: forepq -- forecast periods for quarterly growth -% xinput{33}: forepy -- forecast periods for annual growth -% xinput{34}: ncoef -- k: # of coeffients per equation -% xinput{35}: Bhml -- ML reduced form parameter B (nvar-by-k) -% xinput{36}: lags -- # of lags -% xinput{37}: Psuedo -- 1: for Pseudo out-of-sample; 0: for in-sample (or real-time out-of-sample) -% xinput{38}: q_m = 4 or 12 -- quarterly (4) or monthly (12) -% xinput{39}: imf3ml -- ML impulse responses with row--steps, column--nvar responses, -% 3rd dimension--nvar shocks -% xinput{40}: vlistlog -- sub index for log in vlist -% xinput{41}: vlistper -- sub index for percent in vlist -% xinput{42}: phi -- X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef -% xinput{43}: actup -- acutal periods for backing out structural shocks -% xinput{44}: A0ml -- ML A0; column-equation -% xinput{45}: Bhml -- ML Bh (k-by-nvar) -% xinput{46}: yrEnd -- the end year for the estimation period -% xinput{47}: qmEnd -- the end month or quarter for the estimation period -% xinput{48}: yrStart -- the start year for the estimation period -% xinput{49}: qmStart -- the start month or quarter for the estimation period -% sa0indx: special a0 index. 1: use this; 0: disenable -% simfindx: special impulse response index. 1: use it; 0: disenable -%------------------ -% E.G.: imfcntmulti: (ninv+2,imstp*nvar^2,nstarts) matrix -% cnt: count; for impulse responses; multi (nstarts) sequences -% All output is saved in outB_W, including Range5, invc, ninv, imfcntmulti, -% sckcorcntmulti, Avhxcntmulti, lzvdcntmulti -% -% Written by TAZ 1999 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess=xinput{4}; Indxv=xinput{5}; -IndxGraph=xinput{6}; idmat0=xinput{7}; nstarts=xinput{8}; ndraws1=xinput{9}; ndraws2=xinput{10}; -imndraws=xinput{11}; a0indx=xinput{12}; tdf=xinput{13}; nbuffer=xinput{14}; Sbd=xinput{15}; -nSample = xinput{16}; IndxNmlr=xinput{17}; IndxGibbs=xinput{18}; scf=xinput{19}; H_sr=xinput{20}; -fss=xinput{21}; idfile1=xinput{22}; xxhpc=xinput{23}; ImfErr=xinput{24}; ninv=xinput{25}; -imstp=xinput{26}; forep=xinput{27}; yact=xinput{28}; yactqg=xinput{29}; yactCalyg=xinput{30}; -imfml=xinput{31}; forepq=xinput{32}; forepy=xinput{33}; ncoef=xinput{34}; Bhml=xinput{35}; -lags=xinput{36}; Psuedo=xinput{37}; q_m=xinput{38}; imf3ml=xinput{39}; vlistlog=xinput{40}; -vlistper=xinput{41}; phi=xinput{42}; actup=xinput{43}; A0ml=xinput{44}; Bhml=xinput{45}; -yrEnd=xinput{46}; qmEnd=xinput{47}; yrStart=xinput{48}; qmStart=xinput{49}; - - -if Psuedo - disp('Make sure (1) Psuedo=0 in msstart.m and (2) "actuap=nSample-lags" for strucutral shocks') - disp('Press ctrl-c to abort now') -end - -A0_h = zeros(nvar); -A0gbs = A0_h; % drawn A0 in Gibbs sampling -Avhxml = xhat; % ML estimate -Avhxmean = zeros(nfp,1); -Avhxs = Avhxmean; - -A0xhat = zeros(nvar); -A0xhat(a0indx) = xhat; -% A0hatw = zeros(nvar^2,nbuffer); - -countJump = zeros(nstarts,1); -imstpyer = floor(imstp/q_m); % yearly - -imfmean = zeros(imstp,nvar^2); -imfs = imfmean; -imfyermean = zeros(imstpyer,nvar^2); -imfyers = imfyermean; -imfyer3ml = zeros(imstpyer,nvar,nvar); -imfyer3_h = zeros(imstpyer,nvar,nvar); - - -imfcntmulti = zeros(ninv+2,imstp*nvar^2,nstarts); - % cnt: count; for impulse responses; multi (nstarts) sequences -Avhxcntmulti = zeros(ninv+2,nfp,nstarts); - % cnt: count; for A0; multi (nstarts) sequences -imfyercntmulti = zeros(ninv+2,imstpyer*nvar^2,nstarts); - % cnt: count; for impulse responses; multi (nstarts) sequences -lzvdcntmulti = zeros(ninv+2,imstp*nvar^2,nstarts); - % cnt: count; for lz vd; multi (nstarts) sequences -lzvdyercntmulti = zeros(ninv+2,imstpyer*nvar^2,nstarts); - % cnt: count; for lz vd; multi (nstarts) sequences -sckcorcntmulti = zeros(ninv+2,nvar^2,nstarts); - -%--------------------------------------------------- -% Specify the range for counting the empirical distribution -% -%** load the standard deviations of 6 variables, one for log(y), one for gq, and -%** the third one for yg -eval(['load ' idfile1 '.prn -ascii']); -eval(['ABstd=' idfile1 ';']); -Range5 = cell(9,1); % 8: log, qg, yg, imf, Avhx, imfyer (yearly), lzvd, - % lzvdyer, sckcorv, - -%@@@ Tony's trick to expand the matrix -% -%** In order of log(y), qg, and yg for Range5{i} for i=1:3 -Range5{1} =zeros(forep,nvar,2); % 2: min and max -Range5{1}(:,:,1) = repmat(yact(length(yact(:,1)),:)-10*ABstd(1,:),[forep 1]); % min, 30 std. -Range5{1}(:,:,2) = repmat(yact(length(yact(:,1)),:)+10*ABstd(1,:),[forep 1]); % max, 30 std. -% -Range5{2} =zeros(forepq,nvar,2); % 2: min and max -Range5{2}(:,:,1) = repmat(yactqg(length(yactqg(:,1)),:)-10*ABstd(2,:),[forepq 1]); % min, 30 std. -Range5{2}(:,:,2) = repmat(yactqg(length(yactqg(:,1)),:)+10*ABstd(2,:),[forepq 1]); % max, 30 std. -% -Range5{3} =zeros(forepy,nvar,2); % 2: min and max -Range5{3}(:,:,1) = repmat(yactCalyg(length(yactCalyg(:,1)),:)-10*ABstd(3,:),[forepy 1]); % min, 30 std. -Range5{3}(:,:,2) = repmat(yactCalyg(length(yactCalyg(:,1)),:)+10*ABstd(3,:),[forepy 1]); % max, 30 std. -% -Range5{4} =zeros(imstp,nvar^2,2); % 2: min and max -imfscale = repmat(ABstd(4,:),[1 nvar]); % because nvar variables to 1, ..., nvar shocks -Range5{4}(:,:,1) = repmat(imfml(1,:)-5*imfscale,[imstp 1]); % min, 5 std. -Range5{4}(:,:,2) = repmat(imfml(1,:)+5*imfscale,[imstp 1]); % max, 5 std. - % Range5(4)(:,:,1): imstp-by-nvar^2. Column: nvar responses to 1st shock, - % nvar responses to 2nd shock, ... -% -%*** for parameters A0's -Range5{5} =zeros(nfp,2); % 2: min and max -Avhxscale = abs(Avhxml); -Range5{5}(:,1) = Avhxml-5*Avhxscale; % min, 5 std. -Range5{5}(:,2) = Avhxml+5*Avhxscale; % max, 5 std. - -% -%*** for yearly impulse responses -yer3 = zeros(1+imstpyer,nvar,nvar); -for k=1:imstpyer - yer3(k+1,:,:) = mean(imf3ml(1+q_m*(k-1):q_m*k,:,:),1); % annual average - % yer3: row--steps, column--nvar responses, 3rd dimension--nvar shocks -end -imfyer3ml(:,vlistlog,:) = ( exp(yer3(2:1+imstpyer,vlistlog,:)-yer3(1:imstpyer,vlistlog,:)) - 1 ).*100; -imfyer3ml(:,vlistper,:) = yer3(2:1+imstpyer,vlistper,:) .* 100; - % imfyer3ml: row--steps, column--nvar responses, 3rd dimension--nvar shocks -tmp = max(squeeze(max(imfyer3ml,[],1)),[],2); % nvar-by-1 -tmp = tmp'; % 1-by-nvar (variables) -imfyerml = reshape(imfyer3ml,imstpyer,nvar^2); -imfyermlmax = max(abs(imfyerml)); % for error bands (imfyercnt) later -%*** for annual impulse responses -Range5{6} =zeros(imstpyer,nvar^2,2); % 2: min and max -tmp = repmat(tmp,[1 nvar]); % because nvar variables to 1, ..., nvar shocks -imfyerscl = repmat(tmp,[imstpyer,1]); % imstpyer-by-nvar^2 -Range5{6}(:,:,1) = imfyerml-5*imfyerscl; % min, 5 std. -Range5{6}(:,:,2) = imfyerml+5*imfyerscl; % max, 5 std. - % Range5(6)(:,:,1): imstpyer-by-nvar^2. Column: nvar responses to 1st shock, - % nvar responses to 2nd shock, ... - -%*** lz variance decomposition (nunlike the traditional, non-cumulative). -tmp0=abs(imf3ml); -tmp1 = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 - % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks -lzvd3ml = 100*(tmp0./tmp1); -lzvdml = reshape(lzvd3ml,imstp,nvar^2); -%** for lz vd (non-cumulative) -Range5{7} =zeros(imstp,nvar^2,2); % 2: min and max -Range5{7}(:,:,1) = zeros(imstp,nvar^2); % min, 5 std. -Range5{7}(:,:,2) = 100*ones(imstp,nvar^2); % max, 5 std. - % Range5(7)(:,:,1): imstp-by-nvar^2. Column: nvar responses to 1st shock, - % nvar responses to 2nd shock, ... - -%*** lz annual variance decomposition (nunlike the traditional, non-cumulative). -tmp0=abs(imfyer3ml); -tmp1 = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 - % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks -lzvdyer3ml = 100*(tmp0./tmp1); -lzvdyerml = reshape(lzvdyer3ml,imstpyer,nvar^2); -%** for lz annual vd -Range5{8} =zeros(imstpyer,nvar^2,2); % 2: min and max -Range5{8}(:,:,1) = zeros(imstpyer,nvar^2); % min, 5 std. -Range5{8}(:,:,2) = 100*ones(imstpyer,nvar^2); % max, 5 std. - % Range5(8)(:,:,1): imstpyer-by-nvar^2. Column: nvar responses to 1st shock, - % nvar responses to 2nd shock, ... - -%**** Correlations among structural shocks -philr = phi(size(phi,1)-actup+1,:); % +1 is absolutely needed -yexa = yact(1:actup,:); -Estrexaml = fidcndexa(yexa,philr,A0ml,Bhml,nvar,lags,actup); % actup-by-nvar -sckvarml = (Estrexaml'*Estrexaml)/actup; -sckcorml = corr(sckvarml); -%** for shock correlation sckcor -Range5{9} =zeros(nvar,nvar,2); % 2: min and max -Range5{9}(:,:,1) = (-1)*ones(nvar,nvar); % min, 5 std. -Range5{9}(:,:,2) = ones(nvar,nvar); % max, 5 std. - % Range5(9)(:,:,1): nvar^2. Correlation among structural shocks - - - - -%** -invc = cell(9,1); % interval length (used for counting later). -for i=[1:4 6:9] - invc{i} = Range5{i}(:,:,2) - Range5{i}(:,:,1); -end -invc{5} = Range5{5}(:,2) - Range5{5}(:,1); -% -imfhbin = invc{4} ./ ninv; % bin size for each point of impulse responses -imfloor = Range5{4}(:,:,1); % lowest point next to -infinity -Avhxhbin = invc{5} ./ ninv; % bin size for each point of A0 -Avhxfloor = Range5{5}(:,1); % lowest point next to -infinity -imfyerhbin = invc{6} ./ ninv; % bin size for each point of annual impulse responses -imfyerfloor = Range5{6}(:,:,1); % lowest point next to -infinity -lzvdhbin = invc{7} ./ ninv; % bin size for each point of variance decompositions -lzvdfloor = Range5{7}(:,:,1); % lowest point next to -infinity -lzvdyerhbin = invc{8} ./ ninv; % bin size for each point of annul variance decompositions -lzvdyerfloor = Range5{8}(:,:,1); % lowest point next to -infinity -sckcorhbin = invc{9} ./ ninv; % bin size for each point of shock correlations -sckcorfloor = Range5{9}(:,:,1); % lowest point next to -infinity - - - - -%*** <<>> Specific requests -%*** compute prob(parameter>0) or joint prob. of sign matches in MP and MD -if sa0indx - csix1a0 = [-1 -1 1 1 1 -1 1]'; % for 7 parameters in MP and MD - % from 7th to 13th in Avhx_norm - nspeca0 = 7+3; % number of specific requests - % additional 3: 1 for all MP parameters; 2 for all MD parameters; - % 3 for all paramters in MP and MD - cspeca0 = zeros(nspeca0,1); -end -% -if simfindx - csix1imf = [-1 -1 1 -1 -1 1]'; % for 6 variables to MP shock - % maybe at different horizons (esp. for inflation) - csix1pimf = [1 1 1 24 36 24]'; % the periods for the 6 varialbes to MP shock - % Pcm, M2, FFR, y, P, U. - nspecimf = nvar+2; % number of specific requests - % additional 1: 1 for opposite signs of M2 and R - cspecimf = zeros(nspecimf,1); -end - - - - -%=================================== -% Here begins with the big loop -%=================================== -H1 = chol(hess); % upper triangular so that H1' is a lower triangular decomp -baseW = H_sr; %inv(H1); %H_sr; % covariance matrix without scaling -nswitch=0; %<<>> total number of sign switches -A0inxhat = inv(A0xhat); % inverse of ML estimate -a0indx0 = find(idmat0==0); % index for all zero's in A0; -nn=[nvar lags imstp]; - -[cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss); - -tic -for starts = 1:nstarts - starts - if starts == 1 - A0gbs(a0indx) = xhat; % from "load ..." - if ~IndxGibbs % Metropolist - Avhx = xhat; - hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); - hAvhx = -hAvhx; % converted to logLH - end - else - Avhx = baseW*randn(nfp,1); %H_sr*randn(nfp,1); % D: discarded sequence - csq=randn(tdf,1); - csq=sum(csq .* csq); - Avhx = xhat+Avhx/sqrt(csq/tdf); - %** Normalization by the choice of IndxNmlr - A0gbs(a0indx) = Avhx; - if ~IndxNmlr(5) - [A0gbs,jnk] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); - else - A0ingbs = inv(A0gbs); - [A0gbs,jnk,jnk1] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); - end - % - if ~IndxGibbs % Metropolist - Avhx = A0gbs(a0indx); - hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); - hAvhx = -hAvhx; % converted to logLH - end - end - % - cJump = 0; - - imfcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count; for impulse responses - Avhxcnt = zeros(ninv+2,nfp); % cnt: count; for A0's - imfyercnt = zeros(ninv+2,imstpyer*nvar^2); % cnt: count; for impulse responses - lzvdcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count; for lz vd (non-cumulative) - lzvdyercnt = zeros(ninv+2,imstpyer*nvar^2); % cnt: count; for lz annual vd (non-cumulative) - sckcorcnt = zeros(ninv+2,nvar^2); % cnt: count; for shock correlations - - for draws = 1:ndraws1 - if IndxGibbs - A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); - else % Metropolis - [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... - baseW,nfp,Sbd,fss,nvar,a0indx); - end - end - - wdraws=(starts-1)*ndraws2+0; - for draws = 1:ndraws2 - drawsc = (starts-1)*ndraws2+draws; - if IndxGibbs - A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); - A0gbs(a0indx0) = 0; % set all zeros in A0gbs clean to avoid possible cumulative round-off errors - else % Metropolis - [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... - baseW,nfp,Sbd,fss,nvar,a0indx); - A0gbs(a0indx) = Avhx; - end - - %*** call normalization so that A0_h is normalized - if ~IndxNmlr(5) - [A0_h,nswitch] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); - A0_hin = inv(A0_h); - else - A0ingbs = inv(A0gbs); - [A0_h,nswitch,A0_hin] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); - end - Avhx_norm = A0_h(a0indx); - - if sa0indx - for k=1:7 - cspeca0(k) = cspeca0(k) + ((csix1a0(k)*Avhx_norm(6+k))>0); - end - %*** Joint tests - j1=csix1a0; - j2=Avhx_norm; - %** MP equation - mpall = ((j1(2)*j2(8))/(j1(3)*j2(9)))<0; % & ((j1(1)*j2(7))/(j1(3)*j2(9)))<0; - - cspeca0(8) = cspeca0(8) + mpall; - %** MD equation - mdall = ((j1(4)*j2(10))/(j1(5)*j2(11)))<0; %& ((j1(4)*j2(10))/(j1(6)*j2(12)))<0; - cspeca0(9) = cspeca0(9) + mdall; - mpdall = mpall & mdall; - cspeca0(10) = cspeca0(10) + mpdall; - end - - % - % *** normal draws for posterior Aplus conditional on A0h - % - %** the mean is Aplushm, and the covariance is inv(xxhp)=Lxxhpc*Lxxhpc' - Apindm = randn(ncoef,nvar); - % - if ~all(all(finite(Bhml))) - Aplushm=zeros(ncoef,nvar); - for i=1:nvar - Aplushm(:,i)=Gb{i}*A0_h(:,i); % see Zha's forecast (1) p.9 - % Here, Gb is used to compute A+ where A+(i) = Gb(i)*a0(i) - end - Bh_h = (Aplushm + xxhpc\Apindm)*A0_hin; - else - Bh_h = Bhml + (xxhpc\Apindm)*A0_hin; - end - - if ImfErr - swish_h = A0_hin'; % Switching back to the form A0*y(t) = e(t) - imf_h = zimpulse(Bh_h,swish_h,nn); % in the form that is congenial to RATS - imf3_h=reshape(imf_h,size(imf_h,1),nvar,nvar); - % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks - imfmean = imfmean + imf_h; % posterior mean - imfs = imfs + imf_h.^2; % posterior 2nd moment - imfcnt = empdfsort(imfcnt,imf_h,imfloor,imfhbin,ninv); - % sorted counts (prob.) in bins - - %**** annula impulse responses - for k=1:imstpyer - yer3(k+1,:,:) = mean(imf3_h(1+q_m*(k-1):q_m*k,:,:),1); % annual average - % yer3: initialized earlier already - % yer3: row--steps, column--nvar responses, 3rd dimension--nvar shocks - end - imfyer3_h(:,vlistlog,:) = ( exp(yer3(2:1+imstpyer,vlistlog,:)-yer3(1:imstpyer,vlistlog,:)) - 1 ).*100; - imfyer3_h(:,vlistper,:) = yer3(2:1+imstpyer,vlistper,:) .* 100; - % imfyer3_h: row--steps, column--nvar responses, 3rd dimension--nvar shocks - imfyer_h = reshape(imfyer3_h,imstpyer,nvar^2); - imfyermean = imfyermean + imfyer_h; % posterior mean - imfyers = imfyers + imfyer_h.^2; % posterior 2nd moment - imfyercnt = empdfsort(imfyercnt,imfyer_h,imfyerfloor,imfyerhbin,ninv); - % sorted counts (prob.) in bins - - %**** Leeper-Zha variance decomposition (non-cumulative) - tmp0=abs(imf3_h); - tmp = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 - % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks - lzvd3_h = 100*(tmp0./tmp); - lzvd_h = reshape(lzvd3_h,imstp,nvar^2); - lzvdcnt = empdfsort(lzvdcnt,lzvd_h,lzvdfloor,lzvdhbin,ninv); - % sorted counts (prob.) in bins - - %**** Leeper-Zha annual variance decomposition (non-cumulative) - tmp0=abs(imfyer3_h); - tmp = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 - % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks - lzvdyer3_h = 100*(tmp0./tmp); - lzvdyer_h = reshape(lzvdyer3_h,imstpyer,nvar^2); - lzvdyercnt = empdfsort(lzvdyercnt,lzvdyer_h,lzvdyerfloor,lzvdyerhbin,ninv); - % sorted counts (prob.) in bins - - %**** Correlations among structural shocks - Estrexa_h = fidcndexa(yexa,philr,A0_h,Bh_h,nvar,lags,actup); % actup-by-nvar - sckvar_h = (Estrexa_h'*Estrexa_h)/actup; - sckcor_h = corr(sckvar_h); - sckcorcnt = empdfsort(sckcorcnt,sckcor_h,sckcorfloor,sckcorhbin,ninv); - - if simfindx - for k=1:6 - cspecimf(k) = cspecimf(k) + ((csix1a0(k)*imf_h(1,nvar+k))>0); - % 1st dim in imf_h: periods - end - %*** Joint tests - j1=csix1imf; - j2=imf_h; - j3=csix1pimf; - %** M2 and R in MP equation - mpall = ((j1(2)*j2(j3(2),nvar+2))/(j1(3)*j2(j3(3),nvar+3)))>0; % & ((j1(1)*j2(7))/(j1(3)*j2(9)))<0; - % 1st dim in j2: periods - cspecimf(nvar+1) = cspecimf(nvar+1) + mpall; - %** R and P in MP equation - mpall = ((j1(3)*j2(j3(3),nvar+3))/(j1(5)*j2(j3(5),nvar+5)))>0; % - % 1st dim in j2: periods - cspecimf(nvar+2) = cspecimf(nvar+2) + mpall; - % - % %** MD equation - % mdall = ((j1(4)*j2(10))/(j1(5)*j2(11)))<0; %& ((j1(4)*j2(10))/(j1(6)*j2(12)))<0; - % cspeca0(9) = cspeca0(9) + mdall; - % mpdall = mpall & mdall; - % cspeca0(10) = cspeca0(10) + mpdall; - end - end - - Avhxmean = Avhxmean + Avhx_norm; % 1st step to overall mean of parameter - Avhxs = Avhxs + Avhx_norm.^2; % 1st step to overall 2nd moment of parameter - Avhxcnt = empdfsort(Avhxcnt,Avhx_norm,Avhxfloor,Avhxhbin,ninv); - - - % A0hatw(:,drawsc-wdraws) = A0_h(:); - if ~mod(draws,nbuffer) - starts - draws - wdraws=drawsc - % fwriteid = fopen('outA0.bin','a'); - % count = fwrite(fwriteid,A0hatw,'double'); - % status = fclose('all'); - end - end - % - imfcntmulti(:,:,starts) = imfcnt; - Avhxcntmulti(:,:,starts) = Avhxcnt; - imfyercntmulti(:,:,starts) = imfyercnt; - lzvdcntmulti(:,:,starts) = lzvdcnt; - lzvdyercntmulti(:,:,starts) = lzvdyercnt; - sckcorcntmulti(:,:,starts) = sckcorcnt; - - if ~IndxGibbs - countJump(starts,1) = cJump; - end -end -timend = toc -timeminutes=timend/60 - -if ~IndxGibbs - countJump = countJump/ndraws2 -end - -Avhxmean = Avhxmean/(imndraws); -Avhxs = Avhxs/(imndraws); -Avhxs = sqrt(Avhxs - Avhxmean.^2); % stardard deviation -A0hm = zeros(nvar); -A0hm(a0indx) = Avhxmean % mean -A0hs = zeros(nvar); -A0hs(a0indx) = Avhxs; % standar deviation - -imfmean = imfmean/(imndraws); -imfs = imfs/imndraws; -imfs = sqrt(imfs - imfmean.^2); % standard deviation - -imfyermean = imfyermean/(imndraws); -imfyers = imfyers/imndraws; -imfyers = sqrt(imfyers - imfyermean.^2); % standard deviation - - -save outB_W nstarts ndraws1 ndraws2 imndraws timeminutes Avhxml Avhxmean Avhxs ... - Avhxcntmulti A0xhat A0hm A0hs IndxGibbs countJump nvar Range5 ... - ninv invc nfp a0indx nswitch actup nSample lags yrEnd qmEnd ... - yrStart qmStart q_m sckcorml sckcorcntmulti - -if ImfErr - if simfindx - cspecimf = cspecimf/imndraws; - save outB_W cspecimf -append - end - save outB_W imfml imfmean imfs imfcntmulti imstp cspecimf ... - imfyerml imfyermean imfyers imfyercntmulti imstpyer ... - lzvdml lzvdcntmulti lzvdyerml lzvdyercntmulti -append -end -% -if sa0indx - cspeca0 = cspeca0/imndraws; - save outB_W cspeca0 -append -end - - +function imfvdscksim(xinput,sa0indx,simfindx) +% imfvdscksim(xinput,sa0indx,simfindx) +% Save the simulated pdfs of impulse responses, vd, shocks, and A0's; +% Ref: Waggoner and Zha "Does Normalization Matter for Inference" +% See note Forecast (2) +% +% xinput{1}: nfp -- total number of free parameters +% xinput{2}: nvar -- number of variables +% xinput{3}: xhat -- ML estimate of free parameters in A0 +% xinput{4}: hess -- Hessian of -logLH +% xinput{5}:Indxv -- index for selected variables of interest; normall first 2 are of our interest +% to select variables, always check idmat0 to make sure +% it plots: (1) pdf of 1st v for every buffer, (2) scattered plot of 1st and 2nd for every buffer, +% (2) pdf of 1st v for all sequences; (4) scattered plot of 3rd and 4th for all sequences +% (5) scattered plot of 1st and 2nd for al sequences. +% xinput{6}: IndxGraph - 1: plot graphs; 0: no graphs +% xinput{7}: idmat0 -- Index for non-zero elements in A0 with column to equation +% xinput{8}: nstarts -- # of starting points in Gibbs sampling +% xinput{9}: ndraws1 -- # of 1st loop to be discarded +% xinput{10}: ndraws2 -- # of 2nd loop for saving A0 draws +% xinput{11}: imndraws=nstarts*ndraws2 +% xinput{12}: a0indx -- index number for non-zero elements in A0 +% xinput{13}: tdf -- degrees of freedom for t-distribution +% xinput{14}: nbuffer -- interval for printing, plotting, and saving +% xinput{15}: Sbd -- nvar-by-nvar S{1}, ..., S{n} -- kind of covariance matrix for each simultaneous equation +% xinput{16}: nSample -- the original sample size including lags +% xinput{17}: IndxNmlr -- index for which normalization rule to choose +% xinput{18}: IndxGibbs -- index for WZ Gibbs; 1; Gibbs; 0: Metropolis +% xinput{19}: scf -- reduction scale factor for Metropolis jumping kernel +% xinput{20}: H_sr -- covariance matrix for free elements in A0 (nfp-by-nfp) +% xinput{21}: fss -- effective sample size == nSample-lags+# of dummy observations +% xinput{22}: idfile1 -- calls "iden6std." Save stds. of both data and impulse responses in idfile1 +% xinput{23}: xxhpc -- chol(X'X+inv(H_p_tilde)): upper triangular but its transpose +% is lower triagular Choleski +% xinput{24}: ImfErr -- if 1, impulse response simulation; if 0, disable this simulation +% xinput{25}: ninv -- number of bins pre-specified to put each draw of impulse response +% into a proper bin (or small interval) +% xinput{26}: imstp -- # of steps for impulse responses +% xinput{27}: forep -- forecast periods (# of steps) +% xinput{28}: yact -- actual data (in log except R, U, etc.) +% xinput{29}: yactqg -- quarterly annualized growth in actual data +% xinput{30}: yactCalyg -- calendar annual growth in actual data +% xinput{31}: imfml -- imstp-by-nvar^2 ML impulse responses +% xinput{32}: forepq -- forecast periods for quarterly growth +% xinput{33}: forepy -- forecast periods for annual growth +% xinput{34}: ncoef -- k: # of coeffients per equation +% xinput{35}: Bhml -- ML reduced form parameter B (nvar-by-k) +% xinput{36}: lags -- # of lags +% xinput{37}: Psuedo -- 1: for Pseudo out-of-sample; 0: for in-sample (or real-time out-of-sample) +% xinput{38}: q_m = 4 or 12 -- quarterly (4) or monthly (12) +% xinput{39}: imf3ml -- ML impulse responses with row--steps, column--nvar responses, +% 3rd dimension--nvar shocks +% xinput{40}: vlistlog -- sub index for log in vlist +% xinput{41}: vlistper -- sub index for percent in vlist +% xinput{42}: phi -- X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef +% xinput{43}: actup -- acutal periods for backing out structural shocks +% xinput{44}: A0ml -- ML A0; column-equation +% xinput{45}: Bhml -- ML Bh (k-by-nvar) +% xinput{46}: yrEnd -- the end year for the estimation period +% xinput{47}: qmEnd -- the end month or quarter for the estimation period +% xinput{48}: yrStart -- the start year for the estimation period +% xinput{49}: qmStart -- the start month or quarter for the estimation period +% sa0indx: special a0 index. 1: use this; 0: disenable +% simfindx: special impulse response index. 1: use it; 0: disenable +%------------------ +% E.G.: imfcntmulti: (ninv+2,imstp*nvar^2,nstarts) matrix +% cnt: count; for impulse responses; multi (nstarts) sequences +% All output is saved in outB_W, including Range5, invc, ninv, imfcntmulti, +% sckcorcntmulti, Avhxcntmulti, lzvdcntmulti +% +% Written by TAZ 1999 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +nfp=xinput{1}; nvar=xinput{2}; xhat=xinput{3}; hess=xinput{4}; Indxv=xinput{5}; +IndxGraph=xinput{6}; idmat0=xinput{7}; nstarts=xinput{8}; ndraws1=xinput{9}; ndraws2=xinput{10}; +imndraws=xinput{11}; a0indx=xinput{12}; tdf=xinput{13}; nbuffer=xinput{14}; Sbd=xinput{15}; +nSample = xinput{16}; IndxNmlr=xinput{17}; IndxGibbs=xinput{18}; scf=xinput{19}; H_sr=xinput{20}; +fss=xinput{21}; idfile1=xinput{22}; xxhpc=xinput{23}; ImfErr=xinput{24}; ninv=xinput{25}; +imstp=xinput{26}; forep=xinput{27}; yact=xinput{28}; yactqg=xinput{29}; yactCalyg=xinput{30}; +imfml=xinput{31}; forepq=xinput{32}; forepy=xinput{33}; ncoef=xinput{34}; Bhml=xinput{35}; +lags=xinput{36}; Psuedo=xinput{37}; q_m=xinput{38}; imf3ml=xinput{39}; vlistlog=xinput{40}; +vlistper=xinput{41}; phi=xinput{42}; actup=xinput{43}; A0ml=xinput{44}; Bhml=xinput{45}; +yrEnd=xinput{46}; qmEnd=xinput{47}; yrStart=xinput{48}; qmStart=xinput{49}; + + +if Psuedo + disp('Make sure (1) Psuedo=0 in msstart.m and (2) "actuap=nSample-lags" for strucutral shocks') + disp('Press ctrl-c to abort now') +end + +A0_h = zeros(nvar); +A0gbs = A0_h; % drawn A0 in Gibbs sampling +Avhxml = xhat; % ML estimate +Avhxmean = zeros(nfp,1); +Avhxs = Avhxmean; + +A0xhat = zeros(nvar); +A0xhat(a0indx) = xhat; +% A0hatw = zeros(nvar^2,nbuffer); + +countJump = zeros(nstarts,1); +imstpyer = floor(imstp/q_m); % yearly + +imfmean = zeros(imstp,nvar^2); +imfs = imfmean; +imfyermean = zeros(imstpyer,nvar^2); +imfyers = imfyermean; +imfyer3ml = zeros(imstpyer,nvar,nvar); +imfyer3_h = zeros(imstpyer,nvar,nvar); + + +imfcntmulti = zeros(ninv+2,imstp*nvar^2,nstarts); + % cnt: count; for impulse responses; multi (nstarts) sequences +Avhxcntmulti = zeros(ninv+2,nfp,nstarts); + % cnt: count; for A0; multi (nstarts) sequences +imfyercntmulti = zeros(ninv+2,imstpyer*nvar^2,nstarts); + % cnt: count; for impulse responses; multi (nstarts) sequences +lzvdcntmulti = zeros(ninv+2,imstp*nvar^2,nstarts); + % cnt: count; for lz vd; multi (nstarts) sequences +lzvdyercntmulti = zeros(ninv+2,imstpyer*nvar^2,nstarts); + % cnt: count; for lz vd; multi (nstarts) sequences +sckcorcntmulti = zeros(ninv+2,nvar^2,nstarts); + +%--------------------------------------------------- +% Specify the range for counting the empirical distribution +% +%** load the standard deviations of 6 variables, one for log(y), one for gq, and +%** the third one for yg +eval(['load ' idfile1 '.prn -ascii']); +eval(['ABstd=' idfile1 ';']); +Range5 = cell(9,1); % 8: log, qg, yg, imf, Avhx, imfyer (yearly), lzvd, + % lzvdyer, sckcorv, + +%@@@ Tony's trick to expand the matrix +% +%** In order of log(y), qg, and yg for Range5{i} for i=1:3 +Range5{1} =zeros(forep,nvar,2); % 2: min and max +Range5{1}(:,:,1) = repmat(yact(length(yact(:,1)),:)-10*ABstd(1,:),[forep 1]); % min, 30 std. +Range5{1}(:,:,2) = repmat(yact(length(yact(:,1)),:)+10*ABstd(1,:),[forep 1]); % max, 30 std. +% +Range5{2} =zeros(forepq,nvar,2); % 2: min and max +Range5{2}(:,:,1) = repmat(yactqg(length(yactqg(:,1)),:)-10*ABstd(2,:),[forepq 1]); % min, 30 std. +Range5{2}(:,:,2) = repmat(yactqg(length(yactqg(:,1)),:)+10*ABstd(2,:),[forepq 1]); % max, 30 std. +% +Range5{3} =zeros(forepy,nvar,2); % 2: min and max +Range5{3}(:,:,1) = repmat(yactCalyg(length(yactCalyg(:,1)),:)-10*ABstd(3,:),[forepy 1]); % min, 30 std. +Range5{3}(:,:,2) = repmat(yactCalyg(length(yactCalyg(:,1)),:)+10*ABstd(3,:),[forepy 1]); % max, 30 std. +% +Range5{4} =zeros(imstp,nvar^2,2); % 2: min and max +imfscale = repmat(ABstd(4,:),[1 nvar]); % because nvar variables to 1, ..., nvar shocks +Range5{4}(:,:,1) = repmat(imfml(1,:)-5*imfscale,[imstp 1]); % min, 5 std. +Range5{4}(:,:,2) = repmat(imfml(1,:)+5*imfscale,[imstp 1]); % max, 5 std. + % Range5(4)(:,:,1): imstp-by-nvar^2. Column: nvar responses to 1st shock, + % nvar responses to 2nd shock, ... +% +%*** for parameters A0's +Range5{5} =zeros(nfp,2); % 2: min and max +Avhxscale = abs(Avhxml); +Range5{5}(:,1) = Avhxml-5*Avhxscale; % min, 5 std. +Range5{5}(:,2) = Avhxml+5*Avhxscale; % max, 5 std. + +% +%*** for yearly impulse responses +yer3 = zeros(1+imstpyer,nvar,nvar); +for k=1:imstpyer + yer3(k+1,:,:) = mean(imf3ml(1+q_m*(k-1):q_m*k,:,:),1); % annual average + % yer3: row--steps, column--nvar responses, 3rd dimension--nvar shocks +end +imfyer3ml(:,vlistlog,:) = ( exp(yer3(2:1+imstpyer,vlistlog,:)-yer3(1:imstpyer,vlistlog,:)) - 1 ).*100; +imfyer3ml(:,vlistper,:) = yer3(2:1+imstpyer,vlistper,:) .* 100; + % imfyer3ml: row--steps, column--nvar responses, 3rd dimension--nvar shocks +tmp = max(squeeze(max(imfyer3ml,[],1)),[],2); % nvar-by-1 +tmp = tmp'; % 1-by-nvar (variables) +imfyerml = reshape(imfyer3ml,imstpyer,nvar^2); +imfyermlmax = max(abs(imfyerml)); % for error bands (imfyercnt) later +%*** for annual impulse responses +Range5{6} =zeros(imstpyer,nvar^2,2); % 2: min and max +tmp = repmat(tmp,[1 nvar]); % because nvar variables to 1, ..., nvar shocks +imfyerscl = repmat(tmp,[imstpyer,1]); % imstpyer-by-nvar^2 +Range5{6}(:,:,1) = imfyerml-5*imfyerscl; % min, 5 std. +Range5{6}(:,:,2) = imfyerml+5*imfyerscl; % max, 5 std. + % Range5(6)(:,:,1): imstpyer-by-nvar^2. Column: nvar responses to 1st shock, + % nvar responses to 2nd shock, ... + +%*** lz variance decomposition (nunlike the traditional, non-cumulative). +tmp0=abs(imf3ml); +tmp1 = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 + % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks +lzvd3ml = 100*(tmp0./tmp1); +lzvdml = reshape(lzvd3ml,imstp,nvar^2); +%** for lz vd (non-cumulative) +Range5{7} =zeros(imstp,nvar^2,2); % 2: min and max +Range5{7}(:,:,1) = zeros(imstp,nvar^2); % min, 5 std. +Range5{7}(:,:,2) = 100*ones(imstp,nvar^2); % max, 5 std. + % Range5(7)(:,:,1): imstp-by-nvar^2. Column: nvar responses to 1st shock, + % nvar responses to 2nd shock, ... + +%*** lz annual variance decomposition (nunlike the traditional, non-cumulative). +tmp0=abs(imfyer3ml); +tmp1 = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 + % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks +lzvdyer3ml = 100*(tmp0./tmp1); +lzvdyerml = reshape(lzvdyer3ml,imstpyer,nvar^2); +%** for lz annual vd +Range5{8} =zeros(imstpyer,nvar^2,2); % 2: min and max +Range5{8}(:,:,1) = zeros(imstpyer,nvar^2); % min, 5 std. +Range5{8}(:,:,2) = 100*ones(imstpyer,nvar^2); % max, 5 std. + % Range5(8)(:,:,1): imstpyer-by-nvar^2. Column: nvar responses to 1st shock, + % nvar responses to 2nd shock, ... + +%**** Correlations among structural shocks +philr = phi(size(phi,1)-actup+1,:); % +1 is absolutely needed +yexa = yact(1:actup,:); +Estrexaml = fidcndexa(yexa,philr,A0ml,Bhml,nvar,lags,actup); % actup-by-nvar +sckvarml = (Estrexaml'*Estrexaml)/actup; +sckcorml = corr(sckvarml); +%** for shock correlation sckcor +Range5{9} =zeros(nvar,nvar,2); % 2: min and max +Range5{9}(:,:,1) = (-1)*ones(nvar,nvar); % min, 5 std. +Range5{9}(:,:,2) = ones(nvar,nvar); % max, 5 std. + % Range5(9)(:,:,1): nvar^2. Correlation among structural shocks + + + + +%** +invc = cell(9,1); % interval length (used for counting later). +for i=[1:4 6:9] + invc{i} = Range5{i}(:,:,2) - Range5{i}(:,:,1); +end +invc{5} = Range5{5}(:,2) - Range5{5}(:,1); +% +imfhbin = invc{4} ./ ninv; % bin size for each point of impulse responses +imfloor = Range5{4}(:,:,1); % lowest point next to -infinity +Avhxhbin = invc{5} ./ ninv; % bin size for each point of A0 +Avhxfloor = Range5{5}(:,1); % lowest point next to -infinity +imfyerhbin = invc{6} ./ ninv; % bin size for each point of annual impulse responses +imfyerfloor = Range5{6}(:,:,1); % lowest point next to -infinity +lzvdhbin = invc{7} ./ ninv; % bin size for each point of variance decompositions +lzvdfloor = Range5{7}(:,:,1); % lowest point next to -infinity +lzvdyerhbin = invc{8} ./ ninv; % bin size for each point of annul variance decompositions +lzvdyerfloor = Range5{8}(:,:,1); % lowest point next to -infinity +sckcorhbin = invc{9} ./ ninv; % bin size for each point of shock correlations +sckcorfloor = Range5{9}(:,:,1); % lowest point next to -infinity + + + + +%*** <<>> Specific requests +%*** compute prob(parameter>0) or joint prob. of sign matches in MP and MD +if sa0indx + csix1a0 = [-1 -1 1 1 1 -1 1]'; % for 7 parameters in MP and MD + % from 7th to 13th in Avhx_norm + nspeca0 = 7+3; % number of specific requests + % additional 3: 1 for all MP parameters; 2 for all MD parameters; + % 3 for all paramters in MP and MD + cspeca0 = zeros(nspeca0,1); +end +% +if simfindx + csix1imf = [-1 -1 1 -1 -1 1]'; % for 6 variables to MP shock + % maybe at different horizons (esp. for inflation) + csix1pimf = [1 1 1 24 36 24]'; % the periods for the 6 varialbes to MP shock + % Pcm, M2, FFR, y, P, U. + nspecimf = nvar+2; % number of specific requests + % additional 1: 1 for opposite signs of M2 and R + cspecimf = zeros(nspecimf,1); +end + + + + +%=================================== +% Here begins with the big loop +%=================================== +H1 = chol(hess); % upper triangular so that H1' is a lower triangular decomp +baseW = H_sr; %inv(H1); %H_sr; % covariance matrix without scaling +nswitch=0; %<<>> total number of sign switches +A0inxhat = inv(A0xhat); % inverse of ML estimate +a0indx0 = find(idmat0==0); % index for all zero's in A0; +nn=[nvar lags imstp]; + +[cT,vR,kdf] = gibbsglb(Sbd,idmat0,nvar,fss); + +tic +for starts = 1:nstarts + starts + if starts == 1 + A0gbs(a0indx) = xhat; % from "load ..." + if ~IndxGibbs % Metropolist + Avhx = xhat; + hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); + hAvhx = -hAvhx; % converted to logLH + end + else + Avhx = baseW*randn(nfp,1); %H_sr*randn(nfp,1); % D: discarded sequence + csq=randn(tdf,1); + csq=sum(csq .* csq); + Avhx = xhat+Avhx/sqrt(csq/tdf); + %** Normalization by the choice of IndxNmlr + A0gbs(a0indx) = Avhx; + if ~IndxNmlr(5) + [A0gbs,jnk] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); + else + A0ingbs = inv(A0gbs); + [A0gbs,jnk,jnk1] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); + end + % + if ~IndxGibbs % Metropolist + Avhx = A0gbs(a0indx); + hAvhx = a0asfun(Avhx,Sbd,fss,nvar,a0indx); + hAvhx = -hAvhx; % converted to logLH + end + end + % + cJump = 0; + + imfcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count; for impulse responses + Avhxcnt = zeros(ninv+2,nfp); % cnt: count; for A0's + imfyercnt = zeros(ninv+2,imstpyer*nvar^2); % cnt: count; for impulse responses + lzvdcnt = zeros(ninv+2,imstp*nvar^2); % cnt: count; for lz vd (non-cumulative) + lzvdyercnt = zeros(ninv+2,imstpyer*nvar^2); % cnt: count; for lz annual vd (non-cumulative) + sckcorcnt = zeros(ninv+2,nvar^2); % cnt: count; for shock correlations + + for draws = 1:ndraws1 + if IndxGibbs + A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); + else % Metropolis + [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... + baseW,nfp,Sbd,fss,nvar,a0indx); + end + end + + wdraws=(starts-1)*ndraws2+0; + for draws = 1:ndraws2 + drawsc = (starts-1)*ndraws2+draws; + if IndxGibbs + A0gbs = gibbsvar(A0gbs,cT,vR,nvar,fss,kdf); + A0gbs(a0indx0) = 0; % set all zeros in A0gbs clean to avoid possible cumulative round-off errors + else % Metropolis + [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... + baseW,nfp,Sbd,fss,nvar,a0indx); + A0gbs(a0indx) = Avhx; + end + + %*** call normalization so that A0_h is normalized + if ~IndxNmlr(5) + [A0_h,nswitch] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,[]); + A0_hin = inv(A0_h); + else + A0ingbs = inv(A0gbs); + [A0_h,nswitch,A0_hin] = nmlzvar(A0gbs,A0xhat,A0inxhat,IndxNmlr,nswitch,A0ingbs); + end + Avhx_norm = A0_h(a0indx); + + if sa0indx + for k=1:7 + cspeca0(k) = cspeca0(k) + ((csix1a0(k)*Avhx_norm(6+k))>0); + end + %*** Joint tests + j1=csix1a0; + j2=Avhx_norm; + %** MP equation + mpall = ((j1(2)*j2(8))/(j1(3)*j2(9)))<0; % & ((j1(1)*j2(7))/(j1(3)*j2(9)))<0; + + cspeca0(8) = cspeca0(8) + mpall; + %** MD equation + mdall = ((j1(4)*j2(10))/(j1(5)*j2(11)))<0; %& ((j1(4)*j2(10))/(j1(6)*j2(12)))<0; + cspeca0(9) = cspeca0(9) + mdall; + mpdall = mpall & mdall; + cspeca0(10) = cspeca0(10) + mpdall; + end + + % + % *** normal draws for posterior Aplus conditional on A0h + % + %** the mean is Aplushm, and the covariance is inv(xxhp)=Lxxhpc*Lxxhpc' + Apindm = randn(ncoef,nvar); + % + if ~all(all(finite(Bhml))) + Aplushm=zeros(ncoef,nvar); + for i=1:nvar + Aplushm(:,i)=Gb{i}*A0_h(:,i); % see Zha's forecast (1) p.9 + % Here, Gb is used to compute A+ where A+(i) = Gb(i)*a0(i) + end + Bh_h = (Aplushm + xxhpc\Apindm)*A0_hin; + else + Bh_h = Bhml + (xxhpc\Apindm)*A0_hin; + end + + if ImfErr + swish_h = A0_hin'; % Switching back to the form A0*y(t) = e(t) + imf_h = zimpulse(Bh_h,swish_h,nn); % in the form that is congenial to RATS + imf3_h=reshape(imf_h,size(imf_h,1),nvar,nvar); + % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks + imfmean = imfmean + imf_h; % posterior mean + imfs = imfs + imf_h.^2; % posterior 2nd moment + imfcnt = empdfsort(imfcnt,imf_h,imfloor,imfhbin,ninv); + % sorted counts (prob.) in bins + + %**** annula impulse responses + for k=1:imstpyer + yer3(k+1,:,:) = mean(imf3_h(1+q_m*(k-1):q_m*k,:,:),1); % annual average + % yer3: initialized earlier already + % yer3: row--steps, column--nvar responses, 3rd dimension--nvar shocks + end + imfyer3_h(:,vlistlog,:) = ( exp(yer3(2:1+imstpyer,vlistlog,:)-yer3(1:imstpyer,vlistlog,:)) - 1 ).*100; + imfyer3_h(:,vlistper,:) = yer3(2:1+imstpyer,vlistper,:) .* 100; + % imfyer3_h: row--steps, column--nvar responses, 3rd dimension--nvar shocks + imfyer_h = reshape(imfyer3_h,imstpyer,nvar^2); + imfyermean = imfyermean + imfyer_h; % posterior mean + imfyers = imfyers + imfyer_h.^2; % posterior 2nd moment + imfyercnt = empdfsort(imfyercnt,imfyer_h,imfyerfloor,imfyerhbin,ninv); + % sorted counts (prob.) in bins + + %**** Leeper-Zha variance decomposition (non-cumulative) + tmp0=abs(imf3_h); + tmp = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 + % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks + lzvd3_h = 100*(tmp0./tmp); + lzvd_h = reshape(lzvd3_h,imstp,nvar^2); + lzvdcnt = empdfsort(lzvdcnt,lzvd_h,lzvdfloor,lzvdhbin,ninv); + % sorted counts (prob.) in bins + + %**** Leeper-Zha annual variance decomposition (non-cumulative) + tmp0=abs(imfyer3_h); + tmp = repmat(sum(tmp0,3),[1 1 nvar]); % imstp-by-nvar^2 + % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks + lzvdyer3_h = 100*(tmp0./tmp); + lzvdyer_h = reshape(lzvdyer3_h,imstpyer,nvar^2); + lzvdyercnt = empdfsort(lzvdyercnt,lzvdyer_h,lzvdyerfloor,lzvdyerhbin,ninv); + % sorted counts (prob.) in bins + + %**** Correlations among structural shocks + Estrexa_h = fidcndexa(yexa,philr,A0_h,Bh_h,nvar,lags,actup); % actup-by-nvar + sckvar_h = (Estrexa_h'*Estrexa_h)/actup; + sckcor_h = corr(sckvar_h); + sckcorcnt = empdfsort(sckcorcnt,sckcor_h,sckcorfloor,sckcorhbin,ninv); + + if simfindx + for k=1:6 + cspecimf(k) = cspecimf(k) + ((csix1a0(k)*imf_h(1,nvar+k))>0); + % 1st dim in imf_h: periods + end + %*** Joint tests + j1=csix1imf; + j2=imf_h; + j3=csix1pimf; + %** M2 and R in MP equation + mpall = ((j1(2)*j2(j3(2),nvar+2))/(j1(3)*j2(j3(3),nvar+3)))>0; % & ((j1(1)*j2(7))/(j1(3)*j2(9)))<0; + % 1st dim in j2: periods + cspecimf(nvar+1) = cspecimf(nvar+1) + mpall; + %** R and P in MP equation + mpall = ((j1(3)*j2(j3(3),nvar+3))/(j1(5)*j2(j3(5),nvar+5)))>0; % + % 1st dim in j2: periods + cspecimf(nvar+2) = cspecimf(nvar+2) + mpall; + % + % %** MD equation + % mdall = ((j1(4)*j2(10))/(j1(5)*j2(11)))<0; %& ((j1(4)*j2(10))/(j1(6)*j2(12)))<0; + % cspeca0(9) = cspeca0(9) + mdall; + % mpdall = mpall & mdall; + % cspeca0(10) = cspeca0(10) + mpdall; + end + end + + Avhxmean = Avhxmean + Avhx_norm; % 1st step to overall mean of parameter + Avhxs = Avhxs + Avhx_norm.^2; % 1st step to overall 2nd moment of parameter + Avhxcnt = empdfsort(Avhxcnt,Avhx_norm,Avhxfloor,Avhxhbin,ninv); + + + % A0hatw(:,drawsc-wdraws) = A0_h(:); + if ~mod(draws,nbuffer) + starts + draws + wdraws=drawsc + % fwriteid = fopen('outA0.bin','a'); + % count = fwrite(fwriteid,A0hatw,'double'); + % status = fclose('all'); + end + end + % + imfcntmulti(:,:,starts) = imfcnt; + Avhxcntmulti(:,:,starts) = Avhxcnt; + imfyercntmulti(:,:,starts) = imfyercnt; + lzvdcntmulti(:,:,starts) = lzvdcnt; + lzvdyercntmulti(:,:,starts) = lzvdyercnt; + sckcorcntmulti(:,:,starts) = sckcorcnt; + + if ~IndxGibbs + countJump(starts,1) = cJump; + end +end +timend = toc +timeminutes=timend/60 + +if ~IndxGibbs + countJump = countJump/ndraws2 +end + +Avhxmean = Avhxmean/(imndraws); +Avhxs = Avhxs/(imndraws); +Avhxs = sqrt(Avhxs - Avhxmean.^2); % stardard deviation +A0hm = zeros(nvar); +A0hm(a0indx) = Avhxmean % mean +A0hs = zeros(nvar); +A0hs(a0indx) = Avhxs; % standar deviation + +imfmean = imfmean/(imndraws); +imfs = imfs/imndraws; +imfs = sqrt(imfs - imfmean.^2); % standard deviation + +imfyermean = imfyermean/(imndraws); +imfyers = imfyers/imndraws; +imfyers = sqrt(imfyers - imfyermean.^2); % standard deviation + + +save outB_W nstarts ndraws1 ndraws2 imndraws timeminutes Avhxml Avhxmean Avhxs ... + Avhxcntmulti A0xhat A0hm A0hs IndxGibbs countJump nvar Range5 ... + ninv invc nfp a0indx nswitch actup nSample lags yrEnd qmEnd ... + yrStart qmStart q_m sckcorml sckcorcntmulti + +if ImfErr + if simfindx + cspecimf = cspecimf/imndraws; + save outB_W cspecimf -append + end + save outB_W imfml imfmean imfs imfcntmulti imstp cspecimf ... + imfyerml imfyermean imfyers imfyercntmulti imstpyer ... + lzvdml lzvdcntmulti lzvdyerml lzvdyercntmulti -append +end +% +if sa0indx + cspeca0 = cspeca0/imndraws; + save outB_W cspeca0 -append +end + + diff --git a/MatlabFiles/impgraphs.m b/MatlabFiles/impgraphs.m index e7eeadd8a2eca74a3966843b9ebee94f3cf0bfc2..62ae192cefd0716b4cd922bf86ed679ddb41e095 100644 --- a/MatlabFiles/impgraphs.m +++ b/MatlabFiles/impgraphs.m @@ -1,73 +1,73 @@ -function impgraphs(response,collabel,rowlabel) -%function impgraphs(response,collabel,rowlabel) -% collabel and rowlabel are cell arrays with string contents -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -XTick=[12 24 36 48]; %modify this line for other time units. -%XTickLabel=[] % Use this to suppress labeling. -[nrow,ncol,nt]=size(response); -for irow=1:nrow - smin=min(min(response(irow,:,:))); - smax=max(max(response(irow,:,:))); - if smin<0 - if smax<=0 - yt=[smin 0]; - else - yt=[smin 0 smax]; - end - else % (smin >=0) - if smax > 0 - yt=[0 smax]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - for i=1:length(yt) - if yt(i)==0.0 - if length(yt)==3 & -yt(1)<.2*yt(3) - ytc(i)={''}; - else - ytc(i)={' 0'}; - end - else - ytc(i)={sprintf('%2.4f',yt(i))}; - end - end - scale=[1 nt smin smax]; - for icol=1:ncol - subplot(nrow,ncol,(irow-1)*ncol+icol); - plot(squeeze(response(irow,icol,:)));grid - axis(scale); - if irow==1 - title(collabel{icol}); - end - if icol==1 - ylabel(rowlabel{irow}); - end - set(gca,'XTick',XTick) - set(gca,'YTick',yt) - if irow<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - if icol>1 - set(gca,'YTickLabelMode','manual','YTickLabel',[]) - else - set(gca,'YTickLabelMode','manual','YTickLabel',char(ytc)) - end - end -end \ No newline at end of file +function impgraphs(response,collabel,rowlabel) +%function impgraphs(response,collabel,rowlabel) +% collabel and rowlabel are cell arrays with string contents +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +XTick=[12 24 36 48]; %modify this line for other time units. +%XTickLabel=[] % Use this to suppress labeling. +[nrow,ncol,nt]=size(response); +for irow=1:nrow + smin=min(min(response(irow,:,:))); + smax=max(max(response(irow,:,:))); + if smin<0 + if smax<=0 + yt=[smin 0]; + else + yt=[smin 0 smax]; + end + else % (smin >=0) + if smax > 0 + yt=[0 smax]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + for i=1:length(yt) + if yt(i)==0.0 + if length(yt)==3 & -yt(1)<.2*yt(3) + ytc(i)={''}; + else + ytc(i)={' 0'}; + end + else + ytc(i)={sprintf('%2.4f',yt(i))}; + end + end + scale=[1 nt smin smax]; + for icol=1:ncol + subplot(nrow,ncol,(irow-1)*ncol+icol); + plot(squeeze(response(irow,icol,:)));grid + axis(scale); + if irow==1 + title(collabel{icol}); + end + if icol==1 + ylabel(rowlabel{irow}); + end + set(gca,'XTick',XTick) + set(gca,'YTick',yt) + if irow<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + if icol>1 + set(gca,'YTickLabelMode','manual','YTickLabel',[]) + else + set(gca,'YTickLabelMode','manual','YTickLabel',char(ytc)) + end + end +end diff --git a/MatlabFiles/impulseo.m b/MatlabFiles/impulseo.m index f72badda2f86ae90ca4fc1dc87a10d9bcdc4e91d..0497c11f50f590cc42093982167bc37fb330b744 100644 --- a/MatlabFiles/impulseo.m +++ b/MatlabFiles/impulseo.m @@ -1,77 +1,77 @@ -function imf = impulseo(Bh,swish,nn) -% impulse: computing impulse functions with -% imf = impulseo(Bh,swish) -% where imf is in a format that is conveninet to generate the RATS graphics; -% Bh is the estimated reduced form coefficient in the form -% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix -% form or dimension is the same as "Bh" from the function "sye"; -% swish is the inv(A0) in the structural model A(L)y(t) = e(t). -% nn is the numbers of inputs [nvar,lags,# of impulse responses]. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nvar = nn(1); -lags = nn(2); -imstep = nn(3); % number of steps for impulse responses - -Ah = Bh'; -% Row: nvar equations -% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. - -imf = zeros(imstep,nvar*nvar); -% Column: 1st variable response to nvar shocks, 2nd variable response to -% nvar shocks, and so on. -% Row: steps of impulse responses. -M = zeros(nvar*(lags+1),nvar); -% Stack M0;M1;M2:...;Mlags -M(1:nvar,:) = swish; -Mtem = M(1:nvar,:); % temporary M. -% first (initial) responses to 1 standard deviation shock. Row: responses; Column: shocks -% * put in the form of "imf" -Mtem = Mtem'; -imf(1,:) = Mtem(:)'; - -t = 1; -ims1 = min([imstep-1 lags]); -while t <= ims1 - Mtem = zeros(nvar,nvar); - for k = 1:t - Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(t-k)+1:nvar*(t-k+1),:) + Mtem; - % Row: nvar equations, each for the nvar variables at tth lag - end - M(nvar*t+1:nvar*(t+1),:) = Mtem; - Mtem = Mtem'; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 1st variable to nvar shocks, - % 2nd variable to nvar shocks, etc. - t= t+1; -end - -for t = lags+1:imstep-1 - M(1:nvar*lags,:) = M(nvar+1:nvar*(lags+1),:); - Mtem = zeros(nvar,nvar); - for k = 1:lags - Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(lags-k)+1:nvar*(lags-k+1),:) + Mtem; - % Row: nvar equations, each for the nvar variables at tth lag - end - M(nvar*lags+1:nvar*(lags+1),:) = Mtem; - Mtem = Mtem'; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 1st variable to nvar shocks, - % 2nd variable to nvar shocks, etc. -end - \ No newline at end of file +function imf = impulseo(Bh,swish,nn) +% impulse: computing impulse functions with +% imf = impulseo(Bh,swish) +% where imf is in a format that is conveninet to generate the RATS graphics; +% Bh is the estimated reduced form coefficient in the form +% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix +% form or dimension is the same as "Bh" from the function "sye"; +% swish is the inv(A0) in the structural model A(L)y(t) = e(t). +% nn is the numbers of inputs [nvar,lags,# of impulse responses]. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nvar = nn(1); +lags = nn(2); +imstep = nn(3); % number of steps for impulse responses + +Ah = Bh'; +% Row: nvar equations +% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. + +imf = zeros(imstep,nvar*nvar); +% Column: 1st variable response to nvar shocks, 2nd variable response to +% nvar shocks, and so on. +% Row: steps of impulse responses. +M = zeros(nvar*(lags+1),nvar); +% Stack M0;M1;M2:...;Mlags +M(1:nvar,:) = swish; +Mtem = M(1:nvar,:); % temporary M. +% first (initial) responses to 1 standard deviation shock. Row: responses; Column: shocks +% * put in the form of "imf" +Mtem = Mtem'; +imf(1,:) = Mtem(:)'; + +t = 1; +ims1 = min([imstep-1 lags]); +while t <= ims1 + Mtem = zeros(nvar,nvar); + for k = 1:t + Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(t-k)+1:nvar*(t-k+1),:) + Mtem; + % Row: nvar equations, each for the nvar variables at tth lag + end + M(nvar*t+1:nvar*(t+1),:) = Mtem; + Mtem = Mtem'; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 1st variable to nvar shocks, + % 2nd variable to nvar shocks, etc. + t= t+1; +end + +for t = lags+1:imstep-1 + M(1:nvar*lags,:) = M(nvar+1:nvar*(lags+1),:); + Mtem = zeros(nvar,nvar); + for k = 1:lags + Mtem = Ah(:,nvar*(k-1)+1:nvar*k)*M(nvar*(lags-k)+1:nvar*(lags-k+1),:) + Mtem; + % Row: nvar equations, each for the nvar variables at tth lag + end + M(nvar*lags+1:nvar*(lags+1),:) = Mtem; + Mtem = Mtem'; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 1st variable to nvar shocks, + % 2nd variable to nvar shocks, etc. +end + diff --git a/MatlabFiles/imrgraph.m b/MatlabFiles/imrgraph.m index b05eab206034a9256d2be9b743fae0d04d55eacf..45373932d3b832839f00412372b832f1130622ed 100644 --- a/MatlabFiles/imrgraph.m +++ b/MatlabFiles/imrgraph.m @@ -1,71 +1,71 @@ -function scaleout = imrgraph(imf,nvar,imstp,xlab,ylab) -% function scaleout = imrgraph(imf,nvar,imstp,xlab,ylab) -% imcgraph: impulse, r (row: shock 1 to N), graph -% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock -% etc), row (impusle steps), -% nvar: number of variables -% imstp: step of impulse responses -% xlab,ylab: labels -% -% See imcgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -t = 1:imstp; -temp1=zeros(nvar,1); -temp2=zeros(nvar,1); -maxval=zeros(nvar,1); -minval=zeros(nvar,1); -for i = 1:nvar - for j = 1:nvar - temp1(j)=max(imf(:,(j-1)*nvar+i)); - temp2(j)=min(imf(:,(j-1)*nvar+i)); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Reponses; Row i: Shock 1 to N -%------------- -figure -rowlabel = 1; -for i = 1:nvar - columnlabel = 1; - for j = 1:nvar - k=(i-1)*nvar+j; - subplot(nvar,nvar,k) - plot(t,imf(:,k),t,zeros(length(imf(:,k)),1),':' ); - set(gca,'YLim',[minval(j) maxval(j)]) - set(gca,'XTickLabel',' '); - set(gca,'YTickLabel',' '); - if rowlabel == 1 - %title(['X' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['X' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; -end \ No newline at end of file +function scaleout = imrgraph(imf,nvar,imstp,xlab,ylab) +% function scaleout = imrgraph(imf,nvar,imstp,xlab,ylab) +% imcgraph: impulse, r (row: shock 1 to N), graph +% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock +% etc), row (impusle steps), +% nvar: number of variables +% imstp: step of impulse responses +% xlab,ylab: labels +% +% See imcgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +t = 1:imstp; +temp1=zeros(nvar,1); +temp2=zeros(nvar,1); +maxval=zeros(nvar,1); +minval=zeros(nvar,1); +for i = 1:nvar + for j = 1:nvar + temp1(j)=max(imf(:,(j-1)*nvar+i)); + temp2(j)=min(imf(:,(j-1)*nvar+i)); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Reponses; Row i: Shock 1 to N +%------------- +figure +rowlabel = 1; +for i = 1:nvar + columnlabel = 1; + for j = 1:nvar + k=(i-1)*nvar+j; + subplot(nvar,nvar,k) + plot(t,imf(:,k),t,zeros(length(imf(:,k)),1),':' ); + set(gca,'YLim',[minval(j) maxval(j)]) + set(gca,'XTickLabel',' '); + set(gca,'YTickLabel',' '); + if rowlabel == 1 + %title(['X' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['X' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/invgamcdf.m b/MatlabFiles/invgamcdf.m index 8058d644f607ce0528041e3f837ca5a7d346655d..366ee28e28aa742f83cd6ceb43269e980dea7031 100644 --- a/MatlabFiles/invgamcdf.m +++ b/MatlabFiles/invgamcdf.m @@ -1,44 +1,44 @@ -function P = invgamcdf(X, a, b); - -% This function computes the cumulative density for the inverse gamma -% distribution with shape parameter a and scale parameter b. It uses the -% following closed-form solution for the cdf of the inverse gamma -% distribution: -% ---------Cumulative density function for Inverse-Gamma distribution------- -% --- P(x; a, b) = G(b/x, a)/G(a), where G(b/x, a) is the upper incomplete -% gamma function and G(a) is the gamma function defined as -% G(b/x, a) = int_{b/x}^{\infty} t^{a-1} e^{-t} dt. -% The Matlab definition is different, which is -% gammainc(b/x, a) = (1.0/Gamma(a)) int_{0}^{b/x} t^{a-1} e^{-t} dt. -% Thus, we have -% G(b/x, a)/G(a) = (1-gammainc(b./X, a)). - -% First, check for input errors -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if X<=0; - error('the support for the inverse gamma function needs to be positive') -end; -if a<= 0 || b <=0; - a = abs(a); - b = abs(b); - % abs() is used to allow continuous search for the fsolve function find_invgampar.m. - %error('parameter requirements: a>0, b>0'); -end; - -P = (1-gammainc(b./X, a)); +function P = invgamcdf(X, a, b); + +% This function computes the cumulative density for the inverse gamma +% distribution with shape parameter a and scale parameter b. It uses the +% following closed-form solution for the cdf of the inverse gamma +% distribution: +% ---------Cumulative density function for Inverse-Gamma distribution------- +% --- P(x; a, b) = G(b/x, a)/G(a), where G(b/x, a) is the upper incomplete +% gamma function and G(a) is the gamma function defined as +% G(b/x, a) = int_{b/x}^{\infty} t^{a-1} e^{-t} dt. +% The Matlab definition is different, which is +% gammainc(b/x, a) = (1.0/Gamma(a)) int_{0}^{b/x} t^{a-1} e^{-t} dt. +% Thus, we have +% G(b/x, a)/G(a) = (1-gammainc(b./X, a)). + +% First, check for input errors +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if X<=0; + error('the support for the inverse gamma function needs to be positive') +end; +if a<= 0 || b <=0; + a = abs(a); + b = abs(b); + % abs() is used to allow continuous search for the fsolve function find_invgampar.m. + %error('parameter requirements: a>0, b>0'); +end; + +P = (1-gammainc(b./X, a)); diff --git a/MatlabFiles/invgampar.m b/MatlabFiles/invgampar.m index 97b6004909d8e192f2d12cdbe23335849fbf551e..28437282ed8167f574de94bcda6a6d857ca2020a 100644 --- a/MatlabFiles/invgampar.m +++ b/MatlabFiles/invgampar.m @@ -1,28 +1,28 @@ -function f = invgampar(ab, XLO, XUP, PLO, PUP); - -% The function takes as inputs the parameters ab=[a, b] of the Inverse gamma -% distribution, the bounds of the support [XLO, XUP], the the corresponding -% probability of the bounds [PLO, PUP] and returns the residual value f. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -a = ab(1); b = ab(2); -f1 = PLO - invgamcdf(XLO, a, b); -f2 = PUP - invgamcdf(XUP, a, b); - -f = [f1, f2]; +function f = invgampar(ab, XLO, XUP, PLO, PUP); + +% The function takes as inputs the parameters ab=[a, b] of the Inverse gamma +% distribution, the bounds of the support [XLO, XUP], the the corresponding +% probability of the bounds [PLO, PUP] and returns the residual value f. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +a = ab(1); b = ab(2); +f1 = PLO - invgamcdf(XLO, a, b); +f2 = PUP - invgamcdf(XUP, a, b); + +f = [f1, f2]; diff --git a/MatlabFiles/lcnmean.m b/MatlabFiles/lcnmean.m index b516e1d9f6264244f05222f05f3b8da73ccbeed3..553ead1f40bc5febf238fc9db4e4209cc2302863 100644 --- a/MatlabFiles/lcnmean.m +++ b/MatlabFiles/lcnmean.m @@ -1,35 +1,35 @@ -function cutmean = lcnmean(x,pnIndx) -% -% cutmean = lcnmean(x,pnIndx) -% -% The mean of the truncated normal with the lower bound x if pnIndx>0 -% or the upper bound x if pnIndx<0. Zha Forecast (2) p.27 -% -% x: the lower bound x if pnIndx > 0; the upper bound x if pnIndx < 0 -% pnIndx: 1: truncated for posivie mean (tight); 0 truncated for negative mean (loose) -%------------ -% cutmean: the backed-out mean for the truncated normal -% -% October 1998 Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if pnIndx - cutmean = exp(-x^2/2)/(sqrt(2*pi)*(1-cdf('norm',x,0,1))); -else - cutmean = -exp(-x^2/2)/(sqrt(2*pi)*cdf('norm',x,0,1)); -end +function cutmean = lcnmean(x,pnIndx) +% +% cutmean = lcnmean(x,pnIndx) +% +% The mean of the truncated normal with the lower bound x if pnIndx>0 +% or the upper bound x if pnIndx<0. Zha Forecast (2) p.27 +% +% x: the lower bound x if pnIndx > 0; the upper bound x if pnIndx < 0 +% pnIndx: 1: truncated for posivie mean (tight); 0 truncated for negative mean (loose) +%------------ +% cutmean: the backed-out mean for the truncated normal +% +% October 1998 Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if pnIndx + cutmean = exp(-x^2/2)/(sqrt(2*pi)*(1-cdf('norm',x,0,1))); +else + cutmean = -exp(-x^2/2)/(sqrt(2*pi)*cdf('norm',x,0,1)); +end diff --git a/MatlabFiles/mformd.m b/MatlabFiles/mformd.m index 5f869dc97b08f5c62e23da565e8fada1c8b60f79..20adcfd963d334fce4683d52e5c5b8f3c5e2e17a 100644 --- a/MatlabFiles/mformd.m +++ b/MatlabFiles/mformd.m @@ -1,49 +1,49 @@ -function [phi,YtY] = mformd(z,nn) -% mformd: arrange matrix form data: [Y,YtY] = mformd(z,nn) as structural form -% YA = E, Y: T*(nvar*lags+nvar+1) -% -% where z is the (T+lags)-by-(nvar+1) raw data matrix (nvar of variables + constant); -% nn is the numbers of inputs [nvar,lags,sample period (total)]; -% phi: Y as in the structural form YA = E, Y: T*(nvar*lags+nvar+1) -% YtY: Y'Y: (nvar*lags+nvar+1)*(nvar*lags+nvar+1) -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup of orders and lengths ** -nvar = nn(1); -lags = nn(2); -sp = nn(3); % sample period - -ess = sp-lags; % effective sample size -sb = lags+1; % sample beginning -sl = sp; % sample last period -ncoe = nvar*lags + nvar + 1; % with constant and contemporaneous data - -% ** construct Y as in YA = E where phi = Y ** -x = z(:,1:nvar); -C = z(:,nvar+1); -phi = zeros(ess,ncoe); -phi(:,1:nvar) = x(sb:sl,:); -phi(:,ncoe) = C(1:ess); -for k=1:lags, phi(:,nvar*k+1:nvar*(k+1)) = x(sb-k:sl-k,:); end -% column: T; row: [nvar for 0th lag, nvar for 1st lag, -% ..., nvar for last lag, const] -% Thus, # of columns is nvar*lags+nvar+1 = ncoef. -% ** YtY, residuals ** -[u d v]=svd(phi,0); %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -YtY=vd*vd'; % YtY = phi'*phi; % X'X, k*k (ncoe*ncoe) \ No newline at end of file +function [phi,YtY] = mformd(z,nn) +% mformd: arrange matrix form data: [Y,YtY] = mformd(z,nn) as structural form +% YA = E, Y: T*(nvar*lags+nvar+1) +% +% where z is the (T+lags)-by-(nvar+1) raw data matrix (nvar of variables + constant); +% nn is the numbers of inputs [nvar,lags,sample period (total)]; +% phi: Y as in the structural form YA = E, Y: T*(nvar*lags+nvar+1) +% YtY: Y'Y: (nvar*lags+nvar+1)*(nvar*lags+nvar+1) +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup of orders and lengths ** +nvar = nn(1); +lags = nn(2); +sp = nn(3); % sample period + +ess = sp-lags; % effective sample size +sb = lags+1; % sample beginning +sl = sp; % sample last period +ncoe = nvar*lags + nvar + 1; % with constant and contemporaneous data + +% ** construct Y as in YA = E where phi = Y ** +x = z(:,1:nvar); +C = z(:,nvar+1); +phi = zeros(ess,ncoe); +phi(:,1:nvar) = x(sb:sl,:); +phi(:,ncoe) = C(1:ess); +for k=1:lags, phi(:,nvar*k+1:nvar*(k+1)) = x(sb-k:sl-k,:); end +% column: T; row: [nvar for 0th lag, nvar for 1st lag, +% ..., nvar for last lag, const] +% Thus, # of columns is nvar*lags+nvar+1 = ncoef. +% ** YtY, residuals ** +[u d v]=svd(phi,0); %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +YtY=vd*vd'; % YtY = phi'*phi; % X'X, k*k (ncoe*ncoe) diff --git a/MatlabFiles/mformd1.m b/MatlabFiles/mformd1.m index 3f5f4afc4fa691c5a6b30f151268235a16c7418d..56bf1a908fd69eeba7476002bf100d1d5a8e47d2 100644 --- a/MatlabFiles/mformd1.m +++ b/MatlabFiles/mformd1.m @@ -1,70 +1,70 @@ -function [phi,y,ncoe] = mformd1(z,lags) -% -% [phi,y,ncoe] = mformd1(z,lags) where size(z,1)=T+lags. -% This file is a subset of sye.m, but only designed to arrange matrix form data as -% y(T*nvar) = XB + u, X--phi: T*k, B: k*nvar; where T=sp-lags, k=ncoe. -% Note T>=0. If T=0, y is empty, but phi (X) is still well defined. -% -% z: (T+lags)-by-(nvar+1) raw data matrix (nvar of variables + constant). -% e.g., C = ones(nSample,1); z=[xdget C]; -% lags: number of lags -% phi: (T-lags)-by-k X; where k=ncoe=[nvar for 1st lag, ..., nvar for last lag, const] -% y: Y: (T-lags)-by-nvar -% ncoe: number of coeffcients per equation: k=nvar*lags + 1 -% -% See also sye.m -% -% October 1998 Tao Zha. Revised, 03/13/99 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -% ** setup of orders and lengths ** -[sp,nvar] = size(z); % sp: sample period T include lags -nvar = nvar-1; % -1: takes out the counting of constant - -ess = sp-lags; % effective sample size -sb = lags+1; % sample beginning -sl = sp; % sample last period -ncoe = nvar*lags + 1; % with constant - -% ** construct X for Y = X*B + U where phi = X ** -if ess<0 - warning('The length of the data must be >= lags') - disp('Check yrEnd and qmEnd in parac.m to make sure') - disp('Press ctrl-c to abort') - disp(' ') - pause -elseif ess==0 - x = z(:,1:nvar); - C = z(:,nvar+1); - phi = zeros(1,ncoe); - phi(1,ncoe) = C(1); - for k=1:lags, phi(1,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k+1,:); end - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] - % Thus, # of columns is nvar*lags+1 = ncoef. - y = x(sb:sl,:); -else - x = z(:,1:nvar); - C = z(:,nvar+1); - phi = zeros(ess,ncoe); - phi(:,ncoe) = C(1:ess); - for k=1:lags, phi(:,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k,:); end - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] - % Thus, # of columns is nvar*lags+1 = ncoef. - y = x(sb:sl,:); -end \ No newline at end of file +function [phi,y,ncoe] = mformd1(z,lags) +% +% [phi,y,ncoe] = mformd1(z,lags) where size(z,1)=T+lags. +% This file is a subset of sye.m, but only designed to arrange matrix form data as +% y(T*nvar) = XB + u, X--phi: T*k, B: k*nvar; where T=sp-lags, k=ncoe. +% Note T>=0. If T=0, y is empty, but phi (X) is still well defined. +% +% z: (T+lags)-by-(nvar+1) raw data matrix (nvar of variables + constant). +% e.g., C = ones(nSample,1); z=[xdget C]; +% lags: number of lags +% phi: (T-lags)-by-k X; where k=ncoe=[nvar for 1st lag, ..., nvar for last lag, const] +% y: Y: (T-lags)-by-nvar +% ncoe: number of coeffcients per equation: k=nvar*lags + 1 +% +% See also sye.m +% +% October 1998 Tao Zha. Revised, 03/13/99 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +% ** setup of orders and lengths ** +[sp,nvar] = size(z); % sp: sample period T include lags +nvar = nvar-1; % -1: takes out the counting of constant + +ess = sp-lags; % effective sample size +sb = lags+1; % sample beginning +sl = sp; % sample last period +ncoe = nvar*lags + 1; % with constant + +% ** construct X for Y = X*B + U where phi = X ** +if ess<0 + warning('The length of the data must be >= lags') + disp('Check yrEnd and qmEnd in parac.m to make sure') + disp('Press ctrl-c to abort') + disp(' ') + pause +elseif ess==0 + x = z(:,1:nvar); + C = z(:,nvar+1); + phi = zeros(1,ncoe); + phi(1,ncoe) = C(1); + for k=1:lags, phi(1,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k+1,:); end + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] + % Thus, # of columns is nvar*lags+1 = ncoef. + y = x(sb:sl,:); +else + x = z(:,1:nvar); + C = z(:,nvar+1); + phi = zeros(ess,ncoe); + phi(:,ncoe) = C(1:ess); + for k=1:lags, phi(:,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k,:); end + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] + % Thus, # of columns is nvar*lags+1 = ncoef. + y = x(sb:sl,:); +end diff --git a/MatlabFiles/mnpdf.m b/MatlabFiles/mnpdf.m index 6302ca1bfb962d4491119a0410a95a162d28727e..8fee71fb052bdd18a975b3ef0b50e6839e1d0ec1 100644 --- a/MatlabFiles/mnpdf.m +++ b/MatlabFiles/mnpdf.m @@ -1,44 +1,44 @@ -function y = mnpdf(x,xm,C,constIx) -% y = mnpdf(x,xm,C,constIx) -% The pdf value for multivariate normal distribution -% -% x: p-by-draws matrix of values evaluated at where p=size(x,1) is # of variables -% xm: p-by-draws matrix of the mean of x -% C: p-by-p Choleski square root of PDS S -- the covariance matrix so that S = C*C' -% constIx: index for the constant. 1: constant (normalized); 0: no constant (unnormalized) -%---------- -% y: p-by-draws matrix of pdf's for multivariate normal distribution -% -% Christian P. Robert, "The Bayesian Choice," Springer-Verlag, New York, 1994, -% p. 381. -% -% November 1998 by Tao Zha -% rewritten by CAS 12/98 to take matrix x, return vector y -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -[p,nx]=size(x); -z = C\(x-xm); - -if constIx - dSh=sum(log(diag(C))); % (detSigma)^(1/2) - y = exp(-dSh-sum(z.*z,1)/2) / ((2*pi)^(p/2)); - y = y'; -else - y = exp(-sum(z.*z,1)/2); - y = y'; -end +function y = mnpdf(x,xm,C,constIx) +% y = mnpdf(x,xm,C,constIx) +% The pdf value for multivariate normal distribution +% +% x: p-by-draws matrix of values evaluated at where p=size(x,1) is # of variables +% xm: p-by-draws matrix of the mean of x +% C: p-by-p Choleski square root of PDS S -- the covariance matrix so that S = C*C' +% constIx: index for the constant. 1: constant (normalized); 0: no constant (unnormalized) +%---------- +% y: p-by-draws matrix of pdf's for multivariate normal distribution +% +% Christian P. Robert, "The Bayesian Choice," Springer-Verlag, New York, 1994, +% p. 381. +% +% November 1998 by Tao Zha +% rewritten by CAS 12/98 to take matrix x, return vector y +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +[p,nx]=size(x); +z = C\(x-xm); + +if constIx + dSh=sum(log(diag(C))); % (detSigma)^(1/2) + y = exp(-dSh-sum(z.*z,1)/2) / ((2*pi)^(p/2)); + y = y'; +else + y = exp(-sum(z.*z,1)/2); + y = y'; +end diff --git a/MatlabFiles/mtpdf.m b/MatlabFiles/mtpdf.m index 517f6ab0918b4c57178a9bb64307bde8f43af893..e83b4607302219fe3aea44de940d4789d10dc585 100644 --- a/MatlabFiles/mtpdf.m +++ b/MatlabFiles/mtpdf.m @@ -1,48 +1,48 @@ -function y = mtpdf(x,xm,C,v,constIx) -% y = mtpdf(x,xm,C,v) -% The pdf value for multivariate Student t distribution -% -% x: p-by-draws matrix of values evaluated at where p=size(x,1) is # of variables -% xm: p-by-draws matrix of the mean of x -% C: p-by-p Choleski square root of PDS S, which is the covariance matrix -% in the normal case so that S = C*C' -% v (>0): scaler -- the degrees of freedom -% constIx: index for the constant. 1: constant (normalized); 0: no constant (unnormalized) -%---------- -% y: p-by-draws matrix of pdf's for multivariate Student t distribution with v degrees of freedom -% -% Christian P. Robert, "The Bayesian Choice," Springer-Verlag, New York, 1994, -% p. 382. -% -% December 1998 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -[p,nx]=size(x); -z = C\(x-xm); - - -if constIx - dSh=sum(log(diag(C))); % (detSigma)^(1/2) - %* Use gammaln function to avoid overflows. - term = exp(gammaln((v + p) / 2) - gammaln(v/2) - dSh); - y = (term*(v*pi)^(-p/2)) * (1 + sum(z.*z,1)/v).^(-(v + p)/2); - y = y'; -else - y = (1 + sum(z.*z,1)/v).^(-(v + p)/2); - y = y'; -end +function y = mtpdf(x,xm,C,v,constIx) +% y = mtpdf(x,xm,C,v) +% The pdf value for multivariate Student t distribution +% +% x: p-by-draws matrix of values evaluated at where p=size(x,1) is # of variables +% xm: p-by-draws matrix of the mean of x +% C: p-by-p Choleski square root of PDS S, which is the covariance matrix +% in the normal case so that S = C*C' +% v (>0): scaler -- the degrees of freedom +% constIx: index for the constant. 1: constant (normalized); 0: no constant (unnormalized) +%---------- +% y: p-by-draws matrix of pdf's for multivariate Student t distribution with v degrees of freedom +% +% Christian P. Robert, "The Bayesian Choice," Springer-Verlag, New York, 1994, +% p. 382. +% +% December 1998 by Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +[p,nx]=size(x); +z = C\(x-xm); + + +if constIx + dSh=sum(log(diag(C))); % (detSigma)^(1/2) + %* Use gammaln function to avoid overflows. + term = exp(gammaln((v + p) / 2) - gammaln(v/2) - dSh); + y = (term*(v*pi)^(-p/2)) * (1 + sum(z.*z,1)/v).^(-(v + p)/2); + y = y'; +else + y = (1 + sum(z.*z,1)/v).^(-(v + p)/2); + y = y'; +end diff --git a/MatlabFiles/nmlzvar.m b/MatlabFiles/nmlzvar.m index 8a896d08bb490121dfe90928611b7b9377a1a107..a94cbd78b7603b4257d52ea65e1c496af7bea7db 100644 --- a/MatlabFiles/nmlzvar.m +++ b/MatlabFiles/nmlzvar.m @@ -1,121 +1,121 @@ -function [A0n,nswitch,A0inn] = nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) -% [A0n,nswitch,A0inn] = nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) -% Export normalized new draw A0 (and inv(A0) only if IndxNmlr(5)) and the number of sign switches -% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" -% See Note Forecast (2) pp. 52-53 -% -% A0u: unnormalized A0; column--equation -% A0xhat: ML estimate or posterior mode of A0 -% A0inxhat: inv(A0xhat) -% IndxNmlr: index for which normalization rule to choose -% Only one of the elments in IndxNmlr can be non-zero -% IndxNmlr(1): ML A distance rule (supposed to be the best) -% IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1)) -% IndxNmlr(3): ML Euclidean distance rule (not invariant to scale) -% IndxNmlr(4): Positive diagonal rule -% IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu, -% so we set A0inn=[]) -% Or Euclidean distance rule for A0inv (not invariant to scale) -% IndxNmlr(6): Assigned postive rule (such as off-diagonal elements). Added 1/3/00 -% nswitch: # of sign switches -% A0inu: unnormalized inv(A0); used only if IndxNmlr(5) -%----------------- -% A0n: normalized new A0; column--equation -% nswitch: updated # of sign switches -% A0inn: normalized inv(A0); used only if IndxNmlr(5) -% -% Written by Tao Zha -% 1/3/00: added IndxNmlr(6) so that previous programs may not be compatible. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - - -A0inn = []; % no output for normalized A0in unless IndxNmlr(5) - -if (length(find(IndxNmlr))>1) - warning('You cannot choose more than one normalization rule at a time') - disp('Press ctrl-c to abort') - pause -elseif isempty(find(IndxNmlr)) % no normalization - A0n=A0u; nswitch=0; -elseif IndxNmlr(1) - a0dpindx = find(diag(A0u\A0xhat)<0); - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(2) - a0dpindx = find(diag(A0inxhat*A0u)<0); - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(3) - Adiff = (A0u - A0xhat).^2; % distance that may be far from axhat or A0xhat - Adiffn = (-A0u - A0xhat).^2; % distance by chaning the sign of Atem - cAdiff = sum(Adiff); % each column summed up - cAdiffn = sum(Adiffn); % each column summed up - cAindx = find(cAdiffn<cAdiff); % index for shorter distance - A0n = A0u; - if ~isempty(cAindx) - A0n(:,cAindx) = -A0u(:,cAindx); % find the shortest or nearest distance - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(4) - a0dpindx = find(diag(A0u)<0); - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -elseif IndxNmlr(5) - if (0) - a0dpindx = find(diag(A0inu)<0); - A0n = A0u; - A0inn = A0inu; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); - A0inn(a0dpindx,:) = -A0inu(a0dpindx,:); - nswitch = nswitch + 1; %<<>> # of sign switches - end - else - A0n = []; - Aindiff = (A0inu - A0inxhat).^2; % distance that may be far from A0inxhat - Aindiffn = (-A0inu - A0inxhat).^2; % distance by chaning the sign of A0inu - cAindiff = sum(Aindiff,2); % each row summed up - cAindiffn = sum(Aindiffn, 2); % each row summed up - cAinindx = find(cAindiffn<cAindiff); % index for shorter distance - A0inn = A0inu; - if ~isempty(cAinindx) - A0inn(:,cAinindx) = -A0inu(:,cAinindx); % find the shortest or nearest distance - nswitch = nswitch + 1; %<<>> # of sign switches - end - end -elseif IndxNmlr(6) %*** This one has to be MANUALLY handled - [jnk,nvar]=size(A0u); - A0dummy=A0u; - A0dummy(:,1:2)=-A0u(:,1:2); % keep it to a sign that coincide with Brooking paper - a0dpindx = find(A0dummy(nvar,:)<0); % the last row - A0n = A0u; - if ~isempty(a0dpindx) - A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws - nswitch = nswitch + 1; %<<>> # of sign switches - end -end +function [A0n,nswitch,A0inn] = nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) +% [A0n,nswitch,A0inn] = nmlzvar(A0u,A0xhat,A0inxhat,IndxNmlr,nswitch,A0inu) +% Export normalized new draw A0 (and inv(A0) only if IndxNmlr(5)) and the number of sign switches +% Ref.: D.F. Waggoner and T.A. Zha: "Does Normalization Matter for Inference?" +% See Note Forecast (2) pp. 52-53 +% +% A0u: unnormalized A0; column--equation +% A0xhat: ML estimate or posterior mode of A0 +% A0inxhat: inv(A0xhat) +% IndxNmlr: index for which normalization rule to choose +% Only one of the elments in IndxNmlr can be non-zero +% IndxNmlr(1): ML A distance rule (supposed to be the best) +% IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1)) +% IndxNmlr(3): ML Euclidean distance rule (not invariant to scale) +% IndxNmlr(4): Positive diagonal rule +% IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu, +% so we set A0inn=[]) +% Or Euclidean distance rule for A0inv (not invariant to scale) +% IndxNmlr(6): Assigned postive rule (such as off-diagonal elements). Added 1/3/00 +% nswitch: # of sign switches +% A0inu: unnormalized inv(A0); used only if IndxNmlr(5) +%----------------- +% A0n: normalized new A0; column--equation +% nswitch: updated # of sign switches +% A0inn: normalized inv(A0); used only if IndxNmlr(5) +% +% Written by Tao Zha +% 1/3/00: added IndxNmlr(6) so that previous programs may not be compatible. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + + +A0inn = []; % no output for normalized A0in unless IndxNmlr(5) + +if (length(find(IndxNmlr))>1) + warning('You cannot choose more than one normalization rule at a time') + disp('Press ctrl-c to abort') + pause +elseif isempty(find(IndxNmlr)) % no normalization + A0n=A0u; nswitch=0; +elseif IndxNmlr(1) + a0dpindx = find(diag(A0u\A0xhat)<0); + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(2) + a0dpindx = find(diag(A0inxhat*A0u)<0); + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(3) + Adiff = (A0u - A0xhat).^2; % distance that may be far from axhat or A0xhat + Adiffn = (-A0u - A0xhat).^2; % distance by chaning the sign of Atem + cAdiff = sum(Adiff); % each column summed up + cAdiffn = sum(Adiffn); % each column summed up + cAindx = find(cAdiffn<cAdiff); % index for shorter distance + A0n = A0u; + if ~isempty(cAindx) + A0n(:,cAindx) = -A0u(:,cAindx); % find the shortest or nearest distance + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(4) + a0dpindx = find(diag(A0u)<0); + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +elseif IndxNmlr(5) + if (0) + a0dpindx = find(diag(A0inu)<0); + A0n = A0u; + A0inn = A0inu; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); + A0inn(a0dpindx,:) = -A0inu(a0dpindx,:); + nswitch = nswitch + 1; %<<>> # of sign switches + end + else + A0n = []; + Aindiff = (A0inu - A0inxhat).^2; % distance that may be far from A0inxhat + Aindiffn = (-A0inu - A0inxhat).^2; % distance by chaning the sign of A0inu + cAindiff = sum(Aindiff,2); % each row summed up + cAindiffn = sum(Aindiffn, 2); % each row summed up + cAinindx = find(cAindiffn<cAindiff); % index for shorter distance + A0inn = A0inu; + if ~isempty(cAinindx) + A0inn(:,cAinindx) = -A0inu(:,cAinindx); % find the shortest or nearest distance + nswitch = nswitch + 1; %<<>> # of sign switches + end + end +elseif IndxNmlr(6) %*** This one has to be MANUALLY handled + [jnk,nvar]=size(A0u); + A0dummy=A0u; + A0dummy(:,1:2)=-A0u(:,1:2); % keep it to a sign that coincide with Brooking paper + a0dpindx = find(A0dummy(nvar,:)<0); % the last row + A0n = A0u; + if ~isempty(a0dpindx) + A0n(:,a0dpindx) = -A0u(:,a0dpindx); % normalized new draws + nswitch = nswitch + 1; %<<>> # of sign switches + end +end diff --git a/MatlabFiles/normpar.m b/MatlabFiles/normpar.m index d8ee4958a0cad0e5647f2c3345b79064d6bc9218..8d7e3ba238ad30536d9f4c99f30869d8de26aa59 100644 --- a/MatlabFiles/normpar.m +++ b/MatlabFiles/normpar.m @@ -1,29 +1,29 @@ -function f = normpar(ab, XLO, XUP, PLO, PUP); - -% The function takes as inputs the parameters ab=[a, b] of the Normal -% distribution (a = mean, b = standard deviation), the bounds of the -% support [XLO, XUP], the the corresponding probabilities of the bounds -% [PLO, PUP] and returns the residual value f. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -a = ab(1); b = abs(ab(2)); -f1 = PLO - normcdf(XLO, a, b); -f2 = PUP - normcdf(XUP, a, b); - -f = [f1, f2]; +function f = normpar(ab, XLO, XUP, PLO, PUP); + +% The function takes as inputs the parameters ab=[a, b] of the Normal +% distribution (a = mean, b = standard deviation), the bounds of the +% support [XLO, XUP], the the corresponding probabilities of the bounds +% [PLO, PUP] and returns the residual value f. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +a = ab(1); b = abs(ab(2)); +f1 = PLO - normcdf(XLO, a, b); +f2 = PUP - normcdf(XUP, a, b); + +f = [f1, f2]; diff --git a/MatlabFiles/nqzdiv.m b/MatlabFiles/nqzdiv.m index 4c3f6699f68bb6658e19fe5c959d4bf5a8c2086e..fa8a7f7288a711dc3d2a1ca5ef99672e51b1c704 100644 --- a/MatlabFiles/nqzdiv.m +++ b/MatlabFiles/nqzdiv.m @@ -1,61 +1,61 @@ -function [A,B,P,R] = nqzdiv(stake,A,B,V,P) -%function [A,B,Q,Z] = nqzdiv(stake,A,B,V,P) -% -% Takes U.T. matrices A, B, V, and P and rearranges them -% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right -% corner, while the output A and B are diagonal, and P*A*R=G0, P*B*R=G1. -% Note: the input A and B are U.T.; the output A and B are diagonal. -% -% Modified by T.Zha, 5/26/97 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[n jnk] = size(A); - -ald = diag(diag(A)); % d: diagoanl -bed = diag(diag(B)); -R = inv(V); - -root = abs([diag(ald) diag(bed)]); -root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2)); -root(:,2) = root(:,2)./root(:,1); -for i = n:-1:1 - m=0; - for j=i:-1:1 - if (root(j,2) > stake | root(j,2) < -.1) - m=j; - break - end - end - if (m==0) - return - elseif (m<i-1) - pindx = 1:n; % T.Z., 5/26/97 - pindx(m)=i-1; - pindx(i-1)=m; - %*** permutation begins - ald = ald(pindx,pindx); - bed = bed(pindx,pindx); - P = P(:,pindx); % column permutation, T.Z., 5/26/97 - R = R(pindx,:); % row permutation - end -end - -%*** return the new Q, Z, A, B -A = diag(1./diag(bed)); -B = diag(1./diag(ald)); \ No newline at end of file +function [A,B,P,R] = nqzdiv(stake,A,B,V,P) +%function [A,B,Q,Z] = nqzdiv(stake,A,B,V,P) +% +% Takes U.T. matrices A, B, V, and P and rearranges them +% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right +% corner, while the output A and B are diagonal, and P*A*R=G0, P*B*R=G1. +% Note: the input A and B are U.T.; the output A and B are diagonal. +% +% Modified by T.Zha, 5/26/97 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[n jnk] = size(A); + +ald = diag(diag(A)); % d: diagoanl +bed = diag(diag(B)); +R = inv(V); + +root = abs([diag(ald) diag(bed)]); +root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2)); +root(:,2) = root(:,2)./root(:,1); +for i = n:-1:1 + m=0; + for j=i:-1:1 + if (root(j,2) > stake | root(j,2) < -.1) + m=j; + break + end + end + if (m==0) + return + elseif (m<i-1) + pindx = 1:n; % T.Z., 5/26/97 + pindx(m)=i-1; + pindx(i-1)=m; + %*** permutation begins + ald = ald(pindx,pindx); + bed = bed(pindx,pindx); + P = P(:,pindx); % column permutation, T.Z., 5/26/97 + R = R(pindx,:); % row permutation + end +end + +%*** return the new Q, Z, A, B +A = diag(1./diag(bed)); +B = diag(1./diag(ald)); diff --git a/MatlabFiles/numgrad.m b/MatlabFiles/numgrad.m index 89eb38e36e6a4055982ce2ab7b86c056d7829dca..6385b4a352ac000652f3fc7ef2d2692435529177 100644 --- a/MatlabFiles/numgrad.m +++ b/MatlabFiles/numgrad.m @@ -1,102 +1,102 @@ -function [grdd, badg] = numgrad(fcn,x0,varargin) -%function grdd = fn_gradcd(fcn,x0,varargin) -% computes numerical gradient of a single-valued function or Jacobian -% matrix of a vector-valued function using a central difference with -% function grdd = gradcd(fcn,x0,grdh) -% -% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). -% x0: a column vector n-by-1, at which point the hessian is evaluated. -% grdh: step size, n*1. Set as follows -% step = eps^(1/3); -% %step = 1e-04; -% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); -%-------------------- -% grdd: n-by-k Jacobian matrix (gradients). -% -% Written by Tao Zha, 2002. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -stps = eps^(1/3); -% eps: floating point relative accuracy or machine precision: 2.22e-16 -% stps: step size recommended by Dennis and Schnabel: 6.006e-6 - -x0 = x0(:); -%tailstr = ')'; -%for i=nargin-3:-1:1 -% tailstr=[ ',P' num2str(i) tailstr]; -%end -f0 = eval([fcn '(x0,varargin{:})']); -%f0 = eval([fcn '(x0' tailstr]); - -% ** initializations -n = length(x0); -k = length(f0); % dimension of "fcn" - -% ** Computation of stepsize (dh) -if (0) - dh = 1.0e-06; %grdh; -else - ax0 = abs(x0); - if all(x0) - dax0 = x0 ./ ax0; - else - dax0 = 1; - end - dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; -end - -xdh = x0 + dh; -dh = xdh - x0; % This increases precision slightly -% -argplus = x0(:,ones(n,1)); -argminus = argplus; -dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). -argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". -argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". - -grdd = zeros(k,n); % preallocate to speed the loop. -badg=0; -i = 0; -while i ~= n - i = i+1; - fp = eval([fcn '(argplus(:,i),varargin{:})']); - fm = eval([fcn '(argminus(:,i),varargin{:})']); -% fp = eval([fcn '(argplus(:,i)' tailstr]); -% fm = eval([fcn '(argminus(:,i)' tailstr]); - g0 = fp - fm; - - if abs(g0)< 1e15 - grdd(:,i)=g0; - % disp('good gradient') - else - disp('bad gradient ------------------------') - % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above - grdd(:,i)=0; - badg=1; - % return - % can return here to save time if the gradient will never be - % used when badg returns as true. - end - -end -dhm = dh(:,ones(k,1)); -dhm = dhm'; % k*n -grdd = grdd ./ (2*dhm); % k-by-n. -grdd = grdd'; % n-by-k. - +function [grdd, badg] = numgrad(fcn,x0,varargin) +%function grdd = fn_gradcd(fcn,x0,varargin) +% computes numerical gradient of a single-valued function or Jacobian +% matrix of a vector-valued function using a central difference with +% function grdd = gradcd(fcn,x0,grdh) +% +% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). +% x0: a column vector n-by-1, at which point the hessian is evaluated. +% grdh: step size, n*1. Set as follows +% step = eps^(1/3); +% %step = 1e-04; +% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); +%-------------------- +% grdd: n-by-k Jacobian matrix (gradients). +% +% Written by Tao Zha, 2002. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +stps = eps^(1/3); +% eps: floating point relative accuracy or machine precision: 2.22e-16 +% stps: step size recommended by Dennis and Schnabel: 6.006e-6 + +x0 = x0(:); +%tailstr = ')'; +%for i=nargin-3:-1:1 +% tailstr=[ ',P' num2str(i) tailstr]; +%end +f0 = eval([fcn '(x0,varargin{:})']); +%f0 = eval([fcn '(x0' tailstr]); + +% ** initializations +n = length(x0); +k = length(f0); % dimension of "fcn" + +% ** Computation of stepsize (dh) +if (0) + dh = 1.0e-06; %grdh; +else + ax0 = abs(x0); + if all(x0) + dax0 = x0 ./ ax0; + else + dax0 = 1; + end + dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; +end + +xdh = x0 + dh; +dh = xdh - x0; % This increases precision slightly +% +argplus = x0(:,ones(n,1)); +argminus = argplus; +dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). +argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". +argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". + +grdd = zeros(k,n); % preallocate to speed the loop. +badg=0; +i = 0; +while i ~= n + i = i+1; + fp = eval([fcn '(argplus(:,i),varargin{:})']); + fm = eval([fcn '(argminus(:,i),varargin{:})']); +% fp = eval([fcn '(argplus(:,i)' tailstr]); +% fm = eval([fcn '(argminus(:,i)' tailstr]); + g0 = fp - fm; + + if abs(g0)< 1e15 + grdd(:,i)=g0; + % disp('good gradient') + else + disp('bad gradient ------------------------') + % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above + grdd(:,i)=0; + badg=1; + % return + % can return here to save time if the gradient will never be + % used when badg returns as true. + end + +end +dhm = dh(:,ones(k,1)); +dhm = dhm'; % k*n +grdd = grdd ./ (2*dhm); % k-by-n. +grdd = grdd'; % n-by-k. + diff --git a/MatlabFiles/numgradcd.m b/MatlabFiles/numgradcd.m index bf09580387ed4bea42a868046ef2a39239ecab02..c125fee99a66f5cb8d1b1983bdcda02d95267392 100644 --- a/MatlabFiles/numgradcd.m +++ b/MatlabFiles/numgradcd.m @@ -1,114 +1,114 @@ -function [grdd, badg] = numgradcd(fcn,x0,varargin) -%function grdd = fn_gradcd(fcn,x0,varargin) -% computes numerical gradient of a single-valued function or Jacobian -% matrix of a vector-valued function using a central difference with -% function grdd = gradcd(fcn,x0,grdh) -% -% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). -% x0: a column vector n-by-1, at which point the hessian is evaluated. -% grdh: step size, n*1. Set as follows -% step = eps^(1/3); -% %step = 1e-04; -% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); -%-------------------- -% grdd: n-by-k Jacobian matrix (gradients). -% -% Written by Tao Zha, 2002. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -stps = eps^(1/3); -%stps = 1.0e-02; -% eps: floating point relative accuracy or machine precision: 2.22e-16 -% stps: step size recommended by Dennis and Schnabel: 6.006e-6 - -x0 = x0(:); -%tailstr = ')'; -%for i=nargin-3:-1:1 -% tailstr=[ ',P' num2str(i) tailstr]; -%end -if ischar(fcn) - f0 = eval([fcn '(x0,varargin{:})']); -else - f0 = fcn(x0,varargin{:}); -end -%f0 = eval([fcn '(x0' tailstr]); - -% ** initializations -n = length(x0); -k = length(f0); % dimension of "fcn" - -% ** Computation of stepsize (dh) -if (0) - dh = 1.0e-06; %grdh; -else - ax0 = abs(x0); - if all(x0) - dax0 = x0 ./ ax0; - else - dax0 = 1; - end - dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; -end - -xdh = x0 + dh; -dh = xdh - x0; % This increases precision slightly -% -argplus = x0(:,ones(n,1)); -argminus = argplus; -dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). -argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". -argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". - -grdd = zeros(k,n); % preallocate to speed the loop. -badg=0; -i = 0; -while i ~= n - i = i+1; - if ischar(fcn) - - fp = eval([fcn '(argplus(:,i),varargin{:})']); - fm = eval([fcn '(argminus(:,i),varargin{:})']); - else - - fp = fcn(argplus(:,i),varargin{:}); - fm = fcn(argminus(:,i),varargin{:}); - end -% fp = eval([fcn '(argplus(:,i)' tailstr]); -% fm = eval([fcn '(argminus(:,i)' tailstr]); - g0 = fp - fm; - - if abs(g0)< 1e15 - grdd(:,i)=g0; - % disp('good gradient') - else - disp('bad gradient ------------------------') - % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above - grdd(:,i)=0; - badg=1; - % return - % can return here to save time if the gradient will never be - % used when badg returns as true. - end - -end -dhm = dh(:,ones(k,1)); -dhm = dhm'; % k*n -grdd = grdd ./ (2*dhm); % k-by-n. -grdd = grdd'; % n-by-k. - +function [grdd, badg] = numgradcd(fcn,x0,varargin) +%function grdd = fn_gradcd(fcn,x0,varargin) +% computes numerical gradient of a single-valued function or Jacobian +% matrix of a vector-valued function using a central difference with +% function grdd = gradcd(fcn,x0,grdh) +% +% fcn: a string naming a vector-valued function (f:n-by-1 -> k-by-1). +% x0: a column vector n-by-1, at which point the hessian is evaluated. +% grdh: step size, n*1. Set as follows +% step = eps^(1/3); +% %step = 1e-04; +% grdh = step * (max([abs(x) ones(length(x),1)]'))' .* (abs(x) ./ x); +%-------------------- +% grdd: n-by-k Jacobian matrix (gradients). +% +% Written by Tao Zha, 2002. +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +stps = eps^(1/3); +%stps = 1.0e-02; +% eps: floating point relative accuracy or machine precision: 2.22e-16 +% stps: step size recommended by Dennis and Schnabel: 6.006e-6 + +x0 = x0(:); +%tailstr = ')'; +%for i=nargin-3:-1:1 +% tailstr=[ ',P' num2str(i) tailstr]; +%end +if ischar(fcn) + f0 = eval([fcn '(x0,varargin{:})']); +else + f0 = fcn(x0,varargin{:}); +end +%f0 = eval([fcn '(x0' tailstr]); + +% ** initializations +n = length(x0); +k = length(f0); % dimension of "fcn" + +% ** Computation of stepsize (dh) +if (0) + dh = 1.0e-06; %grdh; +else + ax0 = abs(x0); + if all(x0) + dax0 = x0 ./ ax0; + else + dax0 = 1; + end + dh = stps * (max([ax0 ones(n,1)]'))' .* dax0; +end + +xdh = x0 + dh; +dh = xdh - x0; % This increases precision slightly +% +argplus = x0(:,ones(n,1)); +argminus = argplus; +dnum = 1:n+1:n^2; % positions of diagonals in vec(argplus). +argplus(dnum) = xdh; % replace the diagonals of "argplus" by "xdh". +argminus(dnum) = x0-dh; % replace the diagonals of "argplus" by "xdh". + +grdd = zeros(k,n); % preallocate to speed the loop. +badg=0; +i = 0; +while i ~= n + i = i+1; + if ischar(fcn) + + fp = eval([fcn '(argplus(:,i),varargin{:})']); + fm = eval([fcn '(argminus(:,i),varargin{:})']); + else + + fp = fcn(argplus(:,i),varargin{:}); + fm = fcn(argminus(:,i),varargin{:}); + end +% fp = eval([fcn '(argplus(:,i)' tailstr]); +% fm = eval([fcn '(argminus(:,i)' tailstr]); + g0 = fp - fm; + + if abs(g0)< 1e15 + grdd(:,i)=g0; + % disp('good gradient') + else + disp('bad gradient ------------------------') + % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above + grdd(:,i)=0; + badg=1; + % return + % can return here to save time if the gradient will never be + % used when badg returns as true. + end + +end +dhm = dh(:,ones(k,1)); +dhm = dhm'; % k*n +grdd = grdd ./ (2*dhm); % k-by-n. +grdd = grdd'; % n-by-k. + diff --git a/MatlabFiles/numgradorig.m b/MatlabFiles/numgradorig.m index 9cf92a02ef6fd9cc0843df96e603aaf701760f1d..2aebc4d4d69e42e4aa714d75bae04c1fcde82e5a 100644 --- a/MatlabFiles/numgradorig.m +++ b/MatlabFiles/numgradorig.m @@ -1,116 +1,116 @@ -function [g, badg] = numgrad(fcn,x,varargin) -% function [g badg] = numgrad(fcn,xvarargin) -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% -delta = 1e-6; % works for a general case -%delta = 1e-2; % bigger step -- works for a flat peak -%delta=1e-04; - -n=length(x); -tvec=delta*eye(n); -g=zeros(n,1); -%--------------------old way to deal with variable # of P's-------------- -%tailstr = ')'; -%stailstr = []; -%for i=nargin-2:-1:1 -% tailstr=[ ',P' num2str(i) tailstr]; -% stailstr=[' P' num2str(i) stailstr]; -%end -%f0 = eval([fcn '(x' tailstr]); % Is there a way not to do this? -%---------------------------------------------------------------^yes -f0 = eval([fcn '(x,varargin{:})']); -% disp(' first fcn in numgrad.m ------------------') -%home -% disp('numgrad.m is working. ----') % Jiinil on 9/5/95 -% sizex=size(x),sizetvec=size(tvec),x, % Jinill on 9/6/95 -badg=0; -for i=1:n - scale=1; % originally 1 - % i,tveci=tvec(:,i)% ,plus=x+scale*tvec(:,i) % Jinill Kim on 9/6/95 - if size(x,1)>size(x,2) - tvecv=tvec(i,:); - else - tvecv=tvec(:,i); - end - g0 = (eval([fcn '(x+scale*tvecv'', varargin{:})']) - f0) ... - /(scale*delta); - % disp(' fcn in the i=1:n loop of numgrad.m ------------------')% Jinill 9/6/95 - % disp(' and i is') % Jinill - % i % Jinill - % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see below Jinill 9/6/95 -% -------------------------- special code to essentially quit here - % absg0=abs(g0) % Jinill on 9/6/95 - if abs(g0)< 1e15 - g(i)=g0; - % disp('good gradient') % Jinill Kim - else - disp('bad gradient ------------------------') % Jinill Kim - % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above - g(i)=0; - badg=1; - % return - % can return here to save time if the gradient will never be - % used when badg returns as true. - end -end -%------------------------------------------------------------- -% if g0 > 0 -% sided=2; -% g1 = -(eval([fcn '(x-scale*tvec(:,i)''' tailstr]) - f0) ... -% /(scale*delta); -% if g1<0 -% scale = scale/10; -% else -% break -% end -% else -% sided=1; -% break -% end -% end -% if sided==1 -% g(i)=g0; -% else -% if (g0<1e20) -% if (g1>-1e20) -% g(i)=(g0+g1)/2; -% else -% g(i)=0; -% badg=1; -% disp( ['Banging against wall, parameter ' int2str(i)] ); -% end -% else -% if g1>-1e20 -% if g1<0 -% g(i)=0; -% badg=1; -% disp( ['Banging against wall, parameter ' int2str(i)] ); -% else -% g(i)=g1; -% end -% else -% g(i)=0; -% badg=1; -% disp(['Valley around parameter ' int2str(i)]) -% end -% end -% end -%end -%save g.dat g x f0 -%eval(['save g g x f0 ' stailstr]); +function [g, badg] = numgrad(fcn,x,varargin) +% function [g badg] = numgrad(fcn,xvarargin) +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% +delta = 1e-6; % works for a general case +%delta = 1e-2; % bigger step -- works for a flat peak +%delta=1e-04; + +n=length(x); +tvec=delta*eye(n); +g=zeros(n,1); +%--------------------old way to deal with variable # of P's-------------- +%tailstr = ')'; +%stailstr = []; +%for i=nargin-2:-1:1 +% tailstr=[ ',P' num2str(i) tailstr]; +% stailstr=[' P' num2str(i) stailstr]; +%end +%f0 = eval([fcn '(x' tailstr]); % Is there a way not to do this? +%---------------------------------------------------------------^yes +f0 = eval([fcn '(x,varargin{:})']); +% disp(' first fcn in numgrad.m ------------------') +%home +% disp('numgrad.m is working. ----') % Jiinil on 9/5/95 +% sizex=size(x),sizetvec=size(tvec),x, % Jinill on 9/6/95 +badg=0; +for i=1:n + scale=1; % originally 1 + % i,tveci=tvec(:,i)% ,plus=x+scale*tvec(:,i) % Jinill Kim on 9/6/95 + if size(x,1)>size(x,2) + tvecv=tvec(i,:); + else + tvecv=tvec(:,i); + end + g0 = (eval([fcn '(x+scale*tvecv'', varargin{:})']) - f0) ... + /(scale*delta); + % disp(' fcn in the i=1:n loop of numgrad.m ------------------')% Jinill 9/6/95 + % disp(' and i is') % Jinill + % i % Jinill + % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see below Jinill 9/6/95 +% -------------------------- special code to essentially quit here + % absg0=abs(g0) % Jinill on 9/6/95 + if abs(g0)< 1e15 + g(i)=g0; + % disp('good gradient') % Jinill Kim + else + disp('bad gradient ------------------------') % Jinill Kim + % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above + g(i)=0; + badg=1; + % return + % can return here to save time if the gradient will never be + % used when badg returns as true. + end +end +%------------------------------------------------------------- +% if g0 > 0 +% sided=2; +% g1 = -(eval([fcn '(x-scale*tvec(:,i)''' tailstr]) - f0) ... +% /(scale*delta); +% if g1<0 +% scale = scale/10; +% else +% break +% end +% else +% sided=1; +% break +% end +% end +% if sided==1 +% g(i)=g0; +% else +% if (g0<1e20) +% if (g1>-1e20) +% g(i)=(g0+g1)/2; +% else +% g(i)=0; +% badg=1; +% disp( ['Banging against wall, parameter ' int2str(i)] ); +% end +% else +% if g1>-1e20 +% if g1<0 +% g(i)=0; +% badg=1; +% disp( ['Banging against wall, parameter ' int2str(i)] ); +% else +% g(i)=g1; +% end +% else +% g(i)=0; +% badg=1; +% disp(['Valley around parameter ' int2str(i)]) +% end +% end +% end +%end +%save g.dat g x f0 +%eval(['save g g x f0 ' stailstr]); diff --git a/MatlabFiles/ols.m b/MatlabFiles/ols.m index e4fcb29fa030da961cb04d16707f08209cd71b54..20d7920accadb3d04a0a349b1ad0e7a7518785ec 100644 --- a/MatlabFiles/ols.m +++ b/MatlabFiles/ols.m @@ -1,44 +1,44 @@ -function [Bh,e,xtx,xty] = ols(y,phi) -% ols: estimate a system of equations: [Bh,e,xtx,xty] = ols(y,phi) -% Y(T*nvar) = XB + u, X: T*k, B: k*nvar. -% where Bh: the estimated B; column: nvar; row: number of r.h.s. variables. -% e: estimated residual e = y -xBh, T*nvar -% xtx: X'X: k-by-k -% xty: X'Y: k-by-nvar -% phi: X; T-by-k; column: number of r.h.s. variables (including -% deterministic terms) -% y: Y: T-by-nvar -% -% See also sye.m and syed.m -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup of orders and lengths ** -[u d v]=svd(phi,0); %trial -%xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -dinv = 1./diag(d); % inv(diag(d)) -vdinv=v.*(ones(size(v,2),1)*dinv'); %trial -xtx=vd*vd'; -xtxinv = vdinv*vdinv'; -%xty = phi'*y; % X'Y -uy = u'*y; %trial -xty = vd*uy; %trial -%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). -Bh = xtxinv*xty; -%e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar -e = y - u*uy; \ No newline at end of file +function [Bh,e,xtx,xty] = ols(y,phi) +% ols: estimate a system of equations: [Bh,e,xtx,xty] = ols(y,phi) +% Y(T*nvar) = XB + u, X: T*k, B: k*nvar. +% where Bh: the estimated B; column: nvar; row: number of r.h.s. variables. +% e: estimated residual e = y -xBh, T*nvar +% xtx: X'X: k-by-k +% xty: X'Y: k-by-nvar +% phi: X; T-by-k; column: number of r.h.s. variables (including +% deterministic terms) +% y: Y: T-by-nvar +% +% See also sye.m and syed.m +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup of orders and lengths ** +[u d v]=svd(phi,0); %trial +%xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +dinv = 1./diag(d); % inv(diag(d)) +vdinv=v.*(ones(size(v,2),1)*dinv'); %trial +xtx=vd*vd'; +xtxinv = vdinv*vdinv'; +%xty = phi'*y; % X'Y +uy = u'*y; %trial +xty = vd*uy; %trial +%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). +Bh = xtxinv*xty; +%e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar +e = y - u*uy; diff --git a/MatlabFiles/pdfforg.m b/MatlabFiles/pdfforg.m index c41c494ecc5d48fa2fb974ab30a6a066cd8d3a45..86c3e22c0b6d40a01fb6a8b29bd4206ed0e5381a 100644 --- a/MatlabFiles/pdfforg.m +++ b/MatlabFiles/pdfforg.m @@ -1,53 +1,53 @@ -function [imfpdf,imfpo,imfprob] = pdfforg(imfcnt,imndraws,forep,nvar,ninv,invc,Am) -% [imfpdf,imfpo,imfprob] = pdfforg(imfcnt,imndraws,forep,nvar,ninv,invc,Am) -% -% Produce the dataset for generating p.d.f. and export the dataset for -% probability (NOT density) at each bin -% -% imfcnt: 2+ninv-by-forep*nvar. Counted logcnt, yhatqgcnt, or yhatCalygcnt. -% In the case of impulse responses, forep=imstp and nvar=nvar^2 -% ninv: the number of small interior intervals for sorting. -% invc: 1-by-forep*nvar. Whole inverval lenghth from min to max for one of -% (yhat, yhatqg, or yhatCalyg) -% Am: 1-by-forep*nvar. Range5{i}(:,:,1) is lowest range for for one of -% (yhat, yhatqg, or yhatCalyg) -%----------------- -% imfpdf: 2+ninv-by-forep*nvar. Density -% imfpo: 2+ninv-by-forep*nvar. Bin position (x-axis) in relation to imfs3 -% imfprob: 2+ninv-by-forep*nvar. Probability (NOT density) at each bin -% -% 27 August 1998 Tao Zha -% Revised, October 1998 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -invlength = invc ./ ninv; -invlengthM = repmat(invlength,[2+ninv,1]); -invlengthM([1 2+ninv],:) = 1; - % first (-inf, low bound) and last (high bound, +inf), the interval is set - % to be 1. Of course, theoretically, the interval length should be set - % to infinity, but 1 is large enough compared with invlength. -imfprob = imfcnt ./ imndraws; % probability (NOT density) -imfpdf = imfprob ./ invlengthM; % density - -imfpo = [1:2+ninv]'; % positions for each forecast -imfpo = imfpo - 2; % the first step to put back to original form -imfpo = repmat(imfpo,[1,forep*nvar]); -invcM = repmat(invc,[2+ninv,1]); -AmM = repmat(Am,[2+ninv,1]); -imfpo = ((imfpo .* invcM) ./ ninv) + AmM; % 2+ninv-by-forep*nvar - % the final step to put back to original form of impulse responses \ No newline at end of file +function [imfpdf,imfpo,imfprob] = pdfforg(imfcnt,imndraws,forep,nvar,ninv,invc,Am) +% [imfpdf,imfpo,imfprob] = pdfforg(imfcnt,imndraws,forep,nvar,ninv,invc,Am) +% +% Produce the dataset for generating p.d.f. and export the dataset for +% probability (NOT density) at each bin +% +% imfcnt: 2+ninv-by-forep*nvar. Counted logcnt, yhatqgcnt, or yhatCalygcnt. +% In the case of impulse responses, forep=imstp and nvar=nvar^2 +% ninv: the number of small interior intervals for sorting. +% invc: 1-by-forep*nvar. Whole inverval lenghth from min to max for one of +% (yhat, yhatqg, or yhatCalyg) +% Am: 1-by-forep*nvar. Range5{i}(:,:,1) is lowest range for for one of +% (yhat, yhatqg, or yhatCalyg) +%----------------- +% imfpdf: 2+ninv-by-forep*nvar. Density +% imfpo: 2+ninv-by-forep*nvar. Bin position (x-axis) in relation to imfs3 +% imfprob: 2+ninv-by-forep*nvar. Probability (NOT density) at each bin +% +% 27 August 1998 Tao Zha +% Revised, October 1998 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +invlength = invc ./ ninv; +invlengthM = repmat(invlength,[2+ninv,1]); +invlengthM([1 2+ninv],:) = 1; + % first (-inf, low bound) and last (high bound, +inf), the interval is set + % to be 1. Of course, theoretically, the interval length should be set + % to infinity, but 1 is large enough compared with invlength. +imfprob = imfcnt ./ imndraws; % probability (NOT density) +imfpdf = imfprob ./ invlengthM; % density + +imfpo = [1:2+ninv]'; % positions for each forecast +imfpo = imfpo - 2; % the first step to put back to original form +imfpo = repmat(imfpo,[1,forep*nvar]); +invcM = repmat(invc,[2+ninv,1]); +AmM = repmat(Am,[2+ninv,1]); +imfpo = ((imfpo .* invcM) ./ ninv) + AmM; % 2+ninv-by-forep*nvar + % the final step to put back to original form of impulse responses diff --git a/MatlabFiles/perr1graph.m b/MatlabFiles/perr1graph.m index 4efeb2b5c25dab8f0ffaf8d57aa13c73edd54de6..9c07cc8c60caa1e90a39cb274a1f1645d32e5e1a 100644 --- a/MatlabFiles/perr1graph.m +++ b/MatlabFiles/perr1graph.m @@ -1,133 +1,133 @@ -function scaleout = perr1graph(imf,firstl1,firsth1,... - nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) -% imf: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in -% the graphics), 3rd D: across "ncol" different situations (column in -% the graphics) -% nrow: # of rows for the graphics -% ncol: # of columns for the graphics -% YTickIndx: 1: enable YTick; 0: disable -% scaleIndx: 1: enable scale along Y-axis; 0: disable -%function scaleout = imc2errgraph(imf,firstl1,firsth1,... -% firstl,firsth,nvar,imstp,xlab,ylab) -% imc2errgraph: impulse, c (column: shock 1 to N), 2 error bands, graph -% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock -% etc), row (impusle steps), -% firstl1: lower band, .68 -% highth1: high band, .68 -% firstl: lower band, .90 -% highth: high band, .90 -% nvar: number of variables -% imstp: step of impulse responses -% xlab,ylab: labels -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -t = 1:nstp; -nrow -ncol - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - %jnk1=max(firsth(:,i,j)); - %jnk2=max(firstl(:,i,j)); - jnk3=max(firsth1(:,i,j)); - jnk4=max(firstl1(:,i,j)); - jnk5=max(imf(:,i,j)); - - temp1(j)=max([jnk3 jnk4 jnk5]); - % - %jnk1=min(firstl(:,i,j)); - %jnk2=min(firsth(:,i,j)); - jnk3=min(firstl1(:,i,j)); - jnk4=min(firsth1(:,i,j)); - jnk5=min(imf(:,i,j)); - - temp2(j)=min([jnk3 jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrow,ncol,k1) - plot(t,imf(:,i,j),t,firstl1(:,i,j),'--',t,firsth1(:,i,j),'--') - %t,[firstl(:,i,j) firsth(:,i,j)],':'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if j>1 - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; -end \ No newline at end of file +function scaleout = perr1graph(imf,firstl1,firsth1,... + nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) +% imf: row: "nstp" time horizon (in the graphics), column: "nrow "variables (row in +% the graphics), 3rd D: across "ncol" different situations (column in +% the graphics) +% nrow: # of rows for the graphics +% ncol: # of columns for the graphics +% YTickIndx: 1: enable YTick; 0: disable +% scaleIndx: 1: enable scale along Y-axis; 0: disable +%function scaleout = imc2errgraph(imf,firstl1,firsth1,... +% firstl,firsth,nvar,imstp,xlab,ylab) +% imc2errgraph: impulse, c (column: shock 1 to N), 2 error bands, graph +% imf: impulse responses, column (responses to 1st shock, responses to 2nd shock +% etc), row (impusle steps), +% firstl1: lower band, .68 +% highth1: high band, .68 +% firstl: lower band, .90 +% highth: high band, .90 +% nvar: number of variables +% imstp: step of impulse responses +% xlab,ylab: labels +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +t = 1:nstp; +nrow +ncol + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + %jnk1=max(firsth(:,i,j)); + %jnk2=max(firstl(:,i,j)); + jnk3=max(firsth1(:,i,j)); + jnk4=max(firstl1(:,i,j)); + jnk5=max(imf(:,i,j)); + + temp1(j)=max([jnk3 jnk4 jnk5]); + % + %jnk1=min(firstl(:,i,j)); + %jnk2=min(firsth(:,i,j)); + jnk3=min(firstl1(:,i,j)); + jnk4=min(firsth1(:,i,j)); + jnk5=min(imf(:,i,j)); + + temp2(j)=min([jnk3 jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrow,ncol,k1) + plot(t,imf(:,i,j),t,firstl1(:,i,j),'--',t,firsth1(:,i,j),'--') + %t,[firstl(:,i,j) firsth(:,i,j)],':'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if j>1 + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/perr2graph.m b/MatlabFiles/perr2graph.m index ba33cd00a566223f13c368aa1eb2d8efde67a097..c9af1b41acc7338a291f03fd3fe9cb584a49e60d 100644 --- a/MatlabFiles/perr2graph.m +++ b/MatlabFiles/perr2graph.m @@ -1,128 +1,128 @@ -function scaleout = perr2graph(imf,firstl1,firsth1,... - firstl,firsth,nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) -% scaleout = perr2graph(imf,firstl1,firsth1,... -% firstl,firsth,nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) -% -% imf: nstp-by-nrow-by-ncol -% nrow: # of rows for the graphics (normally variables) -% ncol: # of columns for the graphics (normally situations such as shocks) -% firstl1: lower band, .68, nstp-by-nrow-by-ncol -% highth1: high band, .68, nstp-by-nrow-by-ncol -% firstl: lower band, .90, nstp-by-nrow-by-ncol -% highth: high band, .90, nstp-by-nrow-by-ncol -% YTickIndx: 1: enable YTick; 0: disable -% scaleIndx: 1: enable scale along Y-axis; 0: disable -% xlab,ylab: labels -% -% See imrgraph, imcerrgraph, imrerrgraph -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -t = 1:nstp; -nrow -ncol - -temp1=zeros(ncol,1); -temp2=zeros(ncol,1); -maxval=zeros(nrow,1); -minval=zeros(nrow,1); -for i = 1:nrow - for j = 1:ncol - jnk1=max(firsth(:,i,j)); - jnk2=max(firstl(:,i,j)); - jnk3=max(firsth1(:,i,j)); - jnk4=max(firstl1(:,i,j)); - jnk5=max(imf(:,i,j)); - - temp1(j)=max([jnk1 jnk2 jnk3 jnk4 jnk5]); - % - jnk1=min(firstl(:,i,j)); - jnk2=min(firsth(:,i,j)); - jnk3=min(firstl1(:,i,j)); - jnk4=min(firsth1(:,i,j)); - jnk5=min(imf(:,i,j)); - - temp2(j)=min([jnk1 jnk2 jnk3 jnk4 jnk5]); - end - maxval(i)=max(temp1); - minval(i)=min(temp2); -end - -scaleout = [maxval(:) minval(:)]; - -%-------------- -% Column j: Shock 1 to N; Row i: Responses to -%------------- -figure -rowlabel = 1; -for i = 1:nrow % column: from top to bottom - columnlabel = 1; - - if minval(i)<0 - if maxval(i)<=0 - yt=[minval(i) 0]; - else - yt=[minval(i) 0 maxval(i)]; - end - else % (minval(i) >=0) - if maxval(i) > 0 - yt=[0 maxval(i)]; - else % (identically zero responses) - yt=[-1 0 1]; - end - end - - - scale=[1 nstp minval(i) maxval(i)]; - for j = 1:ncol % row: from left to right - k1=(i-1)*ncol+j; - subplot(nrow,ncol,k1) - plot(t,imf(:,i,j),t,[firstl1(:,i,j) firsth1(:,i,j)],'k--',... - t,[firstl(:,i,j) firsth(:,i,j)],'k-.',t,zeros(length(imf(:,i,j)),1),'k-'); - grid; - if scaleIndx - axis(scale); - end - %set(gca,'YLim',[minval(i) maxval(i)]) - % - set(gca,'XTick',XTick) - if YTickIndx - set(gca,'YTick',yt) - end - - if i<nrow - set(gca,'XTickLabelMode','manual','XTickLabel',[]) - end - %set(gca,'XTickLabel',' '); - if j>1 - set(gca,'YTickLabel',' '); - end - if rowlabel == 1 - %title(['x' num2str(j)]) - %title(eval(['x' num2str(j)])) - title(char(xlab(j))) - end - if columnlabel == 1 - %ylabel(['x' num2str(i)]) - %ylabel(eval(['x' num2str(i)])) - ylabel(char(ylab(i))) - end - columnlabel = 0; - end - rowlabel = 0; -end \ No newline at end of file +function scaleout = perr2graph(imf,firstl1,firsth1,... + firstl,firsth,nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) +% scaleout = perr2graph(imf,firstl1,firsth1,... +% firstl,firsth,nrow,ncol,nstp,xlab,ylab,XTick,YTickIndx,scaleIndx) +% +% imf: nstp-by-nrow-by-ncol +% nrow: # of rows for the graphics (normally variables) +% ncol: # of columns for the graphics (normally situations such as shocks) +% firstl1: lower band, .68, nstp-by-nrow-by-ncol +% highth1: high band, .68, nstp-by-nrow-by-ncol +% firstl: lower band, .90, nstp-by-nrow-by-ncol +% highth: high band, .90, nstp-by-nrow-by-ncol +% YTickIndx: 1: enable YTick; 0: disable +% scaleIndx: 1: enable scale along Y-axis; 0: disable +% xlab,ylab: labels +% +% See imrgraph, imcerrgraph, imrerrgraph +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +t = 1:nstp; +nrow +ncol + +temp1=zeros(ncol,1); +temp2=zeros(ncol,1); +maxval=zeros(nrow,1); +minval=zeros(nrow,1); +for i = 1:nrow + for j = 1:ncol + jnk1=max(firsth(:,i,j)); + jnk2=max(firstl(:,i,j)); + jnk3=max(firsth1(:,i,j)); + jnk4=max(firstl1(:,i,j)); + jnk5=max(imf(:,i,j)); + + temp1(j)=max([jnk1 jnk2 jnk3 jnk4 jnk5]); + % + jnk1=min(firstl(:,i,j)); + jnk2=min(firsth(:,i,j)); + jnk3=min(firstl1(:,i,j)); + jnk4=min(firsth1(:,i,j)); + jnk5=min(imf(:,i,j)); + + temp2(j)=min([jnk1 jnk2 jnk3 jnk4 jnk5]); + end + maxval(i)=max(temp1); + minval(i)=min(temp2); +end + +scaleout = [maxval(:) minval(:)]; + +%-------------- +% Column j: Shock 1 to N; Row i: Responses to +%------------- +figure +rowlabel = 1; +for i = 1:nrow % column: from top to bottom + columnlabel = 1; + + if minval(i)<0 + if maxval(i)<=0 + yt=[minval(i) 0]; + else + yt=[minval(i) 0 maxval(i)]; + end + else % (minval(i) >=0) + if maxval(i) > 0 + yt=[0 maxval(i)]; + else % (identically zero responses) + yt=[-1 0 1]; + end + end + + + scale=[1 nstp minval(i) maxval(i)]; + for j = 1:ncol % row: from left to right + k1=(i-1)*ncol+j; + subplot(nrow,ncol,k1) + plot(t,imf(:,i,j),t,[firstl1(:,i,j) firsth1(:,i,j)],'k--',... + t,[firstl(:,i,j) firsth(:,i,j)],'k-.',t,zeros(length(imf(:,i,j)),1),'k-'); + grid; + if scaleIndx + axis(scale); + end + %set(gca,'YLim',[minval(i) maxval(i)]) + % + set(gca,'XTick',XTick) + if YTickIndx + set(gca,'YTick',yt) + end + + if i<nrow + set(gca,'XTickLabelMode','manual','XTickLabel',[]) + end + %set(gca,'XTickLabel',' '); + if j>1 + set(gca,'YTickLabel',' '); + end + if rowlabel == 1 + %title(['x' num2str(j)]) + %title(eval(['x' num2str(j)])) + title(char(xlab(j))) + end + if columnlabel == 1 + %ylabel(['x' num2str(i)]) + %ylabel(eval(['x' num2str(i)])) + ylabel(char(ylab(i))) + end + columnlabel = 0; + end + rowlabel = 0; +end diff --git a/MatlabFiles/phg233.m b/MatlabFiles/phg233.m index 0e23d5b646b8804bf2f8bd7b2ce7e673b403adce..cbcee066a469d4e653e5596f75b0347ff93b4f65 100644 --- a/MatlabFiles/phg233.m +++ b/MatlabFiles/phg233.m @@ -1,272 +1,272 @@ -function g = phg233(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaya0 = zeros(na0p,1); -vaha0 = zeros(na0p,1); -vaxah = zeros(na0p,1); -vahad = zeros(na0p,1); -vbiga = zeros(na0p,1); - - -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.2; -mu(3) = 1; -%mu(4)=1; -mu(4)=1; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); -phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a SZ paper -sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -ymy=y'*y-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the analytical gradient -%%%%%%% -% -disp(sprintf('Starting loop (of): %g',toc)) - -stril = 0; -Hp0p = zeros(ncoef); -% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - Hp0 = zeros(ncoef,strm); - % initializing Htd_+0*inv(Htd_00)*Htd_0 - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida(stri).*factor0(stri); - sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - Hb = zeros(strm+ncoef); % including A0i and A+i - Hb(1:strm,1:strm) = sg0b; - sg0bxx = sg0b*XX'; - Hb(1:strm,strm+1:strm+nvar) = sg0bxx; - %Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; CAS 9/24/96. Saves a little multiplication by using line below. - Hb(strm+1:strm+nvar,1:strm) = sg0bxx'; - Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0bxx+sg1b; - Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = sgppb; - - % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. - % ** using dummy initial observations - %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation - - % * final unconditional prior variance on A0i and A+i - %Hbzs1=Hb*zs1'; - %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); - % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below - % removes double-counting of dummy observations and a possible scale sensitivity. - Htd = Hb; - % H_~: td: tilde for ~ - - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = Htd(1:strm,1:strm); % unconditional - % ** inverse and chol decomp - H0tdi = inv(H0td); - - % - Hptd10 = Htd(strm+1:strm+nvar,1:strm); - % top matrix of nvar in Htd_+0 - Hptd100 = Hptd10*H0tdi; - Hp0(1:nvar,:) = Hptd100; - Hptd101 = Hptd100*Hptd10'; - Hp0p(1:nvar,1:nvar) = Hptd101; - Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; - % condtional on A0i, H_plus_tilde - - % ** inverse - Hptdi = inv(Hptd); - chhh = Hptdi*Hp0; % <<>> the term not used for "of" - - % common term - xxhp = xtx+Hptdi; - - % ** final conditional prior mean on A+i - alptd = zeros(ncoef,1); - alptd(1:nvar) = XX*A0b(stri,i); - %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 - alptd = alptd + Hp0*A0hb; - % conditional on A0i, alpha-plus-tilde - - % * alpha_plus_* for the ith equation, ncoef*1 - % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); - HptdDinalptd=Hptdi*alptd; - xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy - alpst = xaha'/xxhp; - GlbAph(i,:)=alpst; - % alpst': transpose of alps. - - A0hy = A0h(:,i)'*ymy; - A0hbH = A0hb'*H0tdi; - A0hcxyxx = A0h(:,i)'*cxyxx; - - %%%% - % *** passing the gradient to "pmdg6.m" (analytical gradient) - %%%% - % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) - daya0 = 2.0*A0hy; - daya0 = daya0(:); - vaya0(stril+1:stril+strm) = daya0(stri); - - % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* - % ** (alpha0-alpha0_tilde))/d(a0??) - daha0 = 2.0*A0hbH; - vaha0(stril+1:stril+strm) = daha0(:); - - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); - %% vaxah(stril+1:stril+strm) = daxah'; - daxah = 2*A0hcxyxx; - daxah = daxah(:); - vaxah(stril+1:stril+strm) = daxah(stri); - - - % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) - dahad = 2*HptdDinalptd' * Hp0; - % <<>> multiplications not used in "of" - vahad(stril+1:stril+strm) = dahad'; - - % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) - dbiga = 2*alpst*(cxy(:,stri)+chhh); - % <<>> multiplications not used in "of" - vbiga(stril+1:stril+strm) = dbiga'; - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) -disp(sprintf('Loop end (of): %g', toc)) - -g = zeros(nfp,1); - -%%%%%%% -%%% analytical gradient for A0 below -%%%%%%% -% -% ** dla0 = dlog|A0|/d(a0??) -vdla0 = zeros(na0p,1); -dla0 = inv(A0h)'; -dla0 = dla0(:); -vdla0 = dla0(a0indx); - -g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; - \ No newline at end of file +function g = phg233(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaya0 = zeros(na0p,1); +vaha0 = zeros(na0p,1); +vaxah = zeros(na0p,1); +vahad = zeros(na0p,1); +vbiga = zeros(na0p,1); + + +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.2; +mu(3) = 1; +%mu(4)=1; +mu(4)=1; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); +phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a SZ paper +sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +ymy=y'*y-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the analytical gradient +%%%%%%% +% +disp(sprintf('Starting loop (of): %g',toc)) + +stril = 0; +Hp0p = zeros(ncoef); +% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + Hp0 = zeros(ncoef,strm); + % initializing Htd_+0*inv(Htd_00)*Htd_0 + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida(stri).*factor0(stri); + sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + Hb = zeros(strm+ncoef); % including A0i and A+i + Hb(1:strm,1:strm) = sg0b; + sg0bxx = sg0b*XX'; + Hb(1:strm,strm+1:strm+nvar) = sg0bxx; + %Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; CAS 9/24/96. Saves a little multiplication by using line below. + Hb(strm+1:strm+nvar,1:strm) = sg0bxx'; + Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0bxx+sg1b; + Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = sgppb; + + % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. + % ** using dummy initial observations + %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation + + % * final unconditional prior variance on A0i and A+i + %Hbzs1=Hb*zs1'; + %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); + % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below + % removes double-counting of dummy observations and a possible scale sensitivity. + Htd = Hb; + % H_~: td: tilde for ~ + + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = Htd(1:strm,1:strm); % unconditional + % ** inverse and chol decomp + H0tdi = inv(H0td); + + % + Hptd10 = Htd(strm+1:strm+nvar,1:strm); + % top matrix of nvar in Htd_+0 + Hptd100 = Hptd10*H0tdi; + Hp0(1:nvar,:) = Hptd100; + Hptd101 = Hptd100*Hptd10'; + Hp0p(1:nvar,1:nvar) = Hptd101; + Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; + % condtional on A0i, H_plus_tilde + + % ** inverse + Hptdi = inv(Hptd); + chhh = Hptdi*Hp0; % <<>> the term not used for "of" + + % common term + xxhp = xtx+Hptdi; + + % ** final conditional prior mean on A+i + alptd = zeros(ncoef,1); + alptd(1:nvar) = XX*A0b(stri,i); + %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 + alptd = alptd + Hp0*A0hb; + % conditional on A0i, alpha-plus-tilde + + % * alpha_plus_* for the ith equation, ncoef*1 + % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); + HptdDinalptd=Hptdi*alptd; + xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy + alpst = xaha'/xxhp; + GlbAph(i,:)=alpst; + % alpst': transpose of alps. + + A0hy = A0h(:,i)'*ymy; + A0hbH = A0hb'*H0tdi; + A0hcxyxx = A0h(:,i)'*cxyxx; + + %%%% + % *** passing the gradient to "pmdg6.m" (analytical gradient) + %%%% + % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) + daya0 = 2.0*A0hy; + daya0 = daya0(:); + vaya0(stril+1:stril+strm) = daya0(stri); + + % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* + % ** (alpha0-alpha0_tilde))/d(a0??) + daha0 = 2.0*A0hbH; + vaha0(stril+1:stril+strm) = daha0(:); + + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); + %% vaxah(stril+1:stril+strm) = daxah'; + daxah = 2*A0hcxyxx; + daxah = daxah(:); + vaxah(stril+1:stril+strm) = daxah(stri); + + + % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) + dahad = 2*HptdDinalptd' * Hp0; + % <<>> multiplications not used in "of" + vahad(stril+1:stril+strm) = dahad'; + + % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) + dbiga = 2*alpst*(cxy(:,stri)+chhh); + % <<>> multiplications not used in "of" + vbiga(stril+1:stril+strm) = dbiga'; + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) +disp(sprintf('Loop end (of): %g', toc)) + +g = zeros(nfp,1); + +%%%%%%% +%%% analytical gradient for A0 below +%%%%%%% +% +% ** dla0 = dlog|A0|/d(a0??) +vdla0 = zeros(na0p,1); +dla0 = inv(A0h)'; +dla0 = dla0(:); +vdla0 = dla0(a0indx); + +g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; + diff --git a/MatlabFiles/phg234.m b/MatlabFiles/phg234.m index 36e6f9c79493fb8953426a74d45901755182bb1d..21ddcaf97e69be30e74eb9286bb97df39555261c 100644 --- a/MatlabFiles/phg234.m +++ b/MatlabFiles/phg234.m @@ -1,259 +1,259 @@ -function g = phg234(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% -% Revsions by TZ, 10/12/96: efficiency improvement by streamlining the previous code -% according to the general setup in Sims and Zha "Bayesian Methods for ...". -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaya0 = zeros(na0p,1); -vaha0 = zeros(na0p,1); -vaxah = zeros(na0p,1); -vahad = zeros(na0p,1); -vbiga = zeros(na0p,1); - - -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.3; -mu(3) = 25; -%mu(4)=1; -mu(4)=1; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -%%phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -%%y(1:nvar,:) = mu(5)*y(1:nvar,:); -%%phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -%%y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -%%sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper -sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -ymy=y'*y-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -disp(sprintf('Starting loop (of): %g',toc)) - -stril = 0; -Hp0p = zeros(ncoef); -% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - %%A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - %%factor0=idmat0(:,i); - %%sg0bd = sg0bida(stri).*factor0(stri); - %%sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - %%H0td = sg0b; % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - %%H0tdi = inv(H0td); - - % - Hptd = zeros(ncoef); - Hptd(1:nvar,1:nvar)=sg1b; - Hptd(nvar+1:ncoef,nvar+1:ncoef)=sgppb; - % condtional on A0i, H_plus_tilde - - % ** inverse - Hptdi = inv(Hptd); - %%chhh=Hptdi*Hp0; - chhh = zeros(ncoef,strm); % <<>> the term not used for "of"\ - chhh(1:nvar,:) = Hptdi(1:nvar,1:nvar)*XX; - chhh1 = XX'*chhh(1:nvar,:); - - % common term - xxhp = xtx+Hptdi; - - % ** final conditional prior mean on A+i - alptd = zeros(ncoef,1); - alptd(1:nvar) = XX*A0h(stri,i); - % conditional on A0i, alpha-plus-tilde - - % * alpha_plus_* for the ith equation, ncoef*1 - % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); - %%HptdDinalptd=Hptdi*alptd; - HptdDinalptd=zeros(ncoef,1); - HptdDinalptd(1:nvar) = Hptdi(1:nvar,1:nvar)*alptd(1:nvar); - xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy - alpst = xaha'/xxhp; - GlbAph(i,:)=alpst; - % alpst': transpose of alps. - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms prior to i-th - A0hy = A0h(:,i)'*ymy; - % ** 4th bid term in i-th equation, - % ** with all other 4th big terms prior to i-th - A0hcxyxx = A0h(:,i)'*cxyxx; - %%atdHatd = alptd'*HptdDinalptd; % efficiency improvement - atdHatd = alptd(1:nvar)'*HptdDinalptd(1:nvar); - - %%%% - % *** passing the gradient to "pmdg6.m" (analytical gradient) - %%%% - % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) - daya0 = 2.0*A0hy; - daya0 = daya0(:); - vaya0(stril+1:stril+strm) = daya0(stri); - - % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* - % ** (alpha0-alpha0_tilde))/d(a0??) - %%daha0 = 2.0*A0hbH; - %%vaha0(stril+1:stril+strm) = daha0(:); - - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); - %% vaxah(stril+1:stril+strm) = daxah'; - daxah = 2*A0hcxyxx; - daxah = daxah(:); - vaxah(stril+1:stril+strm) = daxah(stri); - - - % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) - dahad = 2*A0h(stri,i)'*chhh1; - % <<>> multiplications not used in "of" - vahad(stril+1:stril+strm) = dahad(:); - - - % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) - dbiga = 2*alpst*(cxy(:,stri)+chhh); - % <<>> multiplications not used in "of" - vbiga(stril+1:stril+strm) = dbiga'; - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) -disp(sprintf('Loop end (of): %g', toc)) - -%e_tfat = toc - -g = zeros(nfp,1); - -%%%%%%% -%%% analytical gradient for A0 below -%%%%%%% -% -% ** dla0 = dlog|A0|/d(a0??) -vdla0 = zeros(na0p,1); -dla0 = inv(A0h)'; -dla0 = dla0(:); -vdla0 = dla0(a0indx); - -% without the prior |A0|^k -g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; \ No newline at end of file +function g = phg234(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Revsions by TZ, 10/12/96: efficiency improvement by streamlining the previous code +% according to the general setup in Sims and Zha "Bayesian Methods for ...". +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaya0 = zeros(na0p,1); +vaha0 = zeros(na0p,1); +vaxah = zeros(na0p,1); +vahad = zeros(na0p,1); +vbiga = zeros(na0p,1); + + +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.3; +mu(3) = 25; +%mu(4)=1; +mu(4)=1; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +%%phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +%%y(1:nvar,:) = mu(5)*y(1:nvar,:); +%%phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +%%y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +%%sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper +sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +ymy=y'*y-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +disp(sprintf('Starting loop (of): %g',toc)) + +stril = 0; +Hp0p = zeros(ncoef); +% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + %%A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + %%factor0=idmat0(:,i); + %%sg0bd = sg0bida(stri).*factor0(stri); + %%sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + %%H0td = sg0b; % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + %%H0tdi = inv(H0td); + + % + Hptd = zeros(ncoef); + Hptd(1:nvar,1:nvar)=sg1b; + Hptd(nvar+1:ncoef,nvar+1:ncoef)=sgppb; + % condtional on A0i, H_plus_tilde + + % ** inverse + Hptdi = inv(Hptd); + %%chhh=Hptdi*Hp0; + chhh = zeros(ncoef,strm); % <<>> the term not used for "of"\ + chhh(1:nvar,:) = Hptdi(1:nvar,1:nvar)*XX; + chhh1 = XX'*chhh(1:nvar,:); + + % common term + xxhp = xtx+Hptdi; + + % ** final conditional prior mean on A+i + alptd = zeros(ncoef,1); + alptd(1:nvar) = XX*A0h(stri,i); + % conditional on A0i, alpha-plus-tilde + + % * alpha_plus_* for the ith equation, ncoef*1 + % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); + %%HptdDinalptd=Hptdi*alptd; + HptdDinalptd=zeros(ncoef,1); + HptdDinalptd(1:nvar) = Hptdi(1:nvar,1:nvar)*alptd(1:nvar); + xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy + alpst = xaha'/xxhp; + GlbAph(i,:)=alpst; + % alpst': transpose of alps. + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms prior to i-th + A0hy = A0h(:,i)'*ymy; + % ** 4th bid term in i-th equation, + % ** with all other 4th big terms prior to i-th + A0hcxyxx = A0h(:,i)'*cxyxx; + %%atdHatd = alptd'*HptdDinalptd; % efficiency improvement + atdHatd = alptd(1:nvar)'*HptdDinalptd(1:nvar); + + %%%% + % *** passing the gradient to "pmdg6.m" (analytical gradient) + %%%% + % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) + daya0 = 2.0*A0hy; + daya0 = daya0(:); + vaya0(stril+1:stril+strm) = daya0(stri); + + % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* + % ** (alpha0-alpha0_tilde))/d(a0??) + %%daha0 = 2.0*A0hbH; + %%vaha0(stril+1:stril+strm) = daha0(:); + + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); + %% vaxah(stril+1:stril+strm) = daxah'; + daxah = 2*A0hcxyxx; + daxah = daxah(:); + vaxah(stril+1:stril+strm) = daxah(stri); + + + % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) + dahad = 2*A0h(stri,i)'*chhh1; + % <<>> multiplications not used in "of" + vahad(stril+1:stril+strm) = dahad(:); + + + % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) + dbiga = 2*alpst*(cxy(:,stri)+chhh); + % <<>> multiplications not used in "of" + vbiga(stril+1:stril+strm) = dbiga'; + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) +disp(sprintf('Loop end (of): %g', toc)) + +%e_tfat = toc + +g = zeros(nfp,1); + +%%%%%%% +%%% analytical gradient for A0 below +%%%%%%% +% +% ** dla0 = dlog|A0|/d(a0??) +vdla0 = zeros(na0p,1); +dla0 = inv(A0h)'; +dla0 = dla0(:); +vdla0 = dla0(a0indx); + +% without the prior |A0|^k +g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; diff --git a/MatlabFiles/phg235.m b/MatlabFiles/phg235.m index 936ebfd90920a420fc221f5e8fbbfa37ef13b32c..37e61787b150e409666f4c8c604017ca86ac1092 100644 --- a/MatlabFiles/phg235.m +++ b/MatlabFiles/phg235.m @@ -1,211 +1,211 @@ -function g = phg235(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% -% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code -% according to the general setup in Sims and Zha "Bayesian Methods for ...". -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaha0 vaMMa0 GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaha0 = zeros(na0p,1); -vaMMa0 = zeros(na0p,1); - -% -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.2; -mu(3) = 1; -%mu(4)=1; -mu(4)=10; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); -phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper -sgppbdi = 1./sgppbd; -%sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -yty=y'*y; -ymy=yty-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -cyx = cxy'; -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% Analytical gradient for A0 below -%%%%%%% -% -% ** dla0 = dlog|A0|/d(a0??) -vdla0 = zeros(na0p,1); -dla0 = inv(A0h)'; -dla0 = dla0(:); -vdla0 = dla0(a0indx); - - -stril = 0; -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); -Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); - % condtional on A0i, H_plus_tilde -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida(stri).*factor0(stri); - sg0bdi = 1./sg0bd; - %sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdi = 1./sg1bd; - %sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - H0tdi = diag(sg0bdi); - - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdi(1:nvar,1:nvar)=diag(sg1bdi); - % condtional on A0i, H_plus_tilde - - % common terms - xxhp = xtx+Hptdi; - A0hbH = A0hb'*H0tdi; - H1p_1 = zeros(ncoef,nvar); - H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); - %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); - Hm1 = (cyx+H1p_1')/xxhp; - Hm2 = cxy+H1p_1; - GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus* - %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; - alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; - - %%%% - % *** passing the gradient to "pmdg6.m" (analytical gradient) - %%%% - % - % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* - % ** (alpha0-alpha0_tilde))/d(a0??) - daha0 = 2.0*A0hbH; - vaha0(stril+1:stril+strm) = daha0(:); - % - % ** daMMa0 = d(alpha0'*P'*(Y'Y+H_1^(-1)+H_m)*P*apha0) / d(a0?) - daMMa0 = 2.0*alpMpyh; - vaMMa0(stril+1:stril+strm) = daMMa0(:); - - stril = stril + strm; -end - -% without the prior |A0|^k -g = -fss*vdla0 + 0.5*vaha0 + 0.5*vaMMa0; - -%disp(sprintf('Loop end (gradient): %g', toc)) \ No newline at end of file +function g = phg235(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code +% according to the general setup in Sims and Zha "Bayesian Methods for ...". +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaha0 vaMMa0 GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaha0 = zeros(na0p,1); +vaMMa0 = zeros(na0p,1); + +% +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.2; +mu(3) = 1; +%mu(4)=1; +mu(4)=10; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); +phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper +sgppbdi = 1./sgppbd; +%sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +yty=y'*y; +ymy=yty-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +cyx = cxy'; +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% Analytical gradient for A0 below +%%%%%%% +% +% ** dla0 = dlog|A0|/d(a0??) +vdla0 = zeros(na0p,1); +dla0 = inv(A0h)'; +dla0 = dla0(:); +vdla0 = dla0(a0indx); + + +stril = 0; +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); +Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); + % condtional on A0i, H_plus_tilde +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida(stri).*factor0(stri); + sg0bdi = 1./sg0bd; + %sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdi = 1./sg1bd; + %sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + H0tdi = diag(sg0bdi); + + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdi(1:nvar,1:nvar)=diag(sg1bdi); + % condtional on A0i, H_plus_tilde + + % common terms + xxhp = xtx+Hptdi; + A0hbH = A0hb'*H0tdi; + H1p_1 = zeros(ncoef,nvar); + H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); + %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); + Hm1 = (cyx+H1p_1')/xxhp; + Hm2 = cxy+H1p_1; + GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus* + %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; + alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; + + %%%% + % *** passing the gradient to "pmdg6.m" (analytical gradient) + %%%% + % + % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* + % ** (alpha0-alpha0_tilde))/d(a0??) + daha0 = 2.0*A0hbH; + vaha0(stril+1:stril+strm) = daha0(:); + % + % ** daMMa0 = d(alpha0'*P'*(Y'Y+H_1^(-1)+H_m)*P*apha0) / d(a0?) + daMMa0 = 2.0*alpMpyh; + vaMMa0(stril+1:stril+strm) = daMMa0(:); + + stril = stril + strm; +end + +% without the prior |A0|^k +g = -fss*vdla0 + 0.5*vaha0 + 0.5*vaMMa0; + +%disp(sprintf('Loop end (gradient): %g', toc)) diff --git a/MatlabFiles/pmddf233.m b/MatlabFiles/pmddf233.m index 67ce8a1287a90425d4584fc35bd5cee615d3ac59..d6f7ebf00b8e4b45a1ce4a56fd65b074896e4e73 100644 --- a/MatlabFiles/pmddf233.m +++ b/MatlabFiles/pmddf233.m @@ -1,278 +1,278 @@ -function of = pmddf233(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. - -% Copyright (C) 1997-2012 Christopher A. Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaya0 = zeros(na0p,1); -vaha0 = zeros(na0p,1); -vaxah = zeros(na0p,1); -vahad = zeros(na0p,1); -vbiga = zeros(na0p,1); - - -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.2; -mu(3) = 1; -%mu(4)=1; -mu(4)=1; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); -phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a SZ paper -sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -ymy=y'*y-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -tt1 = (-1.0)*fss*sum(t1f); -% Commented out by TZ, 10/3/96, to allow the prior |A0|^k -%%tt1 = (-1.0)*(fss+ncoef)*sum(t1f); - -tt3 = 0; -tt4 = 0; - -disp(sprintf('Starting loop (of): %g',toc)) - -stril = 0; -Hp0p = zeros(ncoef); -% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - Hp0 = zeros(ncoef,strm); - % initializing Htd_+0*inv(Htd_00)*Htd_0 - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida(stri).*factor0(stri); - sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - Hb = zeros(strm+ncoef); % including A0i and A+i - Hb(1:strm,1:strm) = sg0b; - sg0bxx = sg0b*XX'; - Hb(1:strm,strm+1:strm+nvar) = sg0bxx; - %Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; CAS 9/24/96. Saves a little multiplication by using line below. - Hb(strm+1:strm+nvar,1:strm) = sg0bxx'; - Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0bxx+sg1b; - Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = sgppb; - - % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. - % ** using dummy initial observations - %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation - - % * final unconditional prior variance on A0i and A+i - %Hbzs1=Hb*zs1'; - %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); - % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below - % removes double-counting of dummy observations and a possible scale sensitivity. - Htd = Hb; - % H_~: td: tilde for ~ - - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = Htd(1:strm,1:strm); % unconditional - % ** inverse and chol decomp - H0tdi = inv(H0td); - - % - Hptd10 = Htd(strm+1:strm+nvar,1:strm); - % top matrix of nvar in Htd_+0 - Hptd100 = Hptd10*H0tdi; - Hp0(1:nvar,:) = Hptd100; - Hptd101 = Hptd100*Hptd10'; - Hp0p(1:nvar,1:nvar) = Hptd101; - Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; - % condtional on A0i, H_plus_tilde - - % ** inverse - Hptdi = inv(Hptd); - chhh = Hptdi*Hp0; % <<>> the term not used for "of" - - % common term - xxhp = xtx+Hptdi; - - % ** final conditional prior mean on A+i - alptd = zeros(ncoef,1); - alptd(1:nvar) = XX*A0b(stri,i); - %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 - alptd = alptd + Hp0*A0hb; - % conditional on A0i, alpha-plus-tilde - - % * alpha_plus_* for the ith equation, ncoef*1 - % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); - HptdDinalptd=Hptdi*alptd; - xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy - alpst = xaha'/xxhp; - GlbAph(i,:)=alpst; - % alpst': transpose of alps. - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms prior to i-th - A0hy = A0h(:,i)'*ymy; - A0hbH = A0hb'*H0tdi; - tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; - % ** 4th bid term in i-th equation, - % ** with all other 4th big terms prior to i-th - A0hcxyxx = A0h(:,i)'*cxyxx; - atdHatd = alptd'*HptdDinalptd; - tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; - - %%%% - % *** passing the gradient to "pmdg6.m" (analytical gradient) - %%%% - % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) - daya0 = 2.0*A0hy; - daya0 = daya0(:); - vaya0(stril+1:stril+strm) = daya0(stri); - - % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* - % ** (alpha0-alpha0_tilde))/d(a0??) - daha0 = 2.0*A0hbH; - vaha0(stril+1:stril+strm) = daha0(:); - - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); - %% vaxah(stril+1:stril+strm) = daxah'; - daxah = 2*A0hcxyxx; - daxah = daxah(:); - vaxah(stril+1:stril+strm) = daxah(stri); - - - % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) - dahad = 2*HptdDinalptd' * Hp0; - % <<>> multiplications not used in "of" - vahad(stril+1:stril+strm) = dahad'; - - % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) - dbiga = 2*alpst*(cxy(:,stri)+chhh); - % <<>> multiplications not used in "of" - vbiga(stril+1:stril+strm) = dbiga'; - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) -disp(sprintf('Loop end (of): %g', toc)) - -%e_tfat = toc - -of = tt1 + 0.5*tt3 + 0.5*tt4; -FRESHFUNCTION=1; +function of = pmddf233(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. + +% +% Copyright (C) 1997-2012 Christopher A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaya0 = zeros(na0p,1); +vaha0 = zeros(na0p,1); +vaxah = zeros(na0p,1); +vahad = zeros(na0p,1); +vbiga = zeros(na0p,1); + + +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.2; +mu(3) = 1; +%mu(4)=1; +mu(4)=1; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); +phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a SZ paper +sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +ymy=y'*y-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +tt1 = (-1.0)*fss*sum(t1f); +% Commented out by TZ, 10/3/96, to allow the prior |A0|^k +%%tt1 = (-1.0)*(fss+ncoef)*sum(t1f); + +tt3 = 0; +tt4 = 0; + +disp(sprintf('Starting loop (of): %g',toc)) + +stril = 0; +Hp0p = zeros(ncoef); +% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + Hp0 = zeros(ncoef,strm); + % initializing Htd_+0*inv(Htd_00)*Htd_0 + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida(stri).*factor0(stri); + sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + Hb = zeros(strm+ncoef); % including A0i and A+i + Hb(1:strm,1:strm) = sg0b; + sg0bxx = sg0b*XX'; + Hb(1:strm,strm+1:strm+nvar) = sg0bxx; + %Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; CAS 9/24/96. Saves a little multiplication by using line below. + Hb(strm+1:strm+nvar,1:strm) = sg0bxx'; + Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0bxx+sg1b; + Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = sgppb; + + % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. + % ** using dummy initial observations + %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation + + % * final unconditional prior variance on A0i and A+i + %Hbzs1=Hb*zs1'; + %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); + % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below + % removes double-counting of dummy observations and a possible scale sensitivity. + Htd = Hb; + % H_~: td: tilde for ~ + + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = Htd(1:strm,1:strm); % unconditional + % ** inverse and chol decomp + H0tdi = inv(H0td); + + % + Hptd10 = Htd(strm+1:strm+nvar,1:strm); + % top matrix of nvar in Htd_+0 + Hptd100 = Hptd10*H0tdi; + Hp0(1:nvar,:) = Hptd100; + Hptd101 = Hptd100*Hptd10'; + Hp0p(1:nvar,1:nvar) = Hptd101; + Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; + % condtional on A0i, H_plus_tilde + + % ** inverse + Hptdi = inv(Hptd); + chhh = Hptdi*Hp0; % <<>> the term not used for "of" + + % common term + xxhp = xtx+Hptdi; + + % ** final conditional prior mean on A+i + alptd = zeros(ncoef,1); + alptd(1:nvar) = XX*A0b(stri,i); + %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 + alptd = alptd + Hp0*A0hb; + % conditional on A0i, alpha-plus-tilde + + % * alpha_plus_* for the ith equation, ncoef*1 + % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); + HptdDinalptd=Hptdi*alptd; + xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy + alpst = xaha'/xxhp; + GlbAph(i,:)=alpst; + % alpst': transpose of alps. + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms prior to i-th + A0hy = A0h(:,i)'*ymy; + A0hbH = A0hb'*H0tdi; + tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; + % ** 4th bid term in i-th equation, + % ** with all other 4th big terms prior to i-th + A0hcxyxx = A0h(:,i)'*cxyxx; + atdHatd = alptd'*HptdDinalptd; + tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; + + %%%% + % *** passing the gradient to "pmdg6.m" (analytical gradient) + %%%% + % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) + daya0 = 2.0*A0hy; + daya0 = daya0(:); + vaya0(stril+1:stril+strm) = daya0(stri); + + % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* + % ** (alpha0-alpha0_tilde))/d(a0??) + daha0 = 2.0*A0hbH; + vaha0(stril+1:stril+strm) = daha0(:); + + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); + %% vaxah(stril+1:stril+strm) = daxah'; + daxah = 2*A0hcxyxx; + daxah = daxah(:); + vaxah(stril+1:stril+strm) = daxah(stri); + + + % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) + dahad = 2*HptdDinalptd' * Hp0; + % <<>> multiplications not used in "of" + vahad(stril+1:stril+strm) = dahad'; + + % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) + dbiga = 2*alpst*(cxy(:,stri)+chhh); + % <<>> multiplications not used in "of" + vbiga(stril+1:stril+strm) = dbiga'; + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) +disp(sprintf('Loop end (of): %g', toc)) + +%e_tfat = toc + +of = tt1 + 0.5*tt3 + 0.5*tt4; +FRESHFUNCTION=1; diff --git a/MatlabFiles/pmddf234.m b/MatlabFiles/pmddf234.m index 6bad4ee13c7646e30f84ea8f6566cda8a1e3bdcd..9a1c7d413b728e56d51f29d005aa6b15112ad38d 100644 --- a/MatlabFiles/pmddf234.m +++ b/MatlabFiles/pmddf234.m @@ -1,259 +1,259 @@ -function of = pmddf234(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% -% Revsions by TZ, 10/12/96: efficiency improvement by streamlining the previous code -% according to the general setup in Sims and Zha "Bayesian Methods for ...". -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaya0 = zeros(na0p,1); -vaha0 = zeros(na0p,1); -vaxah = zeros(na0p,1); -vahad = zeros(na0p,1); -vbiga = zeros(na0p,1); - - -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.3; -mu(3) = 25; -%mu(4)=1; -mu(4)=1; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -%%phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -%%y(1:nvar,:) = mu(5)*y(1:nvar,:); -%%phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -%%y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -%%sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper -sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -ymy=y'*y-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -% * without the prior |A0|^k -tt1 = (-1.0)*fss*sum(t1f); - -tt3 = 0; -tt4 = 0; - -disp(sprintf('Starting loop (of): %g',toc)) - -stril = 0; -Hp0p = zeros(ncoef); -% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - %%A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - %%factor0=idmat0(:,i); - %%sg0bd = sg0bida(stri).*factor0(stri); - %%sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - %%H0td = sg0b; % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - %%H0tdi = inv(H0td); - - % - Hptd = zeros(ncoef); - Hptd(1:nvar,1:nvar)=sg1b; - Hptd(nvar+1:ncoef,nvar+1:ncoef)=sgppb; - % condtional on A0i, H_plus_tilde - - % ** inverse - Hptdi = inv(Hptd); - %%chhh=Hptdi*Hp0; - chhh = zeros(ncoef,strm); % <<>> the term not used for "of"\ - chhh(1:nvar,:) = Hptdi(1:nvar,1:nvar)*XX; - chhh1 = XX'*chhh(1:nvar,:); - - % common term - xxhp = xtx+Hptdi; - - % ** final conditional prior mean on A+i - alptd = zeros(ncoef,1); - alptd(1:nvar) = XX*A0h(stri,i); - % conditional on A0i, alpha-plus-tilde - - % * alpha_plus_* for the ith equation, ncoef*1 - % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); - %%HptdDinalptd=Hptdi*alptd; - HptdDinalptd=zeros(ncoef,1); - HptdDinalptd(1:nvar) = Hptdi(1:nvar,1:nvar)*alptd(1:nvar); - xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy - alpst = xaha'/xxhp; - GlbAph(i,:)=alpst; - % alpst': transpose of alps. - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms prior to i-th - A0hy = A0h(:,i)'*ymy; - %%A0hbH = A0hb'*H0tdi; - %%tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; - tt3 = tt3 + A0hy*A0h(:,i); - % ** 4th bid term in i-th equation, - % ** with all other 4th big terms prior to i-th - A0hcxyxx = A0h(:,i)'*cxyxx; - %%atdHatd = alptd'*HptdDinalptd; % efficiency improvement - atdHatd = alptd(1:nvar)'*HptdDinalptd(1:nvar); - tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; - - %%%% - % *** passing the gradient to "pmdg6.m" (analytical gradient) - %%%% - % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) - daya0 = 2.0*A0hy; - daya0 = daya0(:); - vaya0(stril+1:stril+strm) = daya0(stri); - - % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* - % ** (alpha0-alpha0_tilde))/d(a0??) - %%daha0 = 2.0*A0hbH; - %%vaha0(stril+1:stril+strm) = daha0(:); - - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) - %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); - %% vaxah(stril+1:stril+strm) = daxah'; - daxah = 2*A0hcxyxx; - daxah = daxah(:); - vaxah(stril+1:stril+strm) = daxah(stri); - - - % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) - dahad = 2*A0h(stri,i)'*chhh1; - % <<>> multiplications not used in "of" - vahad(stril+1:stril+strm) = dahad(:); - - - % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) - dbiga = 2*alpst*(cxy(:,stri)+chhh); - % <<>> multiplications not used in "of" - vbiga(stril+1:stril+strm) = dbiga'; - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) -disp(sprintf('Loop end (of): %g', toc)) - -%e_tfat = toc - -of = tt1 + 0.5*tt3 + 0.5*tt4; -FRESHFUNCTION=1; \ No newline at end of file +function of = pmddf234(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Revsions by TZ, 10/12/96: efficiency improvement by streamlining the previous code +% according to the general setup in Sims and Zha "Bayesian Methods for ...". +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaya0 = zeros(na0p,1); +vaha0 = zeros(na0p,1); +vaxah = zeros(na0p,1); +vahad = zeros(na0p,1); +vbiga = zeros(na0p,1); + + +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.3; +mu(3) = 25; +%mu(4)=1; +mu(4)=1; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +%%phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +%%y(1:nvar,:) = mu(5)*y(1:nvar,:); +%%phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +%%y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +%%sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper +sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +ymy=y'*y-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +% * without the prior |A0|^k +tt1 = (-1.0)*fss*sum(t1f); + +tt3 = 0; +tt4 = 0; + +disp(sprintf('Starting loop (of): %g',toc)) + +stril = 0; +Hp0p = zeros(ncoef); +% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + %%A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + %%factor0=idmat0(:,i); + %%sg0bd = sg0bida(stri).*factor0(stri); + %%sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + %%H0td = sg0b; % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + %%H0tdi = inv(H0td); + + % + Hptd = zeros(ncoef); + Hptd(1:nvar,1:nvar)=sg1b; + Hptd(nvar+1:ncoef,nvar+1:ncoef)=sgppb; + % condtional on A0i, H_plus_tilde + + % ** inverse + Hptdi = inv(Hptd); + %%chhh=Hptdi*Hp0; + chhh = zeros(ncoef,strm); % <<>> the term not used for "of"\ + chhh(1:nvar,:) = Hptdi(1:nvar,1:nvar)*XX; + chhh1 = XX'*chhh(1:nvar,:); + + % common term + xxhp = xtx+Hptdi; + + % ** final conditional prior mean on A+i + alptd = zeros(ncoef,1); + alptd(1:nvar) = XX*A0h(stri,i); + % conditional on A0i, alpha-plus-tilde + + % * alpha_plus_* for the ith equation, ncoef*1 + % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); + %%HptdDinalptd=Hptdi*alptd; + HptdDinalptd=zeros(ncoef,1); + HptdDinalptd(1:nvar) = Hptdi(1:nvar,1:nvar)*alptd(1:nvar); + xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy + alpst = xaha'/xxhp; + GlbAph(i,:)=alpst; + % alpst': transpose of alps. + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms prior to i-th + A0hy = A0h(:,i)'*ymy; + %%A0hbH = A0hb'*H0tdi; + %%tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; + tt3 = tt3 + A0hy*A0h(:,i); + % ** 4th bid term in i-th equation, + % ** with all other 4th big terms prior to i-th + A0hcxyxx = A0h(:,i)'*cxyxx; + %%atdHatd = alptd'*HptdDinalptd; % efficiency improvement + atdHatd = alptd(1:nvar)'*HptdDinalptd(1:nvar); + tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; + + %%%% + % *** passing the gradient to "pmdg6.m" (analytical gradient) + %%%% + % ** d1aya0 = d(alpha0'*Y'MY*alpha0)/d(a0??) + daya0 = 2.0*A0hy; + daya0 = daya0(:); + vaya0(stril+1:stril+strm) = daya0(stri); + + % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* + % ** (alpha0-alpha0_tilde))/d(a0??) + %%daha0 = 2.0*A0hbH; + %%vaha0(stril+1:stril+strm) = daha0(:); + + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + % ** daxah = d(alpha_+^'*X'X*alpha_+^)/d(a0??) + %% daxah = 2*(Aph(:,i)'*xtx) * cxpy(:,stri); + %% vaxah(stril+1:stril+strm) = daxah'; + daxah = 2*A0hcxyxx; + daxah = daxah(:); + vaxah(stril+1:stril+strm) = daxah(stri); + + + % ** dahad = d(alpha_+~'*inv(H_+~)*alpha_+~)/d(a0??) + dahad = 2*A0h(stri,i)'*chhh1; + % <<>> multiplications not used in "of" + vahad(stril+1:stril+strm) = dahad(:); + + + % ** dbiga = d((X'X*alpha_+^+inv(H_+~)*alpha_+*)'*a_+_*)/d(a0??) + dbiga = 2*alpst*(cxy(:,stri)+chhh); + % <<>> multiplications not used in "of" + vbiga(stril+1:stril+strm) = dbiga'; + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) +disp(sprintf('Loop end (of): %g', toc)) + +%e_tfat = toc + +of = tt1 + 0.5*tt3 + 0.5*tt4; +FRESHFUNCTION=1; diff --git a/MatlabFiles/pmddf235.m b/MatlabFiles/pmddf235.m index ca4d78235f8d470488890b21a629fe7e6aa3c35d..72abb4a0a498e7f1e233f149ec9025b1300d3d20 100644 --- a/MatlabFiles/pmddf235.m +++ b/MatlabFiles/pmddf235.m @@ -1,220 +1,220 @@ -function of = pmddf235(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% -% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code -% according to the general setup in Sims and Zha "Bayesian Methods for ...". -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaha0 vaMMa0 GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaha0 = zeros(na0p,1); -vaMMa0 = zeros(na0p,1); - -% -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.2; -mu(3) = 1; -%mu(4)=1; -mu(4)=10; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); -phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper -sgppbdi = 1./sgppbd; -%sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -yty=y'*y; -ymy=yty-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -cyx = cxy'; -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -% * without the prior |A0|^k -tt1 = (-1.0)*fss*sum(t1f); - -tt3 = 0; - -disp(sprintf('Starting loop (of): %g',toc)) - -stril = 0; -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); -Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); - % condtional on A0i, H_plus_tilde -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida(stri).*factor0(stri); - sg0bdi = 1./sg0bd; - %sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdi = 1./sg1bd; - %sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - H0tdi = diag(sg0bdi); - - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdi(1:nvar,1:nvar)=diag(sg1bdi); - % condtional on A0i, H_plus_tilde - - % common terms - xxhp = xtx+Hptdi; - A0hbH = A0hb'*H0tdi; - H1p_1 = zeros(ncoef,nvar); - H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); - %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); - Hm1 = (cyx+H1p_1')/xxhp; - Hm2 = cxy+H1p_1; - GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose - %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; - alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms before the i-th equation - tt3 = tt3 + A0hbH*A0hb + alpMpyh*A0h(stri,i); - - %%%% - % *** passing the gradient to "pmdg6.m" (analytical gradient) - %%%% - % - % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* - % ** (alpha0-alpha0_tilde))/d(a0??) - daha0 = 2.0*A0hbH; - vaha0(stril+1:stril+strm) = daha0(:); - % - % ** daMMa0 = d(alpha0'*P'*(Y'Y+H_1^(-1)+H_m)*P*apha0) / d(a0?) - daMMa0 = 2.0*alpMpyh; - vaMMa0(stril+1:stril+strm) = daMMa0(:); - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) -disp(sprintf('Loop end (of): %g', toc)) - -%e_tfat = toc - -of = tt1 + 0.5*tt3; -FRESHFUNCTION=1; \ No newline at end of file +function of = pmddf235(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code +% according to the general setup in Sims and Zha "Bayesian Methods for ...". +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaha0 vaMMa0 GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaha0 = zeros(na0p,1); +vaMMa0 = zeros(na0p,1); + +% +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.2; +mu(3) = 1; +%mu(4)=1; +mu(4)=10; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); +phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper +sgppbdi = 1./sgppbd; +%sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +yty=y'*y; +ymy=yty-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +cyx = cxy'; +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +% * without the prior |A0|^k +tt1 = (-1.0)*fss*sum(t1f); + +tt3 = 0; + +disp(sprintf('Starting loop (of): %g',toc)) + +stril = 0; +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); +Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); + % condtional on A0i, H_plus_tilde +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida(stri).*factor0(stri); + sg0bdi = 1./sg0bd; + %sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdi = 1./sg1bd; + %sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + H0tdi = diag(sg0bdi); + + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdi(1:nvar,1:nvar)=diag(sg1bdi); + % condtional on A0i, H_plus_tilde + + % common terms + xxhp = xtx+Hptdi; + A0hbH = A0hb'*H0tdi; + H1p_1 = zeros(ncoef,nvar); + H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); + %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); + Hm1 = (cyx+H1p_1')/xxhp; + Hm2 = cxy+H1p_1; + GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose + %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; + alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms before the i-th equation + tt3 = tt3 + A0hbH*A0hb + alpMpyh*A0h(stri,i); + + %%%% + % *** passing the gradient to "pmdg6.m" (analytical gradient) + %%%% + % + % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* + % ** (alpha0-alpha0_tilde))/d(a0??) + daha0 = 2.0*A0hbH; + vaha0(stril+1:stril+strm) = daha0(:); + % + % ** daMMa0 = d(alpha0'*P'*(Y'Y+H_1^(-1)+H_m)*P*apha0) / d(a0?) + daMMa0 = 2.0*alpMpyh; + vaMMa0(stril+1:stril+strm) = daMMa0(:); + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) +disp(sprintf('Loop end (of): %g', toc)) + +%e_tfat = toc + +of = tt1 + 0.5*tt3; +FRESHFUNCTION=1; diff --git a/MatlabFiles/pmddf236.m b/MatlabFiles/pmddf236.m index a8d33d0c07af530d0acdd59794a76731bddbc029..7759785194c7970074cca0b6d7196b2fcd72d98f 100644 --- a/MatlabFiles/pmddf236.m +++ b/MatlabFiles/pmddf236.m @@ -1,229 +1,229 @@ -function of = pmddf236(x,idmat0,idmatp,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% -% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code -% according to the general setup in Sims and Zha "Bayesian Methods for ...". -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaha0 vaMMa0 GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaha0 = zeros(na0p,1); -vaMMa0 = zeros(na0p,1); - -% -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.2; -mu(3) = 1; -%mu(4)=1; -mu(4)=10; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); -phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper -%%sgppbdi = 1./sgppbd; -%sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -yty=y'*y; -ymy=yty-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -cyx = cxy'; -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -% * without the prior |A0|^k -tt1 = (-1.0)*fss*sum(t1f); - -tt3 = 0; - -disp(sprintf('Starting loop (of): %g',toc)) - -stril = 0; -Hptd = zeros(ncoef); -Hptdi=Hptd; -%%Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); -%%Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdi(ncoef,ncoef)=1/sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida(stri).*factor0(stri); - sg0bdi = 1./sg0bd; - %sg0b = diag(sg0bd); - % - factor1=idmatp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdi = 1./sg1bd; - %sg1b = diag(sg1bd); - % - factorpp=idmatp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdi = 1./sgpp_cbd; - - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - H0tdi = diag(sg0bdi); - - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdi(1:nvar,1:nvar)=diag(sg1bdi); - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdi(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdi); - % condtional on A0i, H_plus_tilde - - % common terms - xxhp = xtx+Hptdi; - A0hbH = A0hb'*H0tdi; - H1p_1 = zeros(ncoef,nvar); - H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); - %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); - Hm1 = (cyx+H1p_1')/xxhp; - Hm2 = cxy+H1p_1; - GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose - %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; - alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms before the i-th equation - tt3 = tt3 + A0hbH*A0hb + alpMpyh*A0h(stri,i); - - %%%% - % *** passing the gradient to "pmdg6.m" (analytical gradient) - %%%% - % - % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* - % ** (alpha0-alpha0_tilde))/d(a0??) - daha0 = 2.0*A0hbH; - vaha0(stril+1:stril+strm) = daha0(:); - % - % ** daMMa0 = d(alpha0'*P'*(Y'Y+H_1^(-1)+H_m)*P*apha0) / d(a0?) - daMMa0 = 2.0*alpMpyh; - vaMMa0(stril+1:stril+strm) = daMMa0(:); - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) -disp(sprintf('Loop end (of): %g', toc)) - -%e_tfat = toc - -of = tt1 + 0.5*tt3; -FRESHFUNCTION=1; \ No newline at end of file +function of = pmddf236(x,idmat0,idmatp,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code +% according to the general setup in Sims and Zha "Bayesian Methods for ...". +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaha0 vaMMa0 GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaha0 = zeros(na0p,1); +vaMMa0 = zeros(na0p,1); + +% +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.2; +mu(3) = 1; +%mu(4)=1; +mu(4)=10; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); +phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper +%%sgppbdi = 1./sgppbd; +%sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +yty=y'*y; +ymy=yty-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +cyx = cxy'; +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +% * without the prior |A0|^k +tt1 = (-1.0)*fss*sum(t1f); + +tt3 = 0; + +disp(sprintf('Starting loop (of): %g',toc)) + +stril = 0; +Hptd = zeros(ncoef); +Hptdi=Hptd; +%%Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); +%%Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdi(ncoef,ncoef)=1/sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida(stri).*factor0(stri); + sg0bdi = 1./sg0bd; + %sg0b = diag(sg0bd); + % + factor1=idmatp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdi = 1./sg1bd; + %sg1b = diag(sg1bd); + % + factorpp=idmatp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdi = 1./sgpp_cbd; + + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + H0tdi = diag(sg0bdi); + + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdi(1:nvar,1:nvar)=diag(sg1bdi); + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdi(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdi); + % condtional on A0i, H_plus_tilde + + % common terms + xxhp = xtx+Hptdi; + A0hbH = A0hb'*H0tdi; + H1p_1 = zeros(ncoef,nvar); + H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); + %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); + Hm1 = (cyx+H1p_1')/xxhp; + Hm2 = cxy+H1p_1; + GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose + %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; + alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms before the i-th equation + tt3 = tt3 + A0hbH*A0hb + alpMpyh*A0h(stri,i); + + %%%% + % *** passing the gradient to "pmdg6.m" (analytical gradient) + %%%% + % + % ** daha0 = d((alpha0-alpha0_tilde)'*inv(H_0_tilde)* + % ** (alpha0-alpha0_tilde))/d(a0??) + daha0 = 2.0*A0hbH; + vaha0(stril+1:stril+strm) = daha0(:); + % + % ** daMMa0 = d(alpha0'*P'*(Y'Y+H_1^(-1)+H_m)*P*apha0) / d(a0?) + daMMa0 = 2.0*alpMpyh; + vaMMa0(stril+1:stril+strm) = daMMa0(:); + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) +disp(sprintf('Loop end (of): %g', toc)) + +%e_tfat = toc + +of = tt1 + 0.5*tt3; +FRESHFUNCTION=1; diff --git a/MatlabFiles/pmddg233.m b/MatlabFiles/pmddg233.m index 0091ed6f04af459b34af668eac42f20663742403..300f1865eb0d27beadeccb6ed0587279f00a4e4b 100644 --- a/MatlabFiles/pmddg233.m +++ b/MatlabFiles/pmddg233.m @@ -1,66 +1,66 @@ -function [g,badg] = pmddg233(x,idmat0,idmat1,fss,nvar, ... - ncoef,phi,y,A0b,sg0bid,sgpbid); -% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" -% general program to setup A0 matrix and compute the likelihood -% requires x (parameter vector), a0indx (matrix indicating the free -% parameters in A0), fss (forecast sample size), nvar (number of variables), -% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. -% observations in the system for A+), y (l.h.s. observations for A0), -% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial -% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), -% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, -% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the -% parameters in i-th equation in A0, initial prior covariance matrix). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaya0 vaha0 vaxah vahad vbiga FRESHFUNCTION -% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where -% it is invoked repeatedly without new function evaluations. -if ~FRESHFUNCTION - fjnk = pmddf233(x,idmat0,idmat1,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); -end -FRESHFUNCTION=0; -badg = 0; -% -a0indx=find(idmat0); -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; -g = zeros(nfp,1); -A0h= zeros(nvar); -A0h(a0indx) = x(1:na0p); - % restrictions on A0 - -%disp(sprintf('Starting loop (gradient): %g',toc)) - - -%%%%%%% -%%% analytical gradient for A0 below -%%%%%%% -% -% ** dla0 = dlog|A0|/d(a0??) -vdla0 = zeros(na0p,1); -dla0 = inv(A0h)'; -dla0 = dla0(:); -vdla0 = dla0(a0indx); - -g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; -% Commented out by TZ, 10/3/96, to allow the prior |A0|^k -%%g = -(fss+ncoef)*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; - -%disp(sprintf('Loop end (gradient): %g', toc)) \ No newline at end of file +function [g,badg] = pmddg233(x,idmat0,idmat1,fss,nvar, ... + ncoef,phi,y,A0b,sg0bid,sgpbid); +% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" +% general program to setup A0 matrix and compute the likelihood +% requires x (parameter vector), a0indx (matrix indicating the free +% parameters in A0), fss (forecast sample size), nvar (number of variables), +% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. +% observations in the system for A+), y (l.h.s. observations for A0), +% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial +% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), +% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, +% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the +% parameters in i-th equation in A0, initial prior covariance matrix). +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaya0 vaha0 vaxah vahad vbiga FRESHFUNCTION +% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where +% it is invoked repeatedly without new function evaluations. +if ~FRESHFUNCTION + fjnk = pmddf233(x,idmat0,idmat1,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); +end +FRESHFUNCTION=0; +badg = 0; +% +a0indx=find(idmat0); +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; +g = zeros(nfp,1); +A0h= zeros(nvar); +A0h(a0indx) = x(1:na0p); + % restrictions on A0 + +%disp(sprintf('Starting loop (gradient): %g',toc)) + + +%%%%%%% +%%% analytical gradient for A0 below +%%%%%%% +% +% ** dla0 = dlog|A0|/d(a0??) +vdla0 = zeros(na0p,1); +dla0 = inv(A0h)'; +dla0 = dla0(:); +vdla0 = dla0(a0indx); + +g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; +% Commented out by TZ, 10/3/96, to allow the prior |A0|^k +%%g = -(fss+ncoef)*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; + +%disp(sprintf('Loop end (gradient): %g', toc)) diff --git a/MatlabFiles/pmddg234.m b/MatlabFiles/pmddg234.m index 4b4e95aad8089ab0fa3ea0d944fe3f30fbe01b27..d0e6fbe3db23cfe942147802d192cb77c7dcef5b 100644 --- a/MatlabFiles/pmddg234.m +++ b/MatlabFiles/pmddg234.m @@ -1,65 +1,65 @@ -function [g,badg] = pmddg234(x,idmat0,idmat1,fss,nvar, ... - ncoef,phi,y,A0b,sg0bid,sgpbid); -% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" -% general program to setup A0 matrix and compute the likelihood -% requires x (parameter vector), a0indx (matrix indicating the free -% parameters in A0), fss (forecast sample size), nvar (number of variables), -% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. -% observations in the system for A+), y (l.h.s. observations for A0), -% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial -% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), -% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, -% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the -% parameters in i-th equation in A0, initial prior covariance matrix). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaya0 vaha0 vaxah vahad vbiga FRESHFUNCTION -% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where -% it is invoked repeatedly without new function evaluations. -if ~FRESHFUNCTION - fjnk = pmddf234(x,idmat0,idmat1,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); -end -FRESHFUNCTION=0; -badg = 0; -% -a0indx=find(idmat0); -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; -g = zeros(nfp,1); -A0h= zeros(nvar); -A0h(a0indx) = x(1:na0p); - % restrictions on A0 - -%disp(sprintf('Starting loop (gradient): %g',toc)) - - -%%%%%%% -%%% analytical gradient for A0 below -%%%%%%% -% -% ** dla0 = dlog|A0|/d(a0??) -vdla0 = zeros(na0p,1); -dla0 = inv(A0h)'; -dla0 = dla0(:); -vdla0 = dla0(a0indx); - -% without the prior |A0|^k -g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; - -%disp(sprintf('Loop end (gradient): %g', toc)) \ No newline at end of file +function [g,badg] = pmddg234(x,idmat0,idmat1,fss,nvar, ... + ncoef,phi,y,A0b,sg0bid,sgpbid); +% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" +% general program to setup A0 matrix and compute the likelihood +% requires x (parameter vector), a0indx (matrix indicating the free +% parameters in A0), fss (forecast sample size), nvar (number of variables), +% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. +% observations in the system for A+), y (l.h.s. observations for A0), +% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial +% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), +% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, +% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the +% parameters in i-th equation in A0, initial prior covariance matrix). +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaya0 vaha0 vaxah vahad vbiga FRESHFUNCTION +% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where +% it is invoked repeatedly without new function evaluations. +if ~FRESHFUNCTION + fjnk = pmddf234(x,idmat0,idmat1,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); +end +FRESHFUNCTION=0; +badg = 0; +% +a0indx=find(idmat0); +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; +g = zeros(nfp,1); +A0h= zeros(nvar); +A0h(a0indx) = x(1:na0p); + % restrictions on A0 + +%disp(sprintf('Starting loop (gradient): %g',toc)) + + +%%%%%%% +%%% analytical gradient for A0 below +%%%%%%% +% +% ** dla0 = dlog|A0|/d(a0??) +vdla0 = zeros(na0p,1); +dla0 = inv(A0h)'; +dla0 = dla0(:); +vdla0 = dla0(a0indx); + +% without the prior |A0|^k +g = -fss*vdla0 + 0.5*vaya0 + 0.5*vaha0 + 0.5*vaxah + 0.5*vahad - 0.5*vbiga; + +%disp(sprintf('Loop end (gradient): %g', toc)) diff --git a/MatlabFiles/pmddg235.m b/MatlabFiles/pmddg235.m index 187999952fe8ac0d05e05f891db8e96af5d85604..7993d9208df456b1f15b788110b8cbc76b73c585 100644 --- a/MatlabFiles/pmddg235.m +++ b/MatlabFiles/pmddg235.m @@ -1,65 +1,65 @@ -function [g,badg] = pmddg235(x,idmat0,idmat1,fss,nvar, ... - ncoef,phi,y,A0b,sg0bid,sgpbid); -% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" -% general program to setup A0 matrix and compute the likelihood -% requires x (parameter vector), a0indx (matrix indicating the free -% parameters in A0), fss (forecast sample size), nvar (number of variables), -% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. -% observations in the system for A+), y (l.h.s. observations for A0), -% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial -% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), -% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, -% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the -% parameters in i-th equation in A0, initial prior covariance matrix). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaha0 vaMMa0 FRESHFUNCTION -% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where -% it is invoked repeatedly without new function evaluations. -if ~FRESHFUNCTION - fjnk = pmddf235(x,idmat0,idmat1,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); -end -FRESHFUNCTION=0; -badg = 0; -% -a0indx=find(idmat0); -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; -g = zeros(nfp,1); -A0h= zeros(nvar); -A0h(a0indx) = x(1:na0p); - % restrictions on A0 - -%disp(sprintf('Starting loop (gradient): %g',toc)) - - -%%%%%%% -%%% analytical gradient for A0 below -%%%%%%% -% -% ** dla0 = dlog|A0|/d(a0??) -vdla0 = zeros(na0p,1); -dla0 = inv(A0h)'; -dla0 = dla0(:); -vdla0 = dla0(a0indx); - -% without the prior |A0|^k -g = -fss*vdla0 + 0.5*vaha0 + 0.5*vaMMa0; - -%disp(sprintf('Loop end (gradient): %g', toc)) \ No newline at end of file +function [g,badg] = pmddg235(x,idmat0,idmat1,fss,nvar, ... + ncoef,phi,y,A0b,sg0bid,sgpbid); +% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" +% general program to setup A0 matrix and compute the likelihood +% requires x (parameter vector), a0indx (matrix indicating the free +% parameters in A0), fss (forecast sample size), nvar (number of variables), +% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. +% observations in the system for A+), y (l.h.s. observations for A0), +% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial +% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), +% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, +% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the +% parameters in i-th equation in A0, initial prior covariance matrix). +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaha0 vaMMa0 FRESHFUNCTION +% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where +% it is invoked repeatedly without new function evaluations. +if ~FRESHFUNCTION + fjnk = pmddf235(x,idmat0,idmat1,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); +end +FRESHFUNCTION=0; +badg = 0; +% +a0indx=find(idmat0); +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; +g = zeros(nfp,1); +A0h= zeros(nvar); +A0h(a0indx) = x(1:na0p); + % restrictions on A0 + +%disp(sprintf('Starting loop (gradient): %g',toc)) + + +%%%%%%% +%%% analytical gradient for A0 below +%%%%%%% +% +% ** dla0 = dlog|A0|/d(a0??) +vdla0 = zeros(na0p,1); +dla0 = inv(A0h)'; +dla0 = dla0(:); +vdla0 = dla0(a0indx); + +% without the prior |A0|^k +g = -fss*vdla0 + 0.5*vaha0 + 0.5*vaMMa0; + +%disp(sprintf('Loop end (gradient): %g', toc)) diff --git a/MatlabFiles/pmddg236.m b/MatlabFiles/pmddg236.m index bb7596b024dae92a161d744a91b2a1dbadac0059..9b478f1109470637c28a55d748e8cc2973310406 100644 --- a/MatlabFiles/pmddg236.m +++ b/MatlabFiles/pmddg236.m @@ -1,66 +1,66 @@ -function [g,badg] = pmddg236(x,idmat0,idmatp,fss,nvar, ... - ncoef,phi,y,A0b,sg0bid,sgpbid); -% -% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" -% general program to setup A0 matrix and compute the likelihood -% requires x (parameter vector), a0indx (matrix indicating the free -% parameters in A0), fss (forecast sample size), nvar (number of variables), -% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. -% observations in the system for A+), y (l.h.s. observations for A0), -% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial -% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), -% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, -% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the -% parameters in i-th equation in A0, initial prior covariance matrix). -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaha0 vaMMa0 FRESHFUNCTION -% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where -% it is invoked repeatedly without new function evaluations. -if ~FRESHFUNCTION - fjnk = pmddf236(x,idmat0,idmatp,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); -end -FRESHFUNCTION=0; -badg = 0; -% -a0indx=find(idmat0); -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; -g = zeros(nfp,1); -A0h= zeros(nvar); -A0h(a0indx) = x(1:na0p); - % restrictions on A0 - -%disp(sprintf('Starting loop (gradient): %g',toc)) - - -%%%%%%% -%%% analytical gradient for A0 below -%%%%%%% -% -% ** dla0 = dlog|A0|/d(a0??) -vdla0 = zeros(na0p,1); -dla0 = inv(A0h)'; -dla0 = dla0(:); -vdla0 = dla0(a0indx); - -% without the prior |A0|^k -g = -fss*vdla0 + 0.5*vaha0 + 0.5*vaMMa0; - -%disp(sprintf('Loop end (gradient): %g', toc)) \ No newline at end of file +function [g,badg] = pmddg236(x,idmat0,idmatp,fss,nvar, ... + ncoef,phi,y,A0b,sg0bid,sgpbid); +% +% Leeper-Sims-Zha BVAR setup, analytical gradient for "csminwel.m" +% general program to setup A0 matrix and compute the likelihood +% requires x (parameter vector), a0indx (matrix indicating the free +% parameters in A0), fss (forecast sample size), nvar (number of variables), +% ncoef (number of coefficients in a single equation in A+), phi (r.h.s. +% observations in the system for A+), y (l.h.s. observations for A0), +% ymy (Y'*M*Y), xd0 (X(0) for dummy observations y*(1)), ys1 (dummy initial +% observations y*(1)), xtx (X'X or phi'*phi), A0b (initial prior on A0), +% sg0bid (diagonal of Sigma0_bar on the parameters in i-th equation in A0, +% initial prior covariace matrix), sgpbid (diagonal of Sigma+_bar on the +% parameters in i-th equation in A0, initial prior covariance matrix). +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaha0 vaMMa0 FRESHFUNCTION +% CAS added FRESHFUNCTION 8/20/96 to allow use of pmddg23 in a numerical Hessian calculation, where +% it is invoked repeatedly without new function evaluations. +if ~FRESHFUNCTION + fjnk = pmddf236(x,idmat0,idmatp,fss,nvar,ncoef,phi,y,A0b,sg0bid,sgpbid); +end +FRESHFUNCTION=0; +badg = 0; +% +a0indx=find(idmat0); +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; +g = zeros(nfp,1); +A0h= zeros(nvar); +A0h(a0indx) = x(1:na0p); + % restrictions on A0 + +%disp(sprintf('Starting loop (gradient): %g',toc)) + + +%%%%%%% +%%% analytical gradient for A0 below +%%%%%%% +% +% ** dla0 = dlog|A0|/d(a0??) +vdla0 = zeros(na0p,1); +dla0 = inv(A0h)'; +dla0 = dla0(:); +vdla0 = dla0(a0indx); + +% without the prior |A0|^k +g = -fss*vdla0 + 0.5*vaha0 + 0.5*vaMMa0; + +%disp(sprintf('Loop end (gradient): %g', toc)) diff --git a/MatlabFiles/pmddwf23.m b/MatlabFiles/pmddwf23.m index dcf99fcc8fdf730ad7ec9a6f6c36bbf65ecd0bf6..428ed0ca843ec1392df6fd283245874d03dbd086 100644 --- a/MatlabFiles/pmddwf23.m +++ b/MatlabFiles/pmddwf23.m @@ -1,213 +1,213 @@ -function [of,GlbAphh] = pmddwf23(x,a0indx,fss,nvar,ncoef,phi, ... - y,xd0,ys1,A0b,sg0bid,sgpbid) -%function of = pmddf23(x,a0indx,fss,nvar,ncoef,phi, ... -% y,xd0,ys1,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% xd0 (X(0) for dummy observations y*(1)) -% ys1 (dummy initial observations y*(1)) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaya0 vaha0 vaxah vahad vbiga GlbAph -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -GlbAphh=zeros(ncoef,nvar); - - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -a0 = zeros(nvar^2,1); -a0(a0indx) = x(1:na0p); -A0h = reshape(a0,nvar,nvar); - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -mu(2) = 0.2; -mu(3) = 20; -mu(5) = 1; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): relative tightness for dummy initial observations; -% mu(5): relative tightness for prior dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sg0bi = diag(sg0bida); -sgpbi = diag(sgpbida); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -ymy=y'*y-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -tt1 = (-1.0)*fss*sum(t1f); - -tt3 = 0; -tt4 = 0; - -stril = 0; -Hp0p = zeros(ncoef); -% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance -for i = 1:nvar - stri = find(A0h(:,i)); - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - Hp0 = zeros(ncoef,strm); - % initializing Htd_+0*inv(Htd_00)*Htd_0 - - % ** set up the conditional prior variance sg0bi and sgpbi. - sg0bd = zeros(stri,1); - sg0bd = sg0bida(stri); - sg0b = diag(sg0bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - Hb = zeros(strm+ncoef); % including A0i and A+i - Hb(1:strm,1:strm) = sg0b; - Hb(1:strm,strm+1:strm+nvar) = sg0b*XX'; - Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; - Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0b*XX'+sgpbi(1:nvar,1:nvar); - Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = ... - sgpbi(nvar+1:ncoef,nvar+1:ncoef); - - % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. - % ** using dummy initial observations - %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation - - % * final unconditional prior variance on A0i and A+i - %Hbzs1=Hb*zs1'; - %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); - % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below - % removes double-counting of dummy observations and a possible scale sensitivity. - Htd = Hb; - % H_~: td: tilde for ~ - - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = Htd(1:strm,1:strm); % unconditional - % ** inverse and chol decomp - H0tdi = inv(H0td); - - % - Hptd10 = Htd(strm+1:strm+nvar,1:strm); - % top matrix of nvar in Htd_+0 - Hptd100 = Hptd10*H0tdi; - Hp0(1:nvar,:) = Hptd100; - Hptd101 = Hptd100*Hptd10'; - Hp0p(1:nvar,1:nvar) = Hptd101; - Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; - % condtional on A0i, H_plus_tilde - - % ** inverse - Hptdi = inv(Hptd); - - % common term - xxhp = xtx+Hptdi; - Vxxhp = chol(xxhp); - % inverse of Vxxhp is the upper triangular decomp - % of inv(Vxxhp) (covariance of alpst) - - % ** final conditional prior mean on A+i - alptd = zeros(ncoef,1); - alptd(1:nvar) = XX*A0b(stri,i); - %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 - alptd = alptd + Hp0*A0hb; - % conditional on A0i, alpha-plus-tilde - - % * alpha_plus_* for the ith equation, ncoef*1 - % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); - HptdDinalptd=Hptdi*alptd; - xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy - alpst = xaha'/xxhp; - GlbAph(i,:)=alpst; - % alpst': transpose of alps. - GlbAphh(:,i)=alpst' + Vxxhp\randn(length(alpst),1); - % posterior alpha_plus_* - - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms prior to i-th - A0hy = A0h(:,i)'*ymy; - A0hbH = A0hb'*H0tdi; - tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; - - % ** 4th bid term in i-th equation, - % ** with all other 4th big terms prior to i-th - A0hcxyxx = A0h(:,i)'*cxyxx; - atdHatd = alptd'*HptdDinalptd; - tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; - - stril = stril + strm; -end - -of = tt1 + 0.5*tt3 + 0.5*tt4; - \ No newline at end of file +function [of,GlbAphh] = pmddwf23(x,a0indx,fss,nvar,ncoef,phi, ... + y,xd0,ys1,A0b,sg0bid,sgpbid) +%function of = pmddf23(x,a0indx,fss,nvar,ncoef,phi, ... +% y,xd0,ys1,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% xd0 (X(0) for dummy observations y*(1)) +% ys1 (dummy initial observations y*(1)) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaya0 vaha0 vaxah vahad vbiga GlbAph +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +GlbAphh=zeros(ncoef,nvar); + + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +a0 = zeros(nvar^2,1); +a0(a0indx) = x(1:na0p); +A0h = reshape(a0,nvar,nvar); + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +mu(2) = 0.2; +mu(3) = 20; +mu(5) = 1; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): relative tightness for dummy initial observations; +% mu(5): relative tightness for prior dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sg0bi = diag(sg0bida); +sgpbi = diag(sgpbida); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +ymy=y'*y-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +tt1 = (-1.0)*fss*sum(t1f); + +tt3 = 0; +tt4 = 0; + +stril = 0; +Hp0p = zeros(ncoef); +% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance +for i = 1:nvar + stri = find(A0h(:,i)); + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + Hp0 = zeros(ncoef,strm); + % initializing Htd_+0*inv(Htd_00)*Htd_0 + + % ** set up the conditional prior variance sg0bi and sgpbi. + sg0bd = zeros(stri,1); + sg0bd = sg0bida(stri); + sg0b = diag(sg0bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + Hb = zeros(strm+ncoef); % including A0i and A+i + Hb(1:strm,1:strm) = sg0b; + Hb(1:strm,strm+1:strm+nvar) = sg0b*XX'; + Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; + Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0b*XX'+sgpbi(1:nvar,1:nvar); + Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = ... + sgpbi(nvar+1:ncoef,nvar+1:ncoef); + + % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. + % ** using dummy initial observations + %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation + + % * final unconditional prior variance on A0i and A+i + %Hbzs1=Hb*zs1'; + %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); + % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below + % removes double-counting of dummy observations and a possible scale sensitivity. + Htd = Hb; + % H_~: td: tilde for ~ + + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = Htd(1:strm,1:strm); % unconditional + % ** inverse and chol decomp + H0tdi = inv(H0td); + + % + Hptd10 = Htd(strm+1:strm+nvar,1:strm); + % top matrix of nvar in Htd_+0 + Hptd100 = Hptd10*H0tdi; + Hp0(1:nvar,:) = Hptd100; + Hptd101 = Hptd100*Hptd10'; + Hp0p(1:nvar,1:nvar) = Hptd101; + Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; + % condtional on A0i, H_plus_tilde + + % ** inverse + Hptdi = inv(Hptd); + + % common term + xxhp = xtx+Hptdi; + Vxxhp = chol(xxhp); + % inverse of Vxxhp is the upper triangular decomp + % of inv(Vxxhp) (covariance of alpst) + + % ** final conditional prior mean on A+i + alptd = zeros(ncoef,1); + alptd(1:nvar) = XX*A0b(stri,i); + %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 + alptd = alptd + Hp0*A0hb; + % conditional on A0i, alpha-plus-tilde + + % * alpha_plus_* for the ith equation, ncoef*1 + % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); + HptdDinalptd=Hptdi*alptd; + xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy + alpst = xaha'/xxhp; + GlbAph(i,:)=alpst; + % alpst': transpose of alps. + GlbAphh(:,i)=alpst' + Vxxhp\randn(length(alpst),1); + % posterior alpha_plus_* + + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms prior to i-th + A0hy = A0h(:,i)'*ymy; + A0hbH = A0hb'*H0tdi; + tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; + + % ** 4th bid term in i-th equation, + % ** with all other 4th big terms prior to i-th + A0hcxyxx = A0h(:,i)'*cxyxx; + atdHatd = alptd'*HptdDinalptd; + tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; + + stril = stril + strm; +end + +of = tt1 + 0.5*tt3 + 0.5*tt4; + diff --git a/MatlabFiles/probvalsec.m b/MatlabFiles/probvalsec.m index aabcd4eb08bc1f5b14931b6494790c7a489a8a80..30a1f8bdacb6a0ef9fe33e5559e7b3b16fce6c97 100644 --- a/MatlabFiles/probvalsec.m +++ b/MatlabFiles/probvalsec.m @@ -1,90 +1,90 @@ -function [probelow,valow,yhatmean] = probvalsec(yhatprob,yhatpo,ninv,forep,nvar,findex,... - sindex,valix,prolix) -% [probelow,valow,yhatmean] = probvalsec(yhatprob,yhatpo,ninv,forep,nvar,findex,... -% sindex,valix,prolix) -% -% Probabilites (below) and values for selected variables and levels. -% This program takes outputs from "histpdfcnt.m" which must be run first. -% Compute (1) the probability of the x-value (such as FFR) that is below a level -% prespecified by valix (e.g., probability of R below 5%); (2) the x-value -% (such as median or .60 lower-tail value) below which the probability is at a level -% prespecified by "prolix" (e.g., median when 0.50 is prespecified); (3) the mean -% of the x-values (e.g., the mean of Pcm, M2, FFR, etc.). -% -% yhatprob: 2+ninv-by-forep*shockp(=1 here)*nvar. Probability (NOT density) at each bin -% yhatpo: 2+ninv-by-forep*shockp(=1 here)*nvar. Bin position (x-axis) in relation to yhat -% ninv: the number of bins which are small interior intervals on the x-axis -% forep: forecast periods -- 1st dim (must be compatible with findex) -% nvar: number of shocks or variables -- 2nd dim (must be compatible with sindex) -% findex: index for sected forecast periods 1st dim (c.f., forep) -% sindex: index for selected shocks or variables, 2nd dim (c.f., nvar) -% valix: length(findex)-by-length(sindex). Selected values on the x-axis -% prolix: length(findex)-by-length(sindex). Selected (below) probabilites -%----------- -% probelow: length(findex)-by-length(sindex). The probability of the x-value -% (such as FFR) that is below a level prespecified by valix (e.g., -% probability of R below 5%). -% valow: length(findex)-by-length(sindex). The x-value (such as median or .60 -% lower-tail value) below which the probability is at a level -% prespecified by "prolix" (e.g., median when 0.50 is prespecified); -% yhatmean: forep-by-nvar. The mean of forecasts of Pcm, M2, FFR, etc. -% -% 3/25/99 Tao A. Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -yhatprob2=reshape(yhatprob,2+ninv,forep,nvar); -yhatpo2=reshape(yhatpo,2+ninv,forep,nvar); -% -%** Mean -yhatmean0 = sum(yhatprob.*yhatpo,1); -yhatmean = reshape(yhatmean0,forep,nvar); -% -probelow=zeros(length(findex),length(sindex)); - % probablity of the x-value that is below a specified level - % E.g., probability of R below 5%. -valow=probelow; - % x-value for the probability that is below a specified level - % E.g., median when 0.50 is specified. -cumprob=cumsum(yhatprob2,1); % cumulative probabilities -% -count1=0; -for k1=sindex % forecast variables (or shocks) - count1=count1+1; - count2=0; - for k2=findex % forecast periods - count2=count2+1; - posix = max(find(yhatpo2(:,k2,k1)<valix(count2,count1))); - % index for the position corr. to the x-value respeicied. - if isempty(posix) - probelow(count2,count1) = cumprob(1,k2,k1); - else - probelow(count2,count1) = cumprob(posix,k2,k1); - end - posix1 = max(find(cumprob(:,k2,k1)<prolix(count2,count1))); - % index for the position corr. probability (below) specified. - if isempty(posix1) - valow(count2,count1) = yhatpo2(1,k2,k1); - else - valow(count2,count1) = yhatpo2(posix1,k2,k1); - end - end -end - - - +function [probelow,valow,yhatmean] = probvalsec(yhatprob,yhatpo,ninv,forep,nvar,findex,... + sindex,valix,prolix) +% [probelow,valow,yhatmean] = probvalsec(yhatprob,yhatpo,ninv,forep,nvar,findex,... +% sindex,valix,prolix) +% +% Probabilites (below) and values for selected variables and levels. +% This program takes outputs from "histpdfcnt.m" which must be run first. +% Compute (1) the probability of the x-value (such as FFR) that is below a level +% prespecified by valix (e.g., probability of R below 5%); (2) the x-value +% (such as median or .60 lower-tail value) below which the probability is at a level +% prespecified by "prolix" (e.g., median when 0.50 is prespecified); (3) the mean +% of the x-values (e.g., the mean of Pcm, M2, FFR, etc.). +% +% yhatprob: 2+ninv-by-forep*shockp(=1 here)*nvar. Probability (NOT density) at each bin +% yhatpo: 2+ninv-by-forep*shockp(=1 here)*nvar. Bin position (x-axis) in relation to yhat +% ninv: the number of bins which are small interior intervals on the x-axis +% forep: forecast periods -- 1st dim (must be compatible with findex) +% nvar: number of shocks or variables -- 2nd dim (must be compatible with sindex) +% findex: index for sected forecast periods 1st dim (c.f., forep) +% sindex: index for selected shocks or variables, 2nd dim (c.f., nvar) +% valix: length(findex)-by-length(sindex). Selected values on the x-axis +% prolix: length(findex)-by-length(sindex). Selected (below) probabilites +%----------- +% probelow: length(findex)-by-length(sindex). The probability of the x-value +% (such as FFR) that is below a level prespecified by valix (e.g., +% probability of R below 5%). +% valow: length(findex)-by-length(sindex). The x-value (such as median or .60 +% lower-tail value) below which the probability is at a level +% prespecified by "prolix" (e.g., median when 0.50 is prespecified); +% yhatmean: forep-by-nvar. The mean of forecasts of Pcm, M2, FFR, etc. +% +% 3/25/99 Tao A. Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +yhatprob2=reshape(yhatprob,2+ninv,forep,nvar); +yhatpo2=reshape(yhatpo,2+ninv,forep,nvar); +% +%** Mean +yhatmean0 = sum(yhatprob.*yhatpo,1); +yhatmean = reshape(yhatmean0,forep,nvar); +% +probelow=zeros(length(findex),length(sindex)); + % probablity of the x-value that is below a specified level + % E.g., probability of R below 5%. +valow=probelow; + % x-value for the probability that is below a specified level + % E.g., median when 0.50 is specified. +cumprob=cumsum(yhatprob2,1); % cumulative probabilities +% +count1=0; +for k1=sindex % forecast variables (or shocks) + count1=count1+1; + count2=0; + for k2=findex % forecast periods + count2=count2+1; + posix = max(find(yhatpo2(:,k2,k1)<valix(count2,count1))); + % index for the position corr. to the x-value respeicied. + if isempty(posix) + probelow(count2,count1) = cumprob(1,k2,k1); + else + probelow(count2,count1) = cumprob(posix,k2,k1); + end + posix1 = max(find(cumprob(:,k2,k1)<prolix(count2,count1))); + % index for the position corr. probability (below) specified. + if isempty(posix1) + valow(count2,count1) = yhatpo2(1,k2,k1); + else + valow(count2,count1) = yhatpo2(posix1,k2,k1); + end + end +end + + + diff --git a/MatlabFiles/pwf233.m b/MatlabFiles/pwf233.m index c3096cdca0fabd660143c0e1d73ce8a49ea997e0..d727d1c4b536dc71d5b81141b10433bf5c9c997b 100644 --- a/MatlabFiles/pwf233.m +++ b/MatlabFiles/pwf233.m @@ -1,242 +1,242 @@ -function of = pwf233(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% Copyright (C) 1997-2012 Christopher A. Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaya0 = zeros(na0p,1); -vaha0 = zeros(na0p,1); -vaxah = zeros(na0p,1); -vahad = zeros(na0p,1); -vbiga = zeros(na0p,1); - - -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.2; -mu(3) = 1; -%mu(4)=1; -mu(4)=1; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); -phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a SZ paper -sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -ymy=y'*y-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -tt1 = (-1.0)*fss*sum(t1f); - -tt3 = 0; -tt4 = 0; - -stril = 0; -Hp0p = zeros(ncoef); -% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - Hp0 = zeros(ncoef,strm); - % initializing Htd_+0*inv(Htd_00)*Htd_0 - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida(stri).*factor0(stri); - sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - Hb = zeros(strm+ncoef); % including A0i and A+i - Hb(1:strm,1:strm) = sg0b; - sg0bxx = sg0b*XX'; - Hb(1:strm,strm+1:strm+nvar) = sg0bxx; - %Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; CAS 9/24/96. Saves a little multiplication by using line below. - Hb(strm+1:strm+nvar,1:strm) = sg0bxx'; - Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0bxx+sg1b; - Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = sgppb; - - % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. - % ** using dummy initial observations - %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation - - % * final unconditional prior variance on A0i and A+i - %Hbzs1=Hb*zs1'; - %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); - % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below - % removes double-counting of dummy observations and a possible scale sensitivity. - Htd = Hb; - % H_~: td: tilde for ~ - - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = Htd(1:strm,1:strm); % unconditional - % ** inverse and chol decomp - H0tdi = inv(H0td); - - % - Hptd10 = Htd(strm+1:strm+nvar,1:strm); - % top matrix of nvar in Htd_+0 - Hptd100 = Hptd10*H0tdi; - Hp0(1:nvar,:) = Hptd100; - Hptd101 = Hptd100*Hptd10'; - Hp0p(1:nvar,1:nvar) = Hptd101; - Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; - % condtional on A0i, H_plus_tilde - - % ** inverse - Hptdi = inv(Hptd); - chhh = Hptdi*Hp0; % <<>> the term not used for "of" - - % common term - xxhp = xtx+Hptdi; - - % ** final conditional prior mean on A+i - alptd = zeros(ncoef,1); - alptd(1:nvar) = XX*A0b(stri,i); - %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 - alptd = alptd + Hp0*A0hb; - % conditional on A0i, alpha-plus-tilde - - % * alpha_plus_* for the ith equation, ncoef*1 - % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); - HptdDinalptd=Hptdi*alptd; - xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy - alpst = xaha'/xxhp; - GlbAph(i,:)=alpst; - % alpst': transpose of alps. - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms prior to i-th - A0hy = A0h(:,i)'*ymy; - A0hbH = A0hb'*H0tdi; - tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; - % ** 4th bid term in i-th equation, - % ** with all other 4th big terms prior to i-th - A0hcxyxx = A0h(:,i)'*cxyxx; - atdHatd = alptd'*HptdDinalptd; - tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; - - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) -%e_tfat = toc - -of = tt1 + 0.5*tt3 + 0.5*tt4; -FRESHFUNCTION=1; - \ No newline at end of file +function of = pwf233(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Copyright (C) 1997-2012 Christopher A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaya0 = zeros(na0p,1); +vaha0 = zeros(na0p,1); +vaxah = zeros(na0p,1); +vahad = zeros(na0p,1); +vbiga = zeros(na0p,1); + + +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.2; +mu(3) = 1; +%mu(4)=1; +mu(4)=1; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); +phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a SZ paper +sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +ymy=y'*y-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +tt1 = (-1.0)*fss*sum(t1f); + +tt3 = 0; +tt4 = 0; + +stril = 0; +Hp0p = zeros(ncoef); +% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + Hp0 = zeros(ncoef,strm); + % initializing Htd_+0*inv(Htd_00)*Htd_0 + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida(stri).*factor0(stri); + sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + Hb = zeros(strm+ncoef); % including A0i and A+i + Hb(1:strm,1:strm) = sg0b; + sg0bxx = sg0b*XX'; + Hb(1:strm,strm+1:strm+nvar) = sg0bxx; + %Hb(strm+1:strm+nvar,1:strm) = XX*sg0b; CAS 9/24/96. Saves a little multiplication by using line below. + Hb(strm+1:strm+nvar,1:strm) = sg0bxx'; + Hb(strm+1:strm+nvar,strm+1:strm+nvar) = XX*sg0bxx+sg1b; + Hb(strm+nvar+1:strm+ncoef,strm+nvar+1:strm+ncoef) = sgppb; + + % ** set up the final prior variance on A0i and A+i, i =1,..,6 separately. + % ** using dummy initial observations + %zs1 = [ys1(:,stri) -xd0]; % z*1 for the 1st equation + + % * final unconditional prior variance on A0i and A+i + %Hbzs1=Hb*zs1'; + %Htd = Hb - Hbzs1*((zs1*Hbzs1+mu(1)^2*mu(4)^2*eye(nvar))\Hbzs1'); + % CAS mod 8/7/96: Hope is that dropping above two lines in favor of the one below + % removes double-counting of dummy observations and a possible scale sensitivity. + Htd = Hb; + % H_~: td: tilde for ~ + + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = Htd(1:strm,1:strm); % unconditional + % ** inverse and chol decomp + H0tdi = inv(H0td); + + % + Hptd10 = Htd(strm+1:strm+nvar,1:strm); + % top matrix of nvar in Htd_+0 + Hptd100 = Hptd10*H0tdi; + Hp0(1:nvar,:) = Hptd100; + Hptd101 = Hptd100*Hptd10'; + Hp0p(1:nvar,1:nvar) = Hptd101; + Hptd = Htd(strm+1:strm+ncoef,strm+1:strm+ncoef) - Hp0p; + % condtional on A0i, H_plus_tilde + + % ** inverse + Hptdi = inv(Hptd); + chhh = Hptdi*Hp0; % <<>> the term not used for "of" + + % common term + xxhp = xtx+Hptdi; + + % ** final conditional prior mean on A+i + alptd = zeros(ncoef,1); + alptd(1:nvar) = XX*A0b(stri,i); + %alptd = alptd + Hptdf*(H0tdi*A0hb); CAS efficiency improvement 8/8/96 + alptd = alptd + Hp0*A0hb; + % conditional on A0i, alpha-plus-tilde + + % * alpha_plus_* for the ith equation, ncoef*1 + % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); + HptdDinalptd=Hptdi*alptd; + xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy + alpst = xaha'/xxhp; + GlbAph(i,:)=alpst; + % alpst': transpose of alps. + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms prior to i-th + A0hy = A0h(:,i)'*ymy; + A0hbH = A0hb'*H0tdi; + tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; + % ** 4th bid term in i-th equation, + % ** with all other 4th big terms prior to i-th + A0hcxyxx = A0h(:,i)'*cxyxx; + atdHatd = alptd'*HptdDinalptd; + tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; + + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) +%e_tfat = toc + +of = tt1 + 0.5*tt3 + 0.5*tt4; +FRESHFUNCTION=1; + diff --git a/MatlabFiles/pwf234.m b/MatlabFiles/pwf234.m index 8ccd987057661c6c58a77aeb6c166e85c1e7f1ca..323f849df80293fa89f07e0a13095e7d5cbb6dd8 100644 --- a/MatlabFiles/pwf234.m +++ b/MatlabFiles/pwf234.m @@ -1,224 +1,224 @@ -function of = pwf234(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% -% Revsions by TZ, 10/12/96: efficiency improvement by streamlining the previous code -% according to the general setup in Sims and Zha "Bayesian Methods for ...". -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaya0 = zeros(na0p,1); -vaha0 = zeros(na0p,1); -vaxah = zeros(na0p,1); -vahad = zeros(na0p,1); -vbiga = zeros(na0p,1); - - -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.3; -mu(3) = 25; -%mu(4)=1; -mu(4)=1; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -%%phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -%%y(1:nvar,:) = mu(5)*y(1:nvar,:); -%%phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -%%y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -%%sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper -sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -ymy=y'*y-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -% * without the prior |A0|^k -tt1 = (-1.0)*fss*sum(t1f); - -tt3 = 0; -tt4 = 0; - - -stril = 0; -Hp0p = zeros(ncoef); -% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - %%A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - %%factor0=idmat0(:,i); - %%sg0bd = sg0bida(stri).*factor0(stri); - %%sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - %%H0td = sg0b; % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - %%H0tdi = inv(H0td); - - % - Hptd = zeros(ncoef); - Hptd(1:nvar,1:nvar)=sg1b; - Hptd(nvar+1:ncoef,nvar+1:ncoef)=sgppb; - % condtional on A0i, H_plus_tilde - - % ** inverse - Hptdi = inv(Hptd); - %%chhh=Hptdi*Hp0; - chhh = zeros(ncoef,strm); % <<>> the term not used for "of"\ - chhh(1:nvar,:) = Hptdi(1:nvar,1:nvar)*XX; - chhh1 = XX'*chhh(1:nvar,:); - - % common term - xxhp = xtx+Hptdi; - - % ** final conditional prior mean on A+i - alptd = zeros(ncoef,1); - alptd(1:nvar) = XX*A0h(stri,i); - % conditional on A0i, alpha-plus-tilde - - % * alpha_plus_* for the ith equation, ncoef*1 - % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); - %%HptdDinalptd=Hptdi*alptd; - HptdDinalptd=zeros(ncoef,1); - HptdDinalptd(1:nvar) = Hptdi(1:nvar,1:nvar)*alptd(1:nvar); - xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy - alpst = xaha'/xxhp; - GlbAph(i,:)=alpst; - % alpst': transpose of alps. - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms prior to i-th - A0hy = A0h(:,i)'*ymy; - %%A0hbH = A0hb'*H0tdi; - %%tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; - tt3 = tt3 + A0hy*A0h(:,i); - % ** 4th bid term in i-th equation, - % ** with all other 4th big terms prior to i-th - A0hcxyxx = A0h(:,i)'*cxyxx; - %%atdHatd = alptd'*HptdDinalptd; % efficiency improvement - atdHatd = alptd(1:nvar)'*HptdDinalptd(1:nvar); - tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; - - stril = stril + strm; -end - -%disp(sprintf('Loop %d end: %g', i, toc)) - -%e_tfat = toc - -of = tt1 + 0.5*tt3 + 0.5*tt4; -FRESHFUNCTION=1; \ No newline at end of file +function of = pwf234(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Revsions by TZ, 10/12/96: efficiency improvement by streamlining the previous code +% according to the general setup in Sims and Zha "Bayesian Methods for ...". +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaya0 vaha0 vaxah vahad vbiga GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaya0 = zeros(na0p,1); +vaha0 = zeros(na0p,1); +vaxah = zeros(na0p,1); +vahad = zeros(na0p,1); +vbiga = zeros(na0p,1); + + +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.3; +mu(3) = 25; +%mu(4)=1; +mu(4)=1; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +%%phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +%%y(1:nvar,:) = mu(5)*y(1:nvar,:); +%%phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +%%y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +%%sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper +sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +ymy=y'*y-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +% * without the prior |A0|^k +tt1 = (-1.0)*fss*sum(t1f); + +tt3 = 0; +tt4 = 0; + + +stril = 0; +Hp0p = zeros(ncoef); +% initializing Htd_+0*inv(Htd_00)*Htd_0+: conditional prior covariance +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + %%A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + %%factor0=idmat0(:,i); + %%sg0bd = sg0bida(stri).*factor0(stri); + %%sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + %%H0td = sg0b; % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + %%H0tdi = inv(H0td); + + % + Hptd = zeros(ncoef); + Hptd(1:nvar,1:nvar)=sg1b; + Hptd(nvar+1:ncoef,nvar+1:ncoef)=sgppb; + % condtional on A0i, H_plus_tilde + + % ** inverse + Hptdi = inv(Hptd); + %%chhh=Hptdi*Hp0; + chhh = zeros(ncoef,strm); % <<>> the term not used for "of"\ + chhh(1:nvar,:) = Hptdi(1:nvar,1:nvar)*XX; + chhh1 = XX'*chhh(1:nvar,:); + + % common term + xxhp = xtx+Hptdi; + + % ** final conditional prior mean on A+i + alptd = zeros(ncoef,1); + alptd(1:nvar) = XX*A0h(stri,i); + % conditional on A0i, alpha-plus-tilde + + % * alpha_plus_* for the ith equation, ncoef*1 + % *alps = xxhp\(phi'*y*A0h(:,i)+HptdDinalptd); + %%HptdDinalptd=Hptdi*alptd; + HptdDinalptd=zeros(ncoef,1); + HptdDinalptd(1:nvar) = Hptdi(1:nvar,1:nvar)*alptd(1:nvar); + xaha = cxy*A0h(:,i)+HptdDinalptd; %CAS 8/7/96. Replaced phi'*y with cxy + alpst = xaha'/xxhp; + GlbAph(i,:)=alpst; + % alpst': transpose of alps. + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms prior to i-th + A0hy = A0h(:,i)'*ymy; + %%A0hbH = A0hb'*H0tdi; + %%tt3 = tt3 + A0hy*A0h(:,i) + A0hbH*A0hb; + tt3 = tt3 + A0hy*A0h(:,i); + % ** 4th bid term in i-th equation, + % ** with all other 4th big terms prior to i-th + A0hcxyxx = A0h(:,i)'*cxyxx; + %%atdHatd = alptd'*HptdDinalptd; % efficiency improvement + atdHatd = alptd(1:nvar)'*HptdDinalptd(1:nvar); + tt4 = tt4 + A0hcxyxx*A0h(:,i)+atdHatd-alpst*xaha; + + stril = stril + strm; +end + +%disp(sprintf('Loop %d end: %g', i, toc)) + +%e_tfat = toc + +of = tt1 + 0.5*tt3 + 0.5*tt4; +FRESHFUNCTION=1; diff --git a/MatlabFiles/pwf235.m b/MatlabFiles/pwf235.m index 2a6188b8be0c30b6e0edd745abd45777c39019a8..6de42b706b5acb0e1a42417cb5351b0c26282a79 100644 --- a/MatlabFiles/pwf235.m +++ b/MatlabFiles/pwf235.m @@ -1,206 +1,206 @@ -function [of,GlbAphh] = pwf235(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... - y,A0b,sg0bid,sgpbid) -%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... -% y,A0b,sg0bid,sgpbid) -% Leeper-Sims-Zha BVAR setup -% general program to setup A0 matrix and compute the likelihood -% requires -% x (parameter vector) -% a0indx (matrix indicating the free parameters in A0) -% fss (forecast sample size) -% nvar (number of variables) -% ncoef (number of coefficients in a single equation in A+) -% phi (r.h.s. observations in the system for A+) -% y (l.h.s. observations for A0) -% A0b (initial prior mean on A0) -% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) -% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of -% idmat so that it carries information about relative prior variances. -% -% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code -% according to the general setup in Sims and Zha "Bayesian Methods for ...". -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global vaha0 vaMMa0 GlbAph FRESHFUNCTION -% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables -% it uses have been refreshed by a new pmddf231 call since the last gradient call. -a0indx=find(idmat0); -GlbAphh=zeros(ncoef,nvar); -% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) - -nhp = 0; % <<>> 4 hyperparameters -na0p = length(a0indx); % <<>> number of A0 parameters -nfp = na0p+nhp; - -% *** initializing -vaha0 = zeros(na0p,1); -vaMMa0 = zeros(na0p,1); - -% -A0h = zeros(nvar,nvar); -A0h(a0indx) = x(1:na0p); -%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar - % restrictions on A0 - -[A0hl,A0hu] = lu(A0h); - -% ** hyperparameters -%%mu = x(na0p+1:nfp); -mu = ones(5,1); -mu(1) = 1; -%mu(1) = 2; -mu(2) = 0.2; -mu(3) = 1; -%mu(4)=1; -mu(4)=10; -mu(5) =1; -%mu(5) = 40; -% results from ...\dummy1\foreh\pmdd6.out -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): weight on single dummy initial observation including constant; -% mu(5): weight on nvar sums of coeffs dummy observations. - -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); -y(1:nvar,:) = mu(5)*y(1:nvar,:); -phi(nvar+1,:) = mu(4)*phi(nvar+1,:); -y(nvar+1,:) = mu(4)*y(nvar+1,:); - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper -sgppbdi = 1./sgppbd; -%sgppb = diag(sgppbd); - -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -yty=y'*y; -ymy=yty-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -cyx = cxy'; -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%%%%%%% -%%% build the objective function below -%%%%%%% -% -t1f = diag(abs(A0hu)); -t1f = log(t1f); -% * without the prior |A0|^k -tt1 = (-1.0)*fss*sum(t1f); - -tt3 = 0; - -stril = 0; -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); -Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); - % condtional on A0i, H_plus_tilde -for i = 1:nvar - stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - %at some point during an optimization. - strm = length(stri); - - A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have - % strm where it has stri, and in any case it is "overwritten" below. - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida(stri).*factor0(stri); - sg0bdi = 1./sg0bd; - %sg0b = diag(sg0bd); - % - factor1=idmat1(:,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdi = 1./sg1bd; - %sg1b = diag(sg1bd); - - % ** set up the unconditional prior variance on A0i and A+i - XX = zeros(nvar,strm); - XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - H0tdi = diag(sg0bdi); - - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdi(1:nvar,1:nvar)=diag(sg1bdi); - % condtional on A0i, H_plus_tilde - - % common terms - xxhp = xtx+Hptdi; - Vxxhp = chol(xxhp); - % inverse of Vxxhp is the upper triangular decomp - % of inv(Vxxhp) (covariance of alpst) - A0hbH = A0hb'*H0tdi; - H1p_1 = zeros(ncoef,nvar); - H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); - %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); - Hm1 = (cyx+H1p_1')/xxhp; - Hm2 = cxy+H1p_1; - GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose - GlbAphh(:,i)=GlbAph(i,:)' + Vxxhp\randn(length(GlbAph(i,:)),1); - % posterior alpha_plus_* - - %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; - alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; - - % ** 3rd bid term in i-th equation, - % ** with all other 3rd big terms before the i-th equation - tt3 = tt3 + A0hbH*A0hb + alpMpyh*A0h(stri,i); - - stril = stril + strm; -end - -of = tt1 + 0.5*tt3; \ No newline at end of file +function [of,GlbAphh] = pwf235(x,idmat0,idmat1,fss,nvar,ncoef,phi, ... + y,A0b,sg0bid,sgpbid) +%function of = pmddf232(x,idmat,fss,nvar,ncoef,phi, ... +% y,A0b,sg0bid,sgpbid) +% Leeper-Sims-Zha BVAR setup +% general program to setup A0 matrix and compute the likelihood +% requires +% x (parameter vector) +% a0indx (matrix indicating the free parameters in A0) +% fss (forecast sample size) +% nvar (number of variables) +% ncoef (number of coefficients in a single equation in A+) +% phi (r.h.s. observations in the system for A+) +% y (l.h.s. observations for A0) +% A0b (initial prior mean on A0) +% sg0bid (diagonal of Sigma0_bar, unweighted prior vcv on the parameters in i-th equation in A0) +% sgpbid (diagonal of Sigma+_bar, unweighted prior vcv on the parameters in i-th equation in A+) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale the elements of +% idmat so that it carries information about relative prior variances. +% +% Revsions by TZ, 10/13/96: efficiency improvement by streamlining the previous code +% according to the general setup in Sims and Zha "Bayesian Methods for ...". +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global vaha0 vaMMa0 GlbAph FRESHFUNCTION +% FRESHFUNCTION added 8/20/90 by CAS. It signals the pmddg23 whether the global variables +% it uses have been refreshed by a new pmddf231 call since the last gradient call. +a0indx=find(idmat0); +GlbAphh=zeros(ncoef,nvar); +% pre-allocate GlbAph to be zeros(nvar,lags*nvar+1=ncoef) + +nhp = 0; % <<>> 4 hyperparameters +na0p = length(a0indx); % <<>> number of A0 parameters +nfp = na0p+nhp; + +% *** initializing +vaha0 = zeros(na0p,1); +vaMMa0 = zeros(na0p,1); + +% +A0h = zeros(nvar,nvar); +A0h(a0indx) = x(1:na0p); +%A0h = reshape(a0,nvar,nvar); CAS 9/24/96. The reshape is not necessary if a0 starts as nvar x nvar + % restrictions on A0 + +[A0hl,A0hu] = lu(A0h); + +% ** hyperparameters +%%mu = x(na0p+1:nfp); +mu = ones(5,1); +mu(1) = 1; +%mu(1) = 2; +mu(2) = 0.2; +mu(3) = 1; +%mu(4)=1; +mu(4)=10; +mu(5) =1; +%mu(5) = 40; +% results from ...\dummy1\foreh\pmdd6.out +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): weight on single dummy initial observation including constant; +% mu(5): weight on nvar sums of coeffs dummy observations. + +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); +y(1:nvar,:) = mu(5)*y(1:nvar,:); +phi(nvar+1,:) = mu(4)*phi(nvar+1,:); +y(nvar+1,:) = mu(4)*y(nvar+1,:); + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in an SZ paper +sgppbdi = 1./sgppbd; +%sgppb = diag(sgppbd); + +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +yty=y'*y; +ymy=yty-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +cyx = cxy'; +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%%%%%%% +%%% build the objective function below +%%%%%%% +% +t1f = diag(abs(A0hu)); +t1f = log(t1f); +% * without the prior |A0|^k +tt1 = (-1.0)*fss*sum(t1f); + +tt3 = 0; + +stril = 0; +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); +Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); + % condtional on A0i, H_plus_tilde +for i = 1:nvar + stri = find(idmat0(:,i)); %CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + %at some point during an optimization. + strm = length(stri); + + A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this meant to have + % strm where it has stri, and in any case it is "overwritten" below. + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida(stri).*factor0(stri); + sg0bdi = 1./sg0bd; + %sg0b = diag(sg0bd); + % + factor1=idmat1(:,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdi = 1./sg1bd; + %sg1b = diag(sg1bd); + + % ** set up the unconditional prior variance on A0i and A+i + XX = zeros(nvar,strm); + XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + H0tdi = diag(sg0bdi); + + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdi(1:nvar,1:nvar)=diag(sg1bdi); + % condtional on A0i, H_plus_tilde + + % common terms + xxhp = xtx+Hptdi; + Vxxhp = chol(xxhp); + % inverse of Vxxhp is the upper triangular decomp + % of inv(Vxxhp) (covariance of alpst) + A0hbH = A0hb'*H0tdi; + H1p_1 = zeros(ncoef,nvar); + H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); + %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); + Hm1 = (cyx+H1p_1')/xxhp; + Hm2 = cxy+H1p_1; + GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose + GlbAphh(:,i)=GlbAph(i,:)' + Vxxhp\randn(length(GlbAph(i,:)),1); + % posterior alpha_plus_* + + %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; + alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar))*XX - GlbAph(i,:)*Hm2*XX; + + % ** 3rd bid term in i-th equation, + % ** with all other 3rd big terms before the i-th equation + tt3 = tt3 + A0hbH*A0hb + alpMpyh*A0h(stri,i); + + stril = stril + strm; +end + +of = tt1 + 0.5*tt3; diff --git a/MatlabFiles/qplot2.m b/MatlabFiles/qplot2.m index 5152157cf05424c09e370d6e0716164b20f1b048..feee21cad22c948f1c27cc683bd9cfafb42c92a0 100644 --- a/MatlabFiles/qplot2.m +++ b/MatlabFiles/qplot2.m @@ -1,81 +1,81 @@ -function dummyout = qplot2(datavector,inityear,initquart,quarter_label) -%QPLOT Quarterly data plot -%QPLOT(DATA,YEAR,QUARTER,LABEL) plots quarterly data against years -%and quarters begining with YEAR:QUARTER. Quarters are not labeled if -%LABEL=0. -% -%e.g. if GDP is a vector containing quarterly observations -%on gdp beginning in the third quarter of 1985, the command -%QPLOT(GDP,85,3) plots the observations against years and quarters. -%You may specify the year as 85 or 1985 but using 85 looks better. -% -%Setting LABEL to the values 5 or 10 will cause only every fifth -%or every tenth year to be labeled beginning with the first decade -%after YEAR. - -% QPLOT was written by Clark A. Burdick of the research -% department of the Federal Reserve Bank of Atlanta. -% Original: June 18, 1997 -% Last Modified: July 23, 1997 - -% Copyright (C) 1997-2012 Clark A. Burdick -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -% TO BE DONE: -% 1. Add better bullet proofing -% 2. Cleaning and streamlining -% 3. Better string manipulation -% 4. Options for XTick - - -if nargin == 1 - warning('Proper usage is QPLOT(data,year,quarter,label') - inityear = input('What is the initial year? '); - initquart = input('What is the initial quarter? '); - quarter_label = input('Enter 1 for labeled quarters, 0 for unlableled quarters: '); -end - -if nargin == 3 - quarter_label = 1; -end - -nquart = length(datavector); -nyear = ceil(nquart/4); - -years = inityear + [0:nyear]; -if quarter_label == 5 - years = years.*[round(years/5) == years/5]; -end -if quarter_label == 10 - years = years.*[round(years/10) == years/10]; -end - -xtickvec = (kron(years,[1 0 0 0])+kron(ones(1,nyear+1),[0 2 3 4]))'; - -if quarter_label ~= 1 - xtickvec = num2str(xtickvec); - xtickvec = strrep(xtickvec,{' 0'},{' '}); - xtickvec = strrep(xtickvec,{' 2'},{' '}); - xtickvec = strrep(xtickvec,{' 3'},{' '}); - xtickvec = strrep(xtickvec,{' 4'},{' '}); -end - - -plot(datavector); -set(gca,'XTick',[1:nquart]); -set(gca,'XTickLabel',xtickvec(initquart:initquart+(nquart-1))); \ No newline at end of file +function dummyout = qplot2(datavector,inityear,initquart,quarter_label) +%QPLOT Quarterly data plot +%QPLOT(DATA,YEAR,QUARTER,LABEL) plots quarterly data against years +%and quarters begining with YEAR:QUARTER. Quarters are not labeled if +%LABEL=0. +% +%e.g. if GDP is a vector containing quarterly observations +%on gdp beginning in the third quarter of 1985, the command +%QPLOT(GDP,85,3) plots the observations against years and quarters. +%You may specify the year as 85 or 1985 but using 85 looks better. +% +%Setting LABEL to the values 5 or 10 will cause only every fifth +%or every tenth year to be labeled beginning with the first decade +%after YEAR. + +% QPLOT was written by Clark A. Burdick of the research +% department of the Federal Reserve Bank of Atlanta. +% Original: June 18, 1997 +% Last Modified: July 23, 1997 + +% +% Copyright (C) 1997-2012 Clark A. Burdick +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +% TO BE DONE: +% 1. Add better bullet proofing +% 2. Cleaning and streamlining +% 3. Better string manipulation +% 4. Options for XTick + + +if nargin == 1 + warning('Proper usage is QPLOT(data,year,quarter,label') + inityear = input('What is the initial year? '); + initquart = input('What is the initial quarter? '); + quarter_label = input('Enter 1 for labeled quarters, 0 for unlableled quarters: '); +end + +if nargin == 3 + quarter_label = 1; +end + +nquart = length(datavector); +nyear = ceil(nquart/4); + +years = inityear + [0:nyear]; +if quarter_label == 5 + years = years.*[round(years/5) == years/5]; +end +if quarter_label == 10 + years = years.*[round(years/10) == years/10]; +end + +xtickvec = (kron(years,[1 0 0 0])+kron(ones(1,nyear+1),[0 2 3 4]))'; + +if quarter_label ~= 1 + xtickvec = num2str(xtickvec); + xtickvec = strrep(xtickvec,{' 0'},{' '}); + xtickvec = strrep(xtickvec,{' 2'},{' '}); + xtickvec = strrep(xtickvec,{' 3'},{' '}); + xtickvec = strrep(xtickvec,{' 4'},{' '}); +end + + +plot(datavector); +set(gca,'XTick',[1:nquart]); +set(gca,'XTickLabel',xtickvec(initquart:initquart+(nquart-1))); diff --git a/MatlabFiles/qzdiv.m b/MatlabFiles/qzdiv.m index 2713198a0ee431551066af9d550fd04cd3206b55..260017253ce63ca1a209284ffb05d14e89d99cac 100644 --- a/MatlabFiles/qzdiv.m +++ b/MatlabFiles/qzdiv.m @@ -1,58 +1,58 @@ -function [A,B,Q,Z,v] = qzdiv(stake,A,B,Q,Z,v) -%function [A,B,Q,Z,v] = qzdiv(stake,A,B,Q,Z,v) -% -% Takes U.T. matrices A, B, orthonormal matrices Q,Z, rearranges them -% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right -% corner, while preserving U.T. and orthonormal properties and Q'AZ' and -% Q'BZ'. The columns of v are sorted correspondingly. -% -% by Christopher A. Sims -% modified (to add v to input and output) 7/27/00 -% Copyright (C) 1997-2012 Christopher A. Sims -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -vin = nargin==6; -if ~vin - v=[]; -end -[n jnk] = size(A); -root = abs([diag(A) diag(B)]); -root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2)); -root(:,2) = root(:,2)./root(:,1); -for i = n:-1:1 - m=0; - for j=i:-1:1 - if (root(j,2) > stake | root(j,2) < -.1) - m=j; - break - end - end - if (m==0) - return - end - for k=m:1:i-1 - [A B Q Z] = qzswitch(k,A,B,Q,Z); - tmp = root(k,2); - root(k,2) = root(k+1,2); - root(k+1,2) = tmp; - if vin - tmp=v(:,k); - v(:,k)=v(:,k+1); - v(:,k+1)=tmp; - end - end -end +function [A,B,Q,Z,v] = qzdiv(stake,A,B,Q,Z,v) +%function [A,B,Q,Z,v] = qzdiv(stake,A,B,Q,Z,v) +% +% Takes U.T. matrices A, B, orthonormal matrices Q,Z, rearranges them +% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right +% corner, while preserving U.T. and orthonormal properties and Q'AZ' and +% Q'BZ'. The columns of v are sorted correspondingly. +% +% by Christopher A. Sims +% modified (to add v to input and output) 7/27/00 +% +% Copyright (C) 1997-2012 Christopher A. Sims +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +vin = nargin==6; +if ~vin + v=[]; +end +[n jnk] = size(A); +root = abs([diag(A) diag(B)]); +root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2)); +root(:,2) = root(:,2)./root(:,1); +for i = n:-1:1 + m=0; + for j=i:-1:1 + if (root(j,2) > stake | root(j,2) < -.1) + m=j; + break + end + end + if (m==0) + return + end + for k=m:1:i-1 + [A B Q Z] = qzswitch(k,A,B,Q,Z); + tmp = root(k,2); + root(k,2) = root(k+1,2); + root(k+1,2) = tmp; + if vin + tmp=v(:,k); + v(:,k)=v(:,k+1); + v(:,k+1)=tmp; + end + end +end diff --git a/MatlabFiles/qzdivct.m b/MatlabFiles/qzdivct.m index 128ae219e68f8627cfd373eedfe5349eaf1c763e..066a218d1a4deaaa6952a002ab31382ad6810c76 100644 --- a/MatlabFiles/qzdivct.m +++ b/MatlabFiles/qzdivct.m @@ -12,22 +12,22 @@ function [A,B,Q,Z] = qzdivct(stake,A,B,Q,Z) % qzdiv in that it works on the real part's value, as is appropriate for % continuous time models, instead of on the absolute value, as is % appropriate for discrete time models. -% Copyright (C) 1997-2012 Tao Zha % -% This file is part of Dynare. +% Copyright (C) 1997-2012 Tao Zha % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% realsmall=sqrt(eps)*10; %realsmall=1e-3; @@ -83,4 +83,4 @@ for i = n:-1:1 [gevOld gevOld(:,1).\gevOld(:,2);gev gev(:,1).\gev(:,2)] end end -end \ No newline at end of file +end diff --git a/MatlabFiles/qzswitch.m b/MatlabFiles/qzswitch.m index ad86b0e021e38a8ab95f88bfccad3c6f607f2cad..a6f6cc40d8def60d05a7925605404e2748c6404c 100644 --- a/MatlabFiles/qzswitch.m +++ b/MatlabFiles/qzswitch.m @@ -9,22 +9,22 @@ function [A,B,Q,Z] = qzswitch(i,A,B,Q,Z) % to drive all zeros on the diagonal of A to the lower right, but in this case % the qz transformation is not unique and it is not possible simply to switch % the positions of the diagonal elements of both A and B. -% Copyright (C) 1997-2012 Tao Zha % -% This file is part of Dynare. +% Copyright (C) 1997-2012 Tao Zha % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% realsmall=sqrt(eps)*10; %realsmall=1e-3; @@ -74,4 +74,4 @@ B(i:i+1,:) = xy*B(i:i+1,:); A(:,i:i+1) = A(:,i:i+1)*wz; B(:,i:i+1) = B(:,i:i+1)*wz; Z(:,i:i+1) = Z(:,i:i+1)*wz; -Q(i:i+1,:) = xy*Q(i:i+1,:); \ No newline at end of file +Q(i:i+1,:) = xy*Q(i:i+1,:); diff --git a/MatlabFiles/reset_ini_seed.m b/MatlabFiles/reset_ini_seed.m index 4285e91c76284f96b1982bddafa2277fd5c1510f..78368618a5545b313e614a8ea93a73897c2f6092 100644 --- a/MatlabFiles/reset_ini_seed.m +++ b/MatlabFiles/reset_ini_seed.m @@ -1,27 +1,27 @@ -function reset_ini_seed(seednumber) -%After Matlab starts, run this function to reset the seed number; otherwise, Matlab automatically resets to the same initial seed. -% seednumber: 0 -- random state reset to the clock time; -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if seednumber - randn('state',seednumber); - rand('state',seednumber); -else - randn('state',fix(100*sum(clock))); - rand('state',fix(100*sum(clock))); -end +function reset_ini_seed(seednumber) +%After Matlab starts, run this function to reset the seed number; otherwise, Matlab automatically resets to the same initial seed. +% seednumber: 0 -- random state reset to the clock time; +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if seednumber + randn('state',seednumber); + rand('state',seednumber); +else + randn('state',fix(100*sum(clock))); + rand('state',fix(100*sum(clock))); +end diff --git a/MatlabFiles/rlrpostr.m b/MatlabFiles/rlrpostr.m index abdfabf55d4476d2aab8c48a0d7b645ec256d94d..83a2997aa9f93aeb5149507f0e50629259e2e8d5 100644 --- a/MatlabFiles/rlrpostr.m +++ b/MatlabFiles/rlrpostr.m @@ -1,62 +1,62 @@ -function [P,H0inv,Hpinv] = rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Ui,Vi) -% [P,H0inv,Hpinv] = rlrpostr(xtx,xty,yty,Ptld,H0tld,Hptld,Ui,Vi) -% -% Exporting random Bayesian posterior matrices with linear restrictions -% See Waggoner and Zha's Gibbs sampling paper -% -% xtx: X'X: k-by-k where k=ncoef -% xty: X'Y: k-by-nvar -% yty: Y'Y: nvar-by-nvar -% Ptld: cell(nvar,1), linear transformation for random walk prior for the ith equation -% H0invtld: cell(nvar,1), transformed inv covaraince for free parameters in A0(:,i). -% Hpinvtld: cell(nvar,1), transformed inv covaraince for free parameters in A+(:,i); -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. Imported from dnrprior.m. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. Imported from dnrprior.m. -%----------------- -% P: cell(nvar,1). In each cell, posterior linear transformation for random walk prior for the ith equation % tld: tilda -% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, -% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. -% Hpinv: cell(nvar,1). In each cell, posterior inv(Hp) for the ith equation. -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -nvar = size(yty,1); - -P = cell(nvar,1); % tld: tilda -H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. -Hpinv = cell(nvar,1); % posterior inv(Hp). - - -for n=1:nvar % one for each equation - Hpinv{n} = Vi{n}'*xtx*Vi{n} + Hpinvtld{n}; - P1 = Vi{n}'*xty*Ui{n} + Hpinvtld{n}*Ptld{n}; - P{n} = Hpinv{n}\P1; - H0inv{n} = Ui{n}'*yty*Ui{n} + H0invtld{n} + Ptld{n}'*Hpinvtld{n}*Ptld{n} ... - - P1'*(Hpinv{n}\P1); -end +function [P,H0inv,Hpinv] = rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Ui,Vi) +% [P,H0inv,Hpinv] = rlrpostr(xtx,xty,yty,Ptld,H0tld,Hptld,Ui,Vi) +% +% Exporting random Bayesian posterior matrices with linear restrictions +% See Waggoner and Zha's Gibbs sampling paper +% +% xtx: X'X: k-by-k where k=ncoef +% xty: X'Y: k-by-nvar +% yty: Y'Y: nvar-by-nvar +% Ptld: cell(nvar,1), linear transformation for random walk prior for the ith equation +% H0invtld: cell(nvar,1), transformed inv covaraince for free parameters in A0(:,i). +% Hpinvtld: cell(nvar,1), transformed inv covaraince for free parameters in A+(:,i); +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. Imported from dnrprior.m. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. Imported from dnrprior.m. +%----------------- +% P: cell(nvar,1). In each cell, posterior linear transformation for random walk prior for the ith equation % tld: tilda +% H0inv: cell(nvar,1). In each cell, posterior inverse of covariance inv(H0) for the ith equation, +% resembling old SpH in the exponent term in posterior of A0, but not divided by T yet. +% Hpinv: cell(nvar,1). In each cell, posterior inv(Hp) for the ith equation. +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +nvar = size(yty,1); + +P = cell(nvar,1); % tld: tilda +H0inv = cell(nvar,1); % posterior inv(H0), resemble old SpH, but not divided by T yet. +Hpinv = cell(nvar,1); % posterior inv(Hp). + + +for n=1:nvar % one for each equation + Hpinv{n} = Vi{n}'*xtx*Vi{n} + Hpinvtld{n}; + P1 = Vi{n}'*xty*Ui{n} + Hpinvtld{n}*Ptld{n}; + P{n} = Hpinv{n}\P1; + H0inv{n} = Ui{n}'*yty*Ui{n} + H0invtld{n} + Ptld{n}'*Hpinvtld{n}*Ptld{n} ... + - P1'*(Hpinv{n}\P1); +end diff --git a/MatlabFiles/rlrprior.m b/MatlabFiles/rlrprior.m index 5d9156194b8c9016bca09abaae921dfc65021cb9..165193a56f3ac8b36e00d0d27dd72558cdd1e3b0 100644 --- a/MatlabFiles/rlrprior.m +++ b/MatlabFiles/rlrprior.m @@ -1,55 +1,55 @@ -function [Ptld,H0invtld,Hpinvtld] = rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) -% [Ptld,H0invtld,Hpinvtld] = rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) -% -% Exporting random Bayesian prior with linear restrictions -% See Waggoner and Zha's Gibbs sampling paper -% -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. Imported from dnrprior.m. -% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith -% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and -% ri is the number of free parameters. With this transformation, we have fi = Vi*gi -% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a -% vector of free parameters. There must be at least one free parameter left for -% the ith equation. Imported from dnrprior.m. -% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior -% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior -% nvar: number of endogenous variables -% -------------------- -% Ptld: cell(nvar,1), linear transformation for random walk prior for the ith equation -% H0invtld: cell(nvar,1), transformed inv covaraince for free parameters in A0(:,i). -% Hpinvtld: cell(nvar,1), transformed inv covaraince for free parameters in A+(:,i); -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -Ptld = cell(nvar,1); % tld: tilda -H0invtld = cell(nvar,1); % H0 for different equations under linear restrictions -Hpinvtld = cell(nvar,1); % H+ for different equations under linear restrictions - -for n=1:nvar % one for each equation - Hpinvtld{n} = Vi{n}'*(Hpmulti(:,:,n)\Vi{n}); - Ptld{n} = (Hpinvtld{n}\Vi{n}')*(Hpmulti(:,:,n)\Pi)*Ui{n}; - H0invtld{n} = Ui{n}'*(H0multi(:,:,n)\Ui{n}) + Ui{n}'*Pi'*(Hpmulti(:,:,n)\Pi)*Ui{n} ... - - Ptld{n}'*Hpinvtld{n}*Ptld{n}; -end +function [Ptld,H0invtld,Hpinvtld] = rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) +% [Ptld,H0invtld,Hpinvtld] = rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar) +% +% Exporting random Bayesian prior with linear restrictions +% See Waggoner and Zha's Gibbs sampling paper +% +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. Imported from dnrprior.m. +% Vi: nvar-by-1 cell. In each cell, k-by-ri orthonormal basis for the null of the ith +% equation lagged restriction matrix where k (ncoef) is a total number of RHS variables and +% ri is the number of free parameters. With this transformation, we have fi = Vi*gi +% or Vi'*fi = gi where fi is a vector of total original parameters and gi is a +% vector of free parameters. There must be at least one free parameter left for +% the ith equation. Imported from dnrprior.m. +% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior +% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior +% nvar: number of endogenous variables +% -------------------- +% Ptld: cell(nvar,1), linear transformation for random walk prior for the ith equation +% H0invtld: cell(nvar,1), transformed inv covaraince for free parameters in A0(:,i). +% Hpinvtld: cell(nvar,1), transformed inv covaraince for free parameters in A+(:,i); +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +Ptld = cell(nvar,1); % tld: tilda +H0invtld = cell(nvar,1); % H0 for different equations under linear restrictions +Hpinvtld = cell(nvar,1); % H+ for different equations under linear restrictions + +for n=1:nvar % one for each equation + Hpinvtld{n} = Vi{n}'*(Hpmulti(:,:,n)\Vi{n}); + Ptld{n} = (Hpinvtld{n}\Vi{n}')*(Hpmulti(:,:,n)\Pi)*Ui{n}; + H0invtld{n} = Ui{n}'*(H0multi(:,:,n)\Ui{n}) + Ui{n}'*Pi'*(Hpmulti(:,:,n)\Pi)*Ui{n} ... + - Ptld{n}'*Hpinvtld{n}*Ptld{n}; +end diff --git a/MatlabFiles/rnrprior.m b/MatlabFiles/rnrprior.m index 76ee6ea69fbae58ecb39a07d879d672e6755a10c..b692e954896cd5a55205f354760e5303d1351246 100644 --- a/MatlabFiles/rnrprior.m +++ b/MatlabFiles/rnrprior.m @@ -1,231 +1,231 @@ -function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti,asym0,asymp] ... - = rnrprior(nvar,q_m,lags,xdgel,mu,nexo) -% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti,asym0,asymp] ... -% = rnrprior(nvar,q_m,lags,xdgel,mu,nexo) -% -% Exporting random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions) -% See Waggoner and Zha's Gibbs sampling paper -% -% nvar: number of endogenous variables -% q_m: quarter or month -% lags: the maximum length of lag -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags. Used only to get variances of residuals for -% the scaling purpose. -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1). NOTE: for other -% exogenous terms, the variance of each exogenous term must be taken into -% acount to eliminate the scaling factor. -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% NOTE: for this subdirectory, mu(5) and mu(6) are not used. -% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). -% The constant term is always put to the last of all endogenous and exogenous variables. -% -------------------- -% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations -% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior -% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior -% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior -% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior -% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation -% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -if nargin==5, nexo=1; end -ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. - -H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior -Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior -H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior -Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior - -%*** Constructing Pi for the ith equation under the random walk assumption -Pi = zeros(ncoef,nvar); % same for all equations -Pi(1:nvar,1:nvar) = eye(nvar); % random walk - -% -%@@@ Prepared for Bayesian prior -% -% -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - - - -% -% *** specify the prior for each equation separately, SZ method, -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nSample=size(xdgel,1); % sample size-lags -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/(nSample-lags); - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for A0(:,1), same for all equations!!! -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for lagged and exogeous variables, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i*mu(4)); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; % ith equation -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; - %<<>> No scaling adjustment has been made for exogenous terms other than constant -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper - -Hptd = zeros(ncoef); -Hptdi=Hptd; -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - -%**** Asymmetric Information -asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness -asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp -% if (i==1) -% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% asymp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, -% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -for i = 1:nvar - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - - %*** For A0 - factor0=asym0(:,i); - sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. - sg0bdinv = 1./sg0bd; - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - H0tdinv = diag(sg0bdinv); - % - H0multi(:,:,i)=H0td; - H0invmulti(:,:,i)=H0tdinv; - - - %*** For A+ - if ~(lags==0) % For A1 to remain random walk properties - factor1=asymp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdinv = 1./sg1bd; - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); - if lags>1 - factorpp=asymp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdinv = 1./sgpp_cbd; - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); - % condtional on A0i, H_plus_tilde - end - end - Hpmulti(:,:,i)=Hptd; - Hpinvmulti(:,:,i)=Hptdinv; -end - - +function [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti,asym0,asymp] ... + = rnrprior(nvar,q_m,lags,xdgel,mu,nexo) +% [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti,asym0,asymp] ... +% = rnrprior(nvar,q_m,lags,xdgel,mu,nexo) +% +% Exporting random Bayesian prior of Sims and Zha with asymmetric rior (but no linear restrictions) +% See Waggoner and Zha's Gibbs sampling paper +% +% nvar: number of endogenous variables +% q_m: quarter or month +% lags: the maximum length of lag +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags. Used only to get variances of residuals for +% the scaling purpose. +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1). NOTE: for other +% exogenous terms, the variance of each exogenous term must be taken into +% acount to eliminate the scaling factor. +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% NOTE: for this subdirectory, mu(5) and mu(6) are not used. +% nexo: number of exogenous variables (if not specified, nexo=1 (constant) by default). +% The constant term is always put to the last of all endogenous and exogenous variables. +% -------------------- +% Pi: ncoef-by-nvar matrix for the ith equation under random walk. Same for all equations +% H0multi: nvar-by-nvar-by-nvar; H0 for different equations under asymmetric prior +% Hpmulti: ncoef-by-ncoef-by-nvar; H+ for different equations under asymmetric prior +% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior +% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior +% asym0: nvar-by-nvar asymmetric prior on A0. Column -- equation +% asymp: ncoef-1-by-nvar asymmetric prior on A+ bar constant. Column -- equation +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +if nargin==5, nexo=1; end +ncoef = nvar*lags+nexo; % number of coefficients in *each* equation, RHS coefficients only. + +H0multi=zeros(nvar,nvar,nvar); % H0 for different equations under asymmetric prior +Hpmulti=zeros(ncoef,ncoef,nvar); % H+ for different equations under asymmetric prior +H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior +Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior + +%*** Constructing Pi for the ith equation under the random walk assumption +Pi = zeros(ncoef,nvar); % same for all equations +Pi(1:nvar,1:nvar) = eye(nvar); % random walk + +% +%@@@ Prepared for Bayesian prior +% +% +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + + + +% +% *** specify the prior for each equation separately, SZ method, +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nSample=size(xdgel,1); % sample size-lags +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/(nSample-lags); + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for A0(:,1), same for all equations!!! +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only for the ith equation +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for lagged and exogeous variables, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal, for the ith equation +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i*mu(4)); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); % ith equation + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); % ith equation + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; % ith equation +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef-nexo+1:ncoef) = mu(1)^2*mu(3)^2; + %<<>> No scaling adjustment has been made for exogenous terms other than constant +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper + +Hptd = zeros(ncoef); +Hptdi=Hptd; +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdinv(ncoef,ncoef)=1./sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + +%**** Asymmetric Information +asym0 = ones(nvar,nvar); % if not ones, then we have relative (asymmetric) tightness +asymp = ones(ncoef-1,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for asymp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of asymp +% if (i==1) +% asymp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %asymp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% asymp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for asymp <<<<<<<< + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the prior of A0, +% and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +for i = 1:nvar + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + + %*** For A0 + factor0=asym0(:,i); + sg0bd = sg0bida.*factor0; % Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to work on inv(Sg(i)) or sg0bdinv directly. + sg0bdinv = 1./sg0bd; + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + H0tdinv = diag(sg0bdinv); + % + H0multi(:,:,i)=H0td; + H0invmulti(:,:,i)=H0tdinv; + + + %*** For A+ + if ~(lags==0) % For A1 to remain random walk properties + factor1=asymp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdinv = 1./sg1bd; + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdinv(1:nvar,1:nvar)=diag(sg1bdinv); + if lags>1 + factorpp=asymp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdinv = 1./sgpp_cbd; + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdinv(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdinv); + % condtional on A0i, H_plus_tilde + end + end + Hpmulti(:,:,i)=Hptd; + Hpinvmulti(:,:,i)=Hptdinv; +end + + diff --git a/MatlabFiles/run.m b/MatlabFiles/run.m index c1e7a1e684afdbcb0ed6043ddfcdd7c9891dc375..f239023dca4c66648cd770a48146ef6fdba5dce6 100644 --- a/MatlabFiles/run.m +++ b/MatlabFiles/run.m @@ -1,20 +1,20 @@ -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -intervalcl -clear all -clsort \ No newline at end of file +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +intervalcl +clear all +clsort diff --git a/MatlabFiles/sbcontest.m b/MatlabFiles/sbcontest.m index 1fa6c64b2622f0377d482ef5c487577d612614c4..44cc6bdf11c2fd9da6a82f4cea6fc0d85e2c79e2 100644 --- a/MatlabFiles/sbcontest.m +++ b/MatlabFiles/sbcontest.m @@ -1,79 +1,79 @@ -function [pabove,pbelow]=sbcontest(xinput) -% [pabove,pbelow]=sbcontest(xinput) -% Small Sample Bayesian Contour Test (sbcontest) for overidentified models -% -% xinput{1}: idenmlh -- handle for the file idenml.mat -% xinput{2}: SpHUouth -- handle for the file sphuout.mat -% xinput{3}: fss -- effective sample size == nSample-lags+# of dummy observations -% xinput{4}: imndraws=nstarts*ndraws2 -% xinput{5}: nvar -- # of endogenous variables -% xinput{6}: nbuffer -- interval of whcih for printing, plotting, saving, etc. -%-------------- -% pabove: probablity of the reduced-form LH value above the overidentified LH peak value -% pbelow: probablity of the reduced-form LH value below the overidentified LH peak value -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -idenmlh = xinput{1}; SpHUouth = xinput{2}; fss = xinput{3}; imndraws = xinput{4}; nvar = xinput{5}; -nbuffer = xinput{6}; - -neqn = nvar; %<<>> number of equations -eval(['load ' idenmlh]); -eval(['load ' SpHUouth]); - -pabove=0; -pbelow=0; -load idenml % fhat at ML for identified version -fhat=-fhat; - % this value is strictly smaller than that at the peak of reduced-form LH -disp('If you havent run idenml with Rform=1, you must do so now') -disp('Press ctrl-c to abort now or any other key to continue') -disp(' ') -pause -load SpHUout % this is the output file by running "idenml" with Rform=1 - % with output SpHU -SpHs = SpHU*fss; % for the Wishart draw -SpHsc = chol(SpHs); % upper triangular where Sphsc' is - % lower triangular Choleski, for Wishart draw -tic -for draws=1:imndraws - if ~mod(draws,nbuffer) - draws - end - ranw = randn(neqn,fss-neqn-1); - ranw = SpHsc\ranw; % inv(SpHsc) is upper triagular Choleski of inv(SpHs) - %ranw = SpHsic*ranw; - % normal draws (T-nvar-1)*nvar, with variance inv(SpHs) (note, NOT inv(SpH)) - sinh = ranw*ranw'; % Wishart draws for A0h*A0h' - A0_h = chol2(sinh); % upper triangular Choleski - a0indx = find(A0_h); - - xhat_h = A0_h(a0indx); - jnk = a0lhfun(xhat_h,SpHU,fss,nvar,a0indx); - fhat_h = -jnk; - - if fhat_h > fhat - pabove = pabove+1; - else - pbelow = pbelow+1; - end -end -timend=toc; -timeminutes=timend/60 - -pabove = pabove/imndraws -pbelow = pbelow/imndraws +function [pabove,pbelow]=sbcontest(xinput) +% [pabove,pbelow]=sbcontest(xinput) +% Small Sample Bayesian Contour Test (sbcontest) for overidentified models +% +% xinput{1}: idenmlh -- handle for the file idenml.mat +% xinput{2}: SpHUouth -- handle for the file sphuout.mat +% xinput{3}: fss -- effective sample size == nSample-lags+# of dummy observations +% xinput{4}: imndraws=nstarts*ndraws2 +% xinput{5}: nvar -- # of endogenous variables +% xinput{6}: nbuffer -- interval of whcih for printing, plotting, saving, etc. +%-------------- +% pabove: probablity of the reduced-form LH value above the overidentified LH peak value +% pbelow: probablity of the reduced-form LH value below the overidentified LH peak value +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +idenmlh = xinput{1}; SpHUouth = xinput{2}; fss = xinput{3}; imndraws = xinput{4}; nvar = xinput{5}; +nbuffer = xinput{6}; + +neqn = nvar; %<<>> number of equations +eval(['load ' idenmlh]); +eval(['load ' SpHUouth]); + +pabove=0; +pbelow=0; +load idenml % fhat at ML for identified version +fhat=-fhat; + % this value is strictly smaller than that at the peak of reduced-form LH +disp('If you havent run idenml with Rform=1, you must do so now') +disp('Press ctrl-c to abort now or any other key to continue') +disp(' ') +pause +load SpHUout % this is the output file by running "idenml" with Rform=1 + % with output SpHU +SpHs = SpHU*fss; % for the Wishart draw +SpHsc = chol(SpHs); % upper triangular where Sphsc' is + % lower triangular Choleski, for Wishart draw +tic +for draws=1:imndraws + if ~mod(draws,nbuffer) + draws + end + ranw = randn(neqn,fss-neqn-1); + ranw = SpHsc\ranw; % inv(SpHsc) is upper triagular Choleski of inv(SpHs) + %ranw = SpHsic*ranw; + % normal draws (T-nvar-1)*nvar, with variance inv(SpHs) (note, NOT inv(SpH)) + sinh = ranw*ranw'; % Wishart draws for A0h*A0h' + A0_h = chol2(sinh); % upper triangular Choleski + a0indx = find(A0_h); + + xhat_h = A0_h(a0indx); + jnk = a0lhfun(xhat_h,SpHU,fss,nvar,a0indx); + fhat_h = -jnk; + + if fhat_h > fhat + pabove = pabove+1; + else + pbelow = pbelow+1; + end +end +timend=toc; +timeminutes=timend/60 + +pabove = pabove/imndraws +pbelow = pbelow/imndraws diff --git a/MatlabFiles/simtanzphi.m b/MatlabFiles/simtanzphi.m index f9ae33086ad6c8bb2bb2cc2f9eeed1a37d368b22..f36a7c5554339c913ffb2598384f5c2137d64e52 100644 --- a/MatlabFiles/simtanzphi.m +++ b/MatlabFiles/simtanzphi.m @@ -1,61 +1,60 @@ -function simtanzphi(X,k,nvar,U); -% simtanzphi(X,k,nvar,U) -% Recursive function with global output argument ZPHI -% Export ZPHI: PHI_k--the span of proj(R(k))(w(a(i))|i~=k), whose rank determines -% the degree of simultaneity -% -% X: nvar-by-nvar matrix so that the 1st k columns are orthonormal -% k: <=nvar, orthonormal columns -% nvar: number of variables -% U: nvar-by-1 cell. Each cell contains a set of orthonormal bases for the ith -% column of idmat0s (restriction or R(i)) -%----------- -% ZPHI: global variable PHI_k--the span of proj(R(k))(w(a(i))|i~=k), whose rank determines -% the degree of simultaneity -% -% Copyright (c) 1999 by D.F. Waggoner and T.A. Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -global ZPHI - -if k<nvar - V=[X(:,1:k) U{k+1}]; - [Q,R,eindx]=qr(V,0); % eindx: index vector - Q1=Q; - Q1(:,1:k) = Q(:,find(eindx<=k)); % keep the first k col's in V in Q1 - jnk = find(eindx>k); - jnk1=length(Q(1,:))-k; - Q1(:,k+1:length(Q(1,:))) = Q(:,jnk(1:jnk1)); - tmp = abs(diag(R)); % largest absoluate value in R - jnk = find(tmp<max(tmp)*eps); % index for the zero's in R - if isempty(jnk) - Y = Q1(:,k+1:length(tmp)); - else - Y = Q1(:,k+1:min(jnk)-1); % all meaningful orthonormal columns after Q(1:k) - end - % - for ik=1:length(Y(1,:)) - X=[X(:,1:k) Y(:,ik)]; - simtanzphi(X,k+1,nvar,U); - end -else - Xn=X(:,nvar); - %* Projection of Xn into R{n} - Xnproj=U{nvar}*(Xn'*U{nvar})'; - ZPHI=[ZPHI Xnproj]; -end +function simtanzphi(X,k,nvar,U); +% simtanzphi(X,k,nvar,U) +% Recursive function with global output argument ZPHI +% Export ZPHI: PHI_k--the span of proj(R(k))(w(a(i))|i~=k), whose rank determines +% the degree of simultaneity +% +% X: nvar-by-nvar matrix so that the 1st k columns are orthonormal +% k: <=nvar, orthonormal columns +% nvar: number of variables +% U: nvar-by-1 cell. Each cell contains a set of orthonormal bases for the ith +% column of idmat0s (restriction or R(i)) +%----------- +% ZPHI: global variable PHI_k--the span of proj(R(k))(w(a(i))|i~=k), whose rank determines +% the degree of simultaneity +% +% +% Copyright (C) 1997-2012 Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +global ZPHI + +if k<nvar + V=[X(:,1:k) U{k+1}]; + [Q,R,eindx]=qr(V,0); % eindx: index vector + Q1=Q; + Q1(:,1:k) = Q(:,find(eindx<=k)); % keep the first k col's in V in Q1 + jnk = find(eindx>k); + jnk1=length(Q(1,:))-k; + Q1(:,k+1:length(Q(1,:))) = Q(:,jnk(1:jnk1)); + tmp = abs(diag(R)); % largest absoluate value in R + jnk = find(tmp<max(tmp)*eps); % index for the zero's in R + if isempty(jnk) + Y = Q1(:,k+1:length(tmp)); + else + Y = Q1(:,k+1:min(jnk)-1); % all meaningful orthonormal columns after Q(1:k) + end + % + for ik=1:length(Y(1,:)) + X=[X(:,1:k) Y(:,ik)]; + simtanzphi(X,k+1,nvar,U); + end +else + Xn=X(:,nvar); + %* Projection of Xn into R{n} + Xnproj=U{nvar}*(Xn'*U{nvar})'; + ZPHI=[ZPHI Xnproj]; +end diff --git a/MatlabFiles/smtplis.m b/MatlabFiles/smtplis.m index e609f33e2f3fe000ad55bd5adbb24d3bf5804622..9f89a5ac9a2da148579bf2a013c3966f15a38722 100644 --- a/MatlabFiles/smtplis.m +++ b/MatlabFiles/smtplis.m @@ -1,61 +1,61 @@ -function [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... - H_sr,nfp,Sbd,fss,nvar,a0indx) -% -% Straight Metropolis Algorithm for identified VARs -% -% Avhx: previous draw of parameter x in 1st (kept) sequence -% hAvhx: lh value of previous draw in 1st (kept) sequence -% tdf: degrees of freedom of the jump t-distribution -% cJump: old count for times of jumping -% scf: scale down factor for stand. dev. -- square root of covariance matrix H -% H_sr: square root of covariance matrix H in approximate density -% nfp: number of free parameters -% Sbd: S in block diagonal covariance matrix in asymmetric prior case -% fss: effective sample size, including # of dummy observations -% nvar: number of variables -% a0indx: index of locations of free elements in A0 -%-------------- -% Avhx: new draw of parameter x in 1st (kept) sequence -% hAvhx: lh value of new draw in 1st (kept) sequence -% cJump: new count for times of jumping -% -% December 1998 by Tao Zha - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -%** draw free elements Avh in A0 and hyperparameters from t-dist -Avhz1 = scf*H_sr*randn(nfp,1); % normal draws -csq=randn(tdf,1); -csq=sum(csq .* csq); -Avhz = Avhz1/sqrt(csq/tdf); - -Avhy = Avhx + Avhz; % random walk chain -- Metropolis -% ** actual density, having taken log -hAvhy = a0asfun(Avhy,Sbd,fss,nvar,a0indx); -hAvhy = -hAvhy; % converted to logLH - -mphxy = exp(hAvhy-hAvhx); - -%** draw u from uniform(0,1) -u = rand(1); -Jump = min([mphxy 1]); -if u <= Jump - Avhx = Avhy; - hAvhx = hAvhy; - cJump = cJump+1; -end +function [Avhx,hAvhx,cJump] = smtplis(Avhx,hAvhx,tdf,cJump,scf,... + H_sr,nfp,Sbd,fss,nvar,a0indx) +% +% Straight Metropolis Algorithm for identified VARs +% +% Avhx: previous draw of parameter x in 1st (kept) sequence +% hAvhx: lh value of previous draw in 1st (kept) sequence +% tdf: degrees of freedom of the jump t-distribution +% cJump: old count for times of jumping +% scf: scale down factor for stand. dev. -- square root of covariance matrix H +% H_sr: square root of covariance matrix H in approximate density +% nfp: number of free parameters +% Sbd: S in block diagonal covariance matrix in asymmetric prior case +% fss: effective sample size, including # of dummy observations +% nvar: number of variables +% a0indx: index of locations of free elements in A0 +%-------------- +% Avhx: new draw of parameter x in 1st (kept) sequence +% hAvhx: lh value of new draw in 1st (kept) sequence +% cJump: new count for times of jumping +% +% December 1998 by Tao Zha + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +%** draw free elements Avh in A0 and hyperparameters from t-dist +Avhz1 = scf*H_sr*randn(nfp,1); % normal draws +csq=randn(tdf,1); +csq=sum(csq .* csq); +Avhz = Avhz1/sqrt(csq/tdf); + +Avhy = Avhx + Avhz; % random walk chain -- Metropolis +% ** actual density, having taken log +hAvhy = a0asfun(Avhy,Sbd,fss,nvar,a0indx); +hAvhy = -hAvhy; % converted to logLH + +mphxy = exp(hAvhy-hAvhx); + +%** draw u from uniform(0,1) +u = rand(1); +Jump = min([mphxy 1]); +if u <= Jump + Avhx = Avhy; + hAvhx = hAvhy; + cJump = cJump+1; +end diff --git a/MatlabFiles/smtplis2.m b/MatlabFiles/smtplis2.m index 83fb0add90a10f068c22d1ca7ff9b88b93e546ac..ca1487b615ab2238da85c4f18f6705dd1a189ef2 100644 --- a/MatlabFiles/smtplis2.m +++ b/MatlabFiles/smtplis2.m @@ -1,115 +1,115 @@ -function [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2(Avhx,AvhxD,hAvhx,hAvhxD,... - A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) -% [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2(Avhx,AvhxD,hAvhx,hAvhxD,... -% A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) -% Straight Metropolis Algorithm for identified VARs with 2 parallel sequences -% -% Avhx: previous draw of parameter x in 1st (kept) sequence -% AvhxD: previous draw of parameter x in 2nd (discarded) sequence -% hAvhx: lh value of previous draw in 1st (kept) sequence -% hAvhxD: lh vlaue of previous draw in 2nd (discarded) sequence -% A0xhat: ML estimate of A0 -% tdf: degrees of freedom of the jump t-distribution -% cJump: old count for times of jumping -% scf: scale down factor for stand. dev. -- square root of covariance matrix H -% H_sr: square root of covariance matrix H -% nfp: number of free parameters -% Sbd: S in block diagonal covariance matrix in asymmetric prior case -% fss: effective sample size -% nvar: number of variables -% a0indx: index of locations of free elements in A0 -% hAvhh: highest point of lh -%-------------- -% Avhx: new draw of parameter x in 1st (kept) sequence -% AvhxD: new draw of parameter x in 2nd (discarded) sequence -% hAvhx: lh value of new draw in 1st (kept) sequence -% AvhxD: lh vlaue of new draw in 2nd (discarded) sequence -% cJump: new count for times of jumping -% hAvhh: highest point of lh -% -% November 1998 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if ~(fix(tdf)-tdf==0) - warning('tdf in msstart.m must be integer for drawing chi^2 from normal') - disp('press ctrl-c to abort') - pause -end - -for k=1:2 % parallel sequences; 2nd to be discarded - %** draw free elements Avh in A0 and hyperparameters from t-dist - %gsg = gamrnd(ga,gb); % G-sigma from Gamma draw - %Avhz = (1/sqrt(gsg))*(scf*H_sr*randn(nfp,1)); - % scf is used to control the acceptance ratio -- countJump - Avhz1 = scf*H_sr*randn(nfp,1); % normal draws - %Avhz1 = 2*randn(nfp,1); % normal draws - csq=randn(tdf,1); - csq=sum(csq .* csq); - Avhz = Avhz1/sqrt(csq/tdf); - - if (k==1) - Avhy = Avhx + Avhz; % random walk chain -- Metropolis - else - Avhy = AvhxD + Avhz; % random walk chain -- Metropolis - end - - % ** actual density, having taken log - hAvhy = a0asfun(Avhy,Sbd,fss,nvar,a0indx); - hAvhy = -hAvhy; % converted to logLH - - if (k==1) - mphxy = exp(hAvhy-hAvhx); - else - mphxy = exp(hAvhy-hAvhxD); - end - - %** draw u from uniform(0,1) - u = rand(1); - Jump = min([mphxy 1]); - if u <= Jump - %** Normalization: get the point that is nearest to axhat or A0xhat - Atem=zeros(nvar); - Atem(a0indx) = Avhy; - Adiff = (Atem - A0xhat).^2; - % distance that may be far from axhat or A0xhat - Adiffn = (-Atem - A0xhat).^2; - % distance by chaning the sign of Atem - cAdiff = sum(Adiff); % each column summed up - cAdiffn = sum(Adiffn); % each column summed up - cAindx = find(cAdiffn<cAdiff); % index for shorter distance - Atemn = Atem; - Atemn(:,cAindx) = -Atem(:,cAindx); - % find the shortest or nearest distance - %** get the value of logPoster or logLH - Avhy = Atemn(a0indx); - % - - if (k==1) - Avhx = Avhy; - hAvhx = hAvhy; - if hAvhy > hAvhh - hAvhh = hAvhy; - Avhh = Avhy; - end - cJump = cJump+1; - else - AvhxD = Avhy; - hAvhxD = hAvhy; - end - end -end +function [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2(Avhx,AvhxD,hAvhx,hAvhxD,... + A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) +% [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2(Avhx,AvhxD,hAvhx,hAvhxD,... +% A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) +% Straight Metropolis Algorithm for identified VARs with 2 parallel sequences +% +% Avhx: previous draw of parameter x in 1st (kept) sequence +% AvhxD: previous draw of parameter x in 2nd (discarded) sequence +% hAvhx: lh value of previous draw in 1st (kept) sequence +% hAvhxD: lh vlaue of previous draw in 2nd (discarded) sequence +% A0xhat: ML estimate of A0 +% tdf: degrees of freedom of the jump t-distribution +% cJump: old count for times of jumping +% scf: scale down factor for stand. dev. -- square root of covariance matrix H +% H_sr: square root of covariance matrix H +% nfp: number of free parameters +% Sbd: S in block diagonal covariance matrix in asymmetric prior case +% fss: effective sample size +% nvar: number of variables +% a0indx: index of locations of free elements in A0 +% hAvhh: highest point of lh +%-------------- +% Avhx: new draw of parameter x in 1st (kept) sequence +% AvhxD: new draw of parameter x in 2nd (discarded) sequence +% hAvhx: lh value of new draw in 1st (kept) sequence +% AvhxD: lh vlaue of new draw in 2nd (discarded) sequence +% cJump: new count for times of jumping +% hAvhh: highest point of lh +% +% November 1998 by Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if ~(fix(tdf)-tdf==0) + warning('tdf in msstart.m must be integer for drawing chi^2 from normal') + disp('press ctrl-c to abort') + pause +end + +for k=1:2 % parallel sequences; 2nd to be discarded + %** draw free elements Avh in A0 and hyperparameters from t-dist + %gsg = gamrnd(ga,gb); % G-sigma from Gamma draw + %Avhz = (1/sqrt(gsg))*(scf*H_sr*randn(nfp,1)); + % scf is used to control the acceptance ratio -- countJump + Avhz1 = scf*H_sr*randn(nfp,1); % normal draws + %Avhz1 = 2*randn(nfp,1); % normal draws + csq=randn(tdf,1); + csq=sum(csq .* csq); + Avhz = Avhz1/sqrt(csq/tdf); + + if (k==1) + Avhy = Avhx + Avhz; % random walk chain -- Metropolis + else + Avhy = AvhxD + Avhz; % random walk chain -- Metropolis + end + + % ** actual density, having taken log + hAvhy = a0asfun(Avhy,Sbd,fss,nvar,a0indx); + hAvhy = -hAvhy; % converted to logLH + + if (k==1) + mphxy = exp(hAvhy-hAvhx); + else + mphxy = exp(hAvhy-hAvhxD); + end + + %** draw u from uniform(0,1) + u = rand(1); + Jump = min([mphxy 1]); + if u <= Jump + %** Normalization: get the point that is nearest to axhat or A0xhat + Atem=zeros(nvar); + Atem(a0indx) = Avhy; + Adiff = (Atem - A0xhat).^2; + % distance that may be far from axhat or A0xhat + Adiffn = (-Atem - A0xhat).^2; + % distance by chaning the sign of Atem + cAdiff = sum(Adiff); % each column summed up + cAdiffn = sum(Adiffn); % each column summed up + cAindx = find(cAdiffn<cAdiff); % index for shorter distance + Atemn = Atem; + Atemn(:,cAindx) = -Atem(:,cAindx); + % find the shortest or nearest distance + %** get the value of logPoster or logLH + Avhy = Atemn(a0indx); + % + + if (k==1) + Avhx = Avhy; + hAvhx = hAvhy; + if hAvhy > hAvhh + hAvhh = hAvhy; + Avhh = Avhy; + end + cJump = cJump+1; + else + AvhxD = Avhy; + hAvhxD = hAvhy; + end + end +end diff --git a/MatlabFiles/smtplis2seq.m b/MatlabFiles/smtplis2seq.m index a66258c43a5c4a90ff2cb9465f7aef37d1399438..689a587d889f7818714c47945fdea1db365a9c3f 100644 --- a/MatlabFiles/smtplis2seq.m +++ b/MatlabFiles/smtplis2seq.m @@ -1,115 +1,115 @@ -function [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2seq(Avhx,AvhxD,hAvhx,hAvhxD,... - A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) -% [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2(Avhx,AvhxD,hAvhx,hAvhxD,... -% A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) -% Straight Metropolis Algorithm for identified VARs with 2 parallel sequences -% -% Avhx: previous draw of parameter x in 1st (kept) sequence -% AvhxD: previous draw of parameter x in 2nd (discarded) sequence -% hAvhx: lh value of previous draw in 1st (kept) sequence -% hAvhxD: lh vlaue of previous draw in 2nd (discarded) sequence -% A0xhat: ML estimate of A0 -% tdf: degrees of freedom of the jump t-distribution -% cJump: old count for times of jumping -% scf: scale down factor for stand. dev. -- square root of covariance matrix H -% H_sr: square root of covariance matrix H -% nfp: number of free parameters -% Sbd: S in block diagonal covariance matrix in asymmetric prior case -% fss: effective sample size -% nvar: number of variables -% a0indx: index of locations of free elements in A0 -% hAvhh: highest point of lh -%-------------- -% Avhx: new draw of parameter x in 1st (kept) sequence -% AvhxD: new draw of parameter x in 2nd (discarded) sequence -% hAvhx: lh value of new draw in 1st (kept) sequence -% AvhxD: lh vlaue of new draw in 2nd (discarded) sequence -% cJump: new count for times of jumping -% hAvhh: highest point of lh -% -% November 1998 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -if ~(fix(tdf)-tdf==0) - warning('tdf in msstart.m must be integer for drawing chi^2 from normal') - disp('press ctrl-c to abort') - pause -end - -for k=1:2 % parallel sequences; 2nd to be discarded - %** draw free elements Avh in A0 and hyperparameters from t-dist - %gsg = gamrnd(ga,gb); % G-sigma from Gamma draw - %Avhz = (1/sqrt(gsg))*(scf*H_sr*randn(nfp,1)); - % scf is used to control the acceptance ratio -- countJump - Avhz1 = scf*H_sr*randn(nfp,1); % normal draws - %Avhz1 = 2*randn(nfp,1); % normal draws - csq=randn(tdf,1); - csq=sum(csq .* csq); - Avhz = Avhz1/sqrt(csq/tdf); - - if (k==1) - Avhy = Avhx + Avhz; % random walk chain -- Metropolis - else - Avhy = AvhxD + Avhz; % random walk chain -- Metropolis - end - - % ** actual density, having taken log - hAvhy = a0asfun(Avhy,Sbd,fss,nvar,a0indx); - hAvhy = -hAvhy; % converted to logLH - - if (k==1) - mphxy = exp(hAvhy-hAvhx); - else - mphxy = exp(hAvhy-hAvhxD); - end - - %** draw u from uniform(0,1) - u = rand(1); - Jump = min([mphxy 1]); - if u <= Jump - %** Normalization: get the point that is nearest to axhat or A0xhat - Atem=zeros(nvar); - Atem(a0indx) = Avhy; - Adiff = (Atem - A0xhat).^2; - % distance that may be far from axhat or A0xhat - Adiffn = (-Atem - A0xhat).^2; - % distance by chaning the sign of Atem - cAdiff = sum(Adiff); % each column summed up - cAdiffn = sum(Adiffn); % each column summed up - cAindx = find(cAdiffn<cAdiff); % index for shorter distance - Atemn = Atem; - Atemn(:,cAindx) = -Atem(:,cAindx); - % find the shortest or nearest distance - %** get the value of logPoster or logLH - Avhy = Atemn(a0indx); - % - - if (k==1) - Avhx = Avhy; - hAvhx = hAvhy; - if hAvhy > hAvhh - hAvhh = hAvhy; - Avhh = Avhy; - end - cJump = cJump+1; - else - AvhxD = Avhy; - hAvhxD = hAvhy; - end - end -end \ No newline at end of file +function [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2seq(Avhx,AvhxD,hAvhx,hAvhxD,... + A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) +% [Avhx,AvhxD,hAvhx,hAvhxD,cJump,hAvhh] = smtplis2(Avhx,AvhxD,hAvhx,hAvhxD,... +% A0xhat,tdf,cJump,scf,H_sr,nfp,Sbd,fss,nvar,a0indx,hAvhh) +% Straight Metropolis Algorithm for identified VARs with 2 parallel sequences +% +% Avhx: previous draw of parameter x in 1st (kept) sequence +% AvhxD: previous draw of parameter x in 2nd (discarded) sequence +% hAvhx: lh value of previous draw in 1st (kept) sequence +% hAvhxD: lh vlaue of previous draw in 2nd (discarded) sequence +% A0xhat: ML estimate of A0 +% tdf: degrees of freedom of the jump t-distribution +% cJump: old count for times of jumping +% scf: scale down factor for stand. dev. -- square root of covariance matrix H +% H_sr: square root of covariance matrix H +% nfp: number of free parameters +% Sbd: S in block diagonal covariance matrix in asymmetric prior case +% fss: effective sample size +% nvar: number of variables +% a0indx: index of locations of free elements in A0 +% hAvhh: highest point of lh +%-------------- +% Avhx: new draw of parameter x in 1st (kept) sequence +% AvhxD: new draw of parameter x in 2nd (discarded) sequence +% hAvhx: lh value of new draw in 1st (kept) sequence +% AvhxD: lh vlaue of new draw in 2nd (discarded) sequence +% cJump: new count for times of jumping +% hAvhh: highest point of lh +% +% November 1998 by Tao Zha +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +if ~(fix(tdf)-tdf==0) + warning('tdf in msstart.m must be integer for drawing chi^2 from normal') + disp('press ctrl-c to abort') + pause +end + +for k=1:2 % parallel sequences; 2nd to be discarded + %** draw free elements Avh in A0 and hyperparameters from t-dist + %gsg = gamrnd(ga,gb); % G-sigma from Gamma draw + %Avhz = (1/sqrt(gsg))*(scf*H_sr*randn(nfp,1)); + % scf is used to control the acceptance ratio -- countJump + Avhz1 = scf*H_sr*randn(nfp,1); % normal draws + %Avhz1 = 2*randn(nfp,1); % normal draws + csq=randn(tdf,1); + csq=sum(csq .* csq); + Avhz = Avhz1/sqrt(csq/tdf); + + if (k==1) + Avhy = Avhx + Avhz; % random walk chain -- Metropolis + else + Avhy = AvhxD + Avhz; % random walk chain -- Metropolis + end + + % ** actual density, having taken log + hAvhy = a0asfun(Avhy,Sbd,fss,nvar,a0indx); + hAvhy = -hAvhy; % converted to logLH + + if (k==1) + mphxy = exp(hAvhy-hAvhx); + else + mphxy = exp(hAvhy-hAvhxD); + end + + %** draw u from uniform(0,1) + u = rand(1); + Jump = min([mphxy 1]); + if u <= Jump + %** Normalization: get the point that is nearest to axhat or A0xhat + Atem=zeros(nvar); + Atem(a0indx) = Avhy; + Adiff = (Atem - A0xhat).^2; + % distance that may be far from axhat or A0xhat + Adiffn = (-Atem - A0xhat).^2; + % distance by chaning the sign of Atem + cAdiff = sum(Adiff); % each column summed up + cAdiffn = sum(Adiffn); % each column summed up + cAindx = find(cAdiffn<cAdiff); % index for shorter distance + Atemn = Atem; + Atemn(:,cAindx) = -Atem(:,cAindx); + % find the shortest or nearest distance + %** get the value of logPoster or logLH + Avhy = Atemn(a0indx); + % + + if (k==1) + Avhx = Avhy; + hAvhx = hAvhy; + if hAvhy > hAvhh + hAvhh = hAvhy; + Avhh = Avhy; + end + cJump = cJump+1; + else + AvhxD = Avhy; + hAvhxD = hAvhy; + end + end +end diff --git a/MatlabFiles/srestrictrwzalg.m b/MatlabFiles/srestrictrwzalg.m index cdf1bdc6126f1ea112a033d9b8da1256ee006e83..edbf3c82d154d998ddd8b787ca2b14d0788bd4f9 100644 --- a/MatlabFiles/srestrictrwzalg.m +++ b/MatlabFiles/srestrictrwzalg.m @@ -1,161 +1,160 @@ -function Q = SRestrictRWZalg(A0hatinv,Bhat,nvar,lags,irs) -% Rubio-Waggoner-Zha (RWZ) method of sign restrictions. For related methods, see Canova, Faust, and Uhlig. -% The detailed theoretical foundation of this algorithm can be found in Theorem 3 of Rubio, Waggoner, and Zha (RWZ)'s article "Regime Changes in the Euro Area." -% Other M functions called by this function can be downloaded by clicking on Archived Matlab Library ZhaZippedCode on http://home.earthlink.net/~tzha02/programCode.html -% Strcutural VAR form: Y*A0hat = X*Aphat + E, X where Y is T-by-nvar, A0hat is nvar-by-nvar, X is T-by-k (including the constant term and all other exogenous terms), -% Aphat is k-by-nvar, and E is T-by-nvar. Rows are in the order of 1st lag (with nvar variables) to lags (with nvar variables) plus the exogenous terms. -% Note that columns of A0hat or Aphat correspond to equations. -% Inputs: -% A0hatinv = inv(A0hat). -% Bhat = Aphat*inv(A0hat). -% nvar = number of endogenous variables. -% lags = lag length. -% irs = maximum number of periods in which sign restrictions are imposed. -% Outputs: -% Q: orthogonal rotation matrix so that Q*A0hatinv or A0hat*Q' gives impulse responses that will satisfy -% sign restrictions of Canova, Faust, and Uhlig. -% -% Modified Nov 2004 by T. Zha to -% (1) correct the existing bugs; -% (2) make the signs explicit to avoid the normalization problem when computing error bands; -% (3) construct efficient way (i.e., earlier exit) to make all restrictions satisfied; -% (4) construct efficient way to normalize. -% In this example, we have -% Variables are in the following order: 1: y; 2: P; 3: R; 4: M3; 5: Exec (per $). -% Shocks are in the following order: 1: AS; 2: AD; 3: MP; 4: MD; 5: Exec. -% -% Copyright (c) Rubio, Waggoner, and Zha, 2005. -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -nn = [nvar lags irs]; -control=0; - - -Q=eye(nvar); - -while control==0 - newmatrix=normrnd(0,1,nvar,nvar); - [Q,R]=qr(newmatrix); - for i=1:nvar; - if R(i,i)<0 - Q(:,i)=-Q(:,i); - end - end - imfhat = fn_impulse(Bhat,Q*A0hatinv,nn); - %In the form that is congenial to RATS - imf3hat=reshape(imfhat,size(imfhat,1),nvar,nvar); - %imf3hat: row--steps, column--nvar responses, 3rd dimension--nvar shocks - - %=== Responses to a moneaty policy (MP) shock. - % R>0, M<0, y<0, and P<0 for the irs periods. - a = (imf3hat(1:irs,3,3) > 0) .* (imf3hat(1:irs,4,3) < 0) .* (imf3hat(1:irs,1,3) < 0) .* (imf3hat(1:irs,2,3) < 0); - if (max(a)==0) - %--- Swiching the sign of the shock. - am = (imf3hat(1:irs,3,3) < 0) .* (imf3hat(1:irs,4,3) > 0) .* (imf3hat(1:irs,1,3) > 0) .* (imf3hat(1:irs,2,3) > 0); - if (min(am)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - else - %--- Normalizing according to the switched sign. - Q(3,:) = -Q(3,:); - end - elseif (min(a)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - end - %--- R>0 and M<0 for the irs periods. - % a = (imf3hat(1:irs,3,3) > 0) .* (imf3hat(1:irs,4,3) < 0); - % if (max(a)==0) - % %--- Swiching the sign of the shock. - % am = (imf3hat(1:irs,3,3) < 0) .* (imf3hat(1:irs,4,3) > 0); - % if (min(am)==0) - % continue; %The restrictions are not satisfied. Go the beginning to redraw. - % else - % %--- Normalizing according to the switched sign. - % Q(3,:) = -Q(3,:); - % end - % elseif (min(a)==0) - % continue; %The restrictions are not satisfied. Go the beginning to redraw. - % end - - %=== Responses to an money demand (MD) shock. - % R>0 and M>0 for the irs periods. - a = (imf3hat(1:irs,3,4) > 0) .* (imf3hat(1:irs,4,4) > 0); - if (max(a)==0) - %--- Swiching the sign of the shock and normalize. - am = (imf3hat(1:irs,3,4) < 0) .* (imf3hat(1:irs,4,4) < 0); - if (min(am)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - else - %--- Normalizing according to the switched sign. - Q(4,:) = -Q(4,:); - end - elseif (min(a)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - end - - %=== Responses to an aggregate demand (AD) shock. - % P>0 and y>0 for the irs periods. - a = (imf3hat(1:irs,1,2) > 0) .* (imf3hat(1:irs,2,2) > 0); - if (max(a)==0) - %--- Swiching the sign of the shock and normalize. - am = (imf3hat(1:irs,1,2) < 0) .* (imf3hat(1:irs,2,2) < 0); - if (min(am)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - else - %--- Normalizing according to the switched sign. - Q(2,:) = -Q(2,:); - end - elseif (min(a)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - end - - %=== Responses to an aggregate supply (AS) shock. - % P>0 and y<0 for the irs periods. - a = (imf3hat(1:irs,1,1) < 0) .* (imf3hat(1:irs,2,1) > 0); - if (max(a)==0) - %--- Swiching the sign of the shock and normalize. - am = (imf3hat(1:irs,1,1) > 0) .* (imf3hat(1:irs,2,1) < 0); - if (min(am)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - else - %--- Normalizing according to the switched sign. - Q(1,:) = -Q(1,:); - end - elseif (min(a)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - end - - %=== Responses to an exchange-rate shock (depreciation ==> exports >0 ==> y>0); - % Ex>0 and y>0 for the irs periods. - a= (imf3hat(1:irs,1,5) > 0) .* (imf3hat(1:irs,5,5) > 0); - if (max(a)==0) - %--- Swiching the sign of the shock and normalize. - am = (imf3hat(1:irs,1,5) < 0) .* (imf3hat(1:irs,5,5) < 0); - if (min(am)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - else - %--- Normalizing according to the switched sign. - Q(5,:) = -Q(5,:); - end - elseif (min(a)==0) - continue; %The restrictions are not satisfied. Go the beginning to redraw. - end - - %--- Terminating condition: all restrictions are satisfied. - control=1; -end +function Q = SRestrictRWZalg(A0hatinv,Bhat,nvar,lags,irs) +% Rubio-Waggoner-Zha (RWZ) method of sign restrictions. For related methods, see Canova, Faust, and Uhlig. +% The detailed theoretical foundation of this algorithm can be found in Theorem 3 of Rubio, Waggoner, and Zha (RWZ)'s article "Regime Changes in the Euro Area." +% Other M functions called by this function can be downloaded by clicking on Archived Matlab Library ZhaZippedCode on http://home.earthlink.net/~tzha02/programCode.html +% Strcutural VAR form: Y*A0hat = X*Aphat + E, X where Y is T-by-nvar, A0hat is nvar-by-nvar, X is T-by-k (including the constant term and all other exogenous terms), +% Aphat is k-by-nvar, and E is T-by-nvar. Rows are in the order of 1st lag (with nvar variables) to lags (with nvar variables) plus the exogenous terms. +% Note that columns of A0hat or Aphat correspond to equations. +% Inputs: +% A0hatinv = inv(A0hat). +% Bhat = Aphat*inv(A0hat). +% nvar = number of endogenous variables. +% lags = lag length. +% irs = maximum number of periods in which sign restrictions are imposed. +% Outputs: +% Q: orthogonal rotation matrix so that Q*A0hatinv or A0hat*Q' gives impulse responses that will satisfy +% sign restrictions of Canova, Faust, and Uhlig. +% +% Modified Nov 2004 by T. Zha to +% (1) correct the existing bugs; +% (2) make the signs explicit to avoid the normalization problem when computing error bands; +% (3) construct efficient way (i.e., earlier exit) to make all restrictions satisfied; +% (4) construct efficient way to normalize. +% In this example, we have +% Variables are in the following order: 1: y; 2: P; 3: R; 4: M3; 5: Exec (per $). +% Shocks are in the following order: 1: AS; 2: AD; 3: MP; 4: MD; 5: Exec. +% +% +% Copyright (C) 1997-2012 Juan Rubio-Ramirez, Daniel Waggoner and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +nn = [nvar lags irs]; +control=0; + + +Q=eye(nvar); + +while control==0 + newmatrix=normrnd(0,1,nvar,nvar); + [Q,R]=qr(newmatrix); + for i=1:nvar; + if R(i,i)<0 + Q(:,i)=-Q(:,i); + end + end + imfhat = fn_impulse(Bhat,Q*A0hatinv,nn); + %In the form that is congenial to RATS + imf3hat=reshape(imfhat,size(imfhat,1),nvar,nvar); + %imf3hat: row--steps, column--nvar responses, 3rd dimension--nvar shocks + + %=== Responses to a moneaty policy (MP) shock. + % R>0, M<0, y<0, and P<0 for the irs periods. + a = (imf3hat(1:irs,3,3) > 0) .* (imf3hat(1:irs,4,3) < 0) .* (imf3hat(1:irs,1,3) < 0) .* (imf3hat(1:irs,2,3) < 0); + if (max(a)==0) + %--- Swiching the sign of the shock. + am = (imf3hat(1:irs,3,3) < 0) .* (imf3hat(1:irs,4,3) > 0) .* (imf3hat(1:irs,1,3) > 0) .* (imf3hat(1:irs,2,3) > 0); + if (min(am)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + else + %--- Normalizing according to the switched sign. + Q(3,:) = -Q(3,:); + end + elseif (min(a)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + end + %--- R>0 and M<0 for the irs periods. + % a = (imf3hat(1:irs,3,3) > 0) .* (imf3hat(1:irs,4,3) < 0); + % if (max(a)==0) + % %--- Swiching the sign of the shock. + % am = (imf3hat(1:irs,3,3) < 0) .* (imf3hat(1:irs,4,3) > 0); + % if (min(am)==0) + % continue; %The restrictions are not satisfied. Go the beginning to redraw. + % else + % %--- Normalizing according to the switched sign. + % Q(3,:) = -Q(3,:); + % end + % elseif (min(a)==0) + % continue; %The restrictions are not satisfied. Go the beginning to redraw. + % end + + %=== Responses to an money demand (MD) shock. + % R>0 and M>0 for the irs periods. + a = (imf3hat(1:irs,3,4) > 0) .* (imf3hat(1:irs,4,4) > 0); + if (max(a)==0) + %--- Swiching the sign of the shock and normalize. + am = (imf3hat(1:irs,3,4) < 0) .* (imf3hat(1:irs,4,4) < 0); + if (min(am)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + else + %--- Normalizing according to the switched sign. + Q(4,:) = -Q(4,:); + end + elseif (min(a)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + end + + %=== Responses to an aggregate demand (AD) shock. + % P>0 and y>0 for the irs periods. + a = (imf3hat(1:irs,1,2) > 0) .* (imf3hat(1:irs,2,2) > 0); + if (max(a)==0) + %--- Swiching the sign of the shock and normalize. + am = (imf3hat(1:irs,1,2) < 0) .* (imf3hat(1:irs,2,2) < 0); + if (min(am)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + else + %--- Normalizing according to the switched sign. + Q(2,:) = -Q(2,:); + end + elseif (min(a)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + end + + %=== Responses to an aggregate supply (AS) shock. + % P>0 and y<0 for the irs periods. + a = (imf3hat(1:irs,1,1) < 0) .* (imf3hat(1:irs,2,1) > 0); + if (max(a)==0) + %--- Swiching the sign of the shock and normalize. + am = (imf3hat(1:irs,1,1) > 0) .* (imf3hat(1:irs,2,1) < 0); + if (min(am)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + else + %--- Normalizing according to the switched sign. + Q(1,:) = -Q(1,:); + end + elseif (min(a)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + end + + %=== Responses to an exchange-rate shock (depreciation ==> exports >0 ==> y>0); + % Ex>0 and y>0 for the irs periods. + a= (imf3hat(1:irs,1,5) > 0) .* (imf3hat(1:irs,5,5) > 0); + if (max(a)==0) + %--- Swiching the sign of the shock and normalize. + am = (imf3hat(1:irs,1,5) < 0) .* (imf3hat(1:irs,5,5) < 0); + if (min(am)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + else + %--- Normalizing according to the switched sign. + Q(5,:) = -Q(5,:); + end + elseif (min(a)==0) + continue; %The restrictions are not satisfied. Go the beginning to redraw. + end + + %--- Terminating condition: all restrictions are satisfied. + control=1; +end diff --git a/MatlabFiles/startd.m b/MatlabFiles/startd.m index c9a373bdd1b738a43d0b3124347a60fc93d72467..873a2a9539f1d8f4afea8354d873a82f163d6081 100644 --- a/MatlabFiles/startd.m +++ b/MatlabFiles/startd.m @@ -1,24 +1,24 @@ -function startd(sd) -%function startd(sd) -% to set the directory started in the next time matlab is invoked, -% use this function. E.g. -% sd=cd %to set sd to the current directory -% startd(sd) -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -save '/Users/tzha/ZhaData/Git/TZcode/MatlabFiles/startdir0' sd +function startd(sd) +%function startd(sd) +% to set the directory started in the next time matlab is invoked, +% use this function. E.g. +% sd=cd %to set sd to the current directory +% startd(sd) +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +save '/Users/tzha/ZhaData/Git/TZcode/MatlabFiles/startdir0' sd diff --git a/MatlabFiles/startup.m b/MatlabFiles/startup.m index 05332cf3dc7865f938f6ff831eb6986a8be7f8cd..3df008ad8f2d975641489e6199f3ee744a7de5d1 100644 --- a/MatlabFiles/startup.m +++ b/MatlabFiles/startup.m @@ -1,43 +1,43 @@ -function startup() -% Remembers a previously set startup directory to set the directory, invoke startd. E.g., -% sd=cd % Set sd to the current directory -% startd(sd) -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -%---------------------------------- - -%path(path,'d:\Program Files\MATLAB\R2007a\work\cstz') -%path(path,'c:\softwdisk\matlabr12\toolbox\cstz\cmexfiles\csminwelfinal\csminwelmex') -%path(path,'C:\ZhaData\TZCcode') -%path(path,'C:\Program Files\Intel\MKL\ia32\lib') -%path(path,'C:\Program Files\Intel\MKL\include') -%path(path,'d:\matlabr12\toolbox\cstz\lzpaper2') -%path(path,'d:\matlabr12\toolbox\cstz\rvarcode') -%path(path,'C:\Program Files\MATLAB\R2006b\work\cstz') -path(path,'/Users/tzha/ZhaData/Git/TZcode/MatlabFiles') -path(path,'/Users/tzha/ZhaData/Git/TZcode/MatlabFiles/MSV') -if exist('startdir0.mat')==2 - load /Users/tzha/ZhaData/Git/TZcode/MatlabFiles/startdir0 - cd(sd) -end -format compact - -fn_reset_ini_seed(0); %Reset the random seed to clockcycle. Can be reoverwritten by fn_reset_ini_seed(number); - - - +function startup() +% Remembers a previously set startup directory to set the directory, invoke startd. E.g., +% sd=cd % Set sd to the current directory +% startd(sd) +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +%---------------------------------- + +%path(path,'d:\Program Files\MATLAB\R2007a\work\cstz') +%path(path,'c:\softwdisk\matlabr12\toolbox\cstz\cmexfiles\csminwelfinal\csminwelmex') +%path(path,'C:\ZhaData\TZCcode') +%path(path,'C:\Program Files\Intel\MKL\ia32\lib') +%path(path,'C:\Program Files\Intel\MKL\include') +%path(path,'d:\matlabr12\toolbox\cstz\lzpaper2') +%path(path,'d:\matlabr12\toolbox\cstz\rvarcode') +%path(path,'C:\Program Files\MATLAB\R2006b\work\cstz') +path(path,'/Users/tzha/ZhaData/Git/TZcode/MatlabFiles') +path(path,'/Users/tzha/ZhaData/Git/TZcode/MatlabFiles/MSV') +if exist('startdir0.mat')==2 + load /Users/tzha/ZhaData/Git/TZcode/MatlabFiles/startdir0 + cd(sd) +end +format compact + +fn_reset_ini_seed(0); %Reset the random seed to clockcycle. Can be reoverwritten by fn_reset_ini_seed(number); + + + diff --git a/MatlabFiles/subtitle.m b/MatlabFiles/subtitle.m index ec184e9e2a5a3049c5c0eb51c977607695e60f18..cccfd0fd8eafa5ac1e9bceb8273e5e4f872f18b5 100644 --- a/MatlabFiles/subtitle.m +++ b/MatlabFiles/subtitle.m @@ -1,37 +1,37 @@ - function [ax,h]=subtitle(text) - % - %Centers a title over a group of subplots. - %Returns a handle to the title and the handle to an axis. - % [ax,h]=subtitle(text) - % returns handles to both the axis and the title. - % ax=subtitle(text) - % returns a handle to the axis only. - % Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -% ax=axes('Units','Normal','Position',[.05 .05 .9 .9],'Visible','off','FontSize',14,'FontWeight','Bold'); - ax=axes('Units','Normal','Position',[.05 .05 .9 .9],'Visible','off','FontSize',10,'FontWeight','Bold','FontName','Times New Roman'); -% ax=axes('Units','Normal','Position',[.075 .075 .85 .85],'Visible','off'); - set(get(ax,'Title'),'Visible','on') - title(text); - if (nargout < 2) - return - end - h=get(ax,'Title'); - - %%%END CODE%%% + function [ax,h]=subtitle(text) + % + %Centers a title over a group of subplots. + %Returns a handle to the title and the handle to an axis. + % [ax,h]=subtitle(text) + % returns handles to both the axis and the title. + % ax=subtitle(text) + % returns a handle to the axis only. +% + % Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +% ax=axes('Units','Normal','Position',[.05 .05 .9 .9],'Visible','off','FontSize',14,'FontWeight','Bold'); + ax=axes('Units','Normal','Position',[.05 .05 .9 .9],'Visible','off','FontSize',10,'FontWeight','Bold','FontName','Times New Roman'); +% ax=axes('Units','Normal','Position',[.075 .075 .85 .85],'Visible','off'); + set(get(ax,'Title'),'Visible','on') + title(text); + if (nargout < 2) + return + end + h=get(ax,'Title'); + + %%%END CODE%%% diff --git a/MatlabFiles/suptitle.m b/MatlabFiles/suptitle.m index a8f90f4d5550a964a46753bf06223f5ca25d8d48..e36429d54eaf003e46e2df3dc37f753630e2937f 100644 --- a/MatlabFiles/suptitle.m +++ b/MatlabFiles/suptitle.m @@ -5,22 +5,22 @@ function hout=suptitle(str) % after all subplot commands. % Drea Thomas 6/15/95 drea@mathworks.com -% Copyright (C) 1997-2012 Drea Thomas % -% This file is part of Dynare. +% Copyright (C) 1997-2012 Drea Thomas % -% Dynare is free software: you can redistribute it and/or modify +% This free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % -% Dynare is distributed in the hope that it will be useful, +% It is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% % Warning: If the figure or axis units are non-default, this diff --git a/MatlabFiles/sye.m b/MatlabFiles/sye.m index d85235145f2e07966116d125c0cfa2ba1c9ade90..516f8a6eb23d89253e9dc04e38fe2d257fd28d84 100644 --- a/MatlabFiles/sye.m +++ b/MatlabFiles/sye.m @@ -1,100 +1,100 @@ -function [Bh,e,xtx,xty,phi,y,ncoe,xr] = sye(z,lags) -% Now [Bh,e,xtx,xty,phi,y,ncoe,xr] = sye(z,lags) -% Old: [Bh,e,xtx,xty,phi,y,ncoe,Sigu,xtxinv] = sye(z,lags) -% -% Estimate a system of equations in the form of y(T*nvar) = XB + u, -% X--phi: T*k, B: k*nvar; where T=sp-lags, k=ncoe, -% -% z: (T+lags)-by-(nvar+1) raw data matrix (nvar of variables + constant). -% lags: number of lags -%-------------------- -% Bh: k-by-nvar estimated reduced-form parameter; column: nvar; -% row: k=ncoe=[nvar for 1st lag, ..., nvar for last lag, const] -% e: estimated residual e = y -xBh, T-by-nvar -% xtx: X'X: k-by-k -% xty: X'Y: k-by-nvar -% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, const] -% y: Y: T-by-nvar -% ncoe: number of coeffcients per equation: nvar*lags + 1 -% xr: the economy size (k-by-k) in qr(phi) so that xr=chol(X'*X) -% Sigu: e'*e: nvar-by-nvar. Note, not divided (undivided) by "nobs" -% xtxinv: inv(X'X): k-by-k -% -% See also syed.m (allowing for more predetermined terms) which has not -% been yet updated as "sye.m". -% -% Note, "lags" is something I changed recently, so it may not be compatible -% with old programs, 10/15/98 by TAZ. -% -% Revised, 5/2/99. Replaced outputs Sigu and xtxinv with xr so that previous -% programs may be incompatible. - -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup of orders and lengths ** -[sp,nvar] = size(z); % sp: sample period T include lags -nvar = nvar-1; % -1: takes out the counting of constant - -ess = sp-lags; % effective sample size -sb = lags+1; % sample beginning -sl = sp; % sample last period -ncoe = nvar*lags + 1; % with constant - -% ** construct X for Y = X*B + U where phi = X ** -x = z(:,1:nvar); -C = z(:,nvar+1); -phi = zeros(ess,ncoe); -phi(:,ncoe) = C(1:ess); -for k=1:lags, phi(:,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k,:); end -% row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] -% Thus, # of columns is nvar*lags+1 = ncoef. -% ** estimate: B, XTX, residuals ** -y = x(sb:sl,:); -% -%**** The following, though stable, is too slow ***** -% [u d v]=svd(phi,0); %trial -% %xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) -% vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -% dinv = 1./diag(d); % inv(diag(d)) -% vdinv=v.*(ones(size(v,2),1)*dinv'); %trial -% xtx=vd*vd'; -% xtxinv = vdinv*vdinv'; -% %xty = phi'*y; % X'Y -% uy = u'*y; %trial -% xty = vd*uy; %trial -% %Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). -% Bh = xtxinv*xty; -% %e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar -% e = y - u*uy; -%**** The following, though stable, is too slow ***** - -%===== (Fast but perhaps less accurate) alternative to the above ========= -[xq,xr]=qr(phi,0); -xtx=xr'*xr; -xty=phi'*y; -Bh = xr\(xr'\xty); -e=y-phi*Bh; -%===== (Fast but perhaps less accurate) alternative to the above ========= - - -%* not numerically stable way of computing e'*e -%Sigu = y'*y-xty'*Bh; -%Sigu = y'*(eye(ess)-phi*xtxinv*phi')*y; % probablly better way, commented out - % by TZ, 2/28/98. See following -%Sigu = y'*(eye(ess)-u*u')*y; % I think this is the best, TZ, 2/28/98 - % Note, u*u'=x*inv(x'x)*x. +function [Bh,e,xtx,xty,phi,y,ncoe,xr] = sye(z,lags) +% Now [Bh,e,xtx,xty,phi,y,ncoe,xr] = sye(z,lags) +% Old: [Bh,e,xtx,xty,phi,y,ncoe,Sigu,xtxinv] = sye(z,lags) +% +% Estimate a system of equations in the form of y(T*nvar) = XB + u, +% X--phi: T*k, B: k*nvar; where T=sp-lags, k=ncoe, +% +% z: (T+lags)-by-(nvar+1) raw data matrix (nvar of variables + constant). +% lags: number of lags +%-------------------- +% Bh: k-by-nvar estimated reduced-form parameter; column: nvar; +% row: k=ncoe=[nvar for 1st lag, ..., nvar for last lag, const] +% e: estimated residual e = y -xBh, T-by-nvar +% xtx: X'X: k-by-k +% xty: X'Y: k-by-nvar +% phi: X; T-by-k; column: [nvar for 1st lag, ..., nvar for last lag, const] +% y: Y: T-by-nvar +% ncoe: number of coeffcients per equation: nvar*lags + 1 +% xr: the economy size (k-by-k) in qr(phi) so that xr=chol(X'*X) +% Sigu: e'*e: nvar-by-nvar. Note, not divided (undivided) by "nobs" +% xtxinv: inv(X'X): k-by-k +% +% See also syed.m (allowing for more predetermined terms) which has not +% been yet updated as "sye.m". +% +% Note, "lags" is something I changed recently, so it may not be compatible +% with old programs, 10/15/98 by TAZ. +% +% Revised, 5/2/99. Replaced outputs Sigu and xtxinv with xr so that previous +% programs may be incompatible. + +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup of orders and lengths ** +[sp,nvar] = size(z); % sp: sample period T include lags +nvar = nvar-1; % -1: takes out the counting of constant + +ess = sp-lags; % effective sample size +sb = lags+1; % sample beginning +sl = sp; % sample last period +ncoe = nvar*lags + 1; % with constant + +% ** construct X for Y = X*B + U where phi = X ** +x = z(:,1:nvar); +C = z(:,nvar+1); +phi = zeros(ess,ncoe); +phi(:,ncoe) = C(1:ess); +for k=1:lags, phi(:,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k,:); end +% row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] +% Thus, # of columns is nvar*lags+1 = ncoef. +% ** estimate: B, XTX, residuals ** +y = x(sb:sl,:); +% +%**** The following, though stable, is too slow ***** +% [u d v]=svd(phi,0); %trial +% %xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) +% vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +% dinv = 1./diag(d); % inv(diag(d)) +% vdinv=v.*(ones(size(v,2),1)*dinv'); %trial +% xtx=vd*vd'; +% xtxinv = vdinv*vdinv'; +% %xty = phi'*y; % X'Y +% uy = u'*y; %trial +% xty = vd*uy; %trial +% %Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). +% Bh = xtxinv*xty; +% %e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar +% e = y - u*uy; +%**** The following, though stable, is too slow ***** + +%===== (Fast but perhaps less accurate) alternative to the above ========= +[xq,xr]=qr(phi,0); +xtx=xr'*xr; +xty=phi'*y; +Bh = xr\(xr'\xty); +e=y-phi*Bh; +%===== (Fast but perhaps less accurate) alternative to the above ========= + + +%* not numerically stable way of computing e'*e +%Sigu = y'*y-xty'*Bh; +%Sigu = y'*(eye(ess)-phi*xtxinv*phi')*y; % probablly better way, commented out + % by TZ, 2/28/98. See following +%Sigu = y'*(eye(ess)-u*u')*y; % I think this is the best, TZ, 2/28/98 + % Note, u*u'=x*inv(x'x)*x. diff --git a/MatlabFiles/syed.m b/MatlabFiles/syed.m index e9df9cee59076a1665824f467733ec4616094285..7e75d498394ddb314f01eced090dd0e4f21b9908 100644 --- a/MatlabFiles/syed.m +++ b/MatlabFiles/syed.m @@ -1,84 +1,84 @@ -function [Bh,e,xtx,phi,y] = syed(z,nn) -% syed: estimate a system of equations: [Bh,e,xtx,phi,y] = syed(z,nn) -% Y((T-lags)*nvar) = XB + u, X: (T-lags)*k, B: k*nvar. -% where z is the T*(nvar+ndt) raw data matrix (nvar of variables + -% ndt -- number of deterministic terms); -% nn is 5 inputs [auindx, ndt, nvar,lags,sample period (total)]; -% auindx = 0 (no autoregressive) and 1 (autoregressive); -% total -- including lags, etc. -% Bh: the estimated B; column: nvar; row: [nvar for 1st lag, ..., -% nvar for last lag, deterministic terms (ndt)] -% e: estimated residual e = y -xBh, (T-lags)*nvar -% xtx: X'X -% phi: X; column: [nvar for 1st lag, ..., -% nvar for last lag, deterministic terms (ndt)] -% y: Y -% -% See also "sye.m". -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% ** setup of orders and lengths ** -auindx = nn(1); -ndt = nn(2); % # of deterministic terms including constant -nvar = nn(3); % # of endogenous variables -lags = nn(4); -sp = nn(5); % sample period - -ess = sp-lags; % effective sample size -sb = lags+1; % sample beginning -sl = sp; % sample last period - -% ** construct X for Y = X*B + U where phi = X ** -x = z(:,1:nvar); -C = z(:,nvar+1:nvar+ndt); % C = [] when ndt=0 -% -if auindx == 0 - ncoe = ndt; % with deterministic terms - phi = zeros(sp,ncoe); % preallocating - y = x; -else - y = x(sb:sl,:); - ncoe = nvar*lags + ndt; % with deterministic terms - phi = zeros(ess,ncoe); % preallocating - for k=1:lags, phi(:,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k,:); end -end -% -if length(C) == 0 - phi(:,ncoe-ndt+1:ncoe) = C; -else - phi(:,ncoe-ndt+1:ncoe) = C(1:sp,:); % perhaps, it should have been be C(sb:sp,:). 2/24/00 -end -% -% row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, -% deterministic terms (ndt)] -% Thus, # of columns is nvar*lags+ndt = ncoe. -% ** estimate: B, XTX, residuals ** -[u d v]=svd(phi,0); %trial -%xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -dinv = 1./diag(d); % inv(diag(d)) -vdinv=v.*(ones(size(v,2),1)*dinv'); %trial -xtx=vd*vd'; -xtxinv = vdinv*vdinv'; -%xty = phi'*y; % X'Y -uy = u'*y; %trial -xty = vd*uy; %trial -%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). -Bh = xtxinv*xty; -%e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar -e = y - u*uy; +function [Bh,e,xtx,phi,y] = syed(z,nn) +% syed: estimate a system of equations: [Bh,e,xtx,phi,y] = syed(z,nn) +% Y((T-lags)*nvar) = XB + u, X: (T-lags)*k, B: k*nvar. +% where z is the T*(nvar+ndt) raw data matrix (nvar of variables + +% ndt -- number of deterministic terms); +% nn is 5 inputs [auindx, ndt, nvar,lags,sample period (total)]; +% auindx = 0 (no autoregressive) and 1 (autoregressive); +% total -- including lags, etc. +% Bh: the estimated B; column: nvar; row: [nvar for 1st lag, ..., +% nvar for last lag, deterministic terms (ndt)] +% e: estimated residual e = y -xBh, (T-lags)*nvar +% xtx: X'X +% phi: X; column: [nvar for 1st lag, ..., +% nvar for last lag, deterministic terms (ndt)] +% y: Y +% +% See also "sye.m". +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% ** setup of orders and lengths ** +auindx = nn(1); +ndt = nn(2); % # of deterministic terms including constant +nvar = nn(3); % # of endogenous variables +lags = nn(4); +sp = nn(5); % sample period + +ess = sp-lags; % effective sample size +sb = lags+1; % sample beginning +sl = sp; % sample last period + +% ** construct X for Y = X*B + U where phi = X ** +x = z(:,1:nvar); +C = z(:,nvar+1:nvar+ndt); % C = [] when ndt=0 +% +if auindx == 0 + ncoe = ndt; % with deterministic terms + phi = zeros(sp,ncoe); % preallocating + y = x; +else + y = x(sb:sl,:); + ncoe = nvar*lags + ndt; % with deterministic terms + phi = zeros(ess,ncoe); % preallocating + for k=1:lags, phi(:,nvar*(k-1)+1:nvar*k) = x(sb-k:sl-k,:); end +end +% +if length(C) == 0 + phi(:,ncoe-ndt+1:ncoe) = C; +else + phi(:,ncoe-ndt+1:ncoe) = C(1:sp,:); % perhaps, it should have been be C(sb:sp,:). 2/24/00 +end +% +% row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, +% deterministic terms (ndt)] +% Thus, # of columns is nvar*lags+ndt = ncoe. +% ** estimate: B, XTX, residuals ** +[u d v]=svd(phi,0); %trial +%xtx = phi'*phi; % X'X, k*k (ncoe*ncoe) +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +dinv = 1./diag(d); % inv(diag(d)) +vdinv=v.*(ones(size(v,2),1)*dinv'); %trial +xtx=vd*vd'; +xtxinv = vdinv*vdinv'; +%xty = phi'*y; % X'Y +uy = u'*y; %trial +xty = vd*uy; %trial +%Bh = xtx\xty; %inv(X'X)*(X'Y), k*m (ncoe*nvar). +Bh = xtxinv*xty; +%e = y - phi*Bh; % from Y = XB + U, e: (T-lags)*nvar +e = y - u*uy; diff --git a/MatlabFiles/szasbvar.m b/MatlabFiles/szasbvar.m index a2b13463a67d28efb351f040ae0347d113d56b7e..7166b4ef9c21c75c3779451b4dc6806c2662ef6c 100644 --- a/MatlabFiles/szasbvar.m +++ b/MatlabFiles/szasbvar.m @@ -1,502 +1,500 @@ -function [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... - idmat0,idmatpp,H0invmulti,Hpinvmulti,xxhp] = szasbvar(idfile,q_m,lags,xdgel,mu) -% [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... -% idmat0,idmatpp,H0invmulti,Hpinvmulti] = szasbvar(idfile,q_m,lags,xdgel,mu) -% -% Estimating the Bayesian VAR of Sims and Zha with asymmetric prior (as) -% -% idfile: Identification filename with rows corresponding to equations. -% But all the output will be transposed to columns -% corresponding to equations. -% q_m: quarter or month -% lags: the maximum length of lag -% nhp: number of haperparameters -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1) -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% -------------------- -% -------------------- -% Gb: cell(nvar,1). Each cell, when postmultiplied by A0(:,i), is used to compute A+(:,i) -% where A+ is k-by-m, where k--ncnoef, m--nvar, if asymmetric prior. -% In particular, Aplus(:,i)=Gb{i}*A0(:,i), so Bh = Aplus/A0 -% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the -% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. -% Note,"bd" stands for block diagonal. -% Bh: reduced form B, k(mp+1)-by-m, column--equation. Bh=NaN if asymmetric prior. -% In the form of y=X*B+U where B=[B1|B2| ...|Bp|C] -% where Bi: m-by-m (i=1,..,p--lag length), C: 1-by-ml, constant. -% SpH: divided by T, the final S in the Waggoner-Zha exponential part of p(A0|y) -% SpH=NaN if asymmetric prior -% fss: in-sample-size (for forecasting). Including dummy observations -% ndobs: number of dummy observations, ndobs=nvar+1 -% phi: X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef -% y: y in the form y = X*B+U. Including the dummy observations too, -% T-lags+ndobs-by-nvar. -% nvar: number of variables -% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+1 -% xxhpc: chol(X'X+inv(H_p_tilde)): upper triangular but its transpose -% is lower triagular Choleski -% a0indx: the index number for free parameters in A0. Column meaning equation -% na0p: number of free parameters in A0 -% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. -% idmatpp: asymmetric prior variance for A+ without constant; column -- equation. -% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior -% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior -% xxhp: ncoef-by-nocef, X'X+inv(H_p_tilde) -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale -% the elements of idmat0 or idmatp so that it carries information about relative -% prior variances. -% Revsions by TZ, 10/13/96: Efficiency improvement by streamlining the previous -% code according to the general setup in Sims and Zha's IER and according -% to Zha's notes Forecast (0) (p.3) and Forecast (1) (p.9). -% Quick Revisions: May 2003. See H1p_1 on lines 406-409. -% -% Copyright (c) December 1997 by C.A. Sims and T. Zha, -% -% NOTE1: "nSample" is something I deleted as an input recently, so it may not -% be compatible with old programs, 10/15/98 by TZ. -% NOTE2: I put "mu" as an input arg and delete "nhp" as an input arg, so it may -% not be compatible with old programs, 03/06/99 by TZ -% NOTE3: added three output arguments: H0invmulti and Hpinvmulti and xxhp. 9/27/99 - -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -% -%@@@ Prepared for Bayesian VAR of Sims and Zha -% -%* Load identification and obtain idmat0 -eval(['load ' idfile '.prn -ascii']); -eval(['idmat0=' idfile ';']); -idmat0=idmat0'; % so that each column corresponds to an equation -a0indx=find(idmat0); % column meaning equation -na0p = length(a0indx); % number of free parameters in A0 -nhp = length(mu); % total number of hyperparameters -nfp = na0p + nhp; % total number of free parameters (including hyperparameters) -[nvar,neqn]=size(idmat0); -% -idmatpp = ones(nvar*lags,nvar); % pp: plus without constant. Column -- equation -%>>>>>> B: asymmetric prior variance for idmatpp <<<<<<<< -% -%for i = 1:lags -% rowif = (i-1)*nvar+1; -% rowil = i*nvar; -% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of idmatpp -% if (i==1) -% idmatpp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag -% % note: idmat1 is already transposed. Column -- equation -% else -% %idmatpp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; -% % <<<<<<< toggle + -% % Note: already transposed, since idmat0 is transposed. -% % Meaning: column implies equation -% idmatpp(rowif:rowil,1:nvar) = ones(nvar); -% % >>>>>>> toggle - -% end -%end -% -%>>>>>> E: asymmetric prior variance for idmatpp <<<<<<<< - - -%$$$ available computations -% -%@@@ original -% total number of the sample under study, including lags, etc. -- original sample size -nSample = size(xdgel,1); % the sample size (including lags, of course) -sb = lags+1; % original beginning without dummies -sl = nSample; % original last period without dummies -ssp = nSample - lags; % original number of observations -% -ndobs=nvar+1; % number of dummy observations -ncoef = nvar*lags+1; % number of coefficients in *each* equation, RHS coefficients only. -%*** initializing for global variables -%%GlbAph=zeros(nvar,ncoef); -%Aplus=zeros(ncoef,nvar); -Gb = cell(nvar,1); % Storing potential reduced-form Bh (k-by-m) or prepared - % for computing Aplus (k-by-m), where k--ncnoef, m--nvar -Sbd = cell(nvar,1); % Storing for diag(S(1), ..., S(m)) for the posterior of a0 - % or vec(A0) when one has asymmetric prior. Note, - % "bd" stands for block diagonal. -SpH = ones(nvar,nvar); -%* flp: forecast last period (with dummies); -%* fbp: forecast beginning period (with dummies). -flp = sl+ndobs; -%fbp = ndobs+lags+1; % <<>> true begining by skipping dummies -fss = flp-lags; % forecast sample size (with dummies). - -% ** hyperparameters -% mu = zeros(nhp,1); -% mu(1) = 0.57; -% mu(2) = 0.13; -% mu(3) = 0.1; -% mu(4) = 1; -% mu(5) = 5; %10; -% mu(6) = 5; %10; -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): tightness on lag decay; -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); -% mu(6): weight on single dummy initial observation including constant (cointegration, unit -% roots, and stationarity). - - -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) -% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), -% ** we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - -% -% ** now run the VAR with -% -% **** nvar prior dummy observations with the sum of coefficients -% ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar -% ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] -% ** Now, T=T+ndobs -- added with "ndobs" dummy observations -% -phi = zeros(fss,ncoef); -const = ones(fss,1); -const(1:nvar) = zeros(nvar,1); -phi(:,ncoef) = const; % the first nvar periods: no or zero constant! -% -xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions -%* Dummies -for k=1:nvar - for m=1:lags - phi(ndobs,nvar*(m-1)+k) = xdgelint(k); - phi(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end -end -%* True data -for k=1:lags - phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:sl-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] - % Thus, # of columns is nvar*lags+1 = ncoef. -end -% -% ** Y with "ndobs" dummies added -y = zeros(fss,nvar); -%* Dummies -for k=1:nvar - y(ndobs,k) = xdgelint(k); - y(k,k) = xdgelint(k); - % multiply hyperparameter later -end -%* True data -y(ndobs+1:fss,:) = xdgel(sb:sl,:); - - - -% -% *** specify the prior for each equation separately, SZ method, -% *** -% *** obtaining the residuals for the univariate processes: -% *** a total of "nvar" equations -% *** obtain the posterior peak of A0 which is Sims iden1 (Sims 1986) -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/ssp; - %% sgh(k) = ek'*ek/(fss-7); to match "sqrt(ess)" in RATS univariate regression - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for alpha0, same for all equations!!! -al0b = zeros(nvar*neqn,1); % prior mean for all A0 -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for alpha_plus, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); - %%sgpbid((i-1)*nvar+j) = (1/i)^2/sgsh(j); - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); - else - error('Incompatibility with lags, check the possible errors!!!') - %warning('Incompatibility with lags, check the possible errors!!!') - %return - end - end -end -%%A0bd = sqrt(sg0bid); -% commented out by T.A. Zha, 10/3/96, to avoid double-counting of scaling and the problem -% of potential multiple peaks. -A0bd = zeros(nvar,1); -A0b = sparse(1:nvar,1:nvar,A0bd,nvar,nvar); -A0b = A0b'; % making a column in A0b correspond to an equation - -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -% -phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior -y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior -%----- The following prior designed for GLZ -%phi(1,:) = 1.00*mu(5)*phi(1,:); -%phi(2:nvar,:) = 1.02*mu(7)*phi(2:nvar,:); -%y(1,:) = mu(5)*y(1,:); -%y(2:nvar,:) = mu(7)*y(2:nvar,:); -%---------------------------- -% -phi(nvar+1,:) = mu(6)*phi(nvar+1,:); -y(nvar+1,:) = mu(6)*y(nvar+1,:); - - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper -%%sgppbdi = 1./sgppbd; -%sgppb = diag(sgppbd); - -Hptd = zeros(ncoef); -Hptdi=Hptd; -%%Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); -%%Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdi(ncoef,ncoef)=1/sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde - -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -yty=y'*y; -ymy=yty-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -cyx = cxy'; -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -%================================================= -% Computing the final covariance matrix (S1,...,Sm) for the posterior of A0, -% with the data, and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for -% B if symmetric prior for A+ -%================================================= -% -H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior -Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior -for i = 1:nvar - stri = find(idmat0(:,i)); - % CAS change 9/24/96, to avoid slim chance of an exact zero in x vector - % at some point during an optimization. - %strm = length(stri); % TZ, 11/27/97, no use any more - - %A0hb = A0h(stri,i)-A0b(stri,i); - - % ** set up the conditional prior variance sg0bi and sgpbi. - % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this - % meant to have strm where it has stri, and in any case it is "overwritten" below. - - %------------------------------ - % Introduce prior information on which variables "belong" in various equations. - % In this first trial, we just introduce this information here, in a model-specific way. - % Eventually this info has to be passed parametricly. In our first shot, we just damp down - % all coefficients except those on the diagonal. - factor0=idmat0(:,i); - sg0bd = sg0bida; % added by TZ, 2/26/98. I think at each equation, sg0bd must - % be refreshed. Note, this only works for the prior variance Sg(i) - % of a0(i) being diagonal. If the prior variance Sg(i) is not - % diagonal, we have to work on inv(Sg(i)) or sg0bdi directly. - sg0bd(stri) = sg0bida(stri).*factor0(stri); - sg0bdi = 1./sg0bd; - % - factor1=idmatpp(1:nvar,i); - sg1bd = sgpbida(1:nvar).*factor1; - sg1bdi = 1./sg1bd; - % - if lags>1 - factorpp=idmatpp(nvar+1:ncoef-1,i); - sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; - sgpp_cbdi = 1./sgpp_cbd; - end - - % ** set up the unconditional prior variance on A0i and A+i - %XX = zeros(nvar,strm); - %XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 - % Commented out by TZ, 11/27/97. Streamline. No need for these any more. - - - % * final conditional prior variance on A+i give that on A0i, and - % * unconditional variance on A0+ - H0td = diag(sg0bd); % unconditional - % H_~: td: tilde for ~ - % ** inverse and chol decomp - H0tdi = diag(sg0bdi); - H0invmulti(:,:,i)=H0tdi; - - % - Hptd(1:nvar,1:nvar)=diag(sg1bd); - Hptdi(1:nvar,1:nvar)=diag(sg1bdi); - if lags>1 - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdi(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdi); - % condtional on A0i, H_plus_tilde - end - Hpinvmulti(:,:,i)=Hptdi; - - % common terms - xxhp = xtx+Hptdi; - %Lxxhpc = chol(inv(xxhp))'; % lower triangular - xxhpc = chol(xxhp); % upper triangular but its transpose is lower triagular Choleski - %A0hbH = A0hb'*H0tdi; - %====== The following two lines seem incorrect. The third line is supposed to correc the mistake. May 2003. - % H1p_1 = zeros(ncoef,nvar); - % H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); - H1p_1 = Hptdi(:,1:nvar); - %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); - Hm1 = (cyx+H1p_1')/xxhp; % if symmetric prior, Bh=Hm1' -- reduced form k-by-m. - Gb{i} = Hm1'; % k-by-m, where k--ncoef, m--nvar. - % If asymmetric prior, Gb is used to compute A+ where A+(i) = Gb(i)*a0(i) - % where a0(i) is m-by-1 for the ith column of A0 or the ith equation. - %Hm2 = cxy+H1p_1; - Hm = Hm1*(cxy+H1p_1); - %GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose - %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; - %Hss = XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; - Hss = yty+Hptdi(1:nvar,1:nvar)-Hm; - Sbd{i} = (H0tdi+Hss)./fss; % m-by-m, where m--nvar. If asymmetric prior, Scd is - % usde to form diag(Sbd{1}, ..., Sbd{m}) for a0 or vec(A0) in the - % posterior of A0. Note, "bd" stands for block diagonal and divided by - % "fss" already to make it compatible with SpH used in "a0lhfun" and make it - % it easier according to the notations by Waggoner and Zha -end - - -%%========================================= -%% check if there is asymmetric prior on both A+ and A0 -%%========================================= -% -spindx=1; % A+ index for asymmetric prior -s0indx=1; % A0 index for asymmetric prior -for i=2:nvar - diffGb = Gb{i}-Gb{i-1}; - diffSbd = Sbd{i}-Sbd{i-1}; - if ~any(any(diffGb)) - spindx=spindx+1; - end - if ~any(any(diffSbd)) - s0indx=s0indx+1; - end -end -% -if (spindx==nvar) - Bh = Gb{1}; % reduced-form parameter. Note: does not depend on A0 -else - Bh = NaN; -end -% -if (s0indx==nvar) - SpH = (H0tdi+Hss)/fss; % the final S in the exponential part of p(A0|y) - % divided by nobs in order to make Choleski decomp without optimization - % or in the form conformable to Waggoner and Zha -else - SpH=NaN; -end - - - - - -%---------------------------------------------- -% - -% *** -% *** Form the inverse of covarinace to draw from t- or Gaussian distribution -% *** -%SpHs = SpH*fss; % for the Wishart draw -%SpHsc = chol(SpHs); % upper triangular where Sphsc' is -% % lower triangular Choleski, for Wishart draw -%SpHsic = chol(inv(SpHs))'; % inverse Choleski decomposition -- lower triangular -%A0hin = chol(SpH); % upper triangular, inverse of A0h, each column - % corresponds to an equation. - - -%@@@ The following can be used for other purposes such as forecasting -% -%swish = A0hin'; % each row corresponds to an equation -%A0h = inv(A0hin); % each column corresponds to an equation -%xa0 = A0h(a0indx); - -%%*** form Bh (ncoef*nvar) -%Aplus = Hm1t*A0h; % estimate of Aplus -- the same as Astrar -%Bhp = Hm1t; +function [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... + idmat0,idmatpp,H0invmulti,Hpinvmulti,xxhp] = szasbvar(idfile,q_m,lags,xdgel,mu) +% [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... +% idmat0,idmatpp,H0invmulti,Hpinvmulti] = szasbvar(idfile,q_m,lags,xdgel,mu) +% +% Estimating the Bayesian VAR of Sims and Zha with asymmetric prior (as) +% +% idfile: Identification filename with rows corresponding to equations. +% But all the output will be transposed to columns +% corresponding to equations. +% q_m: quarter or month +% lags: the maximum length of lag +% nhp: number of haperparameters +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1) +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% -------------------- +% -------------------- +% Gb: cell(nvar,1). Each cell, when postmultiplied by A0(:,i), is used to compute A+(:,i) +% where A+ is k-by-m, where k--ncnoef, m--nvar, if asymmetric prior. +% In particular, Aplus(:,i)=Gb{i}*A0(:,i), so Bh = Aplus/A0 +% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the +% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. +% Note,"bd" stands for block diagonal. +% Bh: reduced form B, k(mp+1)-by-m, column--equation. Bh=NaN if asymmetric prior. +% In the form of y=X*B+U where B=[B1|B2| ...|Bp|C] +% where Bi: m-by-m (i=1,..,p--lag length), C: 1-by-ml, constant. +% SpH: divided by T, the final S in the Waggoner-Zha exponential part of p(A0|y) +% SpH=NaN if asymmetric prior +% fss: in-sample-size (for forecasting). Including dummy observations +% ndobs: number of dummy observations, ndobs=nvar+1 +% phi: X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef +% y: y in the form y = X*B+U. Including the dummy observations too, +% T-lags+ndobs-by-nvar. +% nvar: number of variables +% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+1 +% xxhpc: chol(X'X+inv(H_p_tilde)): upper triangular but its transpose +% is lower triagular Choleski +% a0indx: the index number for free parameters in A0. Column meaning equation +% na0p: number of free parameters in A0 +% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. +% idmatpp: asymmetric prior variance for A+ without constant; column -- equation. +% H0invmulti: nvar-by-nvar-by-nvar; inv(H0) for different equations under asymmetric prior +% Hpinvmulti: ncoef-by-ncoef-by-nvar; inv(H+) for different equations under asymmetric prior +% xxhp: ncoef-by-nocef, X'X+inv(H_p_tilde) +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale +% the elements of idmat0 or idmatp so that it carries information about relative +% prior variances. +% Revsions by TZ, 10/13/96: Efficiency improvement by streamlining the previous +% code according to the general setup in Sims and Zha's IER and according +% to Zha's notes Forecast (0) (p.3) and Forecast (1) (p.9). +% Quick Revisions: May 2003. See H1p_1 on lines 406-409. +% +% NOTE1: "nSample" is something I deleted as an input recently, so it may not +% be compatible with old programs, 10/15/98 by TZ. +% NOTE2: I put "mu" as an input arg and delete "nhp" as an input arg, so it may +% not be compatible with old programs, 03/06/99 by TZ +% NOTE3: added three output arguments: H0invmulti and Hpinvmulti and xxhp. 9/27/99 + +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +% +%@@@ Prepared for Bayesian VAR of Sims and Zha +% +%* Load identification and obtain idmat0 +eval(['load ' idfile '.prn -ascii']); +eval(['idmat0=' idfile ';']); +idmat0=idmat0'; % so that each column corresponds to an equation +a0indx=find(idmat0); % column meaning equation +na0p = length(a0indx); % number of free parameters in A0 +nhp = length(mu); % total number of hyperparameters +nfp = na0p + nhp; % total number of free parameters (including hyperparameters) +[nvar,neqn]=size(idmat0); +% +idmatpp = ones(nvar*lags,nvar); % pp: plus without constant. Column -- equation +%>>>>>> B: asymmetric prior variance for idmatpp <<<<<<<< +% +%for i = 1:lags +% rowif = (i-1)*nvar+1; +% rowil = i*nvar; +% idmatw0 = 0.5; % weight assigned to idmat0 in the formation of idmatpp +% if (i==1) +% idmatpp(rowif:rowil,:)=(1-idmatw0)*ones(nvar)+idmatw0*idmat0; % first lag +% % note: idmat1 is already transposed. Column -- equation +% else +% %idmatpp(rowif:rowil,1:nvar) = (1-idmatw0)*ones(nvar)+idmatw0*idmat0; +% % <<<<<<< toggle + +% % Note: already transposed, since idmat0 is transposed. +% % Meaning: column implies equation +% idmatpp(rowif:rowil,1:nvar) = ones(nvar); +% % >>>>>>> toggle - +% end +%end +% +%>>>>>> E: asymmetric prior variance for idmatpp <<<<<<<< + + +%$$$ available computations +% +%@@@ original +% total number of the sample under study, including lags, etc. -- original sample size +nSample = size(xdgel,1); % the sample size (including lags, of course) +sb = lags+1; % original beginning without dummies +sl = nSample; % original last period without dummies +ssp = nSample - lags; % original number of observations +% +ndobs=nvar+1; % number of dummy observations +ncoef = nvar*lags+1; % number of coefficients in *each* equation, RHS coefficients only. +%*** initializing for global variables +%%GlbAph=zeros(nvar,ncoef); +%Aplus=zeros(ncoef,nvar); +Gb = cell(nvar,1); % Storing potential reduced-form Bh (k-by-m) or prepared + % for computing Aplus (k-by-m), where k--ncnoef, m--nvar +Sbd = cell(nvar,1); % Storing for diag(S(1), ..., S(m)) for the posterior of a0 + % or vec(A0) when one has asymmetric prior. Note, + % "bd" stands for block diagonal. +SpH = ones(nvar,nvar); +%* flp: forecast last period (with dummies); +%* fbp: forecast beginning period (with dummies). +flp = sl+ndobs; +%fbp = ndobs+lags+1; % <<>> true begining by skipping dummies +fss = flp-lags; % forecast sample size (with dummies). + +% ** hyperparameters +% mu = zeros(nhp,1); +% mu(1) = 0.57; +% mu(2) = 0.13; +% mu(3) = 0.1; +% mu(4) = 1; +% mu(5) = 5; %10; +% mu(6) = 5; %10; +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): tightness on lag decay; +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); +% mu(6): weight on single dummy initial observation including constant (cointegration, unit +% roots, and stationarity). + + +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 (a*exp(b*l1)) match that of x1 (say, beginning: 1/1) +% ** and the decay of l2 (a*exp(b*l2)) match that of x2 (say, end: 1/5), +% ** we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + +% +% ** now run the VAR with +% +% **** nvar prior dummy observations with the sum of coefficients +% ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar +% ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] +% ** Now, T=T+ndobs -- added with "ndobs" dummy observations +% +phi = zeros(fss,ncoef); +const = ones(fss,1); +const(1:nvar) = zeros(nvar,1); +phi(:,ncoef) = const; % the first nvar periods: no or zero constant! +% +xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions +%* Dummies +for k=1:nvar + for m=1:lags + phi(ndobs,nvar*(m-1)+k) = xdgelint(k); + phi(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end +end +%* True data +for k=1:lags + phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:sl-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] + % Thus, # of columns is nvar*lags+1 = ncoef. +end +% +% ** Y with "ndobs" dummies added +y = zeros(fss,nvar); +%* Dummies +for k=1:nvar + y(ndobs,k) = xdgelint(k); + y(k,k) = xdgelint(k); + % multiply hyperparameter later +end +%* True data +y(ndobs+1:fss,:) = xdgel(sb:sl,:); + + + +% +% *** specify the prior for each equation separately, SZ method, +% *** +% *** obtaining the residuals for the univariate processes: +% *** a total of "nvar" equations +% *** obtain the posterior peak of A0 which is Sims iden1 (Sims 1986) +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],lags); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/ssp; + %% sgh(k) = ek'*ek/(fss-7); to match "sqrt(ess)" in RATS univariate regression + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for alpha0, same for all equations!!! +al0b = zeros(nvar*neqn,1); % prior mean for all A0 +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for alpha_plus, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); + %%sgpbid((i-1)*nvar+j) = (1/i)^2/sgsh(j); + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); + else + error('Incompatibility with lags, check the possible errors!!!') + %warning('Incompatibility with lags, check the possible errors!!!') + %return + end + end +end +%%A0bd = sqrt(sg0bid); +% commented out by T.A. Zha, 10/3/96, to avoid double-counting of scaling and the problem +% of potential multiple peaks. +A0bd = zeros(nvar,1); +A0b = sparse(1:nvar,1:nvar,A0bd,nvar,nvar); +A0b = A0b'; % making a column in A0b correspond to an equation + +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +% +phi(1:nvar,:) = 1*mu(5)*phi(1:nvar,:); % standard Sims and Zha prior +y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior +%----- The following prior designed for GLZ +%phi(1,:) = 1.00*mu(5)*phi(1,:); +%phi(2:nvar,:) = 1.02*mu(7)*phi(2:nvar,:); +%y(1,:) = mu(5)*y(1,:); +%y(2:nvar,:) = mu(7)*y(2:nvar,:); +%---------------------------- +% +phi(nvar+1,:) = mu(6)*phi(nvar+1,:); +y(nvar+1,:) = mu(6)*y(nvar+1,:); + + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper +%%sgppbdi = 1./sgppbd; +%sgppb = diag(sgppbd); + +Hptd = zeros(ncoef); +Hptdi=Hptd; +%%Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); +%%Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdi(ncoef,ncoef)=1/sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde + +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +yty=y'*y; +ymy=yty-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +cyx = cxy'; +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +%================================================= +% Computing the final covariance matrix (S1,...,Sm) for the posterior of A0, +% with the data, and final Gb=(G1,...,Gm) for A+ if asymmetric prior or for +% B if symmetric prior for A+ +%================================================= +% +H0invmulti=zeros(nvar,nvar,nvar); % inv(H0) for different equations under asymmetric prior +Hpinvmulti=zeros(ncoef,ncoef,nvar); % inv(H+) for different equations under asymmetric prior +for i = 1:nvar + stri = find(idmat0(:,i)); + % CAS change 9/24/96, to avoid slim chance of an exact zero in x vector + % at some point during an optimization. + %strm = length(stri); % TZ, 11/27/97, no use any more + + %A0hb = A0h(stri,i)-A0b(stri,i); + + % ** set up the conditional prior variance sg0bi and sgpbi. + % sg0bd = zeros(stri,1); Commented out by CAS, 9/24/96. Looks like this + % meant to have strm where it has stri, and in any case it is "overwritten" below. + + %------------------------------ + % Introduce prior information on which variables "belong" in various equations. + % In this first trial, we just introduce this information here, in a model-specific way. + % Eventually this info has to be passed parametricly. In our first shot, we just damp down + % all coefficients except those on the diagonal. + factor0=idmat0(:,i); + sg0bd = sg0bida; % added by TZ, 2/26/98. I think at each equation, sg0bd must + % be refreshed. Note, this only works for the prior variance Sg(i) + % of a0(i) being diagonal. If the prior variance Sg(i) is not + % diagonal, we have to work on inv(Sg(i)) or sg0bdi directly. + sg0bd(stri) = sg0bida(stri).*factor0(stri); + sg0bdi = 1./sg0bd; + % + factor1=idmatpp(1:nvar,i); + sg1bd = sgpbida(1:nvar).*factor1; + sg1bdi = 1./sg1bd; + % + if lags>1 + factorpp=idmatpp(nvar+1:ncoef-1,i); + sgpp_cbd = sgppbd(1:ncoef-nvar-1) .* factorpp; + sgpp_cbdi = 1./sgpp_cbd; + end + + % ** set up the unconditional prior variance on A0i and A+i + %XX = zeros(nvar,strm); + %XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 + % Commented out by TZ, 11/27/97. Streamline. No need for these any more. + + + % * final conditional prior variance on A+i give that on A0i, and + % * unconditional variance on A0+ + H0td = diag(sg0bd); % unconditional + % H_~: td: tilde for ~ + % ** inverse and chol decomp + H0tdi = diag(sg0bdi); + H0invmulti(:,:,i)=H0tdi; + + % + Hptd(1:nvar,1:nvar)=diag(sg1bd); + Hptdi(1:nvar,1:nvar)=diag(sg1bdi); + if lags>1 + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdi(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdi); + % condtional on A0i, H_plus_tilde + end + Hpinvmulti(:,:,i)=Hptdi; + + % common terms + xxhp = xtx+Hptdi; + %Lxxhpc = chol(inv(xxhp))'; % lower triangular + xxhpc = chol(xxhp); % upper triangular but its transpose is lower triagular Choleski + %A0hbH = A0hb'*H0tdi; + %====== The following two lines seem incorrect. The third line is supposed to correc the mistake. May 2003. + % H1p_1 = zeros(ncoef,nvar); + % H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); + H1p_1 = Hptdi(:,1:nvar); + %%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); + Hm1 = (cyx+H1p_1')/xxhp; % if symmetric prior, Bh=Hm1' -- reduced form k-by-m. + Gb{i} = Hm1'; % k-by-m, where k--ncoef, m--nvar. + % If asymmetric prior, Gb is used to compute A+ where A+(i) = Gb(i)*a0(i) + % where a0(i) is m-by-1 for the ith column of A0 or the ith equation. + %Hm2 = cxy+H1p_1; + Hm = Hm1*(cxy+H1p_1); + %GlbAph(i,:) = A0h(stri,i)'*XX'*Hm1; % alpha_plus_*_transpose + %%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; + %Hss = XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; + Hss = yty+Hptdi(1:nvar,1:nvar)-Hm; + Sbd{i} = (H0tdi+Hss)./fss; % m-by-m, where m--nvar. If asymmetric prior, Scd is + % usde to form diag(Sbd{1}, ..., Sbd{m}) for a0 or vec(A0) in the + % posterior of A0. Note, "bd" stands for block diagonal and divided by + % "fss" already to make it compatible with SpH used in "a0lhfun" and make it + % it easier according to the notations by Waggoner and Zha +end + + +%%========================================= +%% check if there is asymmetric prior on both A+ and A0 +%%========================================= +% +spindx=1; % A+ index for asymmetric prior +s0indx=1; % A0 index for asymmetric prior +for i=2:nvar + diffGb = Gb{i}-Gb{i-1}; + diffSbd = Sbd{i}-Sbd{i-1}; + if ~any(any(diffGb)) + spindx=spindx+1; + end + if ~any(any(diffSbd)) + s0indx=s0indx+1; + end +end +% +if (spindx==nvar) + Bh = Gb{1}; % reduced-form parameter. Note: does not depend on A0 +else + Bh = NaN; +end +% +if (s0indx==nvar) + SpH = (H0tdi+Hss)/fss; % the final S in the exponential part of p(A0|y) + % divided by nobs in order to make Choleski decomp without optimization + % or in the form conformable to Waggoner and Zha +else + SpH=NaN; +end + + + + + +%---------------------------------------------- +% + +% *** +% *** Form the inverse of covarinace to draw from t- or Gaussian distribution +% *** +%SpHs = SpH*fss; % for the Wishart draw +%SpHsc = chol(SpHs); % upper triangular where Sphsc' is +% % lower triangular Choleski, for Wishart draw +%SpHsic = chol(inv(SpHs))'; % inverse Choleski decomposition -- lower triangular +%A0hin = chol(SpH); % upper triangular, inverse of A0h, each column + % corresponds to an equation. + + +%@@@ The following can be used for other purposes such as forecasting +% +%swish = A0hin'; % each row corresponds to an equation +%A0h = inv(A0hin); % each column corresponds to an equation +%xa0 = A0h(a0indx); + +%%*** form Bh (ncoef*nvar) +%Aplus = Hm1t*A0h; % estimate of Aplus -- the same as Astrar +%Bhp = Hm1t; diff --git a/MatlabFiles/szbvar.m b/MatlabFiles/szbvar.m index 46344b45ff754b9ed08f158a0f370e07f88e21cf..058762d352e1dd7fea7593e787676212952d720d 100644 --- a/MatlabFiles/szbvar.m +++ b/MatlabFiles/szbvar.m @@ -1,353 +1,352 @@ -function [A0hin,Hm1t,fss,ndobs,phi,y,nvar,ncoef,SpH,SpHsc,xxhpc,a0indx,na0p,... - idmat0] = szbvar(idfile,q_m,lags,nSample,nhp,xdgel) -% Estimating the Bayesian VAR of Sims and Zha: -% function [A0hin,Hm1t,fss,ndobs,phi,y,nvar,ncoef,SpH,SpHsc,xxhpc,a0indx,na0p,... -% idmat0] = szbvar(idfile,q_m,lags,nSample,nhp,xdgel) -% -% idfile: Identification filename such as "iden4" (with the extension ".prn"). -% q_m: quarter or month -% lags: the maximum length of lag -% nSample: the sample size (including lags, of course) -% nhp: number of haperparameters -% imstp: number of impusle response steps -% xdgel: the general matrix of the original data (no manipulation involved) -% ------ -% A0hin: chol(SpH) -- inverse of A0h, upper triangular, each column corresponds to an equation -% Hm1t: reduced form B -% fss: in-sample-size (for forecasting). Including dummy observations -% ndobs: number of dummy observations, ndobs=nvar+1 -% phi: X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef -% y: y in the form y = X*B+U. Including the dummy observations too, -% T-lags+ndobs-by-nvar. -% nvar: number of variables -% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+1 -% SpH: divided by T, the final S in the Waggoner-Zha exponential part of p(A0|y) -% SpHsc: upper triagular in the lower triangular Choleski of SpH*fss, for Wishart -% xxhpc: chol(X'X+inv(H_p_tilde)): upper triangular but its transpose -% is lower triagular Choleski -% a0indx: the index number for free parameters in A0. Column meaning equation -% na0p: number of free parameters in A0 -% idmat0: identification matrix for A0; only 1's and 0's. Column meaning equation. -% -% Copyright (c) July 1997 by C.A. Sims and T. Zha -% -% Quick Revisions: May 2003. See H1p_1 on lines 301-304. -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -% -%@@@ Prepared for Bayesian VAR of Sims and Zha -% -%* Load identification and obtain idmat0 -eval(['load ' idfile '.prn -ascii']); -eval(['idmat0=' idfile ';']); -idmat0=idmat0'; % so that each column corresponds to an equation -a0indx=find(idmat0); % column meaning equation -na0p = length(a0indx); % number of free parameters in A0 -nfp = na0p + nhp; % total number of free parameter -[nvar,neqn]=size(idmat0); - -%$$$ available computations -% -%@@@ original -% total number of the sample under study, including lags, etc. -- original sample size -sb = lags+1; % original beginning without dummies -sl = nSample; % original last period without dummies -ssp = nSample - lags; % original number of observations -% -ndobs=nvar+1; % number of dummy observations -ncoef = nvar*lags+1; % number of coefficients in *each* equation, RHS coefficients only. -%*** initializing for global variables -%%GlbAph=zeros(nvar,ncoef); -Aplus=zeros(ncoef,nvar); -SpH = ones(nvar,nvar); -%* flp: forecast last period (with dummies); -%* fbp: forecast beginning period (with dummies). -flp = sl+ndobs; -fbp = ndobs+lags+1; % <<>> true begining by skipping dummies -fss = flp-lags; % forecast sample size (with dummies). - -% ** hyperparameters -mu = zeros(nhp,1); -mu(1) = 0.57; -mu(2) = 0.13; -mu(3) = 0.1; -mu(4) = 1; -mu(5) = 5; -mu(6) = 5; -% -% mu(1): overall tightness and also for A0; -% mu(2): relative tightness for A+; -% mu(3): relative tightness for the constant term; -% mu(4): tightness on lag decay; -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); -% mu(6): weight on single dummy initial observation including constant (cointegration, unit -% roots, and stationarity). - - -% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where -% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. -% ** Let the decay of l1 match that of x1 (say, beginning) and the decay -% ** of l2 match that of x2 (say, end), we can solve for a and b which are -% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). -if q_m==12 - l1 = 1; % 1st month == 1st quarter - xx1 = 1; % 1st quarter - l2 = lags; % last month - xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter - %xx2 = 1/6; % last quarter - % 3rd quarter: i.e., we intend to let decay of the 6th month match - % that of the 3rd quarter, so that the 6th month decays a little - % faster than the second quarter which is 1/2. - if lags==1 - b = 0; - else - b = (log(xx1)-log(xx2))/(l1-l2); - end - a = xx1*exp(-b*l1); -end - -% -% ** now run the VAR with -% -% **** nvar prior dummy observations with the sum of coefficients -% ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar -% ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] -% ** Now, T=T+ndobs -- added with "ndobs" dummy observations -% -phi = zeros(fss,ncoef); -const = ones(fss,1); -const(1:nvar) = zeros(nvar,1); -phi(:,ncoef) = const; % the first nvar periods: no or zero constant! -% -xdgelint = mean(xdgel(1:lags,:),1); -% mean of the first lags initial conditions -for k=1:nvar - for m=1:lags - phi(ndobs,nvar*(m-1)+k) = xdgelint(k); - phi(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end -end -for k=1:lags - phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:sl-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] - % Thus, # of columns is nvar*lags+1 = ncoef. -end -% -% ** Y with "ndobs" dummies added -y = zeros(fss,nvar); -for k=1:nvar - y(ndobs,k) = xdgelint(k); - y(k,k) = xdgelint(k); - % <<>> place hyperparameter later -end -y(ndobs+1:fss,:) = xdgel(sb:sl,:); - -% -% *** specify the prior for each equation separately, SZ method, -% *** -% *** obtaining the residuals for the univariate processes: -% *** a total of "nvar" equations -% *** obtain the posterior peak of A0 which is Sims iden1 (Sims 1986) -% ** get the residuals from univariate regressions. -% -sgh = zeros(nvar,1); % square root -sgsh = sgh; % square -nn = [1 lags nSample]; -yu = xdgel; -C = ones(nSample,1); -for k=1:nvar - [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],nn); - clear Bk junk1 junk2 junk3 junk4; - sgsh(k) = ek'*ek/ssp; - %% sgh(k) = ek'*ek/(fss-7); to match "sqrt(ess)" in RATS univariate regression - sgh(k) = sqrt(sgsh(k)); -end -% ** prior variance for alpha0, same for all equations!!! -al0b = zeros(nvar*neqn,0); % prior mean for all A0 -sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only -for j=1:nvar - sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 -end -% ** prior variance for alpha_plus, same for all equations -sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal -for i = 1:lags - if (q_m==12) - lagdecay = a*exp(b*i); - end - % - for j = 1:nvar - if (q_m==12) - % exponential decay to match quarterly decay - sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); - %%sgpbid((i-1)*nvar+j) = (1/i)^2/sgsh(j); - elseif (q_m==4) - sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); - else - warning('Incompatibility with lags, check the possible errors!!!') - return - end - end -end -%%A0bd = sqrt(sg0bid); -% commented out by T.A. Zha, 10/3/96, to avoid double-counting of scaling and the problem -% of potential multiple peaks. -A0bd = zeros(nvar,1); -A0b = sparse(1:nvar,1:nvar,A0bd,nvar,nvar); -A0b = A0b'; % making a column in A0b correspond to an equation - -% - - -%================================================= -% Computing the (prior) covariance matrix for the posterior of A0, no data yet -%================================================= -% -% -% ** weight prior dummy observations -%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); -%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); -%phi(ndobs,:) = mu -% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. -% -phi(1:nvar,:) = mu(5)*phi(1:nvar,:); % standard Sims and Zha prior -y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior -%----- The following prior designed for GLZ -%phi(1,:) = 1.00*mu(5)*phi(1,:); -%phi(2:nvar,:) = 1.02*mu(7)*phi(2:nvar,:); -%y(1,:) = mu(5)*y(1,:); -%y(2:nvar,:) = mu(7)*y(2:nvar,:); -%---------------------------- -% -phi(nvar+1,:) = mu(6)*phi(nvar+1,:); -y(nvar+1,:) = mu(6)*y(nvar+1,:); - - -% ** set up the conditional prior variance sg0bi and sgpbi. -sg0bida = mu(1)^2*sg0bid; -sgpbida = mu(1)^2*mu(2)^2*sgpbid; -sgpbida(ncoef) = mu(1)^2*mu(3)^2; -sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper -%%sgppbdi = 1./sgppbd; -%sgppb = diag(sgppbd); - -Hptd = zeros(ncoef); -Hptdi=Hptd; -%%Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); -%%Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); -Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); -Hptdi(ncoef,ncoef)=1/sgppbd(ncoef-nvar); - % condtional on A0i, H_plus_tilde -sg0bd = sg0bida; -sg0bdi = 1./sg0bd; -sg1bd = sgpbida(1:nvar); -sg1bdi = 1./sg1bd; -if lags>1 - sgpp_cbd = sgppbd(1:ncoef-nvar-1); - sgpp_cbdi = 1./sgpp_cbd; % _cbd: c -- constant, b -- barred (without), d -- diagonal -end - - -% ** set up the unconditional prior variance on A0i and A+i -%%XX = zeros(nvar,strm); -%%XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 -% -% * final conditional prior variance on A+i give that on A0i, and -% * unconditional variance on A0+ -H0td = diag(sg0bd); % unconditional -% H_~: td: tilde for ~ -% ** inverse and chol decomp -H0tdi = diag(sg0bdi); - -% -Hptd(1:nvar,1:nvar)=diag(sg1bd); -Hptdi(1:nvar,1:nvar)=diag(sg1bdi); -if lags>1 - Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); - Hptdi(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdi); - % condtional on A0i, H_plus_tilde -end - - -%================================================= -% Computing the final covariance matrix for the posterior of A0, with the data -%================================================= -% -% ** some common terms -[u d v]=svd(phi,0); %trial -% xtx = phi'*phi; %trial -vd=v.*(ones(size(v,2),1)*diag(d)'); %trial -xtx=vd*vd'; -% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial -yu = y'*u; %trial -cxyxx=yu*yu'; %trial -yty=y'*y; -ymy=yty-cxyxx; %trial -%ymy = y'*M*y; -%cxy = phi'*y; %trial -cxy = vd*yu'; %trial -cyx = cxy'; -%cxpy = xtx\cxy; %not used further except in line below -%cxyxx = cxy'*cxpy; - -% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior -%GlbAph = cxpy*A0h; - - -% common terms -xxhp = xtx+Hptdi; -%Lxxhpc = chol(inv(xxhp))'; % lower triangular -xxhpc = chol(xxhp); % upper triangular but its transpose is lower triagular Choleski -%A0hbH = A0hb'*H0tdi; -%====== The following two lines seem incorrect. The third line is supposed to correc the mistake. May 2003. -% H1p_1 = zeros(ncoef,nvar); -% H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); -H1p_1 = Hptdi(:,1:nvar); -%%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); -Hm1 = (cyx+H1p_1')/xxhp; -Hm1t = Hm1'; -%Hm2 = cxy+H1p_1; -Hm = Hm1*(cxy+H1p_1); -%%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; -Hss = yty+Hptdi(1:nvar,1:nvar)-Hm; -SpH = (H0tdi+Hss)/fss; % the final S in the exponential part of p(A0|y) -% divided by nobs in order to make Choleski decomp without optimization -% or in the form conformable to Waggoner and Zha - -% *** -% *** Form the inverse of covarinace to draw from t- or Gaussian distribution -% *** -SpHs = SpH*fss; % for the Wishart draw -SpHsc = chol(SpHs); % upper triangular where Sphsc' is lower triangular Choleski -%SpHsic = chol(inv(SpHs))'; % inverse Choleski decomposition -- lower triangular - -A0hin = chol(SpH); % upper triangular, inverse of A0h, each column - % corresponds to an equation. - - -%---------------------------------------------- -% -%@@@ The following can be used for other purposes such as forecasting -% -%swish = A0hin'; % each row corresponds to an equation -%A0h = inv(A0hin); % each column corresponds to an equation -%xa0 = A0h(a0indx); - -%%*** form Bh (ncoef*nvar) -%Aplus = Hm1t*A0h; % estimate of Aplus -- the same as Astrar -%Bhp = Hm1t; +function [A0hin,Hm1t,fss,ndobs,phi,y,nvar,ncoef,SpH,SpHsc,xxhpc,a0indx,na0p,... + idmat0] = szbvar(idfile,q_m,lags,nSample,nhp,xdgel) +% Estimating the Bayesian VAR of Sims and Zha: +% function [A0hin,Hm1t,fss,ndobs,phi,y,nvar,ncoef,SpH,SpHsc,xxhpc,a0indx,na0p,... +% idmat0] = szbvar(idfile,q_m,lags,nSample,nhp,xdgel) +% +% idfile: Identification filename such as "iden4" (with the extension ".prn"). +% q_m: quarter or month +% lags: the maximum length of lag +% nSample: the sample size (including lags, of course) +% nhp: number of haperparameters +% imstp: number of impusle response steps +% xdgel: the general matrix of the original data (no manipulation involved) +% ------ +% A0hin: chol(SpH) -- inverse of A0h, upper triangular, each column corresponds to an equation +% Hm1t: reduced form B +% fss: in-sample-size (for forecasting). Including dummy observations +% ndobs: number of dummy observations, ndobs=nvar+1 +% phi: X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef +% y: y in the form y = X*B+U. Including the dummy observations too, +% T-lags+ndobs-by-nvar. +% nvar: number of variables +% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+1 +% SpH: divided by T, the final S in the Waggoner-Zha exponential part of p(A0|y) +% SpHsc: upper triagular in the lower triangular Choleski of SpH*fss, for Wishart +% xxhpc: chol(X'X+inv(H_p_tilde)): upper triangular but its transpose +% is lower triagular Choleski +% a0indx: the index number for free parameters in A0. Column meaning equation +% na0p: number of free parameters in A0 +% idmat0: identification matrix for A0; only 1's and 0's. Column meaning equation. +% +% Quick Revisions: May 2003. See H1p_1 on lines 301-304. +% +% +% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +% +%@@@ Prepared for Bayesian VAR of Sims and Zha +% +%* Load identification and obtain idmat0 +eval(['load ' idfile '.prn -ascii']); +eval(['idmat0=' idfile ';']); +idmat0=idmat0'; % so that each column corresponds to an equation +a0indx=find(idmat0); % column meaning equation +na0p = length(a0indx); % number of free parameters in A0 +nfp = na0p + nhp; % total number of free parameter +[nvar,neqn]=size(idmat0); + +%$$$ available computations +% +%@@@ original +% total number of the sample under study, including lags, etc. -- original sample size +sb = lags+1; % original beginning without dummies +sl = nSample; % original last period without dummies +ssp = nSample - lags; % original number of observations +% +ndobs=nvar+1; % number of dummy observations +ncoef = nvar*lags+1; % number of coefficients in *each* equation, RHS coefficients only. +%*** initializing for global variables +%%GlbAph=zeros(nvar,ncoef); +Aplus=zeros(ncoef,nvar); +SpH = ones(nvar,nvar); +%* flp: forecast last period (with dummies); +%* fbp: forecast beginning period (with dummies). +flp = sl+ndobs; +fbp = ndobs+lags+1; % <<>> true begining by skipping dummies +fss = flp-lags; % forecast sample size (with dummies). + +% ** hyperparameters +mu = zeros(nhp,1); +mu(1) = 0.57; +mu(2) = 0.13; +mu(3) = 0.1; +mu(4) = 1; +mu(5) = 5; +mu(6) = 5; +% +% mu(1): overall tightness and also for A0; +% mu(2): relative tightness for A+; +% mu(3): relative tightness for the constant term; +% mu(4): tightness on lag decay; +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); +% mu(6): weight on single dummy initial observation including constant (cointegration, unit +% roots, and stationarity). + + +% ** monthly lag decay in order to match quarterly decay: a*exp(bl) where +% ** l is the monthly lag. Suppose quarterly decay is 1/x where x=1,2,3,4. +% ** Let the decay of l1 match that of x1 (say, beginning) and the decay +% ** of l2 match that of x2 (say, end), we can solve for a and b which are +% ** b = (log_x1-log_x2)/(l1-l2), and a = x1*exp(-b*l1). +if q_m==12 + l1 = 1; % 1st month == 1st quarter + xx1 = 1; % 1st quarter + l2 = lags; % last month + xx2 = 1/((ceil(lags/3))^mu(4)); % last quarter + %xx2 = 1/6; % last quarter + % 3rd quarter: i.e., we intend to let decay of the 6th month match + % that of the 3rd quarter, so that the 6th month decays a little + % faster than the second quarter which is 1/2. + if lags==1 + b = 0; + else + b = (log(xx1)-log(xx2))/(l1-l2); + end + a = xx1*exp(-b*l1); +end + +% +% ** now run the VAR with +% +% **** nvar prior dummy observations with the sum of coefficients +% ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar +% ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] +% ** Now, T=T+ndobs -- added with "ndobs" dummy observations +% +phi = zeros(fss,ncoef); +const = ones(fss,1); +const(1:nvar) = zeros(nvar,1); +phi(:,ncoef) = const; % the first nvar periods: no or zero constant! +% +xdgelint = mean(xdgel(1:lags,:),1); +% mean of the first lags initial conditions +for k=1:nvar + for m=1:lags + phi(ndobs,nvar*(m-1)+k) = xdgelint(k); + phi(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end +end +for k=1:lags + phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:sl-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] + % Thus, # of columns is nvar*lags+1 = ncoef. +end +% +% ** Y with "ndobs" dummies added +y = zeros(fss,nvar); +for k=1:nvar + y(ndobs,k) = xdgelint(k); + y(k,k) = xdgelint(k); + % <<>> place hyperparameter later +end +y(ndobs+1:fss,:) = xdgel(sb:sl,:); + +% +% *** specify the prior for each equation separately, SZ method, +% *** +% *** obtaining the residuals for the univariate processes: +% *** a total of "nvar" equations +% *** obtain the posterior peak of A0 which is Sims iden1 (Sims 1986) +% ** get the residuals from univariate regressions. +% +sgh = zeros(nvar,1); % square root +sgsh = sgh; % square +nn = [1 lags nSample]; +yu = xdgel; +C = ones(nSample,1); +for k=1:nvar + [Bk,ek,junk1,junk2,junk3,junk4] = sye([yu(:,k) C],nn); + clear Bk junk1 junk2 junk3 junk4; + sgsh(k) = ek'*ek/ssp; + %% sgh(k) = ek'*ek/(fss-7); to match "sqrt(ess)" in RATS univariate regression + sgh(k) = sqrt(sgsh(k)); +end +% ** prior variance for alpha0, same for all equations!!! +al0b = zeros(nvar*neqn,0); % prior mean for all A0 +sg0bid = zeros(nvar,1); % Sigma0_bar diagonal only +for j=1:nvar + sg0bid(j) = 1/sgsh(j); % sgsh = sigmai^2 +end +% ** prior variance for alpha_plus, same for all equations +sgpbid = zeros(ncoef,1); % Sigma_plus_bar, diagonal +for i = 1:lags + if (q_m==12) + lagdecay = a*exp(b*i); + end + % + for j = 1:nvar + if (q_m==12) + % exponential decay to match quarterly decay + sgpbid((i-1)*nvar+j) = lagdecay^2/sgsh(j); + %%sgpbid((i-1)*nvar+j) = (1/i)^2/sgsh(j); + elseif (q_m==4) + sgpbid((i-1)*nvar+j) = (1/i^mu(4))^2/sgsh(j); + else + warning('Incompatibility with lags, check the possible errors!!!') + return + end + end +end +%%A0bd = sqrt(sg0bid); +% commented out by T.A. Zha, 10/3/96, to avoid double-counting of scaling and the problem +% of potential multiple peaks. +A0bd = zeros(nvar,1); +A0b = sparse(1:nvar,1:nvar,A0bd,nvar,nvar); +A0b = A0b'; % making a column in A0b correspond to an equation + +% + + +%================================================= +% Computing the (prior) covariance matrix for the posterior of A0, no data yet +%================================================= +% +% +% ** weight prior dummy observations +%phi(1:nvar,:) = (mu(5)^2/mu(1)^2)*phi(1:nvar,:); +%y(1:nvar,:) = (mu(5)^2/mu(1)^2)*y(1:nvar,:); +%phi(ndobs,:) = mu +% modified by CAS 8/6/96. The dummy obs weights are naturally in std units, not var units. +% +phi(1:nvar,:) = mu(5)*phi(1:nvar,:); % standard Sims and Zha prior +y(1:nvar,:) = mu(5)*y(1:nvar,:); % standard Sims and Zha prior +%----- The following prior designed for GLZ +%phi(1,:) = 1.00*mu(5)*phi(1,:); +%phi(2:nvar,:) = 1.02*mu(7)*phi(2:nvar,:); +%y(1,:) = mu(5)*y(1,:); +%y(2:nvar,:) = mu(7)*y(2:nvar,:); +%---------------------------- +% +phi(nvar+1,:) = mu(6)*phi(nvar+1,:); +y(nvar+1,:) = mu(6)*y(nvar+1,:); + + +% ** set up the conditional prior variance sg0bi and sgpbi. +sg0bida = mu(1)^2*sg0bid; +sgpbida = mu(1)^2*mu(2)^2*sgpbid; +sgpbida(ncoef) = mu(1)^2*mu(3)^2; +sgppbd = sgpbida(nvar+1:ncoef); % corresponding to A++, in a Sims-Zha paper +%%sgppbdi = 1./sgppbd; +%sgppb = diag(sgppbd); + +Hptd = zeros(ncoef); +Hptdi=Hptd; +%%Hptd(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbd); +%%Hptdi(nvar+1:ncoef,nvar+1:ncoef)=diag(sgppbdi); +Hptd(ncoef,ncoef)=sgppbd(ncoef-nvar); +Hptdi(ncoef,ncoef)=1/sgppbd(ncoef-nvar); + % condtional on A0i, H_plus_tilde +sg0bd = sg0bida; +sg0bdi = 1./sg0bd; +sg1bd = sgpbida(1:nvar); +sg1bdi = 1./sg1bd; +if lags>1 + sgpp_cbd = sgppbd(1:ncoef-nvar-1); + sgpp_cbdi = 1./sgpp_cbd; % _cbd: c -- constant, b -- barred (without), d -- diagonal +end + + +% ** set up the unconditional prior variance on A0i and A+i +%%XX = zeros(nvar,strm); +%%XX(stri,:) = eye(strm); % XX in Gelman, etel, on p479 +% +% * final conditional prior variance on A+i give that on A0i, and +% * unconditional variance on A0+ +H0td = diag(sg0bd); % unconditional +% H_~: td: tilde for ~ +% ** inverse and chol decomp +H0tdi = diag(sg0bdi); + +% +Hptd(1:nvar,1:nvar)=diag(sg1bd); +Hptdi(1:nvar,1:nvar)=diag(sg1bdi); +if lags>1 + Hptd(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbd); + Hptdi(nvar+1:ncoef-1,nvar+1:ncoef-1)=diag(sgpp_cbdi); + % condtional on A0i, H_plus_tilde +end + + +%================================================= +% Computing the final covariance matrix for the posterior of A0, with the data +%================================================= +% +% ** some common terms +[u d v]=svd(phi,0); %trial +% xtx = phi'*phi; %trial +vd=v.*(ones(size(v,2),1)*diag(d)'); %trial +xtx=vd*vd'; +% M = eye(fss) - phi*(xtx\phi'); % not used except in line below %trial +yu = y'*u; %trial +cxyxx=yu*yu'; %trial +yty=y'*y; +ymy=yty-cxyxx; %trial +%ymy = y'*M*y; +%cxy = phi'*y; %trial +cxy = vd*yu'; %trial +cyx = cxy'; +%cxpy = xtx\cxy; %not used further except in line below +%cxyxx = cxy'*cxpy; + +% ** estimate A+_hat conditional on A0, ncoef*nvar, but not using full prior +%GlbAph = cxpy*A0h; + + +% common terms +xxhp = xtx+Hptdi; +%Lxxhpc = chol(inv(xxhp))'; % lower triangular +xxhpc = chol(xxhp); % upper triangular but its transpose is lower triagular Choleski +%A0hbH = A0hb'*H0tdi; +%====== The following two lines seem incorrect. The third line is supposed to correc the mistake. May 2003. +% H1p_1 = zeros(ncoef,nvar); +% H1p_1(1:nvar,:) = Hptdi(1:nvar,1:nvar); +H1p_1 = Hptdi(:,1:nvar); +%%Hm = (cyx+H1p_1')*(xxhp\(cxy+H1p_1)); +Hm1 = (cyx+H1p_1')/xxhp; +Hm1t = Hm1'; +%Hm2 = cxy+H1p_1; +Hm = Hm1*(cxy+H1p_1); +%%alpMpyh = A0h(stri,i)'*XX'*(yty+Hptdi(1:nvar,1:nvar)-Hm)*XX; +Hss = yty+Hptdi(1:nvar,1:nvar)-Hm; +SpH = (H0tdi+Hss)/fss; % the final S in the exponential part of p(A0|y) +% divided by nobs in order to make Choleski decomp without optimization +% or in the form conformable to Waggoner and Zha + +% *** +% *** Form the inverse of covarinace to draw from t- or Gaussian distribution +% *** +SpHs = SpH*fss; % for the Wishart draw +SpHsc = chol(SpHs); % upper triangular where Sphsc' is lower triangular Choleski +%SpHsic = chol(inv(SpHs))'; % inverse Choleski decomposition -- lower triangular + +A0hin = chol(SpH); % upper triangular, inverse of A0h, each column + % corresponds to an equation. + + +%---------------------------------------------- +% +%@@@ The following can be used for other purposes such as forecasting +% +%swish = A0hin'; % each row corresponds to an equation +%A0h = inv(A0hin); % each column corresponds to an equation +%xa0 = A0h(a0indx); + +%%*** form Bh (ncoef*nvar) +%Aplus = Hm1t*A0h; % estimate of Aplus -- the same as Astrar +%Bhp = Hm1t; diff --git a/MatlabFiles/tran_a2b.m b/MatlabFiles/tran_a2b.m index 7abce26e1cec2690853d973a2e13aa473fb41b7a..318f112ac750a2429097a56f143eab5dc069f36c 100644 --- a/MatlabFiles/tran_a2b.m +++ b/MatlabFiles/tran_a2b.m @@ -1,45 +1,45 @@ -function b = tran_a2b(A0,Ui,nvar,n0) -% b = tran_a2b(A0,Ui,nvar,n0) -% -% Transform A0 to free parameters b's. Note: columns correspond to equations -% -% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -%---------------- -% b: sum(n0)-by-1 vector of A0 free parameters -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -n0cum = cumsum(n0); -b=zeros(n0cum(end),1); -for kj = 1:nvar - if kj==1 - b(1:n0(kj))=Ui{kj}'*A0(:,kj); - else - b(n0cum(kj-1)+1:n0cum(kj))=Ui{kj}'*A0(:,kj); - end -end +function b = tran_a2b(A0,Ui,nvar,n0) +% b = tran_a2b(A0,Ui,nvar,n0) +% +% Transform A0 to free parameters b's. Note: columns correspond to equations +% +% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +%---------------- +% b: sum(n0)-by-1 vector of A0 free parameters +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +n0cum = cumsum(n0); +b=zeros(n0cum(end),1); +for kj = 1:nvar + if kj==1 + b(1:n0(kj))=Ui{kj}'*A0(:,kj); + else + b(n0cum(kj-1)+1:n0cum(kj))=Ui{kj}'*A0(:,kj); + end +end diff --git a/MatlabFiles/tran_b2a.m b/MatlabFiles/tran_b2a.m index 22b13961048a0172461d5e75c8c26b0b7debd206..c83ff1aa47a24543456c46f83c39a261ff5cbd8b 100644 --- a/MatlabFiles/tran_b2a.m +++ b/MatlabFiles/tran_b2a.m @@ -1,45 +1,45 @@ -function A0 = tran_b2a(b,Ui,nvar,n0) -% A0 = tran_b2a(b,Ui,nvar,n0) -% -% Transform free parameters b's to A0. Note: columns correspond to equations -% -% b: sum(n0)-by-1 vector of A0 free parameters -% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith -% equation contemporaneous restriction matrix where qi is the number of free parameters. -% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector -% of total original parameters and bi is a vector of free parameters. When no -% restrictions are imposed, we have Ui = I. There must be at least one free -% parameter left for the ith equation. -% nvar: number of endogeous variables -% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation -%---------------- -% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) -% -% Tao Zha, February 2000 -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - -b=b(:); -A0 = zeros(nvar); -n0cum = cumsum(n0); -for kj = 1:nvar - if kj==1 - A0(:,kj) = Ui{kj}*b(1:n0(kj)); - else - A0(:,kj) = Ui{kj}*b(n0cum(kj-1)+1:n0cum(kj)); - end -end +function A0 = tran_b2a(b,Ui,nvar,n0) +% A0 = tran_b2a(b,Ui,nvar,n0) +% +% Transform free parameters b's to A0. Note: columns correspond to equations +% +% b: sum(n0)-by-1 vector of A0 free parameters +% Ui: nvar-by-1 cell. In each cell, nvar-by-qi orthonormal basis for the null of the ith +% equation contemporaneous restriction matrix where qi is the number of free parameters. +% With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector +% of total original parameters and bi is a vector of free parameters. When no +% restrictions are imposed, we have Ui = I. There must be at least one free +% parameter left for the ith equation. +% nvar: number of endogeous variables +% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation +%---------------- +% A0: nvar-by-nvar, contempareous matrix (columns correspond to equations) +% +% Tao Zha, February 2000 +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + +b=b(:); +A0 = zeros(nvar); +n0cum = cumsum(n0); +for kj = 1:nvar + if kj==1 + A0(:,kj) = Ui{kj}*b(1:n0(kj)); + else + A0(:,kj) = Ui{kj}*b(n0cum(kj-1)+1:n0cum(kj)); + end +end diff --git a/MatlabFiles/xydata.m b/MatlabFiles/xydata.m index 59bb08118b3d9c61238e105519a8eb8d6aef194c..11da63ffda2af0be2420c047b821a59ec2a32e5d 100644 --- a/MatlabFiles/xydata.m +++ b/MatlabFiles/xydata.m @@ -1,190 +1,188 @@ -function [phi,y,fss,xtx,xty,yty,Bols] = xydata(xdgel,lags,mu) -% [phi,y,xtx,xty,yty,Bols,fss] = xydata(xdgel,lags,mu) -% Construct matrices X, Y, X'X, etc. so that y = X*B + U, where y is T-by-1, X T-by-ncoef, -% and B is ncoef-by-1. -% -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags -% lags: the lag length in the AR(p) process -% mu: 2-by-1 vector of hyperparameters for dummy observations (FRA's parameter settings) -% mu(1): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(2): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -%--------------- -% phi: X: T-by-ncoef where ncoef=nvar*lags + constant and T=fss -% y: Y: T-by-nvar where T=fss -% fss: effective sample size (including dummies if mu is provided) exclusing all lags -% xtx: X'X (Data) -% xty: X'Y (Data) -% yty: Y'Y (Data) -% Bols: ncoef-by-1: OLS estimate of B -% Copyright (c) September 1999 Tao Zha -% -% Copyright Kilian and Zha -%function [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... -% idmat0,idmatpp] = szasbvar(idfile,q_m,lags,xdgel,mu) -% Now version: [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... -% idmat0,idmatpp] = szasbvar(idfile,q_m,lags,xdgel,mu) -% -% Estimating the Bayesian VAR of Sims and Zha with asymmetric prior (as) -% -% idfile: Identification filename with rows corresponding to equations. -% But all the output will be transposed to columns -% corresponding to equations. -% q_m: quarter or month -% lags: the maximum length of lag -% nhp: number of haperparameters -% xdgel: the general matrix of the original data (no manipulation involved) -% with sample size including lags -% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) -% mu(1): overall tightness and also for A0; (0.57) -% mu(2): relative tightness for A+; (0.13) -% mu(3): relative tightness for the constant term; (0.1) -% mu(4): tightness on lag decay; (1) -% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) -% mu(6): weight on single dummy initial observation including constant -% (cointegration, unit roots, and stationarity); (5) -% -------------------- -% -------------------- -% Gb: cell(nvar,1). Each cell, postmultiplied by A0(:,i), is used to compute A+(:,i) -% where A+ is k-by-m, where k--ncnoef, m--nvar, if asymmetric prior -% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the -% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. -% Note,"bd" stands for block diagonal. -% Bh: reduced form B, k(mp+1)-by-m, column--equation. Bh=NaN if asymmetric prior. -% In the form of y=X*B+U where B=[B1|B2| ...|Bp|C] -% where Bi: m-by-m (i=1,..,p--lag length), C: 1-by-ml, constant. -% SpH: divided by T, the final S in the Waggoner-Zha exponential part of p(A0|y) -% SpH=NaN if asymmetric prior -% fss: in-sample-size (for forecasting). Including dummy observations -% ndobs: number of dummy observations, ndobs=nvar+1 -% phi: X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef -% y: y in the form y = X*B+U. Including the dummy observations too, -% T-lags+ndobs-by-nvar. -% nvar: number of variables -% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+1 -% xxhpc: chol(X'X+inv(H_p_tilde)): upper triangular but its transpose -% is lower triagular Choleski -% a0indx: the index number for free parameters in A0. Column meaning equation -% na0p: number of free parameters in A0 -% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. -% idmatpp: asymmetric prior variance for A+ without constant; column -- equation. -% -% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale -% the elements of idmat0 or idmatp so that it carries information about relative -% prior variances. -% Revsions by TZ, 10/13/96: Efficiency improvement by streamlining the previous -% code according to the general setup in Sims and Zha's IER and according -% to Zha's notes Forecast (0) (p.3) and Forecast (1) (p.9). -% -% Copyright (c) September 1999 by Tao Zha -% -% NOTE: "nSample" is something I deleted as an input recently, so it may not -% be compatible with old programs, 10/15/98 by TAZ. -% -% NOTE2: I put "mu" as an input arg and delete "nhp" as an input arg, so it may -% not be compatible with old programs, 03/06/99 by TAZ -% Copyright (C) 1997-2012 Christopher A. Sims and Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[nSample,nvar]=size(xdgel); % sample size including lags and number of variables -ncoef=nvar*lags+1; % number of coefficients in *each* equation, RHS coefficients only, - % with only constant -ndobs=nvar+1; % number of dummy observations -sb = lags+1; % the beginning of original sample without dummies - -if nargin==3 % activate the option of dummy observations - fss = nSample+ndobs-lags; - % Effective sample size including dummies but exclusing all lags - - % - % **** nvar prior dummy observations with the sum of coefficients - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] - % ** Now, T=T+ndobs -- added with "ndobs" dummy observations - % - phi = zeros(fss,ncoef); - const = ones(fss,1); - const(1:nvar) = zeros(nvar,1); - % the first nvar periods: no or zero constant (designed for dummies)! - phi(:,ncoef) = const; - % - xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions - %**** Dummies for phi - for k=1:nvar - for m=1:lags - phi(ndobs,nvar*(m-1)+k) = xdgelint(k); - phi(k,nvar*(m-1)+k) = xdgelint(k); - % <<>> multiply hyperparameter later - end - end - %* True data for phi - for k=1:lags - phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] - % Thus, # of columns is nvar*lags+1 = ncoef. - end - % - % ** Y with "ndobs" dummies added - y = zeros(fss,nvar); - %* Dummies for y - for k=1:nvar - y(ndobs,k) = xdgelint(k); - y(k,k) = xdgelint(k); - % multiply hyperparameter later - end - %* True data for y - y(ndobs+1:fss,:) = xdgel(sb:nSample,:); - % - %*** Dummies once again (finfal version) - phi(1:nvar,:) = 1*mu(1)*phi(1:nvar,:); % standard Sims and Zha prior - y(1:nvar,:) = mu(1)*y(1:nvar,:); % standard Sims and Zha prior - % - phi(nvar+1,:) = mu(2)*phi(nvar+1,:); - y(nvar+1,:) = mu(2)*y(nvar+1,:); -else % dummy observations - fss = nSample-lags; - % Effective sample size with no dummies but exclusing all lags - - % - % **** nvar prior dummy observations with the sum of coefficients - % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar - % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] - % ** Now, T=T+ndobs -- added with "ndobs" dummy observations - % - phi = zeros(fss,ncoef); - const = ones(fss,1); - phi(:,ncoef) = const; - %* True data for phi - for k=1:lags - phi(1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); - % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] - % Thus, # of columns is nvar*lags+1 = ncoef. - end - % - %* True data for y - y(1:fss,:) = xdgel(sb:nSample,:); -end -%*** data input for the posterior density -[xq,xr]=qr(phi,0); -xtx=xr'*xr; % X'X -xty=phi'*y; % X'Y -yty = y'*y; % Y'Y - -Bols = xr\(xr'\xty); % inv(X'X)*X'Y - +function [phi,y,fss,xtx,xty,yty,Bols] = xydata(xdgel,lags,mu) +% [phi,y,xtx,xty,yty,Bols,fss] = xydata(xdgel,lags,mu) +% Construct matrices X, Y, X'X, etc. so that y = X*B + U, where y is T-by-1, X T-by-ncoef, +% and B is ncoef-by-1. +% +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags +% lags: the lag length in the AR(p) process +% mu: 2-by-1 vector of hyperparameters for dummy observations (FRA's parameter settings) +% mu(1): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(2): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +%--------------- +% phi: X: T-by-ncoef where ncoef=nvar*lags + constant and T=fss +% y: Y: T-by-nvar where T=fss +% fss: effective sample size (including dummies if mu is provided) exclusing all lags +% xtx: X'X (Data) +% xty: X'Y (Data) +% yty: Y'Y (Data) +% Bols: ncoef-by-1: OLS estimate of B +% +%function [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... +% idmat0,idmatpp] = szasbvar(idfile,q_m,lags,xdgel,mu) +% Now version: [Gb,Sbd,Bh,SpH,fss,ndobs,phi,y,nvar,ncoef,xxhpc,a0indx,na0p,... +% idmat0,idmatpp] = szasbvar(idfile,q_m,lags,xdgel,mu) +% +% Estimating the Bayesian VAR of Sims and Zha with asymmetric prior (as) +% +% idfile: Identification filename with rows corresponding to equations. +% But all the output will be transposed to columns +% corresponding to equations. +% q_m: quarter or month +% lags: the maximum length of lag +% nhp: number of haperparameters +% xdgel: the general matrix of the original data (no manipulation involved) +% with sample size including lags +% mu: 6-by-1 vector of hyperparameters (the following numbers for Atlanta Fed's forecast) +% mu(1): overall tightness and also for A0; (0.57) +% mu(2): relative tightness for A+; (0.13) +% mu(3): relative tightness for the constant term; (0.1) +% mu(4): tightness on lag decay; (1) +% mu(5): weight on nvar sums of coeffs dummy observations (unit roots); (5) +% mu(6): weight on single dummy initial observation including constant +% (cointegration, unit roots, and stationarity); (5) +% -------------------- +% -------------------- +% Gb: cell(nvar,1). Each cell, postmultiplied by A0(:,i), is used to compute A+(:,i) +% where A+ is k-by-m, where k--ncnoef, m--nvar, if asymmetric prior +% Sbd: cell(nvar,1). Sbd=diag(S(1), ..., S(m)). Already divided by 'fss' for the +% posterior of a0 or A0(:) in Waggoner and Zha when one has asymmetric prior. +% Note,"bd" stands for block diagonal. +% Bh: reduced form B, k(mp+1)-by-m, column--equation. Bh=NaN if asymmetric prior. +% In the form of y=X*B+U where B=[B1|B2| ...|Bp|C] +% where Bi: m-by-m (i=1,..,p--lag length), C: 1-by-ml, constant. +% SpH: divided by T, the final S in the Waggoner-Zha exponential part of p(A0|y) +% SpH=NaN if asymmetric prior +% fss: in-sample-size (for forecasting). Including dummy observations +% ndobs: number of dummy observations, ndobs=nvar+1 +% phi: X in the form of y = X*B+U. Row: nSmaple-lags+ndobs. Column: ncoef +% y: y in the form y = X*B+U. Including the dummy observations too, +% T-lags+ndobs-by-nvar. +% nvar: number of variables +% ncoef: number of coefficients in *each* equation. RHS coefficients only, nvar*lags+1 +% xxhpc: chol(X'X+inv(H_p_tilde)): upper triangular but its transpose +% is lower triagular Choleski +% a0indx: the index number for free parameters in A0. Column meaning equation +% na0p: number of free parameters in A0 +% idmat0: identification matrix for A0 with asymmetric prior; column -- equation. +% idmatpp: asymmetric prior variance for A+ without constant; column -- equation. +% +% Revisions by CAS 9/27/96: If we transmit idmat, rather than a0indx, we can scale +% the elements of idmat0 or idmatp so that it carries information about relative +% prior variances. +% Revsions by TZ, 10/13/96: Efficiency improvement by streamlining the previous +% code according to the general setup in Sims and Zha's IER and according +% to Zha's notes Forecast (0) (p.3) and Forecast (1) (p.9). +% +% +% NOTE: "nSample" is something I deleted as an input recently, so it may not +% be compatible with old programs, 10/15/98 by TAZ. +% +% NOTE2: I put "mu" as an input arg and delete "nhp" as an input arg, so it may +% not be compatible with old programs, 03/06/99 by TAZ +% +% +% Copyright (C) 1997-2012 Lutz Kilian and Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[nSample,nvar]=size(xdgel); % sample size including lags and number of variables +ncoef=nvar*lags+1; % number of coefficients in *each* equation, RHS coefficients only, + % with only constant +ndobs=nvar+1; % number of dummy observations +sb = lags+1; % the beginning of original sample without dummies + +if nargin==3 % activate the option of dummy observations + fss = nSample+ndobs-lags; + % Effective sample size including dummies but exclusing all lags + + % + % **** nvar prior dummy observations with the sum of coefficients + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] + % ** Now, T=T+ndobs -- added with "ndobs" dummy observations + % + phi = zeros(fss,ncoef); + const = ones(fss,1); + const(1:nvar) = zeros(nvar,1); + % the first nvar periods: no or zero constant (designed for dummies)! + phi(:,ncoef) = const; + % + xdgelint = mean(xdgel(1:lags,:),1); % mean of the first lags initial conditions + %**** Dummies for phi + for k=1:nvar + for m=1:lags + phi(ndobs,nvar*(m-1)+k) = xdgelint(k); + phi(k,nvar*(m-1)+k) = xdgelint(k); + % <<>> multiply hyperparameter later + end + end + %* True data for phi + for k=1:lags + phi(ndobs+1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] + % Thus, # of columns is nvar*lags+1 = ncoef. + end + % + % ** Y with "ndobs" dummies added + y = zeros(fss,nvar); + %* Dummies for y + for k=1:nvar + y(ndobs,k) = xdgelint(k); + y(k,k) = xdgelint(k); + % multiply hyperparameter later + end + %* True data for y + y(ndobs+1:fss,:) = xdgel(sb:nSample,:); + % + %*** Dummies once again (finfal version) + phi(1:nvar,:) = 1*mu(1)*phi(1:nvar,:); % standard Sims and Zha prior + y(1:nvar,:) = mu(1)*y(1:nvar,:); % standard Sims and Zha prior + % + phi(nvar+1,:) = mu(2)*phi(nvar+1,:); + y(nvar+1,:) = mu(2)*y(nvar+1,:); +else % dummy observations + fss = nSample-lags; + % Effective sample size with no dummies but exclusing all lags + + % + % **** nvar prior dummy observations with the sum of coefficients + % ** construct X for Y = X*B + U where phi = X: (T-lags)*k, Y: (T-lags)*nvar + % ** columns: k = # of [nvar for 1st lag, ..., nvar for last lag, const] + % ** Now, T=T+ndobs -- added with "ndobs" dummy observations + % + phi = zeros(fss,ncoef); + const = ones(fss,1); + phi(:,ncoef) = const; + %* True data for phi + for k=1:lags + phi(1:fss,nvar*(k-1)+1:nvar*k) = xdgel(sb-k:nSample-k,:); + % row: T-lags; column: [nvar for 1st lag, ..., nvar for last lag, const] + % Thus, # of columns is nvar*lags+1 = ncoef. + end + % + %* True data for y + y(1:fss,:) = xdgel(sb:nSample,:); +end +%*** data input for the posterior density +[xq,xr]=qr(phi,0); +xtx=xr'*xr; % X'X +xty=phi'*y; % X'Y +yty = y'*y; % Y'Y + +Bols = xr\(xr'\xty); % inv(X'X)*X'Y + diff --git a/MatlabFiles/zimpulse.m b/MatlabFiles/zimpulse.m index 70db3814dffd6270ea72cea7d2791708fe1b5ce5..1829a17861c5d6fceb1025877bb7997be1474b21 100644 --- a/MatlabFiles/zimpulse.m +++ b/MatlabFiles/zimpulse.m @@ -1,72 +1,71 @@ -function imf = zimpulse(Bh,swish,nn) -% Computing impulse functions with -% imf = zimpulse(Bh,swish,nn) -% where imf is in a format that is the SAME as in RATS. -% Column: nvar responses to 1st shock, -% nvar responses to 2nd shock, and so on. -% Row: steps of impulse responses. -% Bh is the estimated reduced form coefficient in the form -% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix -% form or dimension is the same as "Bh" from the function "sye"; -% swish is the inv(A0) in the structural model A(L)y(t) = e(t). -% nn is the numbers of inputs [nvar,lags,# of impulse responses]. -% Written by Tao Zha -% -% Copyright (c) 1994 by Tao Zha -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -nvar = nn(1); -lags = nn(2); -imstep = nn(3); % number of steps for impulse responses - -Ah = Bh'; -% Row: nvar equations -% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. - -imf = zeros(imstep,nvar*nvar); -% Column: nvar responses to 1st shock, nvar responses to 2nd shock, and so on. -% Row: steps of impulse responses. -M = zeros(nvar*(lags+1),nvar); -% Stack lags M's in the order of, e.g., [Mlags, ..., M2,M1;M0] -M(1:nvar,:) = swish; -Mtem = M(1:nvar,:); % temporary M. -% first (initial) responses to 1 standard deviation shock. Row: responses; Column: shocks -% * put in the form of "imf" -imf(1,:) = Mtem(:)'; - -t = 1; -ims1 = min([imstep-1 lags]); -while t <= ims1 - Mtem = Ah(:,1:nvar*t)*M(1:nvar*t,:); - % Row: nvar equations, each for the nvar variables at tth lag - M(nvar+1:nvar*(t+1),:)=M(1:nvar*t,:); - M(1:nvar,:) = Mtem; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. - t= t+1; -end - -for t = lags+1:imstep-1 - Mtem = Ah(:,1:nvar*lags)*M(1:nvar*lags,:); - % Row: nvar equations, each for the nvar variables at tth lag - M(nvar+1:nvar*(t+1),:) = M(1:nvar*t,:); - M(1:nvar,:)=Mtem; - imf(t+1,:) = Mtem(:)'; - % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. -end \ No newline at end of file +function imf = zimpulse(Bh,swish,nn) +% Computing impulse functions with +% imf = zimpulse(Bh,swish,nn) +% where imf is in a format that is the SAME as in RATS. +% Column: nvar responses to 1st shock, +% nvar responses to 2nd shock, and so on. +% Row: steps of impulse responses. +% Bh is the estimated reduced form coefficient in the form +% Y(T*nvar) = XB + U, X: T*k, B: k*nvar. The matrix +% form or dimension is the same as "Bh" from the function "sye"; +% swish is the inv(A0) in the structural model A(L)y(t) = e(t). +% nn is the numbers of inputs [nvar,lags,# of impulse responses]. +% Written by Tao Zha +% +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +nvar = nn(1); +lags = nn(2); +imstep = nn(3); % number of steps for impulse responses + +Ah = Bh'; +% Row: nvar equations +% Column: 1st lag (with nvar variables) to lags (with nvar variables) + const = k. + +imf = zeros(imstep,nvar*nvar); +% Column: nvar responses to 1st shock, nvar responses to 2nd shock, and so on. +% Row: steps of impulse responses. +M = zeros(nvar*(lags+1),nvar); +% Stack lags M's in the order of, e.g., [Mlags, ..., M2,M1;M0] +M(1:nvar,:) = swish; +Mtem = M(1:nvar,:); % temporary M. +% first (initial) responses to 1 standard deviation shock. Row: responses; Column: shocks +% * put in the form of "imf" +imf(1,:) = Mtem(:)'; + +t = 1; +ims1 = min([imstep-1 lags]); +while t <= ims1 + Mtem = Ah(:,1:nvar*t)*M(1:nvar*t,:); + % Row: nvar equations, each for the nvar variables at tth lag + M(nvar+1:nvar*(t+1),:)=M(1:nvar*t,:); + M(1:nvar,:) = Mtem; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. + t= t+1; +end + +for t = lags+1:imstep-1 + Mtem = Ah(:,1:nvar*lags)*M(1:nvar*lags,:); + % Row: nvar equations, each for the nvar variables at tth lag + M(nvar+1:nvar*(t+1),:) = M(1:nvar*t,:); + M(1:nvar,:)=Mtem; + imf(t+1,:) = Mtem(:)'; + % stack imf with each step, Row: 6 var to 1st shock, 6 var to 2nd shock, etc. +end diff --git a/MatlabFiles/zroot.m b/MatlabFiles/zroot.m index 033590ba213d609b52941e4870ba0d0f4d9a3fd1..01f464ea26946600b411f010ced14ca498ca4799 100644 --- a/MatlabFiles/zroot.m +++ b/MatlabFiles/zroot.m @@ -1,46 +1,46 @@ -function zstar = zroot(B) -% zroot(B); find roots of a matrix polynomial -% B: the 3 dimensional array B, e.g. B(:,:,1) is B_1, B(:,:,2) is B_2 and -% B(:,:,p) is B_p. Note: rows correpond to equations. See Judge (1), pp. 763-764. -% For the system of equations: -% y_t = B_1*y_{t-1} + ... + B_p*Y_{t-p} + u_t. -% The corresponding matrix polynomial is: -% det(eye(m)-B_1*z-...-B_p*z^p) = 0 -% zroot(B) solves for the roots of this above polynomial. The matrices B_1, B_2,....B_p -% are passed through B. The degree of the matrix polynomial is determined -% by the size of the third dimension of B. -% Each of the B(:,:,i) must be an m by m matrix. - -% ZROOT was written by Clark A. Burdick of the research -% department of the Federal Reserve Bank of Atlanta. -% Original: July 31, 1997 -% Last Modified: July 31, 1997 - -% TO BE DONE: -% Better bullet proofing -% Copyright (C) 1997-2012 Tao Zha -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see <http://www.gnu.org/licenses/>. - - -[a b c] = size(B); -syms z; -thepoly = eye(size(B(:,:,1)))-B(:,:,1)*z; -for i=2:c - thepoly = thepoly-B(:,:,i)*z^i; -end -zstar=roots(sym2poly(det(thepoly))); - +function zstar = zroot(B) +% zroot(B); find roots of a matrix polynomial +% B: the 3 dimensional array B, e.g. B(:,:,1) is B_1, B(:,:,2) is B_2 and +% B(:,:,p) is B_p. Note: rows correpond to equations. See Judge (1), pp. 763-764. +% For the system of equations: +% y_t = B_1*y_{t-1} + ... + B_p*Y_{t-p} + u_t. +% The corresponding matrix polynomial is: +% det(eye(m)-B_1*z-...-B_p*z^p) = 0 +% zroot(B) solves for the roots of this above polynomial. The matrices B_1, B_2,....B_p +% are passed through B. The degree of the matrix polynomial is determined +% by the size of the third dimension of B. +% Each of the B(:,:,i) must be an m by m matrix. + +% ZROOT was written by Clark A. Burdick of the research +% department of the Federal Reserve Bank of Atlanta. +% Original: July 31, 1997 +% Last Modified: July 31, 1997 + +% TO BE DONE: +% Better bullet proofing +% +% Copyright (C) 1997-2012 Tao Zha +% +% This free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% It is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% If you did not received a copy of the GNU General Public License +% with this software, see <http://www.gnu.org/licenses/>. +% + + +[a b c] = size(B); +syms z; +thepoly = eye(size(B(:,:,1)))-B(:,:,1)*z; +for i=2:c + thepoly = thepoly-B(:,:,i)*z^i; +end +zstar=roots(sym2poly(det(thepoly))); +