%% Bootstrap Confidence Intervals on True IRF
% Consider the 4-D VAR(2) model in docid:econ_ug#mw_b768a60b-6d29-45be-9ae9-71800a1720f4. Estimate and plot its orthogonalized IRF and 90% bootstrap confidence intervals on the true IRF.
% Load the Danish money and income data set, then estimate the VAR(2) model. Return the  residuals from model estimation.

load Data_JDanish

Mdl = varm(4,2);
Mdl.SeriesNames = DataTable.Properties.VariableNames;
[Mdl,~,~,E] = estimate(Mdl,DataTable.Series);
T = size(DataTable,1) % Total sample size
n = size(E,1)         % Effective sample size

% E is a 53-by-4 array of residuals.  Columns correspond to the variables in Mdl.SeriesNames. The estimate function requires Mdl.P = 2 observations to initialize a VAR(2) model for estimation. Because presample data (Y0) is unspecified, estimate takes the first two observations in the specified response data to initialize the model.  Therefore, the resulting effective sample size is T – Mdl.P = 53, and rows of E correspond to the observation indices 3 through T.
%
% Estimate the orthogonalized IRF and corresponding 90% bootstrap confidence intervals from the estimated VAR(2) model. Draw 500 paths of length n from the series of residuals.

rng(1); % For reproducibility
[Response,Lower,Upper] = irf(Mdl,"E",E,"NumPaths",500,...
    "Confidence",0.9);

%
% Plot the orthogonalized IRF with its confidence bounds of the bond rate when real income is shocked at time 0.

irfshock2resp3 = Response(:,2,3);
IRFCIShock2Resp3 = [Lower(:,2,3) Upper(:,2,3)];

figure;
h1 = plot(0:19,irfshock2resp3);
hold on
h2 = plot(0:19,IRFCIShock2Resp3,'r--');
legend([h1 h2(1)],["IRF" "90% Confidence Interval"])
xlabel("Time Index");
ylabel("Response");
title("IRF of IB When Y Is Shocked");
grid on
hold off

% The effect of the impulse to real income on the bond rate fades after 10 periods.
% Copyright 2018 The MathWorks, Inc.