%% Test Among Multiple Nested Model Specifications
% Assess model specifications by testing down among multiple restricted models using simulated data. The true model is the ARMA(2,1)
% y_t = 3 + 0.9y_{t-1}-0.5y_{t-2}+\varepsilon_t+0.7\varepsilon_{t-1},
% where \varepsilon_t is Gaussian with mean 0 and variance 1.
% Specify the true ARMA(2,1) model, and simulate 100 response values.

TrueMdl = arima('AR',{0.9,-0.5},'MA',0.7,...
    'Constant',3,'Variance',1);
T = 100;
rng(1); % For reproducibility
y = simulate(TrueMdl,T);

%
% Specify the unrestricted model and the candidate models for testing down.

Mdl = {arima(2,0,2),arima(2,0,1),arima(2,0,0),arima(1,0,2),arima(1,0,1),...
    arima(1,0,0),arima(0,0,2),arima(0,0,1)};
rMdlNames = {'ARMA(2,1)','AR(2)','ARMA(1,2)','ARMA(1,1)',...
    'AR(1)','MA(2)','MA(1)'};

% Mdl is a 1-by-7 cell array.  Mdl{1} is the unrestricted model, and all other cells contain a candidate model.
%
% Fit the candidate models to the simulated data.

logL = zeros(size(Mdl,1),1); % Preallocate loglikelihoods
dof = logL;                  % Preallocate degrees of freedom
for k = 1:size(Mdl,2)
    [EstMdl,~,logL(k)] = estimate(Mdl{k},y,'Display','off');
    dof(k) = 4 - (EstMdl.P + EstMdl.Q); % Number of restricted parameters
end
uLogL = logL(1);     
rLogL = logL(2:end); 
dof = dof(2:end);

% uLogL and rLogL are the values of the unrestricted loglikelihood evaluated at the unrestricted and restricted model parameter estimates, respectively.
%
% Apply the likelihood ratio test at a 1% significance level to find the appropriate, restricted model specification(s).

alpha = .01;
h = lratiotest(uLogL,rLogL,dof,alpha);
RestrictedModels = rMdlNames(~h)

% The most appropriate restricted models are ARMA(2,1), ARMA(1,2), ARMA(1,1), or MA(2).
% You can test down again, but use ARMA(2,1) as the unrestricted model. In this case, you must remove MA(2) from the possible restricted models.
% Copyright 2012 The MathWorks, Inc.