%% Forecast the GDP Using Regression Model with ARMA Errors
% Forecast stationary, log GDP using a regression model with ARMA(1,1) errors, including CPI as a predictor.
% Load the U.S. macroeconomic data set and preprocess the data.

load Data_USEconModel;
logGDP = log(DataTable.GDP);
dlogGDP = diff(logGDP);          % For stationarity
dCPI = diff(DataTable.CPIAUCSL); % For stationarity
numObs = length(dlogGDP);
gdp = dlogGDP(1:end-15);   % Estimation sample
cpi = dCPI(1:end-15);
T = length(gdp);        % Effective sample size
frstHzn =  T+1:numObs;  % Forecast horizon
hoCPI = dCPI(frstHzn);  % Holdout sample
dts = dates(2:end);     % Date nummbers

%
% Fit a regression model with ARMA(1,1) errors.

Mdl = regARIMA('ARLags',1,'MALags',1);
EstMdl = estimate(Mdl,gdp,'X',cpi);

%
% Forecast the GDP rate over a 15-quarter horizon. Use the estimation sample as a presample for the forecast.

[gdpF,gdpMSE] = forecast(EstMdl,15,'Y0',gdp,...
    'X0',cpi,'XF',hoCPI);

%
% Plot the forecasts and 95% forecast intervals.

figure
h1 = plot(dts(end-65:end),dlogGDP(end-65:end),...
    'Color',[.7,.7,.7]);
datetick
hold on
h2 = plot(dts(frstHzn),gdpF,'b','LineWidth',2);
h3 = plot(dts(frstHzn),gdpF+1.96*sqrt(gdpMSE),'r:',...
		'LineWidth',2);
plot(dts(frstHzn),gdpF-1.96*sqrt(gdpMSE),'r:','LineWidth',2);
ha = gca;
title(['{\bf Forecasts and Approximate 95% }'...
    '{\bf Forecast Intervals for GDP rate}']);
ph = patch([repmat(dts(frstHzn(1)),1,2) repmat(dts(frstHzn(end)),1,2)],...
    [ha.YLim fliplr(ha.YLim)],...
    [0 0 0 0],'b');
ph.FaceAlpha = 0.1;
legend([h1 h2 h3],{'Observed GDP rate','Forecasted GDP rate ',...
    '95% Forecast Interval'},'Location','Best','AutoUpdate','off');
axis tight
hold off

% Copyright 2012 The MathWorks, Inc.