%% Estimate Markov-Switching Dynamic Regression Model
% Consider a two-state Markov-switching dynamic regression model of the postwar US real GDP growth rate, as estimated in docid:econ_ug.mw_2b9b64d5-885a-40c5-a25c-1a6af51f0dc4.
%
%% Create Partially Specified Model for Estimation
% Create a Markov-switching dynamic regression model for the naive estimator by specifying a two-state discrete-time Markov chain with an unknown transition matrix and AR(0) (constant only) submodels for both regimes. Label the regimes.

P = NaN(2);
mc = dtmc(P,'StateNames',["Expansion" "Recession"]);
mdl = arima(0,0,0);
Mdl = msVAR(mc,[mdl; mdl]);

% Mdl is a partially specified msVAR object. NaN-valued elements of the Switch and SubModels properties indicate estimable parameters.
%
%% Create Fully Specified Model Containing Initial Values
% The estimation procedure requires initial values for all estimable parameters.  Create a fully specified Markov-switching dynamic regression model that has the same structure as Mdl, but set all estimable parameters to initial values.  This example uses arbitrary initial values.

P0 = 0.5*ones(2);
mc0 = dtmc(P0,'StateNames',Mdl.StateNames);
mdl01 = arima('Constant',1,'Variance',1);
mdl02 = arima('Constant',-1,'Variance',1);
Mdl0 = msVAR(mc0,[mdl01; mdl02]);

% Mdl0 is a fully specified msVAR object.
%
%% Load and Preprocess Data
% Load the US GDP data set.

load Data_GDP

% Data contains quarterly measurements of the US real GDP in the period 1947:Q1–2005:Q2. The estimation period in docid:econ_ug.mw_2b9b64d5-885a-40c5-a25c-1a6af51f0dc4 is 1947:Q2–2004:Q2. For more details on the data set, enter Description at the command line.
% Transform the data to an annualized rate series by:
% Converting the data to a quarterly rate within the estimation period
% Annualizing the quarterly rates

qrate = diff(Data(2:230))./Data(2:229); % Quarterly rate
arate = 100*((1 + qrate).^4 - 1);       % Annualized rate

%
%% Estimate Model
% Fit the model Mdl to the annualized rate series arate.  Specify Mdl0 as the model containing the initial estimable parameter values.

EstMdl = estimate(Mdl,Mdl0,arate);

% EstMdl is an estimated (fully specified) Markov-switching dynamic regression model. EstMdl.Switch is an estimated discrete-time Markov chain model (dtmc object), and EstMdl.Submodels is a vector of estimated univariate VAR(0) models (varm objects).
% Display the estimated state-specific dynamic models.

EstMdlExp = EstMdl.Submodels(1)
EstMdlRec = EstMdl.Submodels(2)

% Display the estimated state transition matrix.

EstP = EstMdl.Switch.P

%
% Copyright 2019 The MathWorks, Inc.