%% Create Fully Specified Univariate Model
% This example shows how to create a fully specified, two-state Markov-switching dynamic regression model.
% Suppose that an economy switches between two regimes: an expansion and a recession. If the economy is in an expansion, the probability the expansion persists in the next time step is 0.9, and the probability that it switches to a recession is 0.1. If the economy is in an recession, the probability the recession persists in the next time step is 0.7, and the probability that it switches to a recession is 0.3.
% Suppose that y_t is a univariate response process representing an economic measurement that can suggest which state the economy experiences during a period. During an expansion, y_t is this AR(2) model:
% y_t=5+0.3y_{t-1}+0.2y_{t-2}+\varepsilon_{1t},
% where \varepsilon_{1t} is an iid Gaussian process with mean 0 and variance 2. During a recession, y_t is this AR(1) model:
% y_t=-5+0.1y_{t-1}+\varepsilon_{2t},
% where \varepsilon_{2t} is an iid Gaussian process with mean 0 and variance 1.
%
%% Describe Switching Mechanism
% The right-stochastic transition matrix describing the regime switching probabilities is
% \[P = \left[ {\begin{array}{*{20}{c}}
% {0.9}&{0.1}\\
% {0.3}&{0.7}
% \end{array}} \right].\]
% Create a two-state discrete-time Markov chain model that describes the regime switching mechanism by passing P to mc. Label the regimes.

P = [0.9 0.1; 0.3 0.7];
mc = dtmc(P,'StateNames',["Expansion" "Recession"])

% mc is a dtmc object.
%
%% Describe State-Specific Dynamic Regression Submodels
% For each regime, create an AR model for y_t by using arima. Specify all parameter values, and enter a description for the models.

% Constants
C1 = 5;
C2 = -5;

% AR coefficients
AR1 = [0.3 0.2]; % 2 lags
AR2 = 0.1;       % 1 lags

% Innovations variances
v1 = 2;
v2 = 1;

% Submodels:
mdl1 = arima('Constant',C1,'AR',AR1,...
    'Variance',v1,'Description','Expansion State')
mdl2 = arima('Constant',C2,'AR',AR2,...
    'Variance',v2,'Description','Recession State')

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

mdl = [mdl1; mdl2];

%
%% Create Markov-Switching Dynamic Regression Model
% Create the Markov-switching dynamic regression model that describes the dynamic behavior of the economy with respect to y_t.

Mdl = msVAR(mc,mdl)

% Mdl is a fully specified msVAR object representing a univariate two-state Markov-switching dynamic regression model. You can pass Mdl to any msVAR object function for further analysis, or initialize the estimation procedure using the parameter values of Mdl.

Mdl.Submodels(1)
Mdl.Submodels(2)

% msVAR converts the arima object submodels to 1-D varm object equivalents.
% Copyright 2019 The MathWorks, Inc.