%% Forecast Responses from Posterior Predictive Distribution
% Consider the 3-D VAR(4) model for the US inflation (INFL), unemployment (UNRATE), and federal funds (FEDFUNDS) rates.
% \left[ {\begin{array}{*{20}{l}}
% {\texttt{INFL}_t}\\
% {\texttt{UNRATE}_t}\\
% {\texttt{FEDFUNDS}_t}
% \end{array}} \right] = c + \sum\limits_{j = 1}^4 {{\Phi _j}\left[ {\begin{array}{*{20}{l}}
% {\texttt{INFL}_{t-j}\\
% {\texttt{UNRATE}_{t-j}\\
% {\texttt{FEDFUNDS}_{t-j}
% \end{array}} \right]} + \left[ {\begin{array}{*{20}{c}}
% {{\varepsilon _{1,t}}}\\
% {{\varepsilon _{2,t}}}\\
% {{\varepsilon _{3,t}}}
% \end{array}} \right].
% For all t, \varepsilon_t is a series of independent 3-D normal innovations with a mean of 0 and covariance \Sigma. Assume a diffuse prior distribution for the parameters \left({\left\lbrack \Phi_1 ,\ldotp \ldotp \ldotp ,\Phi_4 ,c\right\rbrack }^{\prime } ,\Sigma \right).
%% Load and Preprocess Data
% Load the US macroeconomic data set.  Compute the inflation rate, stabilize the unemployment and federal funds rates, and remove missing values.

load Data_USEconModel
seriesnames = ["INFL" "UNRATE" "FEDFUNDS"];
DataTable.INFL = 100*[NaN; price2ret(DataTable.CPIAUCSL)];
DataTable.DUNRATE = [NaN; diff(DataTable.UNRATE)];
DataTable.DFEDFUNDS = [NaN; diff(DataTable.FEDFUNDS)];
seriesnames(2:3) = "D" + seriesnames(2:3);
rmDataTable = rmmissing(DataTable);

%
%% Create Prior Model
% Create a diffuse prior model. Specify the response series names.

numseries = numel(seriesnames);
numlags = 4;

PriorMdl = bayesvarm(numseries,numlags,'SeriesNames',seriesnames);

%
%% Forecast Responses
% Directly forecast two years (eight quarters) of observations from the posterior predictive distribution. forecast estimates the posterior distribution of the parameters, and then forms the posterior predictive distribution.

numperiods = 8;
YF = forecast(PriorMdl,numperiods,rmDataTable{:,seriesnames});

% YF is an 8-by-3 matrix of forecasted responses.
% Plot the forecasted responses.

fh = rmDataTable.Time(end) + calquarters(0:8);
for j = 1:PriorMdl.NumSeries
subplot(3,1,j)
plot(rmDataTable.Time(end - 20:end),rmDataTable{end - 20:end,seriesnames(j)},'r',...
    fh,[rmDataTable{end,seriesnames(j)}; YF(:,j)],'b');
legend("Observed","Forecasted",'Location','NorthWest')
title(seriesnames(j))
end

% Copyright 2019 The MathWorks, Inc.
%