%% Conduct Ljung-Box Q-Test over Various Lags
% Conduct multiple Ljung-Box Q-tests for autocorrelation by including various lags in the test statistic. The data set is a time series of 57 consecutive days of overshorts from an underground gasoline tank in Colorado [2]. That is, the current overshort (y_t) represents the accuracy in measuring the amount of fuel:
% In the tank at the end of day t
% In the tank at the end of day t-1
% Delivered to the tank on day t
% Sold on day t.
% Load the data set.

load('Data_Overshort')
y = Data;
T = length(y); % Sample size

figure
plot(y)
title('Overshorts for 57 Consecutive Days')

% lbqtest is appropriate for a series with a constant mean. Since the series appears to fluctuate around a constant mean, you do not need to transform the data.
%
% Compute the residuals.

res = y - mean(y);

%
% Assess whether the residuals are autocorrelated. Include 5, 10, and 15 lags in the test statistic computation.

[h,pValue] = lbqtest(res,'lags',[5,10,15])

% h and pValue are vectors containing three elements corresponding to tests at each of the three lags. The first element of each output corresponds to the test at lag 5, the second element corresponds to the test at lag 10, and the third element corresponds to the test at lag 15.
% h = 1 indicates the rejection of the null hypothesis that the residuals are not autocorrelated. pValue indicates the strength at which the test rejects the null hypothesis. Since all three p{\rm-values} are less than 0.01, there is strong evidence to reject the null hypothesis that the residuals are not autocorrelated.
% Copyright 2015 The MathWorks, Inc.