ssfortran.MLEModel#

class ssfortran.MLEModel(endog, k_states, k_params, k_posdef=None)#

A model whose system matrices are set by Python code.

Subclass it as statsmodels’ MLEModel: set the fixed matrices (self[name] = value) and the initialization (self.initialize_*) in __init__, and override

  • update(params), which sets the matrices that depend on the constrained parameters with self[name] = value;

  • start_params, a property;

  • optionally transform_params and untransform_params (the default is no transform) and param_names.

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

Observations, time first; NaN marks missing values.

k_statesint

Number of states m.

k_paramsint

Number of parameters.

k_posdefint, optional

Number of state disturbances r; default k_states.

See also

MappedModel

Declared models, without Python in the loop.

Notes

The library calls update at every likelihood evaluation, and the analytic score calls it 2k more times per gradient for its matrix derivatives. Python therefore runs inside the optimization; declared and built-in models are faster, and only they work with fit_many(). An exception in update is raised again when the library returns, and the model stays usable.

Examples

>>> class LocalLevel(ss.MLEModel):
...     def __init__(self, y):
...         super().__init__(y, k_states=1, k_params=2)
...         self["design"] = self["transition"] = self["selection"] = [[1.0]]
...         self.initialize_diffuse()
...     @property
...     def start_params(self):
...         return np.array([1.0, 1.0])
...     def transform_params(self, x):
...         return np.exp(2 * np.asarray(x))
...     def untransform_params(self, p):
...         return 0.5 * np.log(p)
...     def update(self, params):
...         self["obs_cov"] = [[params[0]]]
...         self["state_cov"] = [[params[1]]]
>>> y = np.cumsum(np.random.default_rng(4).standard_normal(100))
>>> LocalLevel(y).fit().converged
True
__getitem__(name)#

Copy of a system matrix of the model’s representation.

__setitem__(name, value)#

Set a system matrix of the model’s representation.

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, **kwargs)#

Estimate the parameters by maximum likelihood.

Parameters:
start_paramsarray_like, optional

Constrained starting values; default start_params.

**kwargs

As for Model.fit().

Returns:
FitResults

Estimates and fit statistics.

initialize(a1, Pstar, Pinf)#

Initialize with \(\alpha_1 \sim N(a_1, P_* + \kappa P_\infty)\).

The general form of DK §5.1, with \(\kappa \to \infty\) handled exactly.

Parameters:
a1array_like, shape (m,)

Mean.

Pstararray_like, shape (m, m)

Variance of the proper part.

Pinfarray_like, shape (m, m)

Variance direction of the diffuse part; usually a selection \(A A'\).

initialize_approximate_diffuse(variance=1000000.0)#

Initialize with mean zero and a large variance, variance * I.

Parameters:
variancefloat, optional

Variance of each state; default 1e6, as in statsmodels.

See also

initialize_diffuse

The exact treatment (DK §5.2).

initialize_block(start, stop, kind, a1=None, P1=None, variance=1000000.0)#

Initialize a block of states, leaving the others as they are.

Blocks combine, for example a diffuse trend with a stationary ARMA block (DK §5.6).

Parameters:
start, stopint

The block is states start:stop (0-based, like a slice).

kindint

INIT_KNOWN, INIT_APPROX_DIFFUSE, INIT_STATIONARY or INIT_DIFFUSE.

a1, P1array_like, optional

Mean (stop - start,) and variance for INIT_KNOWN.

variancefloat, optional

Variance for INIT_APPROX_DIFFUSE.

Notes

A stationary block must not depend on states outside it through T.

Examples

A diffuse level with a stationary AR(1) disturbance:

>>> rep = ss.Representation(np.zeros(20), k_states=2)
>>> rep["transition"] = [[1.0, 0.0], [0.0, 0.5]]
>>> rep.initialize_block(0, 1, ss.INIT_DIFFUSE)
>>> rep.initialize_block(1, 2, ss.INIT_STATIONARY)
initialize_diffuse()#

Initialize every state as exact diffuse (DK §5.2).

The initial variance is \(\kappa I\) with \(\kappa \to \infty\), handled exactly by the exact initial Kalman filter; the log likelihood is then the diffuse log likelihood (DK §7.2.2).

See also

initialize_approximate_diffuse

A large finite variance instead.

initialize_known(a1, P1)#

Initialize with a known mean and variance.

Parameters:
a1array_like, shape (m,)

Mean of the initial state.

P1array_like, shape (m, m)

Variance of the initial state.

See also

initialize_diffuse

Exact diffuse initialization.

initialize_stationary

The unconditional distribution.

initialize_block

Different initializations for blocks of states.

initialize_stationary()#

Initialize with the unconditional distribution of the state.

The mean is \((I - T)^{-1} c\) and the variance solves \(P = T P T' + R Q R'\) (DK §5.6.2), recomputed from the current matrices at every filter run. The model must be time-invariant in T, R, Q and c at the first period.

Raises:
StateSpaceError

From the filter, with code 6, if T has an eigenvalue on or outside the unit circle.

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; override to name them.

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 representation, which update fills.

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().

update(params)#

Set the system matrices from the parameters; override this.

Parameters:
paramsndarray, shape (k,)

Constrained parameters.