%% Specify Presample Data
% Consider the data in docid:econ_ug.mw_4a734b08-4bfa-4749-9816-7dc6832c6c20, but assume that the period of interest is 1960:Q1–2004:Q2. Also, consider adding an autoregressive term to each submodel.
%
% Create a partially specified Markov-switching dynamic regression model for estimation. Specify AR(1) submodels.

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

% Because the submodels are AR(1), each requires one presample observation to initialize its dynamic component for estimation.
% Create the model containing initial parameter values for the estimation procedure.

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

% Load the data. Transform the entire set to an annualized rate series.

load Data_GDP
qrate = diff(Data)./Data(1:(end - 1)); 
arate = 100*((1 + qrate).^4 - 1);

% Identify the presample and estimation sample periods using the dates associated with the annualized rate series. Because the transformation applies the first difference, you must drop the first observation date from the original sample.

dates = datetime(dates(2:end),'ConvertFrom','datenum',...
    'Format','yyyy:QQQ','Locale','en_US');
estPrd = datetime(["1960:Q2" "2004:Q2"],'InputFormat','yyyy:QQQ',...
    'Format','yyyy:QQQ','Locale','en_US');
idxEst = isbetween(dates,estPrd(1),estPrd(2));
idxPre = dates < estPrd(1); % The presample is the previous quarter.

% Fit the model to the estimation sample data. Specify the presample observation and plot the loglikelihood at each iteration when the estimation procedure terminates.

EstMdl = estimate(Mdl,Mdl0,arate(idxEst),'Y0',arate(idxPre),...
    'IterationPlot',true);

% Copyright 2019 The MathWorks, Inc.