%% Use Simulations to Forecast Conditional Variances
% Simulate conditional variances of the daily NASDAQ Composite Index returns for 500 days. Use the simulations to make forecasts and approximate 95% forecast intervals.
% Load the NASDAQ data included with the toolbox. Convert the index to returns.

load Data_EquityIdx
nasdaq = DataTable.NASDAQ;
r = price2ret(nasdaq);
n = length(r);

%
% Fit a GARCH(1,1) model to the entire data set. Infer conditional variances to use as presample conditional variances for the forecast simulation.

Mdl = garch(1,1);
EstMdl = estimate(Mdl,r);
v0 = infer(EstMdl,r);

%
% Simulate 1000 samples paths with 500 observations each. Use the observed returns and inferred conditional variances as presample data.

rng default; % For reproducibility
vS = simulate(EstMdl,500,'NumPaths',1000,'E0',r,'V0',v0);

%
% Plot the simulation mean forecast and approximate 95% forecast intervals, along with the conditional variances inferred from the data.

lower = prctile(vS,2.5,2);
upper = prctile(vS,97.5,2);
mn = mean(vS,2);

figure
h1 = plot(v0,'Color',[.7,.7,.7]);
hold on
h2 = plot(n+1:n+500,lower,'r:','LineWidth',1.5);
plot(n+1:n+500,upper,'r:','LineWidth',1.5);
h3 = plot(n+1:n+500,mn,'k','LineWidth',2);
xlim([0,n+500])
legend([h1,h2,h3],'Inferred',...
      '95% Forecast Intervals',...
      'Simulation Mean','Location','Northwest')
title('Simulated Conditional Variance Forecasts')
hold off

% The mean conditional variance approaches an asymptote as the forecast horizon increases.
% Copyright 2015 The MathWorks, Inc.