%% Forecast Composite Conditional Mean and Variance Model
% Consider the following AR(1) conditional mean model with a GARCH(1,1) conditional variance model for the daily NASDAQ rate series (as a percent) from January 2, 1990 through December 31, 2001.
% y_t=0.073+0.138y_{t-1}+\varepsilon_t\\
% \sigma^2_t=0.022+0.873\sigma^2_{t-1}+0.119\varepsilon_{t-1},
% where \varepsilon_t is a series of independent random Gaussian variables with a mean of 0.
% Create the model.

CondVarMdl = garch('Constant',0.022,'GARCH',0.873,'ARCH',0.119);
Mdl = arima('Constant',0.073,'AR',0.138,'Variance',CondVarMdl);

% Load the equity index data set. Convert the table to a timetable, and convert the NASDAQ price series to a return series. Because the return series has one less observation than the price series, prepad the return series to synchronize it with variables in the timetable.

load Data_EquityIdx
dates = datetime(dates,'ConvertFrom','datenum','Locale','en_US');
TT = table2timetable(DataTable,'RowTimes',dates);
T = size(TT,1);
y0 = 100*price2ret(DataTable.NASDAQ); 
[e0,v0] = infer(Mdl,y0);
n = numel(y0);
TT{:,["NASDAQRet" "Residuals" "CondVar"]} = [nan(T-n,3); y0 e0 v0];

% Forecast the model over a 25-day horizon. Supply the entire data set as a presample (forecast uses only the latest required observations to initialize the conditional mean and variance models). Return forecasted responses and conditional variances.

fh = 25;
fhdates = TT.Time(end) + caldays(0:fh);  % Forecast horizon dates
[y,~,v] = forecast(Mdl,fh,TT.NASDAQRet);

% Plot the forecasted responses and conditional variances with the observed series from August 2001.

pdates = TT.Time > datetime(2001,8,1);
plot(TT.Time(pdates),TT.NASDAQRet(pdates))
hold on
plot(fhdates,[TT.NASDAQRet(end); y])
hold off
plot(TT.Time(pdates),TT.CondVar(pdates))
hold on
plot(fhdates,[TT.CondVar(end); v]);
hold off

% Copyright 2020 The MathWorks, Inc.