%% Simulate Conditional Mean and Variance Models
% This example shows how to simulate responses and conditional variances from a composite conditional mean and variance model.
%% Load the Data and Fit a Model
% Load the NASDAQ data included with the toolbox. Fit a conditional mean and variance model to the daily returns. Scale the returns to percentage returns for numerical stability

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

Mdl = arima('ARLags',1,'Variance',garch(1,1),...
    'Distribution','t');
EstMdl = estimate(Mdl,r,'Variance0',{'Constant0',0.001});
[e0,v0] = infer(EstMdl,r);

%
%% Simulate Returns, Innovations, and Conditional Variances
% Use simulate to generate 100 sample paths for the returns, innovations, and conditional variances for a 1000-period future horizon. Use the observed returns and inferred residuals and conditional variances as presample data.

rng 'default';
[y,e,v] = simulate(EstMdl,1000,'NumPaths',100,...
    'Y0',r,'E0',e0,'V0',v0);

figure
plot(r)
hold on
plot(T+1:T+1000,y)
xlim([0,T+1000])
title('Simulated Returns')
hold off

% The simulation shows increased volatility over the forecast horizon.
%
%% Plot Conditional Variances
% Plot the inferred and simulated conditional variances.

figure
plot(v0)
hold on
plot(T+1:T+1000,v)
xlim([0,T+1000])
title('Simulated Conditional Variances')
hold off

% The increased volatility in the simulated returns is due to larger conditional variances over the forecast horizon.
%
%% Plot Standardized Innovations
% Standardize the innovations using the square root of the conditional variance process. Plot the standardized innovations over the forecast horizon.

figure
plot(e./sqrt(v))
xlim([0,1000])
title('Simulated Standardized Innovations')

% The fitted model assumes the standardized innovations follow a standardized Student's t distribution. Thus, the simulated innovations have more larger values than would be expected from a Gaussian innovation distribution.
% Copyright 2015 The MathWorks, Inc.