%sgu_tot_run_baaff.m estimates country-by-country  SVARs for the vector x_t = [spread_t tot_t  tb_t gdp_t c_t i_t rer_t] with an intercept. Omitting the intercept, the program delivers the matrices hx and PI in  x_t = hx x_{t-1} + PI eps_t, where eps_t~(0,I).  It also computes the share of the variances of these 6 variables explained by tot shocks. 
%(c) Stephanie Schmitt-Grohe and Martín Uribe, December 2014

clear all

%Baseline case: Quadratic Detrending
load detrend_data.mat  DD country_name   ndate ntot ntb ngdp nc ni nrer nbaaff
%produced by running  detrend_data.m in directory Z:\uribe\tot\IER\mfiles and
%setting method = 'time'

%HP Filtering: 
%load detrend_data_HP.mat  DD country_name   ndate ntot ntb ngdp nc ni nrer
%produced with detrend_data.m in directory Z:\uribe\tot\IER\mfiles and
%setting method = 'HP'

ncou = length(DD);
nv = size(DD{1},2)-1; %eliminated  column is the year 
v_share = zeros(ncou,nv);
R2 = zeros(nv,ncou);
U = cell(0);
R = ones(nv);
R(1,3:end) = 0;
R(2,3:end) = 0;
y0 = zeros(ncou,nv);
T = 11; %length of impulse responses;

for k=1:ncou
%construct current and lagged data for country k
d = DD{k}(:,[nbaaff ntot ntb ngdp nc ni nrer]);
y0(k,:) = d(1,:);
 [hx(:,:,k),PI(:,:,k),R2(:,k),A(:,:,k),B(:,:,k),stdu(:,k),U{k}] = svar_estim(d,R,0);
%estimates by OLS the system 
%x_t = Bx_t-1 + Ax_t + u_t, and set PI = (I-A)\B and PI= (I-A)\diag(stdu) (note: by construction, the var-cov of u_t is diagonal), to get x_t = hx x_t-1 +PIe_t, where u_t = PI e_t

[~,vdx]=variance_decomposition(eye(nv),hx(:,:,k),PI(:,:,k));
v_share(k,:) = vdx(2,:)*100;
v_share_rshock(k,:) = vdx(1,:)*100;

%Impulse Responses
x0 = PI(:,2,k)/PI(2,2,k);
x =ir(eye(nv),hx(:,:,k),x0,T);
IR(:,:,k) = x(:,1:nv);

end

save sgu_tot_run_baaff_first.mat U PI hx y0 v_share IR country_name R2
%save sgu_tot_run_baaff_HP.mat U PI hx y0 v_share IR country_name R2