ssfortran.StructuralModel#

class ssfortran.StructuralModel(endog, components, loading=None, loading_free=None)#

A model assembled from structural components (DK ch. 3).

The state vector stacks the components’ states in the order given, and the system matrices are block diagonal (DK eq. 3.10). Each block is initialized as its component needs: diffuse for nonstationary components, from the unconditional distribution for stationary ones (DK §5.6).

Parameters:
endogarray_like, shape (n,) or (n, p)

Observations, time first; NaN marks missing values.

componentslist

Irregular, Level, Trend, Seasonal, Cycle, Regression, ARIMA, ContinuousLevel or ContinuousTrend instances. With p > 1 each applies to every series (seemingly unrelated time series equations, DK §3.3), except Regression and ARIMA, which apply to one series.

loadingarray_like, shape (p, p_sig), optional

Signal loadings \(\Lambda\): components not marked at_observations describe p_sig signals, and \(Z = \Lambda Z_{sig}\) (DK §3.3.2, §3.7).

loading_freearray_like of bool, shape (p, p_sig), optional

Entries of loading to estimate; they become the last parameters.

Notes

Parameters are ordered component by component. Variances are mapped to the optimizer’s scale by \(\sigma^2 = \exp(2\psi)\) (DK §7.3.2); full covariances through a Cholesky factor with log diagonal.

Examples

A basic structural model: level, trigonometric seasonal and irregular (DK §8.2):

>>> rng = np.random.default_rng(2)
>>> season = np.tile([1.0, -0.5, 0.3, -0.8], 30)
>>> noise = 0.3 * rng.standard_normal(120)
>>> y = np.cumsum(0.2 * rng.standard_normal(120)) + season + noise
>>> comps = [ss.Irregular(), ss.Level(), ss.Seasonal(4, "trig")]
>>> mod = ss.StructuralModel(y, comps)
>>> mod.param_names
['sigma2.irregular', 'sigma2.level', 'sigma2.seasonal']
>>> res = mod.fit()
>>> sorted(res.components())
['irregular', 'level', 'seasonal']
components(params, variance=False)#

Compute the smoothed contribution of each component to the data.

For a component with states \(b\), the contribution is \(Z_{t,b} \hat\alpha_{t,b}\); for the irregular it is \(\hat\varepsilon_t\). The contributions add up to the observations.

Parameters:
paramsarray_like, shape (k,)

Constrained parameters.

variancebool, optional

Also return the variances of the contributions.

Returns:
componentsdict

{name: ndarray}, shape (n,) or (n, p). Names are the component kinds ("level", "seasonal", …), numbered when repeated.

variancesdict

The same for the variances; only with variance=True.

Raises:
TypeError

If the model is not a StructuralModel.

property concentrate_scale#

Whether a scale is concentrated out of the likelihood.

When true, H, Q and \(P_*\) set by the parameters are relative to a scale \(\sigma^2\), which is estimated in closed form (DK §2.10.2) and is not a parameter.

filter(params)#

Run the Kalman filter at given parameters.

Parameters:
paramsarray_like, shape (k,)

Constrained parameters.

Returns:
FilterResults

The filter output.

fit(start_params=None, maxiter=500, m=10, factr=10000000.0, pgtol=1e-05, compute_cov=True, gradient='auto')#

Estimate the parameters by maximum likelihood (DK §7.3).

L-BFGS-B minimizes -loglike / n over the unconstrained parameters. The defaults are those of statsmodels.

Parameters:
start_paramsarray_like, optional

Constrained starting values; default start_params.

maxiterint, optional

Maximum number of iterations.

mint, optional

Number of L-BFGS corrections.

factrfloat, optional

Stop when the relative reduction of the objective is below factr times the machine epsilon; 10 gives a tight optimum.

pgtolfloat, optional

Stop when the projected gradient is below pgtol.

compute_covbool, optional

Compute cov_params and bse from a numerical Hessian.

gradient{“auto”, “analytic”, “numerical”}, optional

"auto" uses the analytic score where it applies (DK §7.3.3) and central differences elsewhere.

Returns:
FitResults

Estimates and fit statistics.

Raises:
StateSpaceError

If the likelihood cannot be evaluated at the start.

Notes

The score covers parameters in H, R, Q and \(P_*\) through the smoothed disturbances (DK eq. 7.14, 7.16). Parameters that move Z or T get central differences, as DK recommend. Standard errors come from the Hessian in the unconstrained parameters and the delta method.

Examples

A local level with variances 1 (irregular) and 0.25 (level):

>>> rng = np.random.default_rng(2)
>>> y = np.cumsum(0.5 * rng.standard_normal(1000)) + rng.standard_normal(1000)
>>> res = ss.StructuralModel(y, [ss.Irregular(), ss.Level()]).fit()
>>> res.param_names
['sigma2.irregular', 'sigma2.level']
>>> np.round(res.params, 2)
array([1.04, 0.22])
loglike(params)#

Evaluate the log likelihood.

Parameters:
paramsarray_like, shape (k,)

Constrained parameters.

Returns:
float

Log likelihood, concentrated when concentrate_scale is set; the scale is then in scale.

property param_names#

Parameter names, e.g. "sigma2.level".

representation(params)#

Build the representation at given parameters.

Parameters:
paramsarray_like, shape (k,)

Constrained parameters.

Returns:
Representation

A copy, on the data’s scale when the scale is concentrated out.

property scale#

Concentrated scale at the last likelihood evaluation.

smooth(params)#

Run the filter and smoother at given parameters.

Parameters:
paramsarray_like, shape (k,)

Constrained parameters.

Returns:
SmootherResults

Smoothed states and disturbances.

property ssm#

The model’s own representation.

Changes to it, such as filter_method or tol_steady, apply to later likelihood evaluations. Its system matrices reflect the last parameters evaluated. MappedModel and MLEModel set its matrices and initialization through mod[name] = value and their initialize_* methods.

property start_params#

Starting values for estimation, constrained.

transform_params(unconstrained)#

Map unconstrained values to parameters.

Parameters:
unconstrainedarray_like, shape (k,)

Values on the optimizer’s scale.

Returns:
ndarray, shape (k,)

Constrained parameters, e.g. variances \(\exp(2x)\) (DK §7.3.2).

untransform_params(constrained)#

Map parameters to the optimizer’s unconstrained scale.

Parameters:
constrainedarray_like, shape (k,)

Parameters.

Returns:
ndarray, shape (k,)

The inverse of transform_params().