% Code from Mertens and Ravn (2018) modified by Dias and Duarte
% All mistakes are our own. Please email joao.duarte@novasbe.pt for any
% mistakes or bugs found.
% last update: 8/10/2018

% DESCRIPTION
%
% Report the F-statistc and R-squared of figure 1. 
% F-statistics and R-squared can be obtained for other models or
% instruments by changing the variables or proxy.

clear all; close all; 
addpath('auxiliary files')

% Create DATASET
%%%%%%%%%%%%%%%%
mdata = xlsread('datasets/data/monthly_data.xlsx');
%mdata(:,15) = mdata(:,15)./mdata(:,3);
%mdata(:,11) = mdata(:,11)./mdata(:,3); % compute real rents
mdata(:,3:4) = log(mdata(:,3:4))*100;
mdata(:,11:15) = log(mdata(:,11:15))*100;
mdata(isnan(mdata))=0;
mdata = mdata(43:end,:); % Activate to start the sample in 1983 
% 1 year	2 month	3 cpi 4 ip 5 ff	6 gs1	7 gs2	8 ebp  9
% mortg_spread_m	10 cp3m_spread_m 11 Rents 12 CPINET 13 PCE 14 PCENET 15
% Shelter

pdata = xlsread('datasets/data/monthly_factors.xlsx');
ppdata = zeros(length(mdata),size(pdata,2));
ppdata(end-length(pdata)-12+1:end-12,:) = pdata;
% 1 year	2 month	3 mp1_tc 4 ff4_tc	5 ed2_tc	6 ed3_tc	7 ed4_tc

DATASET.TSERIES = [mdata ppdata(:,3:end)];
DATASET.LABEL   = {'YEAR','MONTH','CPI','IP','FF','GS1','GS2','EBP','MSPREAD','CPSPREAD','RENTS','CPINET','PCE', 'PCENET', 'Shelter','MP1','FF4','ED2','ED3','ED4'};
DATASET.UNIT    = [0         0      1     1    2    2     2     2       2       2    2      2     2     2     2     2  2 2 2 ]; 
DATASET.FIGLABELS= [{'YEAR','MONTH','Price Level','Industrial Production','Federal Funds Rate','One-Year Rate','Two-Year Rate','Excess Bond Premium','MSPREAD','CPSPREAD','Housing Rents','CPI Net of Shelter','PCE', 'PCE Net of Shelter','Shelter','MP1','FF4','ED2','ED3','ED4'};];  
DATASET.MAP = containers.Map(DATASET.LABEL,1:size(DATASET.TSERIES,2));

% VAR specification
%%%%%%%%%%%%%%%%%%%%
VAR.p      = 12;                                % Number of Lags
VAR.irhor  = 48;                                % Impulse Response Horizon
VAR.select_vars      = {'GS1','IP','EBP','CPI','RENTS'};
VAR.vars             = DATASET.TSERIES(:,cell2mat(values(DATASET.MAP,VAR.select_vars)));
VAR.MAP              = containers.Map([VAR.select_vars],[1:size(VAR.vars,2)]);
VAR.proxies          = DATASET.TSERIES(:,cell2mat(values(DATASET.MAP,{'FF4'})));
VAR.DET              = ones(length(VAR.vars),1); % Deterministic Terms

VAR        = doProxySVAR(VAR);

tbl = table(VAR.m(85:end-12), VAR.res(85:end-12,1), 'VariableNames',{'proxy','res'});

mdl = fitlm(tbl,'res ~ proxy', 'Intercept', true);

R2 = mdl.Rsquared;

F = anova(mdl);

disp("The R-Squared is " + R2.Adjusted)
disp("And the F-statistic is " + F{1,4})

