%% Specify Conditional Mean and Variance Models
% This example shows how to specify a composite conditional mean and variance model using arima.
%% Load the Data
% Load the NASDAQ data included with the toolbox. Convert the daily close composite index series to a percentage return series.

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

figure
plot(r)
xlim([0 T])
title('NASDAQ Daily Returns')

% The returns appear to fluctuate around a constant level, but exhibit volatility clustering. Large changes in the returns tend to cluster together, and small changes tend to cluster together. That is, the series exhibits conditional heteroscedasticity.
% The returns are of relatively high frequency. Therefore, the daily changes can be small. For numerical stability, it is good practice to scale such data.
%
%% Check for Autocorrelation
% Plot the sample autocorrelation function (ACF) and partial autocorrelation function (PACF) for the return series.

figure
subplot(2,1,1)
autocorr(r)
subplot(2,1,2)
parcorr(r)

% The autocorrelation functions suggests there is significant autocorrelation at lag one.
%
%% Test the Significance of Autocorrelations
% Conduct a Ljung-Box Q-test at lag 5.

[h,p] = lbqtest(r,'Lags',5)

% The null hypothesis that all autocorrelations are 0 up to lag 5 is rejected (h = 1).
%
%% Check for Conditional Heteroscedasticity.
% Plot the sample ACF and PACF of the squared return series.

figure
subplot(2,1,1)
autocorr(r.^2)
subplot(2,1,2)
parcorr(r.^2)

% The autocorrelation functions show significant serial dependence, which suggests that the series is conditionally heteroscedastic.
%
%% Test for Significant ARCH Effects
% Conduct an Engle's ARCH test. Test the null hypothesis of no conditional heteroscedasticity against the alternative hypothesis of an ARCH model with two lags (which is locally equivalent to a GARCH(1,1) model).

[h,p] = archtest(r-mean(r),'lags',2)

% The null hypothesis is rejected in favor of the alternative hypothesis (h = 1).
%
%% Specify a Conditional Mean and Variance Model.
% Specify an AR(1) model for the conditional mean of the NASDAQ returns, and a GARCH(1,1) model for the conditional variance. This is a model of the form
% {r_t} = c + {\phi _1}{r_{t - 1}} + {\varepsilon _t},
% where {\varepsilon _t} = {\sigma _t}{z_t},
% \sigma _t^2 = \kappa  + {\gamma _1}\sigma _{t - 1}^2 + {\alpha _1}\varepsilon _{t - 1}^2,
% and z_t is an independent and identically distributed standardized Gaussian process.

Mdl = arima('ARLags',1,'Variance',garch(1,1))

% The model output shows that a garch model is stored in the Variance property of the arima model, Mdl.
% Copyright 2015 The MathWorks, Inc.