%% Conduct the Ljung-Box Q-Test
% This example shows how to conduct the Ljung-Box Q-test for autocorrelation.
% The time series is 57 consecutive days of overshorts from a gasoline tank in Colorado.
%% Step 1. Load the data.
% Load the time series of overshorts.

load('Data_Overshort.mat')
Y = Data;
N = length(Y);

figure
plot(Y)
xlim([0,N])
title('Overshorts for 57 Consecutive Days')

% The data appears to fluctuate around a constant mean, so no data transformations are needed before conducting the Ljung-Box Q-test.
%
%% Step 2. Conduct the Ljung-Box Q-test.
% Conduct the Ljung-Box Q-test for autocorrelation at lags 5, 10, and 15.

[h,p,Qstat,crit] = lbqtest(Y,'Lags',[5,10,15])

% All outputs are vectors with 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.
% The test decisions are stored in the vector h. The value h = 1 means reject the null hypothesis. Vector p contains the p-values for the three tests. At the \alpha = 0.05 significance level, the null hypothesis of no autocorrelation is rejected at all three lags. The conclusion is that there is significant autocorrelation in the series.
% The test statistics and  \chi^2 critical values are given in outputs Qstat and crit, respectively.
% Copyright 2015 The MathWorks, Inc.