%% Forecast Conditional Variances by Monte-Carlo Simulation
% Simulate conditional variances of the daily NASDAQ Composite Index returns for 500 days. Use the simulations to make forecasts and approximate 95% forecast intervals. Compare the forecasts among GARCH(1,1), EGARCH(1,1), and GJR(1,1) fits.
% Load the NASDAQ data included with the toolbox. Convert the index to returns.

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

%
% Fit GARCH(1,1), EGARCH(1,1), and GJR(1,1) models to the entire data set. Infer conditional variances to use as presample conditional variances for the forecast simulation.

Mdl = cell(3,1); % Preallocation
Mdl{1} = garch(1,1);
Mdl{2} = egarch(1,1);
Mdl{3} = gjr(1,1);

EstMdl = cellfun(@(x)estimate(x,r,'Display','off'),Mdl,...
    'UniformOutput',false);
v0 = cellfun(@(x)infer(x,r),EstMdl,'UniformOutput',false);

% EstMdl is 3-by-1 cell vector. Each cell is a different type of estimated conditional variance model, e.g., EstMdl{1} is an estimated GARCH(1,1) model. V0 is a 3-by-1 cell vector, and each cell contains the inferred conditional variances from the corresponding, estimated model.
%
% Simulate 1000 samples paths with 500 observations each. Use the observed returns and inferred conditional variances as presample data.

vSim = cell(3,1); % Preallocation

for j = 1:3
    rng default; % For reproducibility
    vSim{j} = simulate(EstMdl{j},500,'NumPaths',1000,'E0',r,'V0',v0{j});  
end

% vSim is a 3-by-1 cell vector, and each cell contains a 500-by-1000 matrix of simulated conditional variances generated from the corresponding, estimated model.
%
% Plot the simulation mean forecasts and approximate 95% forecast intervals, along with the conditional variances inferred from the data.

lower = cellfun(@(x)prctile(x,2.5,2),vSim,'UniformOutput',false);
upper = cellfun(@(x)prctile(x,97.5,2),vSim,'UniformOutput',false);
mn = cellfun(@(x)mean(x,2),vSim,'UniformOutput',false);
datesPlot = dates(end - 250:end);
datesFH = dates(end) + (1:500)';

h = zeros(3,4);

figure
for j = 1:3
    col = zeros(1,3);
    col(j) = 1;    
    h(j,1) = plot(datesPlot,v0{j}(end-250:end),'Color',col);
    hold on
    h(j,2) = plot(datesFH,mn{j},'Color',col,'LineWidth',3);
    h(j,3:4) = plot([datesFH datesFH],[lower{j} upper{j}],':',...
        'Color',col,'LineWidth',2);
end
hGCA = gca;
plot(datesFH(1)*[1 1],hGCA.YLim,'k--');
datetick;
axis tight;
h = h(:,1:3);
legend(h(:),'GARCH - Inferred','EGARCH - Inferred','GJR - Inferred',...
      'GARCH - Sim. Mean','EGARCH - Sim. Mean','GJR - Sim. Mean',...
      'GARCH - 95% Fore. Int.','EGARCH - 95% Fore. Int.',...
      'GJR - 95% Fore. Int.','Location','NorthEast')
title('Simulated Conditional Variance Forecasts')
hold off

% Copyright 2015 The MathWorks, Inc.