%% Compute Optimal Point Forecasts
% Forecast a response path from a two-state Markov-switching dynamic regression model for a 1-D response process. This example uses arbitrary parameter values for the data-generating process (DGP).
%
%% Create Fully Specified Model for DGP
% Create a two-state discrete-time Markov chain model that describes the regime switching mechanism. Label the regimes.

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

% mc is a fully specified dtmc object.
% For each regime, use arima to create an AR model that describes the response process within the regime. Store the submodels in a vector.

mdl1 = arima('Constant',5,'AR',[0.3 0.2],...
    'Variance',2);
mdl2 = arima('Constant',-5,'AR',0.1,...
    'Variance',1);
mdl = [mdl1; mdl2];

% mdl1 and mdl2 are fully specified arima objects.
% Create a Markov-switching dynamic regression model from the switching mechanism mc and the vector of submodels mdl.

Mdl = msVAR(mc,mdl);

% Mdl is a fully specified msVAR object.
%
%% Simulate Response Data from DGP
% forecast requires enough data before the forecast horizon to initialize the model. Simulate 120 observations from the DGP.

rng(1); % For reproducibility
y = simulate(Mdl,120);

% y is a 120-by-1 random path of responses.
%
%% Compute Optimal Point Forecasts
% Treat the first 100 observations of the simulated response data as the presample for the forecast, and treat the last 20 observations as a holdout sample.

idx0 = 1:100;
idx1 = 101:120;
y0 = y(idx0);
y1 = y(idx1);

% Compute 1- through 20-step-ahead optimal point forecasts from the model.

yf = forecast(Mdl,y0,20);

% yf is a 20-by-1 vector of optimal point forecasts.
% Plot the simulated response data and forecasts.

figure
hold on
plot(idx0,y0,'b');
h = plot(idx1,y1,'b--');
h1 = plot(idx1,yf,'r');
yfill = [ylim fliplr(ylim)];
xfill = [idx0(end) idx0(end) idx1(end) idx1(end)];
fill(xfill,yfill,'k','FaceAlpha',0.05)
legend([h h1],["Actual" "Optimal"],'Location','NorthWest')
title('Forecasts')
hold off

% Copyright 2019 The MathWorks, Inc.
%
%