%% Simulate Response Path from SETAR Model
% Suppose a data-generating process (DGP) is a two-state, self-exciting threshold autoregressive (SETAR) model for a 1-D response variable. Specify all parameter values (this example uses arbitrary values).
%
%% Create Fully Specified Model for DGP
% Create a discrete threshold transition at level 0. Label the regimes to reflect the state of the economy:
% When the threshold variable (currently unknown) is in \left(-\infty ,0\right), the economy is in a recession.
% When the threshold variable is in \left.\lbrack 0,\infty \right), the economy is expanding.

t = 0;
tt = threshold(t,StateNames=["Recession" "Expansion"])

% tt is a fully specified threshold object that describes the switching mechanism of the threshold-switching model.
% Assume the following univariate models describe the response process of the system:
% Recession: y_t =-1+0\ldotp 1y_{t-1} +\varepsilon_{1,t}, where \varepsilon_{1,t} \sim N\left(0,1\right).
% Expansion: y_t =1++0\ldotp 3y_{t-1} +0\ldotp 2y_{t-2} +\varepsilon_{2,t}, where \varepsilon_{2,t} \sim N\left(0,2^2 \right).
% For each regime, use arima to create an AR model that describes the response process within the regime.

c1 = -1;
c2 = 1;
ar1 = 0.1;       
ar2 = [0.3 0.2]; 
v1 = 1;
v2 = 4;

mdl1 = arima(Constant=c1,AR=ar1,Variance=v1,...
    Description="Recession State Model")
mdl2 = arima(Constant=c2,AR=ar2,Variance=v2,...
    Description="Expansion State Model")

% mdl1 and mdl2 are fully specified arima objects.
% Store the submodels in a vector with order corresponding to the regimes in tt.StateNames.

mdl = [mdl1; mdl2];

% Use tsVAR to create a TAR model from the switching mechanism tt and the state-specific submodels mdl.

Mdl = tsVAR(tt,mdl)
Mdl.Submodels(2)

% Mdl is a fully specified tsVAR object representing a univariate two-state TAR model. tsVAR stores specified arima submodels as varm objects.
%
%% Simulate Response Data from DGP
% Generate one random response path of length 50 from the model. simulate assumes that the threshold variable is y_{t-1}, which implies that the model is self-exciting.

rng(1); % For reproducibility
y = simulate(Mdl,50);

% y is a 50-by-1 vector of one response path.
% Plot the response path with the threshold by using ttplot.

figure
ttplot(Mdl.Switch,Data=y)

% Copyright 2021 The MathWorks, Inc.