%% Compare Conditional Variance Forecasts of NYSE Returns
% Forecast the conditional variance of the NASDAQ Composite Index returns over a 500-day horizon using GARCH(1,1), EGARCH(1,1) and GJR(1,1) models.
% Load the NASDAQ data included with the toolbox. Convert the index to returns. Plot the returns.

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

figure;
plot(dates(2:end),r,dates(2:end),meanR*ones(T,1),'--r');
datetick;
title('Daily NASDAQ Returns');
xlabel('Day');
ylabel('Return');

% The variance of the series seems to change. This change is an indication of volatility clustering. The conditional mean model offset is very close to zero.
%
% Fit GARCH(1,1), EGARCH(1,1), and GJR(1,1) models to the data. By default, the software sets the conditional mean model offset to zero.

MdlGARCH = garch(1,1);
MdlEGARCH = egarch(1,1);
MdlGJR = gjr(1,1);

EstMdlGARCH = estimate(MdlGARCH,r);  
EstMdlEGARCH = estimate(MdlEGARCH,r);  
EstMdlGJR = estimate(MdlGJR,r);

%
% Forecast the conditional variance for 500 days using the fitted models. Use the observed returns as presample innovations for the forecasts.

vFGARCH = forecast(EstMdlGARCH,500,r);  
vFEGARCH = forecast(EstMdlEGARCH,500,r);  
vFGJR= forecast(EstMdlGJR,500,r);

%
% Plot the forecasts along with the conditional variances inferred from the data.

vGARCH = infer(EstMdlGARCH,r);
vEGARCH = infer(EstMdlEGARCH,r);
vGJR = infer(EstMdlGJR,r);
datesFH = dates(end):(dates(end)+1000); % 1000 period forecast horizon

figure;
subplot(3,1,1);
plot(dates(end-250:end),vGARCH(end-250:end),'b',...
    datesFH(2:end-500),vFGARCH,'b--');
legend('Inferred','Forecast','Location','NorthEast');
title('GARCH(1,1) Conditional Variances');
datetick;
axis tight;
subplot(3,1,2);
plot(dates(end-250:end),vEGARCH(end-250:end),'r',...
    datesFH(2:end-500),vFEGARCH,'r--');
legend('Inferred','Forecast','Location','NorthEast');
title('EGARCH(1,1) Conditional Variances');
datetick;
axis tight;

subplot(3,1,3);
plot(dates(end-250:end),vGJR(end-250:end),'k',...
    datesFH(2:end-500),vFGJR,'k--');
legend('Inferred','Forecast','Location','NorthEast');
title('GJR(1,1) Conditional Variances');
datetick;
axis tight;

%
% Plot conditional variance forecasts for 1000 days.

vF1000GARCH = forecast(EstMdlGARCH,1000,r);
vF1000EGARCH = forecast(EstMdlEGARCH,1000,r);
vF1000GJR = forecast(EstMdlGJR,1000,r);

figure;
plot(datesFH(2:end),vF1000GARCH,'b',...
    datesFH(2:end),vF1000EGARCH,'r',...
    datesFH(2:end),vF1000GJR,'k');
legend('GARCH','EGARCH','GJR','Location','NorthEast');
title('Conditional Variance Forecast Asymptote')    
datetick;

% The forecasts converge asymptotically to the unconditional variances of their respective processes.
% Copyright 2015 The MathWorks, Inc.