%% Compute Filtered 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 [1].
%
%% 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 [1] 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 Filtered State Probabilities
% Compute filtered state probabilities for the data and model.

FS = filter(Mdl,arate);
FS(end,:)

% FS is a 228-by-2 matrix of filtered state probabilities. Rows correspond to periods in the data arate, and columns correspond to the regimes.
% Plot the filtered probabilities of recession, as in [1], Figure 6.

figure;
plot(dates(3:230),FS(:,2),'r')
datetick('x')
title('Current Filter Probabilities and NBER Recessions')
recessionplot

%
%% Compute Smoothed State Probabilities
% Compute smoothed state probabilities, and then plot the smoothed probabilities of recession as in [1], Figure 6.

SS = smooth(Mdl,arate);

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

% Copyright 2019 The MathWorks, Inc.
%