%bootb.m
%
%For given VAR coefficient estimates and residuals, this program
%generates artificial dataset and estimates new VAR coefficients
%
%Program recenters and rescales residuals but does not compute the bias
%adjustment of the original VAR coefficient estimates as suggested by
%Kilian [1998] (bootstrap-after-boostrap), nor does it take into account lag
%order uncertainty as suggested by Kilian [1998].
%
%Written and last modified by André Kurmann, UQAM, August 9, 2005
%--------------------------------------------------------------------------

function bhat=bootb(b,REG,e,p,nconst)

[T,n]=size(e);

%recenter the residuals e(t) and rescale them to ensure desired variance
%(see Berkowitz and Kilian (2000), p.5)
e=(e-ones(T,1)*mean(e))*sqrt(T/(T-2*p));

%generate T random draws with replacement from e(t)
select=ceil(rand(T,1)*T);			%ceil = rounds up to next integer
u=e(select,:);

% 4b: randomly select block of size p of starting values (see Berkowitz and Kilian (2000), p.6)
select=ceil(rand(1,1)*T);
REGhat=REG(select,:);

% 4c: create simulated dataset
for i=1:T;
   Yhat(i,:)=REGhat(i,:)*b+u(i,:);
   if nconst==0;
       REGhat(i+1,:)=[Yhat(i,:) REGhat(i,1:n*(p-1))];
   elseif nconst==1;
       REGhat(i+1,:)=[Yhat(i,:) REGhat(i,1:n*(p-1)) 1];
   end
end
REGhat=REGhat(1:T,:);

%simulated coeff estimates
bhat=inv(REGhat'*REGhat)*REGhat'*Yhat;