%% Estimate and Plot VEC Model FEVD
% Fit a 4-D VEC(2) model with two cointegrating relations to Danish money and income rate series. Then, estimate and plot the orthogonalized FEVD from the estimated model.
% Load the Danish money and income data set.

load Data_JDanish

% The data set includes four times series in the table DataTable.  For more details on the data set, enter Description at the command line.
%
% Create a vecm model object that represents a 4-D VEC(2) model with two cointegrating relations. Specify the variable names.

Mdl = vecm(4,2,2);
Mdl.SeriesNames = DataTable.Properties.VariableNames;

% Mdl is a vecm model object specifying the structure of a 4-D VEC(2) model; it is a template for estimation.
%
% Fit the VEC(2) model to the data set.

Mdl = estimate(Mdl,DataTable.Series);

% Mdl is a fully specified vecm model object representing an estimated 4-D VEC(2) model.
%
% Estimate the orthogonalized FEVD from the estimated VEC(2) model.

Decomposition = fevd(Mdl);

% Decomposition is a 20-by-4-by-4 array representing the FEVD of Mdl. Rows correspond to consecutive time points from time 1 to 20, columns correspond to variables receiving a one-standard-deviation innovation shock at time 0, and pages correspond to variables whose forecast error variance fevd decomposes.  Mdl.SeriesNames specifies the variable order.
% Because Decomposition represents an orthogonalized FEVD, rows should sum to 1. This characteristic illustrates that orthogonalized FEVDs represent proportions of variance contributions.  Confirm that all rows of Decomposition sum to 1.

rowsums = sum(Decomposition,2);
sum((rowsums - 1).^2 > eps)

% Row sums among the pages are close to 1.
% Display the contributions to the forecast error variance of the bond rate when real income is shocked at time 0.

Decomposition(:,2,3)

%
% The armafevd function plots the FEVD of VAR models characterized by AR coefficient matrices.  Plot the FEVD of a VEC model by:
% Expressing the VEC(2) model as a VAR(3) model by passing Mdl to varm
% Passing the VAR model AR coefficients and innovations covariance matrix to armafevd
% Plot the VEC(2) model FEVD for 40 periods.

VARMdl = varm(Mdl);
armafevd(VARMdl.AR,[],"InnovCov",VARMdl.Covariance,...
    "NumObs",40);

% Each plot shows the four FEVDs of a variable when all other variables are shocked at time 0. Mdl.SeriesNames specifies the variable order.
% Copyright 2018 The MathWorks, Inc.
%
%