%% Specify Presample Data
% Consider the 3-D VAR(4) model of docid:econ_ug.mw_1f230922-b87b-4b6a-a9d5-1cc611d85f95. In this case, fit the model to the data starting in 1970.
%% 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 variable names.

numseries = numel(seriesnames);
numlags = 4;

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

%
%% Partition Time Base for Subsamples
% A VAR(4) model requires p = 4 presample observations to initialize the AR component for estimation. Define index sets corresponding to the required presample and estimation samples.

idxpre = rmDataTable.Time < datetime('1970','InputFormat','yyyy');  % Presample indices
idxest = ~idxpre;                                                   % Estimation sample indices
T = sum(idxest)

% The effective sample size is 157 observations.
%
%% Estimate Posterior Distribution
% Estimate the posterior distribution. Specify only the required presample observations by using the 'Y0' name-value pair argument.

Y0 = rmDataTable{find(idxpre,PriorMdl.P,'last'),seriesnames};
PosteriorMdl = estimate(PriorMdl,rmDataTable{idxest,seriesnames},...
    'Y0',Y0);

% Copyright 2019 The MathWorks, Inc.