%% Simulate Response Series from VAR(4) Model
% Fit a VAR(4) model to the consumer price index (CPI) and unemployment rate data. Then, simulate responses from 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. Create a new data set containing the transformed variables, and do not include any rows containing at least one missing observation.

rcpi = price2ret(DataTable.CPIAUCSL);
unrate = DataTable.UNRATE(2:end);
dates = DataTable.Time(2:end);
idx = all(~ismissing([rcpi unrate]),2);
Data = array2timetable([rcpi(idx) unrate(idx)],...
    'RowTimes',DataTable.Time(idx),'VariableNames',{'rcpi','unrate'});

%
% 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,Data.Variables);

% EstMdl is a fully specified, estimated varm model object.
%
% Simulate a response series path from the estimated model with length equal to the path in the data.

rng(1); % For reproducibility
numobs = size(Data,1);
Y = simulate(EstMdl,numobs);

% Y is a 245-by-2 matrix of simulated responses. The first and second columns contain the simulated CPI growth rate and unemployment rate, respectively.
%
% Plot the simulated and true responses.

figure;
plot(Data.Time,Y(:,1));
hold on;
plot(Data.Time,Data.rcpi)
title('CPI Growth Rate');
ylabel('Growth rate');
xlabel('Date');
legend('Simulation','True')

figure;
plot(Data.Time,Y(:,2));
hold on;
plot(Data.Time,Data.unrate)
ylabel('Percent');
xlabel('Date');
title('Unemployment Rate');
legend('Simulation','True')

% Copyright 2012 The MathWorks, Inc.