%% Account for Residual Heteroscedasticity Using FGLS Estimation
% Model the nominal GNP (GNPN) growth rate accounting for the effects of the growth rates of the consumer price index (CPI), real wages (WR), and the money stock (MS). Account for classical linear model departures.
% Load the Nelson Plosser data set.

load Data_NelsonPlosser
varIdx = [8,10,11,2];               % Variable indices
idx = ~any(ismissing(DataTable),2); % Identify nonmissing values 
Tbl = DataTable(idx,varIdx);        % Tabular array of variables
T = sum(idx);                       % Sample size

%
% Plot the series.

figure;
for j = 1:4;
    subplot(2,2,j);
    plot(dates(idx),Tbl{:,j});
    title(Tbl.Properties.VariableNames{j});
    axis tight;
end;

% All series appear nonstationary.
%
% Apply the log, and then the first difference to each series.

dLogTbl = array2table(diff(log(Tbl{:,:})),...
    'VariableNames',strcat(Tbl.Properties.VariableNames,'Rate'));

%
% Regress GNPNRate onto the other variables in dLogTbl. Examine a scatter plot and correlograms of the residuals.

Mdl = fitlm(dLogTbl);

figure;
plotResiduals(Mdl,'caseorder');
axis tight;

figure;
subplot(2,1,1);
autocorr(Mdl.Residuals.Raw);
subplot(2,1,2);
parcorr(Mdl.Residuals.Raw);

% The residuals appear to flare in, and so they exhibit heteroscedasticity. The correlograms suggest that there is no autocorrelation.
%
% Estimate FGLS coefficients by accounting for the heteroscedasticity of the residuals. Specify that the estimated innovation covariance is diagonal with the squared residuals as weights.

fgls(dLogTbl,'innovMdl','HC0','display','final');

% Copyright 2015 The MathWorks, Inc.