%% Simulate Parameters from Analytically Intractable 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 semiconjugate.
%% 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 semiconjugate Bayesian VAR(4) prior model for the three response series. Specify the response variable names.

numseries = numel(seriesnames);
numlags = 4;

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

%
%% Simulate Parameters from Posterior
% Because the joint posterior distribution of a semiconjugate prior model is analytically intractable, simulate sequentially draws from the full conditional distributions.
% Draw 1000 samples from the posterior distribution. Specify a burn-in period of 10,000, and a thinning factor of 5.  Start the Gibbs sampler by assuming the posterior mean of \Sigma is the 3-D identity matrix.

rng(1)
[Coeff,Sigma] = simulate(PriorMdl,rmDataTable{:,seriesnames},...
    'NumDraws',1000,'BurnIn',1e4,'Thin',5,'Sigma0',eye(3));

% 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.
% Copyright 2019 The MathWorks, Inc.
%
%