%% Perform Monte Carlo Estimation
% This example shows how to use Monte Carlo estimation to obtain an interval estimate of the threshold mid-level.
% Consider a SETAR model for the real US GDP growth rate y_t with AR(4) submodels.  Suppose the threshold variable is y_t (self exciting with 0 delay).
% Create a discrete threshold transition at unknown mid-level t_1. Label the states "Recession" and "Expansion".

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

% For each state, create a partially specified AR(4) model with one coefficient at lag 4. Store the state submodels in a vector.

submdl = arima(ARLags=4);
mdl = [submdl; submdl];

% Each submodel has an unknown, estimable lag 4 coefficient, model constant, and innovations variance.
% Create a partially specified TAR model from the threshold transition and submodel vector.

Mdl = tsVAR(tt,mdl);

% Create a fully specified threshold transition that has the same structure as tt, but set the mid-level to 0.

tt0 = threshold(0);

% Load the US macroeconomic data set. Compute the real GDP growth rate as a percent.

load Data_USEconModel
rGDP = DataTable.GDP./DataTable.GDPDEF;
pRGDP = 100*price2ret(rGDP);
T = numel(pRGDP);

% Fit the TAR to the real GDP rate series.

EstMdl = estimate(Mdl,tt0,pRGDP,Z=pRGDP,Type="exogenous");

% Simulate 100 response paths from the estimated model.

rng(100) % For reproducibility
numPaths= 100;
Y = simulate(EstMdl,T,NumPaths=numPaths,Z=pRGDP,Type="exogenous");

% Fit the TAR model to each simulated response path.  Specify the estimated threshold transition EstMdl.Switch to initialize the estimation procedure. For each path, store the estimated threshold transition mid-level.

tMC = nan(T,1);
for j = 1:numPaths
    EstMdlSim = estimate(Mdl,EstMdl.Switch,Y(:,j),Z=Y(:,j),Type="exogenous");
    tMC(j) = EstMdlSim.Switch.Levels;
end

% tMC is a 100-by-1 vector representing a Monte Carlo sample of threshold transitions.
% Obtain a 95% confidence interval on the true threshold transition by computing the 0.25 and .975 quantiles of the Monte Carlo sample.

tCI = quantile(tMC,[0.025 0.975])

% A 95% confidence interval on the true threshold transition is (0.52%, 0.98%).
% Copyright 2020 The MathWorks, Inc.