%% Test for Structural Break in Volatility
% Check whether a cusum of squares test can detect a structural break in volatility in simulated data.
% Simulate a series of data from this regression model
% \left\{ {\begin{array}{*{20}{c}}
% {{y_t} = \left[ {\begin{array}{*{20}{c}}
% 1&2&3
% \end{array}} \right]{x_t} + {\varepsilon _{1t}};\;t = 1,...,50}\\
% {{y_t} = \left[ {\begin{array}{*{20}{c}}
% 1&2&3
% \end{array}} \right]{x_t} + {\varepsilon _{2t}};t = 51,...,100}
% \end{array}} \right..
% x_t is a series of observations from three standard Gaussian predictor variables. \varepsilon_{1t} and \varepsilon_{2t} are series of Gaussian innovations both with mean 0 and standard deviation 0.1 and 0.2, respectively.

rng(1); % For reproducibility
T = 100;
X = randn(T,3);
sigma1 = 0.1;
sigma2 = 0.2;
e = [sigma1*randn(T/2,1); sigma2*randn(T/2,1)];
b = (1:3)';
y = X*b + e;

%
% Conduct a cusum of squares test using a 5% level of significance. Plot the test statistics and critical region bands. Indicate that there is no model intercept. Request to return whether the test statistics cross into critical region at each iteration.

[~,H] = cusumtest(X,y,'Test','cusumsq','Plot','on',...
    'Direction',{'forward','backward'},'Display','off','Intercept',false);

% Because the test statistics cross the critical lines at least once for both tests, the tests reject the null hypothesis of constant volatility at 5% level. The test statistics change direction around iteration 50, which is consistent with the simulated break in volatility in the data.
% H is a 2-by-97 logical matrix containing the sequence of decisions for each iteration of each cusum of squares test. The first row corresponds to the forward cusum of squares test, and the second row corresponds to the backward cusum of squares test.
%
% For the forward test, determine the iterations that result in the test statistics crossing the critical line.

bp = find(H(1,:) == 1)

% Copyright 2012 The MathWorks, Inc.