%% Robust Recursive Regression Standard Errors
% If a linear regression model violates classical linear model assumptions, then OLS coefficient standard errors are incorrect. However, recreg has options to estimate coefficients and standard errors that are robust to heteroscedastic or autocorrelated innovations.
% Simulate a series from this piecewise regression model with AR(1) errors whose regression coefficient changes at time 51.
% \left\{ {\begin{array}{*{20}{c}}
% {\begin{array}{*{20}{l}}
% {{y_t} = 5 + 3{x_t} + {u_t}}\\
% {{u_t} = 0.6{u_{t - 1}} + {\varepsilon _t}}
% \end{array};t = 1,...,50}\\
% {\begin{array}{*{20}{l}}
% {{y_t} = 5 - {x_t} + {u_t}}\\
% {{u_t} = 0.6{u_{t - 1}} + {\varepsilon _t}}
% \end{array};t = 51,...,100}
% \end{array}} \right..
% \varepsilon_t is a series of Gaussian innovations with mean 0 and standard deviation 0.5.  x_t is Gaussian with mean 1 and standard deviation 0.25.

rng(1); % For reproducibility
T = 100;
muX = 1;
sigmaX = 0.25;
x = sigmaX*randn(T,1) + muX;
ar = 0.6;
sigma = 0.5;
c = 5;
b = [3 -1];
y = zeros(T,1);
Mdl1 = regARIMA('AR',ar,'Variance',sigma,'Intercept',c,'Beta',b(1));
y(1:T/2) = simulate(Mdl1,T/2,'X',x(1:T/2));
Mdl2 = regARIMA('AR',ar,'Variance',sigma,'Intercept',c,'Beta',b(2));
y((T/2 + 1):T) = simulate(Mdl2,T/2,'X',x((T/2 + 1):T));

%
% Estimate recursive regression coefficients using OLS.

[CoeffOLS,SEOLS] = recreg(x,y,'Plot','separate');

% After transient effects, 5 is within the confidence bounds of the intercept estimates. There is an insignificant, but persistent shock at iteration 50. The coefficient estimates show the structural change after iteration 60.
%
% To account for autocorrelated innovations, estimate recursive regression coefficients using OLS, but with Newey-West robust standard errors. For estimating the HAC standard errors, use the quadratic-spectral weighting scheme.

hacOptions.Weights = 'QS';
[CoeffNW,SENW] = recreg(x,y,'Estimator','hac','Options',hacOptions,...
    'Plot','separate');

% The HAC coefficient estimates are the same as the OLS estimates. The confidence bounds are slightly different because the standard error estimators are different.
% Copyright 2012 The MathWorks, Inc.