%% Simulate Parameters from Analytically Tractable Posterior Distribution
% Consider the 3-D VAR(4) model of docid:econ_ug.mw_e84f08d4-511a-43bf-a850-ddb425b855d5. In this case, assume that the prior distribution is diffuse.
%% 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 Bayesian VAR(4) prior model for the three response series. Specify the response series names.

numseries = numel(seriesnames);
numlags = 4;

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

%
%% Estimate Posterior Distribution
% Estimate the posterior distribution. Return the estimation summary.

[PosteriorMdl,Summary] = estimate(PriorMdl,rmDataTable{:,seriesnames});

% PosteriorMdl is a conjugatebvarm model, which is analytically tractable.
%
%% Simulate Parameters from Posterior
% Draw 1000 samples from the posterior distribution.

rng(1)
[Coeff,Sigma] = simulate(PosteriorMdl,'NumDraws',1000);

% Coeff is a 39-by-1000 matrix of randomly drawn coefficients.  Each column is an individual draw, and each row is an individual coefficient. Sigma is a 3-by-3-by-1000 array of randomly drawn innovations covariance matrices. Each page is an individual draw.
% Display the first coefficient drawn from the distribution with corresponding parameter names, and display the first drawn innovations  covariance matrix.

Coeffs = table(Coeff(:,1),'RowNames',Summary.CoeffMap)
Sigma(:,:,1)

% Copyright 2019 The MathWorks, Inc.
%