%% Estimate FGLS Coefficients Using Default Options
% Suppose the sensitivity of the U.S. Consumer Price Index (CPI) to changes in the paid compensation of employees (COE) is of interest.
% Load the US macroeconomic data set. Plot the CPI and COE series.

load Data_USEconModel

figure;
subplot(2,1,1)
plot(dates,DataTable.CPIAUCSL);
title '{\bf Consumer Price Index, Q1 in 1947 to Q1 in 2009}';
datetick;
axis tight;
subplot(2,1,2);
plot(dates,DataTable.COE);
title '{\bf Compensation Paid to Employees, Q1 in 1947 to Q1 in 2009}';
datetick;
axis tight;

%
% The series are nonstationary. Stabilize them by applying the log, and then the first difference.

CPI = diff(log(DataTable.CPIAUCSL));
COE = diff(log(DataTable.COE));

%
% Regress CPI onto COE including an intercept to obtain ordinary least squares (OLS) estimates. Generate a lagged residual plot.

Mdl = fitlm(COE,CPI);

figure;
plotResiduals(Mdl,'lagged')

% There is an upward trend in the residual plot, which suggests that the innovations comprise an autoregressive process. This violates one of the classical linear model assumptions. Consequently, hypothesis tests based on the regression coefficients are incorrect, even asymptotically.
%
% Estimate the regression coefficients using FGLS. By default, fgls includes an intercept in the regression model and imposes an AR(1) model on the innovations. Optionally, display the OLS and FGLS estimates by specifying 'final' for the 'display' name-value pair argument.

coeff = fgls(CPI,COE,'display','final');

% If the COE series is exogenous with respect to the CPI, then the FGLS estimates (coeff) are consistent and asymptotically more efficient than the OLS estimates.
% Copyright 2015 The MathWorks, Inc.