%% Estimate Posterior 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 that the joint prior distribution of the VAR model parameters \left({\left\lbrack \Phi_1 ,\ldotp \ldotp \ldotp ,\Phi_4 ,c\right\rbrack }^{\prime } ,\Sigma \right) is diffuse.
%
%% Load and Preprocess Data
% Load the US macroeconomic data set.  Compute the inflation rate.  Plot all response series.

load Data_USEconModel
seriesnames = ["INFL" "UNRATE" "FEDFUNDS"];
DataTable.INFL = 100*[NaN; price2ret(DataTable.CPIAUCSL)];

figure
plot(DataTable.Time,DataTable{:,seriesnames})
legend(seriesnames)

% Stabilize the unemployment and federal funds rates by applying the first difference to each series.

DataTable.DUNRATE = [NaN; diff(DataTable.UNRATE)];
DataTable.DFEDFUNDS = [NaN; diff(DataTable.FEDFUNDS)];
seriesnames(2:3) = "D" + seriesnames(2:3);

% Remove all missing values from the data.

rmDataTable = rmmissing(DataTable);

%
%% Create Prior Model
% Create a diffuse Bayesian VAR(4) prior model for the three response series. Specify the response variable names.

numseries = numel(seriesnames);
numlags = 4;

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

% PriorMdl is a diffusebvarm model object.
%
%% Estimate Posterior Distribution
% Estimate the posterior distribution by passing the prior model and entire data series to estimate.

PosteriorMdl = estimate(PriorMdl,rmDataTable{:,seriesnames})

% PosteriorMdl is a conjugatebvarm model object; the posterior is analytically tractable. The command line displays the posterior means (Mean) and standard deviations (Std) of all coefficients and the innovations covariance matrix. Row AR{k}(i,j) contains the posterior estimates of \phi_{k,\textrm{ij}}, the lag k AR coefficient of response variable j in response equation i. By default, estimate uses the first four observations as a presample to initialize the model.
% Display the posterior means of the AR coefficient matrices by using dot notation.

AR1 = PosteriorMdl.AR{1}
AR2 = PosteriorMdl.AR{2}
AR3 = PosteriorMdl.AR{3}
AR4 = PosteriorMdl.AR{4}

%
% Copyright 2019 The MathWorks, Inc.
%
%
%