%% Assess Autocorrelation in Inferred Residuals
% Infer residuals from an estimated ARIMA model, and assess whether the residuals exhibit autocorrelation using lbqtest.
% Load the Australian Consumer Price Index (CPI) data set. The time series (cpi) is the log quarterly CPI from 1972 to 1991. Remove the trend in the series by taking the first difference.

load Data_JAustralian
cpi = DataTable.PAU;
T = length(cpi);
dCPI = diff(cpi);

figure
plot(dates(2:T),dCPI)
title('Differenced Australian CPI')
xlabel('Year')
ylabel('CPI growth rate')
datetick
axis tight

% The differenced series appears stationary.
%
% Fit an AR(1) model to the series, and then infer residuals from the estimated model.

Mdl = arima(1,0,0);
EstMdl = estimate(Mdl,dCPI);
res = infer(EstMdl,dCPI);
stdRes = res/sqrt(EstMdl.Variance); % Standardized residuals

%
% Assess whether the residuals are autocorrelated by conducting a Ljung-Box Q-test. The standardized residuals originate from the estimated model (EstMdl) containing parameters. When using such residuals, it is best practice to do the following:
% Adjust the degrees of freedom (dof) of the test statistic distribution to account for the estimated parameters.
% Set the number of lags to include in the test statistic.
% When you count the estimated parameters, skip the constant and variance parameters.

lags = 10;         
dof  = lags - 1; % One autoregressive parameter

[h,pValue] = lbqtest(stdRes,'Lags',lags,'DOF',dof)

% pValue = 0.0130 suggests that there is significant autocorrelation in the residuals at the 5% level.
% Copyright 2015 The MathWorks, Inc.