%% Create Empirical Prior Model
% Consider the multiple linear regression model that predicts the US real gross national product (GNPR) using a linear combination of industrial production index (IPI), total employment (E), and real wages (WR).
% \texttt{GNPR}_t=\beta_0+\beta_1\texttt{IPI}_t+\beta_2\texttt{E}_t+\beta_3\texttt{WR}_t+\varepsilon_t.
% For all t time points, \varepsilon_t is a series of independent Gaussian disturbances with a mean of 0 and variance \sigma^2.
% Assume that the prior distributions are:
% \beta\vert\sigma^2 \sim N_4\left({\rm M},V\right). {\rm M} is a 4-by-1 vector of means, and V is a scaled 4-by-4 positive definite covariance matrix.
% \sigma^2 \sim IG(A,B). A and B are the shape and scale, respectively, of an inverse gamma distribution.
% These assumptions and the data likelihood imply a normal-inverse-gamma semiconjugate model. That is, the conditional posteriors are conjugate to the prior with respect to the data likelihood, but the marginal posterior is analytically intractable.
% Create a normal-inverse-gamma semiconjugate prior model for the linear regression parameters. Specify the number of predictors p.

p = 3;
PriorMdl = bayeslm(p,'ModelType','semiconjugate')

% Mdl is a semiconjugateblm Bayesian linear regression model object representing the prior distribution of the regression coefficients and disturbance variance. At the command window, bayeslm displays a summary of the prior distributions.
%
% Load the Nelson-Plosser data set. Create variables for the response and predictor series.

load Data_NelsonPlosser
VarNames = {'IPI'; 'E'; 'WR'};
X = DataTable{:,VarNames};
y = DataTable{:,'GNPR'};

%
% Estimate the marginal posterior distributions of \beta and \sigma^2.

rng(1); % For reproducibility
PosteriorMdl = estimate(PriorMdl,X,y);

% PosteriorMdl is an empiricalblm model object storing draws from the posterior distributions of \beta and \sigma^2 given the data. estimate displays a summary of the marginal posterior distributions to the command window. Rows of the summary correspond to regression coefficients and the disturbance variance, and columns to characteristics of the posterior distribution. The characteristics include:
% CI95, which contains the 95% Bayesian equitailed credible intervals for the parameters. For example, the posterior probability that the regression coefficient of WR is in [1.762, 3.178] is 0.95.
% Positive, which contains the posterior probability that the parameter is greater than 0. For example, the probability that the intercept is greater than 0 is 0.005.
% In this case, the marginal posterior is analytically intractable. Therefore, estimate uses Gibbs sampling to draw from the posterior and estimate the posterior characteristics.
% Copyright 2012 The MathWorks, Inc.