%% Compare Several VAR Model Fits
% Consider these four VAR models of consumer price index (CPI) and unemployment rate: VAR(0), VAR(1), VAR(4), and VAR(8). Using historical data, estimate each, and then compare the model fits using the resulting BIC.
% Load the Data_USEconModel data set. Declare variables for the consumer price index (CPI) and unemployment rate (UNRATE) series. Remove any missing values from the beginning of the series.

load Data_USEconModel
cpi = DataTable.CPIAUCSL;
unrate = DataTable.UNRATE;
idx = all(~isnan([cpi unrate]),2);
cpi = cpi(idx);
unrate = unrate(idx);

%
% Stabilize CPI by converting it to a series of growth rates. Synchronize the two series by removing the first observation from the unemployment rate series.

rcpi = price2ret(cpi);
unrate = unrate(2:end);

%
% Within a loop:
% Create a VAR model using the shorthand syntax.
% Estimate the VAR Model. Reserve the maximum value of p as presample observations.
% Store the estimation results.

numseries = 2;
p = [0 1 4 8];
estMdlResults = cell(numel(p),1); % Preallocation
Y0 = [rcpi(1:max(p)) unrate(1:max(p))];
Y = [rcpi((max(p) + 1):end) unrate((max(p) + 1):end)];

for j = 1:numel(p)
    Mdl = varm(numseries,p(j));
    EstMdl = estimate(Mdl,Y,'Y0',Y);
    estMdlResults{j} = summarize(EstMdl);
end

% estMdlResults is a 4-by-1 cell array of structure arrays containing the estimation results of each model.
%
% Extract the BIC from each set of results.

BIC = cellfun(@(x)x.BIC,estMdlResults)

% The model corresponding to the lowest BIC has the best fit among the models considered. Therefore, the VAR(4) is the best fitting model.
% Copyright 2012 The MathWorks, Inc.