%% Plot Time-Varying IRF
% Simulate data from a time-varying state-space model, fit a model to the data, then plot the time-varying IRF of the estimated model.
% Consider the DGP represented by this system
% \begin{array}{l}
% x_t=\left\{\begin{array}{l}
% 0.75x_{t-1} + u_t; & t < 11\\
% -0.1x_{t-1} + 3u_t; & t \ge 11\\
% \end{array}\right.\\
% y_t=1.5x_t+2\varepsilon_t.
% \end{array}
% The function timeVariantAR1ParamMap.m, stored in mlr/examples/econ/main, specifies the model structure. mlr is the value of matlabroot.

type timeVariantAR1ParamMap.m

% Implicitly create a partially specified state-space model representing the DGP. For this example, fix the measurement-sensitivity coefficient C to 1.5.

C = 1.5;
fixCParamMap = @(x)timeVariantAR1ParamMap([x(1:4), C, x(5)]);
DGP = ssm(fixCParamMap);

% Simulate 20 observations from the DGP. Because DGP is partially specified, pass the true parameter values to simulate by using the 'Params' name-value pair argument.

rng(10) % For reproducibility
A1 = 0.75;
A2 = -0.1; 
B1 = 1;
B2 = 3;
D = 2;
trueParams = [A1 A2 2*log(B1) 2*log(B2) 2*log(D)]; % Transform variances for parameter map
y = simulate(DGP,20,'Params',trueParams);

% y is a 20-by-1 vector of simulated measurements y_t from the DGP.
% Because DGP is a partially specified, implicit model object, its parameters are unknown. Therefore, it can serve as a model template for estimation.
% Fit the model to the simulated data. Specify random standard Gaussian draws for the initial parameter values. Return the parameter estimates.

[~,estParams] = estimate(DGP,y,randn(1,5),'Display','off')

% estParams is a 1-by-5 vector of parameter estimates. The output argument list of the parameter mapping function determines the order of the estimates: A{1}, A{2}, B{1}, B{2}, and D.
% Plot the IRF of the measurement and state variables by supplying DGP (not the estimated model) and the estimated parameters by using the 'Params' name-value pair argument.

h = irfplot(DGP,'Params',estParams);
xline(h(1,1).Parent,10.5,'--')
xline(h(1,2).Parent,10.5,'--')

% The figures show time-varying IRFs of the measurement and state variables. The first 10 periods correspond to the IRF of the first state equation. During period 11, what remains of the shock transfers to the second state equation, and filters through that system until it diminishes.
% Copyright 2020 The MathWorks, Inc.
%