%% Tune Delay Parameter for SETAR Estimation
% estimate does not fit the delay parameter d to the data; you must specify its value when you call estimate. This example shows how to tune d.
% Create the following fully specified SETAR model for the DGP.
% State 1: y_t =\varepsilon_{1,t}, where \varepsilon_{1,t} \sim N\left(0,1\right).
% State 2: y_t =2+\varepsilon_{2,t}, where \varepsilon_{2,t} \sim N\left(0,2\right)
% The system is in state 1 when y_{t-4} <0, and it is in state 2 otherwise.

ttDGP = threshold(0);
mdl1DGP = arima(Constant=0,Variance=1);
mdl2DGP = arima(Constant=2,Variance=2);
mdlDGP = [mdl1DGP; mdl2DGP];
MdlDGP = tsVAR(ttDGP,mdlDGP);

% Generate a random response path of length 200 from the DGP. Specify that the threshold variable delay is 4.

rng(1) % For reproducibiliy
y = simulate(MdlDGP,200,Delay=4);

plot(y)

% Create a partially specified threshold-switching model that has the same structure as the data-generating process, but specify the transition mid-level, submodel coefficients, and state-specific variances as unknown for estimation.

tt = threshold(NaN);
mdl = arima(0,0,0);
Mdl = tsVAR(tt,[mdl; mdl]);

% Fully specify a threshold transition that has the same structure as tt, but set the mid-level to 0.5.

tt0 = threshold(0.5);

% Tune the d by choosing a set of plausible values for it, and fitting the SETAR model to the simulated data for each value in the set. Choose the model that minimizes the loglikelihood.

d = 1:8;
nd = numel(d);
logL = zeros(nd,1);     % Preallocate for loglikelihoods
EstMdl = cell(nd,1);    % Preallocate for estimated models

for j = 1:nd
    [EstMdl{j},logL(j)] = estimate(Mdl,tt0,y,Delay=d(j));
end

% Extract the model that minimizes the loglikelihood.

[~,optDelay] = max(logL)
OptEstMdl = EstMdl{optDelay};

% The optimal delay is 4, which matches the delay of the DGP.
% Display an estimation summary of the optimal model, and display its estimated switching mechanism.

summarize(OptEstMdl)

% The estimates are close to the parameters of the DGP.
% Copyright 2021 The MathWorks, Inc.