%% Compute Smoothed Probabilities of Recession
% Consider a two-state Markov-switching dynamic regression model of the postwar US real GDP growth rate. The model has the parameter estimates presented in docid:econ_ug.mw_7d9189c9-cfde-43ae-8835-2caa20c4d98a.
%
%% Create Markov-Switching Dynamic Regression Model
% Create a fully specified discrete-time Markov chain model that describes the regime switching mechanism. Label the regimes.

P = [0.92 0.08; 0.26 0.74];
mc = dtmc(P,'StateNames',["Expansion" "Recession"]);

% Create separate, fully specified AR(0) models for the two regimes.

sigma = 3.34; % Homoscedastic models across states
mdl1 = arima('Constant',4.62,'Variance',sigma^2);
mdl2 = arima('Constant',-0.48,'Variance',sigma^2);
mdl = [mdl1 mdl2];

% Create the Markov-switching dynamic regression model from the switching mechanism mc and the state-specific submodels mdl.

Mdl = msVAR(mc,mdl);

% Mdl 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 period of interest 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

% The transformation drops the first observation.
%
%% Compute Smoothed State Probabilities
% Compute smoothed state probabilities for the data and model.  Display the smoothed state distribution for 1972:Q2.

SS = smooth(Mdl,arate);
SS(end,:)

% SS is a 228-by-2 matrix of smoothed state probabilities. Rows correspond to periods in the data arate, and columns correspond to the regimes.
% Plot the smoothed probabilities of recession, as in docid:econ_ug.mw_7d9189c9-cfde-43ae-8835-2caa20c4d98a, Figure 6.

figure;
plot(dates(3:230),SS(:,2),'r')
datetick('x')
recessionplot
title("Full-Sample Smoothed Probabilities and NBER Recessions")

% Copyright 2019 The MathWorks, Inc.
%
%