%% Infer VAR(4) Model Innovations
% Fit a VAR(4) model to the consumer price index (CPI) and unemployment rate data. Then, infer the model innovations using the estimated model.
% Load the Data_USEconModel data set.

load Data_USEconModel

%
% Plot the two series on separate plots.

figure;
plot(DataTable.Time,DataTable.CPIAUCSL);
title('Consumer Price Index');
ylabel('Index');
xlabel('Date');
figure;
plot(DataTable.Time,DataTable.UNRATE);
title('Unemployment Rate');
ylabel('Percent');
xlabel('Date');

%
% Stabilize the 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(DataTable.CPIAUCSL);
unrate = DataTable.UNRATE(2:end);

%
% Create a default VAR(4) model using the shorthand syntax.

Mdl = varm(2,4);

%
% Estimate the model using the entire data set.

EstMdl = estimate(Mdl,[rcpi unrate]);

% EstMdl is a fully specified, estimated varm model object.
%
% Infer innovations from the estimated model.

E = infer(EstMdl,[rcpi unrate]);

% E is a 241-by-2 matrix of inferred innovations. The first and second columns contain the residuals corresponding to the CPI growth rate and unemployment rate, respectively.
% Alternatively, you can return residuals when you call estimate by supplying an output variable in the fourth position.
%
% Plot the residuals on separate plots. Synchronize the residuals with the dates by removing any missing observations from the data and removing the first Mdl.P dates.

idx = all(~isnan([rcpi unrate]),2);
datesr = DataTable.Time(idx);

figure;
plot(datesr((Mdl.P + 1):end),E(:,1));
ylabel('Consumer price index');
xlabel('Date');
title('Residual plot');
hold on
plot([min(datesr) max(datesr)],[0 0],'r--');
hold off

figure;
plot(datesr((Mdl.P + 1):end),E(:,2));
ylabel('Unemployment rate');
xlabel('Date');
title('Residual plot');
hold on
plot([min(datesr) max(datesr)],[0 0],'r--');
hold off

% The residuals corresponding to the CPI growth rate exhibit heteroscedasticity because the series appears to cycle through periods of higher and lower variance.
% Copyright 2012 The MathWorks, Inc.