%% Coefficients and bands for alternative measures of financial conditions
% This script produces charts of estimated quantile regression coefficients
% with bootstrapped confidence bands for alternative measures of financial
% conditions and NFCI subcomponents, presented in the following figures:
% - Figure A.6. GDP Growth and Other Predictors.
% - Figure A.7. GDP Growth and Subcomponents of NFCI.
% 
% From the replication files for:
% Tobias Adrian, Nina Boyarchenko, and Domenico Giannone (2018):
% "Vulnerable Growth," American Economic Review.
%% Clear workspace, set file paths and graphics settings
clear
close all
clc

set(0, 'defaultAxesFontName', 'Times');
set(0, 'DefaultAxesFontSize',15)
set(0, 'defaultAxesLineStyleOrder', '-|--|:', 'defaultLineLineWidth', 1.5)
setappdata(0, 'defaultAxesXTickFontSize', 1)
setappdata(0, 'defaultAxesYTickFontSize', 1)

% Folder to store figures
FigSubFolder = 'FigAlternativeMeasures';
if ~exist(FigSubFolder, 'dir')
    mkdir(FigSubFolder);
end

%% Load data and fix forecast settings
load('DataVulnerabilityAppendix.mat', 'X', 'Time', 'Mnem')
% Use 1973Q1-2015Q4 subsample
jtFirst = find(year(Time) == 1973 & month(Time) ==  1);
jtLast  = find(year(Time) == 2015 & month(Time) == 10);
Time = Time(jtFirst:jtLast);
X = X(jtFirst:jtLast, :);
clear('jtFirst', 'jtLast')

% Forecast settings
H = [1, 4];          % Horizons to forecast (# of quarters ahead)
QQ = 0.05:0.05:0.95; % Quantiles to estimate in quantile regressions

% Construct average growth rates
y = X(:, strcmp(Mnem, 'A191RL1Q225SBEA'));
for h = H
    Yh(:, h) = filter(ones(1, h) / h, 1, y);
    Yh(1:(h - 1), h) = NaN;
end

% Bootstrap settings
nDrawsBoot = 1000; % number of bootstrap replications
nLagsBootVAR = 4;  % number of lags to use in approximating VAR

%% Estimate quantile regressions, generate bootstrapped confidence bands
regressorNamesFull  = {'VXO', 'CredSpread', 'TermSpread', 'NFCIRISK', 'NFCICREDIT', 'NFCILEVERAGE'};
regressorNamesShort = {'VXO', 'CS',         'TS',         'RISK',     'CRED',       'LEV'};
ylimsRegressors = [
    -0.3,  0.2;
    -4.0,  3.0;
    -0.2,  1.6;
    -2.5,  1.5;
    -3.0,  1.5;
    -3.0,  0.0
];

for iRegressor = 1:length(regressorNamesFull)
    % Quantile regressions include a single alternative measure and GDP
    Res = QRboot(X(:, strcmp(Mnem, regressorNamesFull{iRegressor})), y, H, 1, QQ,...
                 nDrawsBoot, nLagsBootVAR);
    j = 2; % j denotes the column index within the matrix of regressors for
           % the regressor of interest
    ylims = ylimsRegressors(iRegressor, :);
    for h = H
        BQ = Res.BQ(j, :, h);
        B2 = Res.B2(j, h);
        bBQ = squeeze(Res.bBQ(j,:,h,:));
        bB2 = squeeze(Res.bB2(j,h,:));
        filename = fullfile(FigSubFolder, ['GDPv', regressorNamesShort{iRegressor}, '_coefs_Q', num2str(h), '.pdf']);
        PlotQRbands(BQ, bBQ, B2, bBQ, QQ,...
                    'ylims', ylims, 'filename', filename);
    end
end