%% Specify Lags for Test Statistic
% To draw valid inferences from Engle's ARCH test, you should determine a suitable number of lags for the model. Do this by fitting the model over a range of plausible lags, and comparing the fitted models. Choose the number of lags that yields the best fitting model for the ARCH test.
%% Load and Process the Data
% Load the NASDAQ data included in the toolbox. Convert the daily close composite index series to a percentage return series.

load Data_EquityIdx
dates = datetime(dates,"ConvertFrom",'datenum');

price = DataTable.NASDAQ;
ret = 100*price2ret(price);

figure
plot(dates(2:end),ret)
title('NASDAQ Daily Returns')

% The last quarter of the return series seems to have higher variance than the first three quarters. This volatile behavior indicates conditional heteroscedasticity. Also, the series seems to fluctuate at a constant level.
% 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.
%
%% Determine Suitable Number of Lags for Test
% Fit the model over a grid of lags. Choose the number of lags that corresponds to the best fitting model.

numLags = 4;
logL = zeros(numLags,1); % Preallocation

for k = 1:numLags
    Mdl = garch(0,k);                                   % Create ARCH(k) model
    [~,~,logL(k)] = estimate(Mdl,ret,'Display','off');  % Obtain loglikelihood
end

aic = aicbic(logL,1:numLags);   % Get AIC
[~,lags] = min(aic)             % Obtain suitable number of lags

% lags = 4 indicates that it is reasonable to include four lags in the ARCH test statistic.
%
%% Conduct ARCH Test
% Calculate the residuals, and use them to conduct the ARCH test at a 1% significance level.

r = ret - mean(ret); % Returns fluctuate at constant level
[h,pValue,stat,cValue] = archtest(r,'Lags',lags,'Alpha',0.01)

% h = 1 indicates to reject the null hypothesis of no ARCH effects against the ARCH(4) alternative.  pValue = 0 indicates that the evidence is strong for the rejection of the null.
% Copyright 2012 The MathWorks, Inc.