%% Smooth States of Diffuse State-Space Model Containing Regression Component
% Suppose that the linear relationship between unemployment rate and the nominal gross national product (nGNP) is of interest. Suppose further that unemployment rate is an AR(1) series. Symbolically, and in state-space form, the model is
% \begin{array}{l}
% x_{t} = \phi x_{t - 1} + \sigma u_{t}\\
% {y_t} - \beta {Z_t} = {x_{t}},
% \end{array}
% where:
% x_{t} is the unemployment rate at time t.
% y_{t} is the observed change in the unemployment rate being deflated by the return of nGNP (Z_t).
% u_{t} is the Gaussian series of state disturbances having mean 0 and unknown standard deviation \sigma.
% Load the Nelson-Plosser data set, which contains the unemployment rate and nGNP series, among other things.

load Data_NelsonPlosser

%
% Preprocess the data by taking the natural logarithm of the nGNP series, and removing the starting NaN values from each series.

isNaN = any(ismissing(DataTable),2);       % Flag periods containing NaNs
gnpn = DataTable.GNPN(~isNaN);
y = diff(DataTable.UR(~isNaN));
T = size(gnpn,1);                          % The sample size
Z = price2ret(gnpn);

% This example continues using the series without NaN values. However, using the Kalman filter framework, the software can accommodate series containing missing values.
%
% Specify the coefficient matrices.

A = NaN;
B = NaN;
C = 1;

%
% Create the state-space model using dssm by supplying the coefficient matrices and specifying that the state values come from a diffuse distribution. The diffuse specification indicates complete ignorance about the moments of the initial distribution.

StateType = 2;
Mdl = dssm(A,B,C,'StateType',StateType);

%
% Estimate the parameters. Specify the regression component and its initial value for optimization using the 'Predictors' and 'Beta0' name-value pair arguments, respectively. Display the estimates and all optimization diagnostic information. Restrict the estimate of \sigma to all positive, real numbers.

params0 = [0.3 0.2]; % Initial values chosen arbitrarily
Beta0 = 0.1;
[EstMdl,estParams] = estimate(Mdl,y,params0,'Predictors',Z,'Beta0',Beta0,...
    'lb',[-Inf 0 -Inf]);

% EstMdl is a dssm model, and you can access its properties using dot notation.
%
% Smooth the estimated diffuse state-space model. EstMdl does not store the data or the regression coefficients, so you must pass in them in using the name-value pair arguments 'Predictors' and 'Beta', respectively. Plot the smoothed states.

SmoothedX = smooth(EstMdl,y,'Predictors',Z,'Beta',estParams(end));

figure
plot(dates(end-(T-1)+1:end),SmoothedX);
xlabel('Period')
ylabel('Change in the unemployment rate')
title('Smoothed Change in the Unemployment Rate')
axis tight

% Copyright 2015 The MathWorks, Inc.