%% Forecast Responses Using Conditional Posterior Predictive Distribution
% Consider the regression model in Forecast Responses Using Posterior Predictive Distribution.
% Create a normal-inverse-gamma semiconjugate prior model for the linear regression parameters. Specify the number of predictors p and the names of the regression coefficients.

p = 3;
PriorMdl = bayeslm(p,'ModelType','semiconjugate','VarNames',["IPI" "E" "WR"]);

%
% Load the Nelson-Plosser data set. Create variables for the response and predictor series.

load Data_NelsonPlosser
X = DataTable{:,PriorMdl.VarNames(2:end)};
y = DataTable{:,'GNPR'};

%
% Hold out the last 10 periods of data from estimation so you can use them to forecast real GNP. Turn off the estimation display.

fhs = 10; % Forecast horizon size
X = DataTable{1:(end - fhs),PriorMdl.VarNames(2:end)}; 
y = DataTable{1:(end - fhs),'GNPR'};
XF = DataTable{(end - fhs + 1):end,PriorMdl.VarNames(2:end)}; % Future predictor data
yFT = DataTable{(end - fhs + 1):end,'GNPR'};                  % True future responses

%
% Forecast responses by using the conditional posterior predictive distribution of beta given \sigma^2 = 2 and using the future predictor data XF. Specify the in-sample observations X and y (the observations from which MATLAB® composes the posterior). Plot the true values of the response and the forecasted values.

yF = forecast(PriorMdl,XF,X,y,'Sigma2',2);

figure;
plot(dates,DataTable.GNPR);
hold on
plot(dates((end - fhs + 1):end),yF)
h = gca;
hp = patch([dates(end - fhs + 1) dates(end) dates(end) dates(end - fhs + 1)],...
    h.YLim([1,1,2,2]),[0.8 0.8 0.8])
uistack(hp,'bottom');
legend('Forecast Horizon','True GNPR','Forecasted GNPR','Location','NW')
title('Real Gross National Product: 1909 - 1970');
ylabel('rGNP');
xlabel('Year');
hold off

% Copyright 2012 The MathWorks, Inc.