%% Forecast Responses of a Regression Model with ARIMA Errors
% Forecast responses from the following regression model with ARMA(2,1) errors over a 30-period horizon:
% \begin{array}{*{20}{l}}
% \begin{array}{c}
% {y_t} = {X_t}\left[ {\begin{array}{*{20}{c}}
% {0.1}\\
% { - 0.2}
% \end{array}} \right] + {u_t}\\
% {u_t} = 0.5{u_{t - 1}} - 0.8{u_{t - 2}} + {\varepsilon _t} - 0.5{\varepsilon _{t - 1}},
% \end{array}
% \end{array}
% where \varepsilon_{t} is Gaussian with variance 0.1.
% Specify the model. Simulate responses from the model and two predictor series.

Mdl0 = regARIMA('Intercept',0,'AR',{0.5 -0.8},...
    'MA',-0.5,'Beta',[0.1 -0.2],'Variance',0.1);
rng(1); % For reproducibility
X =  randn(130,2);
y = simulate(Mdl0,130,'X',X);

%
% Fit the model to the first 100 observations, and reserve the remaining 30 observations to evaluate forecast performance.

Mdl = regARIMA('ARLags',1:2);
EstMdl = estimate(Mdl,y(1:100),'X',X(1:100,:));

% EstMdl is a new regARIMA model containing the estimates. The estimates are close to their true values.
%
% Use EstMdl to forecast a 30-period horizon. Visually compare the forecasts to the holdout data using a plot.

[yF,yMSE] = forecast(EstMdl,30,'Y0',y(1:100),...
    'X0',X(1:100,:),'XF',X(101:end,:));

figure
plot(y,'Color',[.7,.7,.7]);
hold on
plot(101:130,yF,'b','LineWidth',2);
plot(101:130,yF+1.96*sqrt(yMSE),'r:',...
		'LineWidth',2);
plot(101:130,yF-1.96*sqrt(yMSE),'r:','LineWidth',2);
h = gca;
ph = patch([repmat(101,1,2) repmat(130,1,2)],...
        [h.YLim fliplr(h.YLim)],...
        [0 0 0 0],'b');
ph.FaceAlpha = 0.1;
legend('Observed','Forecast',...
		'95% Forecast Interval','Location','Best');
title(['30-Period Forecasts and Approximate 95% '...
			'Forecast Intervals'])
axis tight
hold off

% Many observations in the holdout sample fall beyond the 95% forecast intervals. Two reasons for this are:
% The predictors are randomly generated in this example. estimate treats the predictors as fixed. Subsequently, the 95% forecast intervals based on the estimates from estimate do not account for the variability in the predictors.
% By shear chance, the estimation period seems less volatile than the forecast period. estimate uses the less volatile estimation period data to estimate the parameters. Therefore, forecast intervals based on the estimates should not cover observations that have an underlying innovations process with larger variability.
% Copyright 2015 The MathWorks, Inc.