code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def transform_params(self, unconstrained):
"""
Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer, to be
transformed.
Returns
-------
constrained : array_like
Array of constrained parameters which may be used in likelihood
evaluation.
Notes
-----
Constrains the factor transition to be stationary and variances to be
positive.
"""
unconstrained = np.array(unconstrained, ndmin=1)
dtype = unconstrained.dtype
constrained = np.zeros(unconstrained.shape, dtype=dtype)
# 1. Factor loadings
# The factor loadings do not need to be adjusted
constrained[self._params_loadings] = (
unconstrained[self._params_loadings])
# 2. Exog
# The regression coefficients do not need to be adjusted
constrained[self._params_exog] = (
unconstrained[self._params_exog])
# 3. Error covariances
# If we have variances, force them to be positive
if self.error_cov_type in ['scalar', 'diagonal']:
constrained[self._params_error_cov] = (
unconstrained[self._params_error_cov]**2)
# Otherwise, nothing needs to be done
elif self.error_cov_type == 'unstructured':
constrained[self._params_error_cov] = (
unconstrained[self._params_error_cov])
# 4. Factor transition VAR
# VAR transition: optionally force to be stationary
if self.enforce_stationarity and self.factor_order > 0:
# Transform the parameters
unconstrained_matrices = (
unconstrained[self._params_factor_transition].reshape(
self.k_factors, self._factor_order))
# This is always an identity matrix, but because the transform
# done prior to update (where the ssm representation matrices
# change), it may be complex
cov = self.ssm['state_cov', :self.k_factors, :self.k_factors].real
coefficient_matrices, variance = (
constrain_stationary_multivariate(unconstrained_matrices, cov))
constrained[self._params_factor_transition] = (
coefficient_matrices.ravel())
else:
constrained[self._params_factor_transition] = (
unconstrained[self._params_factor_transition])
# 5. Error transition VAR
# VAR transition: optionally force to be stationary
if self.enforce_stationarity and self.error_order > 0:
# Joint VAR specification
if self.error_var:
unconstrained_matrices = (
unconstrained[self._params_error_transition].reshape(
self.k_endog, self._error_order))
start = self.k_factors
end = self.k_factors + self.k_endog
cov = self.ssm['state_cov', start:end, start:end].real
coefficient_matrices, variance = (
constrain_stationary_multivariate(
unconstrained_matrices, cov))
constrained[self._params_error_transition] = (
coefficient_matrices.ravel())
# Separate AR specifications
else:
coefficients = (
unconstrained[self._params_error_transition].copy())
for i in range(self.k_endog):
start = i * self.error_order
end = (i + 1) * self.error_order
coefficients[start:end] = constrain_stationary_univariate(
coefficients[start:end])
constrained[self._params_error_transition] = coefficients
else:
constrained[self._params_error_transition] = (
unconstrained[self._params_error_transition])
return constrained | Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer, to be
transformed.
Returns
-------
constrained : array_like
Array of constrained parameters which may be used in likelihood
evaluation.
Notes
-----
Constrains the factor transition to be stationary and variances to be
positive. | transform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/dynamic_factor.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/dynamic_factor.py | BSD-3-Clause |
def untransform_params(self, constrained):
"""
Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer.
Parameters
----------
constrained : array_like
Array of constrained parameters used in likelihood evaluation, to
be transformed.
Returns
-------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer.
"""
constrained = np.array(constrained, ndmin=1)
dtype = constrained.dtype
unconstrained = np.zeros(constrained.shape, dtype=dtype)
# 1. Factor loadings
# The factor loadings do not need to be adjusted
unconstrained[self._params_loadings] = (
constrained[self._params_loadings])
# 2. Exog
# The regression coefficients do not need to be adjusted
unconstrained[self._params_exog] = (
constrained[self._params_exog])
# 3. Error covariances
# If we have variances, force them to be positive
if self.error_cov_type in ['scalar', 'diagonal']:
unconstrained[self._params_error_cov] = (
constrained[self._params_error_cov]**0.5)
# Otherwise, nothing needs to be done
elif self.error_cov_type == 'unstructured':
unconstrained[self._params_error_cov] = (
constrained[self._params_error_cov])
# 3. Factor transition VAR
# VAR transition: optionally force to be stationary
if self.enforce_stationarity and self.factor_order > 0:
# Transform the parameters
constrained_matrices = (
constrained[self._params_factor_transition].reshape(
self.k_factors, self._factor_order))
cov = self.ssm['state_cov', :self.k_factors, :self.k_factors].real
coefficient_matrices, variance = (
unconstrain_stationary_multivariate(
constrained_matrices, cov))
unconstrained[self._params_factor_transition] = (
coefficient_matrices.ravel())
else:
unconstrained[self._params_factor_transition] = (
constrained[self._params_factor_transition])
# 5. Error transition VAR
# VAR transition: optionally force to be stationary
if self.enforce_stationarity and self.error_order > 0:
# Joint VAR specification
if self.error_var:
constrained_matrices = (
constrained[self._params_error_transition].reshape(
self.k_endog, self._error_order))
start = self.k_factors
end = self.k_factors + self.k_endog
cov = self.ssm['state_cov', start:end, start:end].real
coefficient_matrices, variance = (
unconstrain_stationary_multivariate(
constrained_matrices, cov))
unconstrained[self._params_error_transition] = (
coefficient_matrices.ravel())
# Separate AR specifications
else:
coefficients = (
constrained[self._params_error_transition].copy())
for i in range(self.k_endog):
start = i * self.error_order
end = (i + 1) * self.error_order
coefficients[start:end] = (
unconstrain_stationary_univariate(
coefficients[start:end]))
unconstrained[self._params_error_transition] = coefficients
else:
unconstrained[self._params_error_transition] = (
constrained[self._params_error_transition])
return unconstrained | Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer.
Parameters
----------
constrained : array_like
Array of constrained parameters used in likelihood evaluation, to
be transformed.
Returns
-------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer. | untransform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/dynamic_factor.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/dynamic_factor.py | BSD-3-Clause |
def update(self, params, transformed=True, includes_fixed=False,
complex_step=False):
"""
Update the parameters of the model
Updates the representation matrices to fill in the new parameter
values.
Parameters
----------
params : array_like
Array of new parameters.
transformed : bool, optional
Whether or not `params` is already transformed. If set to False,
`transform_params` is called. Default is True..
Returns
-------
params : array_like
Array of parameters.
Notes
-----
Let `n = k_endog`, `m = k_factors`, and `p = factor_order`. Then the
`params` vector has length
:math:`[n \times m] + [n] + [m^2 \times p]`.
It is expanded in the following way:
- The first :math:`n \times m` parameters fill out the factor loading
matrix, starting from the [0,0] entry and then proceeding along rows.
These parameters are not modified in `transform_params`.
- The next :math:`n` parameters provide variances for the error_cov
errors in the observation equation. They fill in the diagonal of the
observation covariance matrix, and are constrained to be positive by
`transofrm_params`.
- The next :math:`m^2 \times p` parameters are used to create the `p`
coefficient matrices for the vector autoregression describing the
factor transition. They are transformed in `transform_params` to
enforce stationarity of the VAR(p). They are placed so as to make
the transition matrix a companion matrix for the VAR. In particular,
we assume that the first :math:`m^2` parameters fill the first
coefficient matrix (starting at [0,0] and filling along rows), the
second :math:`m^2` parameters fill the second matrix, etc.
"""
params = self.handle_params(params, transformed=transformed,
includes_fixed=includes_fixed)
# 1. Factor loadings
# Update the design / factor loading matrix
self.ssm[self._idx_loadings] = (
params[self._params_loadings].reshape(self.k_endog, self.k_factors)
)
# 2. Exog
if self.k_exog > 0:
exog_params = params[self._params_exog].reshape(
self.k_endog, self.k_exog).T
self.ssm[self._idx_exog] = np.dot(self.exog, exog_params).T
# 3. Error covariances
if self.error_cov_type in ['scalar', 'diagonal']:
self.ssm[self._idx_error_cov] = (
params[self._params_error_cov])
elif self.error_cov_type == 'unstructured':
error_cov_lower = np.zeros((self.k_endog, self.k_endog),
dtype=params.dtype)
error_cov_lower[self._idx_lower_error_cov] = (
params[self._params_error_cov])
self.ssm[self._idx_error_cov] = (
np.dot(error_cov_lower, error_cov_lower.T))
# 4. Factor transition VAR
self.ssm[self._idx_factor_transition] = (
params[self._params_factor_transition].reshape(
self.k_factors, self.factor_order * self.k_factors))
# 5. Error transition VAR
if self.error_var:
self.ssm[self._idx_error_transition] = (
params[self._params_error_transition].reshape(
self.k_endog, self._error_order))
else:
self.ssm[self._idx_error_transition] = (
params[self._params_error_transition]) | Update the parameters of the model
Updates the representation matrices to fill in the new parameter
values.
Parameters
----------
params : array_like
Array of new parameters.
transformed : bool, optional
Whether or not `params` is already transformed. If set to False,
`transform_params` is called. Default is True..
Returns
-------
params : array_like
Array of parameters.
Notes
-----
Let `n = k_endog`, `m = k_factors`, and `p = factor_order`. Then the
`params` vector has length
:math:`[n \times m] + [n] + [m^2 \times p]`.
It is expanded in the following way:
- The first :math:`n \times m` parameters fill out the factor loading
matrix, starting from the [0,0] entry and then proceeding along rows.
These parameters are not modified in `transform_params`.
- The next :math:`n` parameters provide variances for the error_cov
errors in the observation equation. They fill in the diagonal of the
observation covariance matrix, and are constrained to be positive by
`transofrm_params`.
- The next :math:`m^2 \times p` parameters are used to create the `p`
coefficient matrices for the vector autoregression describing the
factor transition. They are transformed in `transform_params` to
enforce stationarity of the VAR(p). They are placed so as to make
the transition matrix a companion matrix for the VAR. In particular,
we assume that the first :math:`m^2` parameters fill the first
coefficient matrix (starting at [0,0] and filling along rows), the
second :math:`m^2` parameters fill the second matrix, etc. | update | python | statsmodels/statsmodels | statsmodels/tsa/statespace/dynamic_factor.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/dynamic_factor.py | BSD-3-Clause |
def factors(self):
"""
Estimates of unobserved factors
Returns
-------
out : Bunch
Has the following attributes shown in Notes.
Notes
-----
The output is a bunch of the following format:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, level is always the first component of the state vector
out = None
spec = self.specification
if spec.k_factors > 0:
offset = 0
end = spec.k_factors
res = self.filter_results
out = Bunch(
filtered=res.filtered_state[offset:end],
filtered_cov=res.filtered_state_cov[offset:end, offset:end],
smoothed=None, smoothed_cov=None,
offset=offset)
if self.smoothed_state is not None:
out.smoothed = self.smoothed_state[offset:end]
if self.smoothed_state_cov is not None:
out.smoothed_cov = (
self.smoothed_state_cov[offset:end, offset:end])
return out | Estimates of unobserved factors
Returns
-------
out : Bunch
Has the following attributes shown in Notes.
Notes
-----
The output is a bunch of the following format:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | factors | python | statsmodels/statsmodels | statsmodels/tsa/statespace/dynamic_factor.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/dynamic_factor.py | BSD-3-Clause |
def coefficients_of_determination(self):
"""
Coefficients of determination (:math:`R^2`) from regressions of
individual estimated factors on endogenous variables.
Returns
-------
coefficients_of_determination : ndarray
A `k_endog` x `k_factors` array, where
`coefficients_of_determination[i, j]` represents the :math:`R^2`
value from a regression of factor `j` and a constant on endogenous
variable `i`.
Notes
-----
Although it can be difficult to interpret the estimated factor loadings
and factors, it is often helpful to use the coefficients of
determination from univariate regressions to assess the importance of
each factor in explaining the variation in each endogenous variable.
In models with many variables and factors, this can sometimes lend
interpretation to the factors (for example sometimes one factor will
load primarily on real variables and another on nominal variables).
See Also
--------
plot_coefficients_of_determination
"""
from statsmodels.tools import add_constant
spec = self.specification
coefficients = np.zeros((spec.k_endog, spec.k_factors))
which = 'filtered' if self.smoothed_state is None else 'smoothed'
for i in range(spec.k_factors):
exog = add_constant(self.factors[which][i])
for j in range(spec.k_endog):
endog = self.filter_results.endog[j]
coefficients[j, i] = OLS(endog, exog).fit().rsquared
return coefficients | Coefficients of determination (:math:`R^2`) from regressions of
individual estimated factors on endogenous variables.
Returns
-------
coefficients_of_determination : ndarray
A `k_endog` x `k_factors` array, where
`coefficients_of_determination[i, j]` represents the :math:`R^2`
value from a regression of factor `j` and a constant on endogenous
variable `i`.
Notes
-----
Although it can be difficult to interpret the estimated factor loadings
and factors, it is often helpful to use the coefficients of
determination from univariate regressions to assess the importance of
each factor in explaining the variation in each endogenous variable.
In models with many variables and factors, this can sometimes lend
interpretation to the factors (for example sometimes one factor will
load primarily on real variables and another on nominal variables).
See Also
--------
plot_coefficients_of_determination | coefficients_of_determination | python | statsmodels/statsmodels | statsmodels/tsa/statespace/dynamic_factor.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/dynamic_factor.py | BSD-3-Clause |
def plot_coefficients_of_determination(self, endog_labels=None,
fig=None, figsize=None):
"""
Plot the coefficients of determination
Parameters
----------
endog_labels : bool, optional
Whether or not to label the endogenous variables along the x-axis
of the plots. Default is to include labels if there are 5 or fewer
endogenous variables.
fig : Figure, optional
If given, subplots are created in this figure instead of in a new
figure. Note that the grid will be created in the provided
figure using `fig.add_subplot()`.
figsize : tuple, optional
If a figure is created, this argument allows specifying a size.
The tuple is (width, height).
Notes
-----
Produces a `k_factors` x 1 plot grid. The `i`th plot shows a bar plot
of the coefficients of determination associated with factor `i`. The
endogenous variables are arranged along the x-axis according to their
position in the `endog` array.
See Also
--------
coefficients_of_determination
"""
from statsmodels.graphics.utils import _import_mpl, create_mpl_fig
_import_mpl()
fig = create_mpl_fig(fig, figsize)
spec = self.specification
# Should we label endogenous variables?
if endog_labels is None:
endog_labels = spec.k_endog <= 5
# Plot the coefficients of determination
coefficients_of_determination = self.coefficients_of_determination
plot_idx = 1
locations = np.arange(spec.k_endog)
for coeffs in coefficients_of_determination.T:
# Create the new axis
ax = fig.add_subplot(spec.k_factors, 1, plot_idx)
ax.set_ylim((0, 1))
ax.set(title='Factor %i' % plot_idx, ylabel=r'$R^2$')
bars = ax.bar(locations, coeffs)
if endog_labels:
width = bars[0].get_width()
ax.xaxis.set_ticks(locations + width / 2)
ax.xaxis.set_ticklabels(self.model.endog_names)
else:
ax.set(xlabel='Endogenous variables')
ax.xaxis.set_ticks([])
plot_idx += 1
return fig | Plot the coefficients of determination
Parameters
----------
endog_labels : bool, optional
Whether or not to label the endogenous variables along the x-axis
of the plots. Default is to include labels if there are 5 or fewer
endogenous variables.
fig : Figure, optional
If given, subplots are created in this figure instead of in a new
figure. Note that the grid will be created in the provided
figure using `fig.add_subplot()`.
figsize : tuple, optional
If a figure is created, this argument allows specifying a size.
The tuple is (width, height).
Notes
-----
Produces a `k_factors` x 1 plot grid. The `i`th plot shows a bar plot
of the coefficients of determination associated with factor `i`. The
endogenous variables are arranged along the x-axis according to their
position in the `endog` array.
See Also
--------
coefficients_of_determination | plot_coefficients_of_determination | python | statsmodels/statsmodels | statsmodels/tsa/statespace/dynamic_factor.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/dynamic_factor.py | BSD-3-Clause |
def initialize(self):
"""
Initialize the SARIMAX model.
Notes
-----
These initialization steps must occur following the parent class
__init__ function calls.
"""
super().initialize()
# Cache the indexes of included polynomial orders (for update below)
# (but we do not want the index of the constant term, so exclude the
# first index)
self._polynomial_ar_idx = np.nonzero(self.polynomial_ar)[0][1:]
self._polynomial_ma_idx = np.nonzero(self.polynomial_ma)[0][1:]
self._polynomial_seasonal_ar_idx = np.nonzero(
self.polynomial_seasonal_ar
)[0][1:]
self._polynomial_seasonal_ma_idx = np.nonzero(
self.polynomial_seasonal_ma
)[0][1:]
# Save the indices corresponding to the reduced form lag polynomial
# parameters in the transition and selection matrices so that they
# do not have to be recalculated for each update()
start_row = self._k_states_diff
end_row = start_row + self.k_ar + self.k_seasonal_ar
col = self._k_states_diff
if not self.hamilton_representation:
self.transition_ar_params_idx = (
np.s_['transition', start_row:end_row, col]
)
else:
self.transition_ar_params_idx = (
np.s_['transition', col, start_row:end_row]
)
start_row += 1
end_row = start_row + self.k_ma + self.k_seasonal_ma
col = 0
if not self.hamilton_representation:
self.selection_ma_params_idx = (
np.s_['selection', start_row:end_row, col]
)
else:
self.design_ma_params_idx = (
np.s_['design', col, start_row:end_row]
)
# Cache indices for exog variances in the state covariance matrix
if self.state_regression and self.time_varying_regression:
idx = np.diag_indices(self.k_posdef)
self._exog_variance_idx = ('state_cov', idx[0][-self._k_exog:],
idx[1][-self._k_exog:]) | Initialize the SARIMAX model.
Notes
-----
These initialization steps must occur following the parent class
__init__ function calls. | initialize | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def initialize_default(self, approximate_diffuse_variance=None):
"""Initialize default"""
if approximate_diffuse_variance is None:
approximate_diffuse_variance = self.ssm.initial_variance
if self.use_exact_diffuse:
diffuse_type = 'diffuse'
else:
diffuse_type = 'approximate_diffuse'
# Set the loglikelihood burn parameter, if not given in constructor
if self._loglikelihood_burn is None:
k_diffuse_states = self.k_states
if self.enforce_stationarity:
k_diffuse_states -= self._k_order
self.loglikelihood_burn = k_diffuse_states
init = Initialization(
self.k_states,
approximate_diffuse_variance=approximate_diffuse_variance)
if self.enforce_stationarity:
# Differencing operators are at the beginning
init.set((0, self._k_states_diff), diffuse_type)
# Stationary component in the middle
init.set((self._k_states_diff,
self._k_states_diff + self._k_order),
'stationary')
# Regression components at the end
init.set((self._k_states_diff + self._k_order,
self._k_states_diff + self._k_order + self._k_exog),
diffuse_type)
# If we're not enforcing a stationarity, then we cannot initialize a
# stationary component
else:
init.set(None, diffuse_type)
self.ssm.initialization = init | Initialize default | initialize_default | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def initial_design(self):
"""Initial design matrix"""
# Basic design matrix
design = np.r_[
[1] * self._k_diff,
([0] * (self.seasonal_periods - 1) + [1]) * self._k_seasonal_diff,
[1] * self.state_error, [0] * (self._k_order - 1)
]
if len(design) == 0:
design = np.r_[0]
# If we have exogenous regressors included as part of the state vector
# then the exogenous data is incorporated as a time-varying component
# of the design matrix
if self.state_regression:
if self._k_order > 0:
design = np.c_[
np.reshape(
np.repeat(design, self.nobs),
(design.shape[0], self.nobs)
).T,
self.exog
].T[None, :, :]
else:
design = self.exog.T[None, :, :]
return design | Initial design matrix | initial_design | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def initial_state_intercept(self):
"""Initial state intercept vector"""
# TODO make this self._k_trend > 1 and adjust the update to take
# into account that if the trend is a constant, it is not time-varying
if self._k_trend > 0:
state_intercept = np.zeros((self.k_states, self.nobs))
else:
state_intercept = np.zeros((self.k_states,))
return state_intercept | Initial state intercept vector | initial_state_intercept | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def initial_transition(self):
"""Initial transition matrix"""
transition = np.zeros((self.k_states, self.k_states))
# Exogenous regressors component
if self.state_regression:
start = -self._k_exog
# T_\beta
transition[start:, start:] = np.eye(self._k_exog)
# Autoregressive component
start = -(self._k_exog + self._k_order)
end = -self._k_exog if self._k_exog > 0 else None
else:
# Autoregressive component
start = -self._k_order
end = None
# T_c
if self._k_order > 0:
transition[start:end, start:end] = companion_matrix(self._k_order)
if self.hamilton_representation:
transition[start:end, start:end] = np.transpose(
companion_matrix(self._k_order)
)
# Seasonal differencing component
# T^*
if self._k_seasonal_diff > 0:
seasonal_companion = companion_matrix(self.seasonal_periods).T
seasonal_companion[0, -1] = 1
for d in range(self._k_seasonal_diff):
start = self._k_diff + d * self.seasonal_periods
end = self._k_diff + (d + 1) * self.seasonal_periods
# T_c^*
transition[start:end, start:end] = seasonal_companion
# i
if d < self._k_seasonal_diff - 1:
transition[start, end + self.seasonal_periods - 1] = 1
# \iota
transition[start, self._k_states_diff] = 1
# Differencing component
if self._k_diff > 0:
idx = np.triu_indices(self._k_diff)
# T^**
transition[idx] = 1
# [0 1]
if self.seasonal_periods > 0:
start = self._k_diff
end = self._k_states_diff
transition[:self._k_diff, start:end] = (
([0] * (self.seasonal_periods - 1) + [1]) *
self._k_seasonal_diff)
# [1 0]
column = self._k_states_diff
transition[:self._k_diff, column] = 1
return transition | Initial transition matrix | initial_transition | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def initial_selection(self):
"""Initial selection matrix"""
if not (self.state_regression and self.time_varying_regression):
if self.k_posdef > 0:
selection = np.r_[
[0] * (self._k_states_diff),
[1] * (self._k_order > 0), [0] * (self._k_order - 1),
[0] * ((1 - self.mle_regression) * self._k_exog)
][:, None]
if len(selection) == 0:
selection = np.zeros((self.k_states, self.k_posdef))
else:
selection = np.zeros((self.k_states, 0))
else:
selection = np.zeros((self.k_states, self.k_posdef))
# Typical state variance
if self._k_order > 0:
selection[0, 0] = 1
# Time-varying regression coefficient variances
for i in range(self._k_exog, 0, -1):
selection[-i, -i] = 1
return selection | Initial selection matrix | initial_selection | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def start_params(self):
"""
Starting parameters for maximum likelihood estimation
"""
# Perform differencing if necessary (i.e. if simple differencing is
# false so that the state-space model will use the entire dataset)
trend_data = self._trend_data
if not self.simple_differencing and (
self._k_diff > 0 or self._k_seasonal_diff > 0):
endog = diff(self.endog, self._k_diff,
self._k_seasonal_diff, self.seasonal_periods)
if self.exog is not None:
exog = diff(self.exog, self._k_diff,
self._k_seasonal_diff, self.seasonal_periods)
else:
exog = None
trend_data = trend_data[:endog.shape[0], :]
else:
endog = self.endog.copy()
exog = self.exog.copy() if self.exog is not None else None
endog = endog.squeeze()
# Although the Kalman filter can deal with missing values in endog,
# conditional sum of squares cannot
if np.any(np.isnan(endog)):
mask = ~np.isnan(endog).squeeze()
endog = endog[mask]
if exog is not None:
exog = exog[mask]
if trend_data is not None:
trend_data = trend_data[mask]
# Regression effects via OLS
params_exog = []
if self._k_exog > 0:
params_exog = np.linalg.pinv(exog).dot(endog)
endog = endog - np.dot(exog, params_exog)
if self.state_regression:
params_exog = []
# Non-seasonal ARMA component and trend
(params_trend, params_ar, params_ma,
params_variance) = self._conditional_sum_squares(
endog, self.k_ar, self.polynomial_ar, self.k_ma,
self.polynomial_ma, self._k_trend, trend_data,
warning_description='ARMA and trend')
# If we have estimated non-stationary start parameters but enforce
# stationarity is on, start with 0 parameters and warn
invalid_ar = (
self.k_ar > 0 and
self.enforce_stationarity and
not is_invertible(np.r_[1, -params_ar])
)
if invalid_ar:
warn('Non-stationary starting autoregressive parameters'
' found. Using zeros as starting parameters.')
params_ar *= 0
# If we have estimated non-invertible start parameters but enforce
# invertibility is on, raise an error
invalid_ma = (
self.k_ma > 0 and
self.enforce_invertibility and
not is_invertible(np.r_[1, params_ma])
)
if invalid_ma:
warn('Non-invertible starting MA parameters found.'
' Using zeros as starting parameters.', UserWarning)
params_ma *= 0
# Seasonal Parameters
_, params_seasonal_ar, params_seasonal_ma, params_seasonal_variance = (
self._conditional_sum_squares(
endog, self.k_seasonal_ar, self.polynomial_seasonal_ar,
self.k_seasonal_ma, self.polynomial_seasonal_ma,
warning_description='seasonal ARMA'))
# If we have estimated non-stationary start parameters but enforce
# stationarity is on, warn and set start params to 0
invalid_seasonal_ar = (
self.k_seasonal_ar > 0 and
self.enforce_stationarity and
not is_invertible(np.r_[1, -params_seasonal_ar])
)
if invalid_seasonal_ar:
warn('Non-stationary starting seasonal autoregressive'
' Using zeros as starting parameters.')
params_seasonal_ar *= 0
# If we have estimated non-invertible start parameters but enforce
# invertibility is on, raise an error
invalid_seasonal_ma = (
self.k_seasonal_ma > 0 and
self.enforce_invertibility and
not is_invertible(np.r_[1, params_seasonal_ma])
)
if invalid_seasonal_ma:
warn('Non-invertible starting seasonal moving average'
' Using zeros as starting parameters.')
params_seasonal_ma *= 0
# Variances
params_exog_variance = []
if self.state_regression and self.time_varying_regression:
# TODO how to set the initial variance parameters?
params_exog_variance = [1] * self._k_exog
if (self.state_error and type(params_variance) is list and
len(params_variance) == 0):
if not (type(params_seasonal_variance) is list and
len(params_seasonal_variance) == 0):
params_variance = params_seasonal_variance
elif self._k_exog > 0:
params_variance = np.inner(endog, endog)
else:
params_variance = np.inner(endog, endog) / self.nobs
params_measurement_variance = 1 if self.measurement_error else []
# We want to bound the starting variance away from zero
params_variance = np.atleast_1d(np.array(params_variance))
if params_variance.size:
# Avoid comparisons with empty arrays due to changes in NumPy 2.2
params_variance = np.atleast_1d(max(params_variance[0], 1e-10))
# Remove state variance as parameter if scale is concentrated out
if self.concentrate_scale:
params_variance = []
# Combine all parameters
return np.r_[
params_trend,
params_exog,
params_ar,
params_ma,
params_seasonal_ar,
params_seasonal_ma,
params_exog_variance,
params_measurement_variance,
params_variance
] | Starting parameters for maximum likelihood estimation | start_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def endog_names(self, latex=False):
"""Names of endogenous variables"""
diff = ''
if self.k_diff > 0:
if self.k_diff == 1:
diff = r'\Delta' if latex else 'D'
else:
diff = (r'\Delta^%d' if latex else 'D%d') % self.k_diff
seasonal_diff = ''
if self.k_seasonal_diff > 0:
if self.k_seasonal_diff == 1:
seasonal_diff = ((r'\Delta_%d' if latex else 'DS%d') %
(self.seasonal_periods))
else:
seasonal_diff = ((r'\Delta_%d^%d' if latex else 'D%dS%d') %
(self.k_seasonal_diff, self.seasonal_periods))
endog_diff = self.simple_differencing
if endog_diff and self.k_diff > 0 and self.k_seasonal_diff > 0:
return (('%s%s %s' if latex else '%s.%s.%s') %
(diff, seasonal_diff, self.data.ynames))
elif endog_diff and self.k_diff > 0:
return (('%s %s' if latex else '%s.%s') %
(diff, self.data.ynames))
elif endog_diff and self.k_seasonal_diff > 0:
return (('%s %s' if latex else '%s.%s') %
(seasonal_diff, self.data.ynames))
else:
return self.data.ynames | Names of endogenous variables | endog_names | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def param_terms(self):
"""
List of parameters actually included in the model, in sorted order.
TODO Make this an dict with slice or indices as the values.
"""
model_orders = self.model_orders
# Get basic list from model orders
params = [
order for order in self.params_complete
if model_orders[order] > 0
]
# k_exog may be positive without associated parameters if it is in the
# state vector
if 'exog' in params and not self.mle_regression:
params.remove('exog')
return params | List of parameters actually included in the model, in sorted order.
TODO Make this an dict with slice or indices as the values. | param_terms | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def param_names(self):
"""
List of human readable parameter names (for parameters actually
included in the model).
"""
params_sort_order = self.param_terms
model_names = self.model_names
return [
name for param in params_sort_order for name in model_names[param]
] | List of human readable parameter names (for parameters actually
included in the model). | param_names | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def model_orders(self):
"""
The orders of each of the polynomials in the model.
"""
return {
'trend': self._k_trend,
'exog': self._k_exog,
'ar': self.k_ar,
'ma': self.k_ma,
'seasonal_ar': self.k_seasonal_ar,
'seasonal_ma': self.k_seasonal_ma,
'reduced_ar': self.k_ar + self.k_seasonal_ar,
'reduced_ma': self.k_ma + self.k_seasonal_ma,
'exog_variance': self._k_exog if (
self.state_regression and self.time_varying_regression) else 0,
'measurement_variance': int(self.measurement_error),
'variance': int(self.state_error and not self.concentrate_scale),
} | The orders of each of the polynomials in the model. | model_orders | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def model_names(self):
"""
The plain text names of all possible model parameters.
"""
return self._get_model_names(latex=False) | The plain text names of all possible model parameters. | model_names | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def model_latex_names(self):
"""
The latex names of all possible model parameters.
"""
return self._get_model_names(latex=True) | The latex names of all possible model parameters. | model_latex_names | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def transform_params(self, unconstrained):
"""
Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation.
Used primarily to enforce stationarity of the autoregressive lag
polynomial, invertibility of the moving average lag polynomial, and
positive variance parameters.
Parameters
----------
unconstrained : array_like
Unconstrained parameters used by the optimizer.
Returns
-------
constrained : array_like
Constrained parameters used in likelihood evaluation.
Notes
-----
If the lag polynomial has non-consecutive powers (so that the
coefficient is zero on some element of the polynomial), then the
constraint function is not onto the entire space of invertible
polynomials, although it only excludes a very small portion very close
to the invertibility boundary.
"""
unconstrained = np.array(unconstrained, ndmin=1)
constrained = np.zeros(unconstrained.shape, unconstrained.dtype)
start = end = 0
# Retain the trend parameters
if self._k_trend > 0:
end += self._k_trend
constrained[start:end] = unconstrained[start:end]
start += self._k_trend
# Retain any MLE regression coefficients
if self.mle_regression:
end += self._k_exog
constrained[start:end] = unconstrained[start:end]
start += self._k_exog
# Transform the AR parameters (phi) to be stationary
if self.k_ar_params > 0:
end += self.k_ar_params
if self.enforce_stationarity:
constrained[start:end] = (
constrain_stationary_univariate(unconstrained[start:end])
)
else:
constrained[start:end] = unconstrained[start:end]
start += self.k_ar_params
# Transform the MA parameters (theta) to be invertible
if self.k_ma_params > 0:
end += self.k_ma_params
if self.enforce_invertibility:
constrained[start:end] = (
-constrain_stationary_univariate(unconstrained[start:end])
)
else:
constrained[start:end] = unconstrained[start:end]
start += self.k_ma_params
# Transform the seasonal AR parameters (\tilde phi) to be stationary
if self.k_seasonal_ar > 0:
end += self.k_seasonal_ar_params
if self.enforce_stationarity:
constrained[start:end] = (
constrain_stationary_univariate(unconstrained[start:end])
)
else:
constrained[start:end] = unconstrained[start:end]
start += self.k_seasonal_ar_params
# Transform the seasonal MA parameters (\tilde theta) to be invertible
if self.k_seasonal_ma_params > 0:
end += self.k_seasonal_ma_params
if self.enforce_invertibility:
constrained[start:end] = (
-constrain_stationary_univariate(unconstrained[start:end])
)
else:
constrained[start:end] = unconstrained[start:end]
start += self.k_seasonal_ma_params
# Transform the standard deviation parameters to be positive
if self.state_regression and self.time_varying_regression:
end += self._k_exog
constrained[start:end] = unconstrained[start:end]**2
start += self._k_exog
if self.measurement_error:
constrained[start] = unconstrained[start]**2
start += 1
end += 1
if self.state_error and not self.concentrate_scale:
constrained[start] = unconstrained[start]**2
# start += 1
# end += 1
return constrained | Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation.
Used primarily to enforce stationarity of the autoregressive lag
polynomial, invertibility of the moving average lag polynomial, and
positive variance parameters.
Parameters
----------
unconstrained : array_like
Unconstrained parameters used by the optimizer.
Returns
-------
constrained : array_like
Constrained parameters used in likelihood evaluation.
Notes
-----
If the lag polynomial has non-consecutive powers (so that the
coefficient is zero on some element of the polynomial), then the
constraint function is not onto the entire space of invertible
polynomials, although it only excludes a very small portion very close
to the invertibility boundary. | transform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def untransform_params(self, constrained):
"""
Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer
Used primarily to reverse enforcement of stationarity of the
autoregressive lag polynomial and invertibility of the moving average
lag polynomial.
Parameters
----------
constrained : array_like
Constrained parameters used in likelihood evaluation.
Returns
-------
constrained : array_like
Unconstrained parameters used by the optimizer.
Notes
-----
If the lag polynomial has non-consecutive powers (so that the
coefficient is zero on some element of the polynomial), then the
constraint function is not onto the entire space of invertible
polynomials, although it only excludes a very small portion very close
to the invertibility boundary.
"""
constrained = np.array(constrained, ndmin=1)
unconstrained = np.zeros(constrained.shape, constrained.dtype)
start = end = 0
# Retain the trend parameters
if self._k_trend > 0:
end += self._k_trend
unconstrained[start:end] = constrained[start:end]
start += self._k_trend
# Retain any MLE regression coefficients
if self.mle_regression:
end += self._k_exog
unconstrained[start:end] = constrained[start:end]
start += self._k_exog
# Transform the AR parameters (phi) to be stationary
if self.k_ar_params > 0:
end += self.k_ar_params
if self.enforce_stationarity:
unconstrained[start:end] = (
unconstrain_stationary_univariate(constrained[start:end])
)
else:
unconstrained[start:end] = constrained[start:end]
start += self.k_ar_params
# Transform the MA parameters (theta) to be invertible
if self.k_ma_params > 0:
end += self.k_ma_params
if self.enforce_invertibility:
unconstrained[start:end] = (
unconstrain_stationary_univariate(-constrained[start:end])
)
else:
unconstrained[start:end] = constrained[start:end]
start += self.k_ma_params
# Transform the seasonal AR parameters (\tilde phi) to be stationary
if self.k_seasonal_ar > 0:
end += self.k_seasonal_ar_params
if self.enforce_stationarity:
unconstrained[start:end] = (
unconstrain_stationary_univariate(constrained[start:end])
)
else:
unconstrained[start:end] = constrained[start:end]
start += self.k_seasonal_ar_params
# Transform the seasonal MA parameters (\tilde theta) to be invertible
if self.k_seasonal_ma_params > 0:
end += self.k_seasonal_ma_params
if self.enforce_invertibility:
unconstrained[start:end] = (
unconstrain_stationary_univariate(-constrained[start:end])
)
else:
unconstrained[start:end] = constrained[start:end]
start += self.k_seasonal_ma_params
# Untransform the standard deviation
if self.state_regression and self.time_varying_regression:
end += self._k_exog
unconstrained[start:end] = constrained[start:end]**0.5
start += self._k_exog
if self.measurement_error:
unconstrained[start] = constrained[start]**0.5
start += 1
end += 1
if self.state_error and not self.concentrate_scale:
unconstrained[start] = constrained[start]**0.5
# start += 1
# end += 1
return unconstrained | Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer
Used primarily to reverse enforcement of stationarity of the
autoregressive lag polynomial and invertibility of the moving average
lag polynomial.
Parameters
----------
constrained : array_like
Constrained parameters used in likelihood evaluation.
Returns
-------
constrained : array_like
Unconstrained parameters used by the optimizer.
Notes
-----
If the lag polynomial has non-consecutive powers (so that the
coefficient is zero on some element of the polynomial), then the
constraint function is not onto the entire space of invertible
polynomials, although it only excludes a very small portion very close
to the invertibility boundary. | untransform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def update(self, params, transformed=True, includes_fixed=False,
complex_step=False):
"""
Update the parameters of the model
Updates the representation matrices to fill in the new parameter
values.
Parameters
----------
params : array_like
Array of new parameters.
transformed : bool, optional
Whether or not `params` is already transformed. If set to False,
`transform_params` is called. Default is True..
Returns
-------
params : array_like
Array of parameters.
"""
params = self.handle_params(params, transformed=transformed,
includes_fixed=includes_fixed)
params_trend = None
params_exog = None
params_ar = None
params_ma = None
params_seasonal_ar = None
params_seasonal_ma = None
params_exog_variance = None
params_measurement_variance = None
params_variance = None
# Extract the parameters
start = end = 0
end += self._k_trend
params_trend = params[start:end]
start += self._k_trend
if self.mle_regression:
end += self._k_exog
params_exog = params[start:end]
start += self._k_exog
end += self.k_ar_params
params_ar = params[start:end]
start += self.k_ar_params
end += self.k_ma_params
params_ma = params[start:end]
start += self.k_ma_params
end += self.k_seasonal_ar_params
params_seasonal_ar = params[start:end]
start += self.k_seasonal_ar_params
end += self.k_seasonal_ma_params
params_seasonal_ma = params[start:end]
start += self.k_seasonal_ma_params
if self.state_regression and self.time_varying_regression:
end += self._k_exog
params_exog_variance = params[start:end]
start += self._k_exog
if self.measurement_error:
params_measurement_variance = params[start]
start += 1
end += 1
if self.state_error and not self.concentrate_scale:
params_variance = params[start]
# start += 1
# end += 1
# Update lag polynomials
if self.k_ar > 0:
if self._polynomial_ar.dtype == params.dtype:
self._polynomial_ar[self._polynomial_ar_idx] = -params_ar
else:
polynomial_ar = self._polynomial_ar.real.astype(params.dtype)
polynomial_ar[self._polynomial_ar_idx] = -params_ar
self._polynomial_ar = polynomial_ar
if self.k_ma > 0:
if self._polynomial_ma.dtype == params.dtype:
self._polynomial_ma[self._polynomial_ma_idx] = params_ma
else:
polynomial_ma = self._polynomial_ma.real.astype(params.dtype)
polynomial_ma[self._polynomial_ma_idx] = params_ma
self._polynomial_ma = polynomial_ma
if self.k_seasonal_ar > 0:
idx = self._polynomial_seasonal_ar_idx
if self._polynomial_seasonal_ar.dtype == params.dtype:
self._polynomial_seasonal_ar[idx] = -params_seasonal_ar
else:
polynomial_seasonal_ar = (
self._polynomial_seasonal_ar.real.astype(params.dtype)
)
polynomial_seasonal_ar[idx] = -params_seasonal_ar
self._polynomial_seasonal_ar = polynomial_seasonal_ar
if self.k_seasonal_ma > 0:
idx = self._polynomial_seasonal_ma_idx
if self._polynomial_seasonal_ma.dtype == params.dtype:
self._polynomial_seasonal_ma[idx] = params_seasonal_ma
else:
polynomial_seasonal_ma = (
self._polynomial_seasonal_ma.real.astype(params.dtype)
)
polynomial_seasonal_ma[idx] = params_seasonal_ma
self._polynomial_seasonal_ma = polynomial_seasonal_ma
# Get the reduced form lag polynomial terms by multiplying the regular
# and seasonal lag polynomials
# Note: that although the numpy np.polymul examples assume that they
# are ordered from highest degree to lowest, whereas our are from
# lowest to highest, it does not matter.
if self.k_seasonal_ar > 0:
reduced_polynomial_ar = -np.polymul(
self._polynomial_ar, self._polynomial_seasonal_ar
)
else:
reduced_polynomial_ar = -self._polynomial_ar
if self.k_seasonal_ma > 0:
reduced_polynomial_ma = np.polymul(
self._polynomial_ma, self._polynomial_seasonal_ma
)
else:
reduced_polynomial_ma = self._polynomial_ma
# Observation intercept
# Exogenous data with MLE estimation of parameters enters through a
# time-varying observation intercept (is equivalent to simply
# subtracting it out of the endogenous variable first)
if self.mle_regression:
self.ssm['obs_intercept'] = np.dot(self.exog, params_exog)[None, :]
# State intercept (Harvey) or additional observation intercept
# (Hamilton)
# SARIMA trend enters through the a time-varying state intercept,
# associated with the first row of the stationary component of the
# state vector (i.e. the first element of the state vector following
# any differencing elements)
if self._k_trend > 0:
data = np.dot(self._trend_data, params_trend).astype(params.dtype)
if not self.hamilton_representation:
self.ssm['state_intercept', self._k_states_diff, :] = data
else:
# The way the trend enters in the Hamilton representation means
# that the parameter is not an ``intercept'' but instead the
# mean of the process. The trend values in `data` are meant for
# an intercept, and so must be transformed to represent the
# mean instead
if self.hamilton_representation:
data /= np.sum(-reduced_polynomial_ar)
# If we already set the observation intercept for MLE
# regression, just add to it
if self.mle_regression:
self.ssm.obs_intercept += data[None, :]
# Otherwise set it directly
else:
self.ssm['obs_intercept'] = data[None, :]
# Observation covariance matrix
if self.measurement_error:
self.ssm['obs_cov', 0, 0] = params_measurement_variance
# Transition matrix
if self.k_ar > 0 or self.k_seasonal_ar > 0:
self.ssm[self.transition_ar_params_idx] = reduced_polynomial_ar[1:]
elif not self.ssm.transition.dtype == params.dtype:
# This is required if the transition matrix is not really in use
# (e.g. for an MA(q) process) so that it's dtype never changes as
# the parameters' dtype changes. This changes the dtype manually.
self.ssm['transition'] = self.ssm['transition'].real.astype(
params.dtype)
# Selection matrix (Harvey) or Design matrix (Hamilton)
if self.k_ma > 0 or self.k_seasonal_ma > 0:
if not self.hamilton_representation:
self.ssm[self.selection_ma_params_idx] = (
reduced_polynomial_ma[1:]
)
else:
self.ssm[self.design_ma_params_idx] = reduced_polynomial_ma[1:]
# State covariance matrix
if self.k_posdef > 0:
if not self.concentrate_scale:
self['state_cov', 0, 0] = params_variance
if self.state_regression and self.time_varying_regression:
self.ssm[self._exog_variance_idx] = params_exog_variance
return params | Update the parameters of the model
Updates the representation matrices to fill in the new parameter
values.
Parameters
----------
params : array_like
Array of new parameters.
transformed : bool, optional
Whether or not `params` is already transformed. If set to False,
`transform_params` is called. Default is True..
Returns
-------
params : array_like
Array of parameters. | update | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def _get_extension_time_varying_matrices(
self, params, exog, out_of_sample, extend_kwargs=None,
transformed=True, includes_fixed=False, **kwargs):
"""
Get time-varying state space system matrices for extended model
Notes
-----
We need to override this method for SARIMAX because we need some
special handling in the `simple_differencing=True` case.
"""
# Get the appropriate exog for the extended sample
exog = self._validate_out_of_sample_exog(exog, out_of_sample)
# Get the tmp endog, exog
if self.simple_differencing:
nobs = self.data.orig_endog.shape[0] + out_of_sample
tmp_endog = np.zeros((nobs, self.k_endog))
if exog is not None:
tmp_exog = np.c_[self.data.orig_exog.T, exog.T].T
else:
tmp_exog = None
else:
tmp_endog = np.zeros((out_of_sample, self.k_endog))
tmp_exog = exog
# Create extended model
if extend_kwargs is None:
extend_kwargs = {}
if not self.simple_differencing and self.k_trend > 0:
extend_kwargs.setdefault(
'trend_offset', self.trend_offset + self.nobs)
extend_kwargs.setdefault('validate_specification', False)
mod_extend = self.clone(
endog=tmp_endog, exog=tmp_exog, **extend_kwargs)
mod_extend.update(params, transformed=transformed,
includes_fixed=includes_fixed,)
# Retrieve the extensions to the time-varying system matrices and
# put them in kwargs
for name in self.ssm.shapes.keys():
if name == 'obs' or name in kwargs:
continue
original = getattr(self.ssm, name)
extended = getattr(mod_extend.ssm, name)
so = original.shape[-1]
se = extended.shape[-1]
if ((so > 1 or se > 1) or (
so == 1 and self.nobs == 1 and
np.any(original[..., 0] != extended[..., 0]))):
kwargs[name] = extended[..., -out_of_sample:]
return kwargs | Get time-varying state space system matrices for extended model
Notes
-----
We need to override this method for SARIMAX because we need some
special handling in the `simple_differencing=True` case. | _get_extension_time_varying_matrices | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def arroots(self):
"""
(array) Roots of the reduced form autoregressive lag polynomial
"""
return np.roots(self.polynomial_reduced_ar)**-1 | (array) Roots of the reduced form autoregressive lag polynomial | arroots | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def maroots(self):
"""
(array) Roots of the reduced form moving average lag polynomial
"""
return np.roots(self.polynomial_reduced_ma)**-1 | (array) Roots of the reduced form moving average lag polynomial | maroots | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def arfreq(self):
"""
(array) Frequency of the roots of the reduced form autoregressive
lag polynomial
"""
z = self.arroots
if not z.size:
return
return np.arctan2(z.imag, z.real) / (2 * np.pi) | (array) Frequency of the roots of the reduced form autoregressive
lag polynomial | arfreq | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def mafreq(self):
"""
(array) Frequency of the roots of the reduced form moving average
lag polynomial
"""
z = self.maroots
if not z.size:
return
return np.arctan2(z.imag, z.real) / (2 * np.pi) | (array) Frequency of the roots of the reduced form moving average
lag polynomial | mafreq | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def arparams(self):
"""
(array) Autoregressive parameters actually estimated in the model.
Does not include seasonal autoregressive parameters (see
`seasonalarparams`) or parameters whose values are constrained to be
zero.
"""
return self._params_ar | (array) Autoregressive parameters actually estimated in the model.
Does not include seasonal autoregressive parameters (see
`seasonalarparams`) or parameters whose values are constrained to be
zero. | arparams | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def seasonalarparams(self):
"""
(array) Seasonal autoregressive parameters actually estimated in the
model. Does not include nonseasonal autoregressive parameters (see
`arparams`) or parameters whose values are constrained to be zero.
"""
return self._params_seasonal_ar | (array) Seasonal autoregressive parameters actually estimated in the
model. Does not include nonseasonal autoregressive parameters (see
`arparams`) or parameters whose values are constrained to be zero. | seasonalarparams | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def maparams(self):
"""
(array) Moving average parameters actually estimated in the model.
Does not include seasonal moving average parameters (see
`seasonalmaparams`) or parameters whose values are constrained to be
zero.
"""
return self._params_ma | (array) Moving average parameters actually estimated in the model.
Does not include seasonal moving average parameters (see
`seasonalmaparams`) or parameters whose values are constrained to be
zero. | maparams | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def seasonalmaparams(self):
"""
(array) Seasonal moving average parameters actually estimated in the
model. Does not include nonseasonal moving average parameters (see
`maparams`) or parameters whose values are constrained to be zero.
"""
return self._params_seasonal_ma | (array) Seasonal moving average parameters actually estimated in the
model. Does not include nonseasonal moving average parameters (see
`maparams`) or parameters whose values are constrained to be zero. | seasonalmaparams | python | statsmodels/statsmodels | statsmodels/tsa/statespace/sarimax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/sarimax.py | BSD-3-Clause |
def transform_params(self, unconstrained):
"""
Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer, to be
transformed.
Returns
-------
constrained : array_like
Array of constrained parameters which may be used in likelihood
evaluation.
Notes
-----
Constrains the factor transition to be stationary and variances to be
positive.
"""
unconstrained = np.array(unconstrained, ndmin=1)
constrained = np.zeros(unconstrained.shape, dtype=unconstrained.dtype)
# 1. Intercept terms: nothing to do
constrained[self._params_trend] = unconstrained[self._params_trend]
# 2. AR terms: optionally force to be stationary
if self.k_ar > 0 and self.enforce_stationarity:
# Create the state covariance matrix
if self.error_cov_type == 'diagonal':
state_cov = np.diag(unconstrained[self._params_state_cov]**2)
elif self.error_cov_type == 'unstructured':
state_cov_lower = np.zeros(self.ssm['state_cov'].shape,
dtype=unconstrained.dtype)
state_cov_lower[self._idx_lower_state_cov] = (
unconstrained[self._params_state_cov])
state_cov = np.dot(state_cov_lower, state_cov_lower.T)
# Transform the parameters
coefficients = unconstrained[self._params_ar].reshape(
self.k_endog, self.k_endog * self.k_ar)
coefficient_matrices, variance = (
constrain_stationary_multivariate(coefficients, state_cov))
constrained[self._params_ar] = coefficient_matrices.ravel()
else:
constrained[self._params_ar] = unconstrained[self._params_ar]
# 3. MA terms: optionally force to be invertible
if self.k_ma > 0 and self.enforce_invertibility:
# Transform the parameters, using an identity variance matrix
state_cov = np.eye(self.k_endog, dtype=unconstrained.dtype)
coefficients = unconstrained[self._params_ma].reshape(
self.k_endog, self.k_endog * self.k_ma)
coefficient_matrices, variance = (
constrain_stationary_multivariate(coefficients, state_cov))
constrained[self._params_ma] = coefficient_matrices.ravel()
else:
constrained[self._params_ma] = unconstrained[self._params_ma]
# 4. Regression terms: nothing to do
constrained[self._params_regression] = (
unconstrained[self._params_regression])
# 5. State covariance terms
# If we have variances, force them to be positive
if self.error_cov_type == 'diagonal':
constrained[self._params_state_cov] = (
unconstrained[self._params_state_cov]**2)
# Otherwise, nothing needs to be done
elif self.error_cov_type == 'unstructured':
constrained[self._params_state_cov] = (
unconstrained[self._params_state_cov])
# 5. Measurement error variance terms
if self.measurement_error:
# Force these to be positive
constrained[self._params_obs_cov] = (
unconstrained[self._params_obs_cov]**2)
return constrained | Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer, to be
transformed.
Returns
-------
constrained : array_like
Array of constrained parameters which may be used in likelihood
evaluation.
Notes
-----
Constrains the factor transition to be stationary and variances to be
positive. | transform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/varmax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/varmax.py | BSD-3-Clause |
def untransform_params(self, constrained):
"""
Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer.
Parameters
----------
constrained : array_like
Array of constrained parameters used in likelihood evaluation, to
be transformed.
Returns
-------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer.
"""
constrained = np.array(constrained, ndmin=1)
unconstrained = np.zeros(constrained.shape, dtype=constrained.dtype)
# 1. Intercept terms: nothing to do
unconstrained[self._params_trend] = constrained[self._params_trend]
# 2. AR terms: optionally were forced to be stationary
if self.k_ar > 0 and self.enforce_stationarity:
# Create the state covariance matrix
if self.error_cov_type == 'diagonal':
state_cov = np.diag(constrained[self._params_state_cov])
elif self.error_cov_type == 'unstructured':
state_cov_lower = np.zeros(self.ssm['state_cov'].shape,
dtype=constrained.dtype)
state_cov_lower[self._idx_lower_state_cov] = (
constrained[self._params_state_cov])
state_cov = np.dot(state_cov_lower, state_cov_lower.T)
# Transform the parameters
coefficients = constrained[self._params_ar].reshape(
self.k_endog, self.k_endog * self.k_ar)
unconstrained_matrices, variance = (
unconstrain_stationary_multivariate(coefficients, state_cov))
unconstrained[self._params_ar] = unconstrained_matrices.ravel()
else:
unconstrained[self._params_ar] = constrained[self._params_ar]
# 3. MA terms: optionally were forced to be invertible
if self.k_ma > 0 and self.enforce_invertibility:
# Transform the parameters, using an identity variance matrix
state_cov = np.eye(self.k_endog, dtype=constrained.dtype)
coefficients = constrained[self._params_ma].reshape(
self.k_endog, self.k_endog * self.k_ma)
unconstrained_matrices, variance = (
unconstrain_stationary_multivariate(coefficients, state_cov))
unconstrained[self._params_ma] = unconstrained_matrices.ravel()
else:
unconstrained[self._params_ma] = constrained[self._params_ma]
# 4. Regression terms: nothing to do
unconstrained[self._params_regression] = (
constrained[self._params_regression])
# 5. State covariance terms
# If we have variances, then these were forced to be positive
if self.error_cov_type == 'diagonal':
unconstrained[self._params_state_cov] = (
constrained[self._params_state_cov]**0.5)
# Otherwise, nothing needs to be done
elif self.error_cov_type == 'unstructured':
unconstrained[self._params_state_cov] = (
constrained[self._params_state_cov])
# 5. Measurement error variance terms
if self.measurement_error:
# These were forced to be positive
unconstrained[self._params_obs_cov] = (
constrained[self._params_obs_cov]**0.5)
return unconstrained | Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer.
Parameters
----------
constrained : array_like
Array of constrained parameters used in likelihood evaluation, to
be transformed.
Returns
-------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer. | untransform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/varmax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/varmax.py | BSD-3-Clause |
def _set_final_exog(self, exog):
"""
Set the final state intercept value using out-of-sample `exog` / trend
Parameters
----------
exog : ndarray
Out-of-sample `exog` values, usually produced by
`_validate_out_of_sample_exog` to ensure the correct shape (this
method does not do any additional validation of its own).
out_of_sample : int
Number of out-of-sample periods.
Notes
-----
We need special handling for simulating or forecasting with `exog` or
trend, because if we had these then the last predicted_state has been
set to NaN since we did not have the appropriate `exog` to create it.
Since we handle trend in the same way as `exog`, we still have this
issue when only trend is used without `exog`.
"""
cache_value = self._final_exog
if self.k_exog > 0:
if exog is not None:
exog = np.atleast_1d(exog)
if exog.ndim == 2:
exog = exog[:1]
try:
exog = np.reshape(exog[:1], (self.k_exog,))
except ValueError:
raise ValueError('Provided exogenous values are not of the'
' appropriate shape. Required %s, got %s.'
% (str((self.k_exog,)),
str(exog.shape)))
self._final_exog = exog
try:
yield
finally:
self._final_exog = cache_value | Set the final state intercept value using out-of-sample `exog` / trend
Parameters
----------
exog : ndarray
Out-of-sample `exog` values, usually produced by
`_validate_out_of_sample_exog` to ensure the correct shape (this
method does not do any additional validation of its own).
out_of_sample : int
Number of out-of-sample periods.
Notes
-----
We need special handling for simulating or forecasting with `exog` or
trend, because if we had these then the last predicted_state has been
set to NaN since we did not have the appropriate `exog` to create it.
Since we handle trend in the same way as `exog`, we still have this
issue when only trend is used without `exog`. | _set_final_exog | python | statsmodels/statsmodels | statsmodels/tsa/statespace/varmax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/varmax.py | BSD-3-Clause |
def _set_final_exog(self, exog):
"""
Set the final state intercept value using out-of-sample `exog` / trend
Parameters
----------
exog : ndarray
Out-of-sample `exog` values, usually produced by
`_validate_out_of_sample_exog` to ensure the correct shape (this
method does not do any additional validation of its own).
out_of_sample : int
Number of out-of-sample periods.
Notes
-----
This context manager calls the model-level context manager and
additionally updates the last element of filter_results.state_intercept
appropriately.
"""
mod = self.model
with mod._set_final_exog(exog):
cache_value = self.filter_results.state_intercept[:, -1]
mod.update(self.params)
self.filter_results.state_intercept[:mod.k_endog, -1] = (
mod['state_intercept', :mod.k_endog, -1])
try:
yield
finally:
self.filter_results.state_intercept[:, -1] = cache_value | Set the final state intercept value using out-of-sample `exog` / trend
Parameters
----------
exog : ndarray
Out-of-sample `exog` values, usually produced by
`_validate_out_of_sample_exog` to ensure the correct shape (this
method does not do any additional validation of its own).
out_of_sample : int
Number of out-of-sample periods.
Notes
-----
This context manager calls the model-level context manager and
additionally updates the last element of filter_results.state_intercept
appropriately. | _set_final_exog | python | statsmodels/statsmodels | statsmodels/tsa/statespace/varmax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/varmax.py | BSD-3-Clause |
def _set_final_predicted_state(self, exog, out_of_sample):
"""
Set the final predicted state value using out-of-sample `exog` / trend
Parameters
----------
exog : ndarray
Out-of-sample `exog` values, usually produced by
`_validate_out_of_sample_exog` to ensure the correct shape (this
method does not do any additional validation of its own).
out_of_sample : int
Number of out-of-sample periods.
Notes
-----
We need special handling for forecasting with `exog`, because
if we had these then the last predicted_state has been set to NaN since
we did not have the appropriate `exog` to create it.
"""
flag = out_of_sample and self.model.k_exog > 0
if flag:
tmp_endog = concat([
self.model.endog[-1:], np.zeros((1, self.model.k_endog))])
if self.model.k_exog > 0:
tmp_exog = concat([self.model.exog[-1:], exog[:1]])
else:
tmp_exog = None
tmp_trend_offset = self.model.trend_offset + self.nobs - 1
tmp_mod = self.model.clone(tmp_endog, exog=tmp_exog,
trend_offset=tmp_trend_offset)
constant = self.filter_results.predicted_state[:, -2]
stationary_cov = self.filter_results.predicted_state_cov[:, :, -2]
tmp_mod.ssm.initialize_known(constant=constant,
stationary_cov=stationary_cov)
tmp_res = tmp_mod.filter(self.params, transformed=True,
includes_fixed=True, return_ssm=True)
# Patch up `predicted_state`
self.filter_results.predicted_state[:, -1] = (
tmp_res.predicted_state[:, -2])
try:
yield
finally:
if flag:
self.filter_results.predicted_state[:, -1] = np.nan | Set the final predicted state value using out-of-sample `exog` / trend
Parameters
----------
exog : ndarray
Out-of-sample `exog` values, usually produced by
`_validate_out_of_sample_exog` to ensure the correct shape (this
method does not do any additional validation of its own).
out_of_sample : int
Number of out-of-sample periods.
Notes
-----
We need special handling for forecasting with `exog`, because
if we had these then the last predicted_state has been set to NaN since
we did not have the appropriate `exog` to create it. | _set_final_predicted_state | python | statsmodels/statsmodels | statsmodels/tsa/statespace/varmax.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/varmax.py | BSD-3-Clause |
def setup(self):
"""
Setup the structural time series representation
"""
# Initialize the ordered sets of parameters
self.parameters = {}
self.parameters_obs_intercept = {}
self.parameters_obs_cov = {}
self.parameters_transition = {}
self.parameters_state_cov = {}
# Initialize the fixed components of the state space matrices,
i = 0 # state offset
j = 0 # state covariance offset
if self.irregular:
self.parameters_obs_cov['irregular_var'] = 1
if self.level:
self.ssm['design', 0, i] = 1.
self.ssm['transition', i, i] = 1.
if self.trend:
self.ssm['transition', i, i+1] = 1.
if self.stochastic_level:
self.ssm['selection', i, j] = 1.
self.parameters_state_cov['level_var'] = 1
j += 1
i += 1
if self.trend:
self.ssm['transition', i, i] = 1.
if self.stochastic_trend:
self.ssm['selection', i, j] = 1.
self.parameters_state_cov['trend_var'] = 1
j += 1
i += 1
if self.seasonal:
n = self.seasonal_periods - 1
self.ssm['design', 0, i] = 1.
self.ssm['transition', i:i + n, i:i + n] = (
companion_matrix(np.r_[1, [1] * n]).transpose()
)
if self.stochastic_seasonal:
self.ssm['selection', i, j] = 1.
self.parameters_state_cov['seasonal_var'] = 1
j += 1
i += n
if self.freq_seasonal:
for ix, h in enumerate(self.freq_seasonal_harmonics):
# These are the \gamma_jt and \gamma^*_jt terms in D&K (3.8)
n = 2 * h
p = self.freq_seasonal_periods[ix]
lambda_p = 2 * np.pi / float(p)
t = 0 # frequency transition matrix offset
for block in range(1, h + 1):
# ibid. eqn (3.7)
self.ssm['design', 0, i+t] = 1.
# ibid. eqn (3.8)
cos_lambda_block = np.cos(lambda_p * block)
sin_lambda_block = np.sin(lambda_p * block)
trans = np.array([[cos_lambda_block, sin_lambda_block],
[-sin_lambda_block, cos_lambda_block]])
trans_s = np.s_[i + t:i + t + 2]
self.ssm['transition', trans_s, trans_s] = trans
t += 2
if self.stochastic_freq_seasonal[ix]:
self.ssm['selection', i:i + n, j:j + n] = np.eye(n)
cov_key = f'freq_seasonal_var_{ix!r}'
self.parameters_state_cov[cov_key] = 1
j += n
i += n
if self.cycle:
self.ssm['design', 0, i] = 1.
self.parameters_transition['cycle_freq'] = 1
if self.damped_cycle:
self.parameters_transition['cycle_damp'] = 1
if self.stochastic_cycle:
self.ssm['selection', i:i+2, j:j+2] = np.eye(2)
self.parameters_state_cov['cycle_var'] = 1
j += 2
self._idx_cycle_transition = np.s_['transition', i:i+2, i:i+2]
i += 2
if self.autoregressive:
self.ssm['design', 0, i] = 1.
self.parameters_transition['ar_coeff'] = self.ar_order
self.parameters_state_cov['ar_var'] = 1
self.ssm['selection', i, j] = 1
self.ssm['transition', i:i+self.ar_order, i:i+self.ar_order] = (
companion_matrix(self.ar_order).T
)
self._idx_ar_transition = (
np.s_['transition', i, i:i+self.ar_order]
)
j += 1
i += self.ar_order
if self.regression:
if self.mle_regression:
self.parameters_obs_intercept['reg_coeff'] = self.k_exog
else:
design = np.repeat(self.ssm['design', :, :, 0], self.nobs,
axis=0)
self.ssm['design'] = design.transpose()[np.newaxis, :, :]
self.ssm['design', 0, i:i+self.k_exog, :] = (
self.exog.transpose())
self.ssm['transition', i:i+self.k_exog, i:i+self.k_exog] = (
np.eye(self.k_exog)
)
i += self.k_exog
# Update to get the actual parameter set
self.parameters.update(self.parameters_obs_cov)
self.parameters.update(self.parameters_state_cov)
self.parameters.update(self.parameters_transition) # ordered last
self.parameters.update(self.parameters_obs_intercept)
self.k_obs_intercept = sum(self.parameters_obs_intercept.values())
self.k_obs_cov = sum(self.parameters_obs_cov.values())
self.k_transition = sum(self.parameters_transition.values())
self.k_state_cov = sum(self.parameters_state_cov.values())
self.k_params = sum(self.parameters.values())
# Other indices
idx = np.diag_indices(self.ssm.k_posdef)
self._idx_state_cov = ('state_cov', idx[0], idx[1])
# Some of the variances may be tied together (repeated parameter usage)
# Use list() for compatibility with python 3.5
param_keys = list(self.parameters_state_cov.keys())
self._var_repetitions = np.ones(self.k_state_cov, dtype=int)
if self.freq_seasonal:
for ix, is_stochastic in enumerate(self.stochastic_freq_seasonal):
if is_stochastic:
num_harmonics = self.freq_seasonal_harmonics[ix]
repeat_times = 2 * num_harmonics
cov_key = f'freq_seasonal_var_{ix!r}'
cov_ix = param_keys.index(cov_key)
self._var_repetitions[cov_ix] = repeat_times
if self.stochastic_cycle and self.cycle:
cov_ix = param_keys.index('cycle_var')
self._var_repetitions[cov_ix] = 2
self._repeat_any_var = any(self._var_repetitions > 1) | Setup the structural time series representation | setup | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def transform_params(self, unconstrained):
"""
Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
"""
unconstrained = np.array(unconstrained, ndmin=1)
constrained = np.zeros(unconstrained.shape, dtype=unconstrained.dtype)
# Positive parameters: obs_cov, state_cov
offset = self.k_obs_cov + self.k_state_cov
constrained[:offset] = unconstrained[:offset]**2
# Cycle parameters
if self.cycle:
# Cycle frequency must be between between our bounds
low, high = self.cycle_frequency_bound
constrained[offset] = (
1 / (1 + np.exp(-unconstrained[offset]))
) * (high - low) + low
offset += 1
# Cycle damping (if present) must be between 0 and 1
if self.damped_cycle:
constrained[offset] = (
1 / (1 + np.exp(-unconstrained[offset]))
)
offset += 1
# Autoregressive coefficients must be stationary
if self.autoregressive:
constrained[offset:offset + self.ar_order] = (
constrain_stationary_univariate(
unconstrained[offset:offset + self.ar_order]
)
)
offset += self.ar_order
# Nothing to do with betas
constrained[offset:offset + self.k_exog] = (
unconstrained[offset:offset + self.k_exog]
)
return constrained | Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation | transform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def untransform_params(self, constrained):
"""
Reverse the transformation
"""
constrained = np.array(constrained, ndmin=1)
unconstrained = np.zeros(constrained.shape, dtype=constrained.dtype)
# Positive parameters: obs_cov, state_cov
offset = self.k_obs_cov + self.k_state_cov
unconstrained[:offset] = constrained[:offset]**0.5
# Cycle parameters
if self.cycle:
# Cycle frequency must be between between our bounds
low, high = self.cycle_frequency_bound
x = (constrained[offset] - low) / (high - low)
unconstrained[offset] = np.log(
x / (1 - x)
)
offset += 1
# Cycle damping (if present) must be between 0 and 1
if self.damped_cycle:
unconstrained[offset] = np.log(
constrained[offset] / (1 - constrained[offset])
)
offset += 1
# Autoregressive coefficients must be stationary
if self.autoregressive:
unconstrained[offset:offset + self.ar_order] = (
unconstrain_stationary_univariate(
constrained[offset:offset + self.ar_order]
)
)
offset += self.ar_order
# Nothing to do with betas
unconstrained[offset:offset + self.k_exog] = (
constrained[offset:offset + self.k_exog]
)
return unconstrained | Reverse the transformation | untransform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def level(self):
"""
Estimates of unobserved level component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, level is always the first component of the state vector
out = None
spec = self.specification
if spec.level:
offset = 0
out = Bunch(filtered=self.filtered_state[offset],
filtered_cov=self.filtered_state_cov[offset, offset],
smoothed=None, smoothed_cov=None,
offset=offset)
if self.smoothed_state is not None:
out.smoothed = self.smoothed_state[offset]
if self.smoothed_state_cov is not None:
out.smoothed_cov = self.smoothed_state_cov[offset, offset]
return out | Estimates of unobserved level component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | level | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def trend(self):
"""
Estimates of of unobserved trend component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, trend is always the second component of the state vector
# (because level is always present if trend is present)
out = None
spec = self.specification
if spec.trend:
offset = int(spec.level)
out = Bunch(filtered=self.filtered_state[offset],
filtered_cov=self.filtered_state_cov[offset, offset],
smoothed=None, smoothed_cov=None,
offset=offset)
if self.smoothed_state is not None:
out.smoothed = self.smoothed_state[offset]
if self.smoothed_state_cov is not None:
out.smoothed_cov = self.smoothed_state_cov[offset, offset]
return out | Estimates of of unobserved trend component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | trend | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def seasonal(self):
"""
Estimates of unobserved seasonal component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, seasonal always follows level/trend (if they are present)
# Note that we return only the first seasonal state, but there are
# in fact seasonal_periods-1 seasonal states, however latter states
# are just lagged versions of the first seasonal state.
out = None
spec = self.specification
if spec.seasonal:
offset = int(spec.trend + spec.level)
out = Bunch(filtered=self.filtered_state[offset],
filtered_cov=self.filtered_state_cov[offset, offset],
smoothed=None, smoothed_cov=None,
offset=offset)
if self.smoothed_state is not None:
out.smoothed = self.smoothed_state[offset]
if self.smoothed_state_cov is not None:
out.smoothed_cov = self.smoothed_state_cov[offset, offset]
return out | Estimates of unobserved seasonal component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | seasonal | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def freq_seasonal(self):
"""
Estimates of unobserved frequency domain seasonal component(s)
Returns
-------
out: list of Bunch instances
Each item has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, freq_seasonal components always follows level/trend
# and seasonal.
# There are 2 * (harmonics) seasonal states per freq_seasonal
# component.
# The sum of every other state enters the measurement equation.
# Additionally, there can be multiple components of this type.
# These facts make this property messier in implementation than the
# others.
# Fortunately, the states are conditionally mutually independent
# (conditional on previous timestep's states), so that the calculations
# of the variances are simple summations of individual variances and
# the calculation of the returned state is likewise a summation.
out = []
spec = self.specification
if spec.freq_seasonal:
previous_states_offset = int(spec.trend + spec.level
+ self._k_states_by_type['seasonal'])
previous_f_seas_offset = 0
for ix, h in enumerate(spec.freq_seasonal_harmonics):
offset = previous_states_offset + previous_f_seas_offset
period = spec.freq_seasonal_periods[ix]
# Only the gamma_jt terms enter the measurement equation (cf.
# D&K 2012 (3.7))
states_in_sum = np.arange(0, 2 * h, 2)
filtered_state = np.sum(
[self.filtered_state[offset + j] for j in states_in_sum],
axis=0)
filtered_cov = np.sum(
[self.filtered_state_cov[offset + j, offset + j] for j in
states_in_sum], axis=0)
item = Bunch(
filtered=filtered_state,
filtered_cov=filtered_cov,
smoothed=None, smoothed_cov=None,
offset=offset,
pretty_name='seasonal {p}({h})'.format(p=repr(period),
h=repr(h)))
if self.smoothed_state is not None:
item.smoothed = np.sum(
[self.smoothed_state[offset+j] for j in states_in_sum],
axis=0)
if self.smoothed_state_cov is not None:
item.smoothed_cov = np.sum(
[self.smoothed_state_cov[offset+j, offset+j]
for j in states_in_sum], axis=0)
out.append(item)
previous_f_seas_offset += 2 * h
return out | Estimates of unobserved frequency domain seasonal component(s)
Returns
-------
out: list of Bunch instances
Each item has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | freq_seasonal | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def cycle(self):
"""
Estimates of unobserved cycle component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, cycle always follows level/trend, seasonal, and freq
# seasonal.
# Note that we return only the first cyclical state, but there are
# in fact 2 cyclical states. The second cyclical state is not simply
# a lag of the first cyclical state, but the first cyclical state is
# the one that enters the measurement equation.
out = None
spec = self.specification
if spec.cycle:
offset = int(spec.trend + spec.level
+ self._k_states_by_type['seasonal']
+ self._k_states_by_type['freq_seasonal'])
out = Bunch(filtered=self.filtered_state[offset],
filtered_cov=self.filtered_state_cov[offset, offset],
smoothed=None, smoothed_cov=None,
offset=offset)
if self.smoothed_state is not None:
out.smoothed = self.smoothed_state[offset]
if self.smoothed_state_cov is not None:
out.smoothed_cov = self.smoothed_state_cov[offset, offset]
return out | Estimates of unobserved cycle component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | cycle | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def autoregressive(self):
"""
Estimates of unobserved autoregressive component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, autoregressive always follows level/trend, seasonal,
# freq seasonal, and cyclical.
# If it is an AR(p) model, then there are p associated
# states, but the second - pth states are just lags of the first state.
out = None
spec = self.specification
if spec.autoregressive:
offset = int(spec.trend + spec.level
+ self._k_states_by_type['seasonal']
+ self._k_states_by_type['freq_seasonal']
+ self._k_states_by_type['cycle'])
out = Bunch(filtered=self.filtered_state[offset],
filtered_cov=self.filtered_state_cov[offset, offset],
smoothed=None, smoothed_cov=None,
offset=offset)
if self.smoothed_state is not None:
out.smoothed = self.smoothed_state[offset]
if self.smoothed_state_cov is not None:
out.smoothed_cov = self.smoothed_state_cov[offset, offset]
return out | Estimates of unobserved autoregressive component
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | autoregressive | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def regression_coefficients(self):
"""
Estimates of unobserved regression coefficients
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins
"""
# If present, state-vector regression coefficients always are last
# (i.e. they follow level/trend, seasonal, freq seasonal, cyclical, and
# autoregressive states). There is one state associated with each
# regressor, and all are returned here.
out = None
spec = self.specification
if spec.regression:
if spec.mle_regression:
import warnings
warnings.warn('Regression coefficients estimated via maximum'
' likelihood. Estimated coefficients are'
' available in the parameters list, not as part'
' of the state vector.', OutputWarning)
else:
offset = int(spec.trend + spec.level
+ self._k_states_by_type['seasonal']
+ self._k_states_by_type['freq_seasonal']
+ self._k_states_by_type['cycle']
+ spec.ar_order)
start = offset
end = offset + spec.k_exog
out = Bunch(
filtered=self.filtered_state[start:end],
filtered_cov=self.filtered_state_cov[start:end, start:end],
smoothed=None, smoothed_cov=None,
offset=offset
)
if self.smoothed_state is not None:
out.smoothed = self.smoothed_state[start:end]
if self.smoothed_state_cov is not None:
out.smoothed_cov = (
self.smoothed_state_cov[start:end, start:end])
return out | Estimates of unobserved regression coefficients
Returns
-------
out: Bunch
Has the following attributes:
- `filtered`: a time series array with the filtered estimate of
the component
- `filtered_cov`: a time series array with the filtered estimate of
the variance/covariance of the component
- `smoothed`: a time series array with the smoothed estimate of
the component
- `smoothed_cov`: a time series array with the smoothed estimate of
the variance/covariance of the component
- `offset`: an integer giving the offset in the state vector where
this component begins | regression_coefficients | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def plot_components(self, which=None, alpha=0.05,
observed=True, level=True, trend=True,
seasonal=True, freq_seasonal=True,
cycle=True, autoregressive=True,
legend_loc='upper right', fig=None, figsize=None):
"""
Plot the estimated components of the model.
Parameters
----------
which : {'filtered', 'smoothed'}, or None, optional
Type of state estimate to plot. Default is 'smoothed' if smoothed
results are available otherwise 'filtered'.
alpha : float, optional
The confidence intervals for the components are (1 - alpha) %
observed : bool, optional
Whether or not to plot the observed series against
one-step-ahead predictions.
Default is True.
level : bool, optional
Whether or not to plot the level component, if applicable.
Default is True.
trend : bool, optional
Whether or not to plot the trend component, if applicable.
Default is True.
seasonal : bool, optional
Whether or not to plot the seasonal component, if applicable.
Default is True.
freq_seasonal : bool, optional
Whether or not to plot the frequency domain seasonal component(s),
if applicable. Default is True.
cycle : bool, optional
Whether or not to plot the cyclical component, if applicable.
Default is True.
autoregressive : bool, optional
Whether or not to plot the autoregressive state, if applicable.
Default is True.
fig : Figure, optional
If given, subplots are created in this figure instead of in a new
figure. Note that the grid will be created in the provided
figure using `fig.add_subplot()`.
figsize : tuple, optional
If a figure is created, this argument allows specifying a size.
The tuple is (width, height).
Notes
-----
If all options are included in the model and selected, this produces
a 6x1 plot grid with the following plots (ordered top-to-bottom):
0. Observed series against predicted series
1. Level
2. Trend
3. Seasonal
4. Freq Seasonal
5. Cycle
6. Autoregressive
Specific subplots will be removed if the component is not present in
the estimated model or if the corresponding keyword argument is set to
False.
All plots contain (1 - `alpha`) % confidence intervals.
"""
from scipy.stats import norm
from statsmodels.graphics.utils import _import_mpl, create_mpl_fig
plt = _import_mpl()
fig = create_mpl_fig(fig, figsize)
# Determine which results we have
if which is None:
which = 'filtered' if self.smoothed_state is None else 'smoothed'
# Determine which plots we have
spec = self.specification
comp = [
('level', level and spec.level),
('trend', trend and spec.trend),
('seasonal', seasonal and spec.seasonal),
]
if freq_seasonal and spec.freq_seasonal:
for ix, _ in enumerate(spec.freq_seasonal_periods):
key = f'freq_seasonal_{ix!r}'
comp.append((key, True))
comp.extend(
[('cycle', cycle and spec.cycle),
('autoregressive', autoregressive and spec.autoregressive)])
components = dict(comp)
llb = self.filter_results.loglikelihood_burn
# Number of plots
k_plots = observed + np.sum(list(components.values()))
# Get dates, if applicable
if hasattr(self.data, 'dates') and self.data.dates is not None:
dates = self.data.dates._mpl_repr()
else:
dates = np.arange(len(self.data.endog))
# Get the critical value for confidence intervals
critical_value = norm.ppf(1 - alpha / 2.)
plot_idx = 1
# Observed, predicted, confidence intervals
if observed:
ax = fig.add_subplot(k_plots, 1, plot_idx)
plot_idx += 1
# Plot the observed dataset
ax.plot(dates[llb:], self.model.endog[llb:], color='k',
label='Observed')
# Get the predicted values and confidence intervals
predict = self.filter_results.forecasts[0]
std_errors = np.sqrt(self.filter_results.forecasts_error_cov[0, 0])
ci_lower = predict - critical_value * std_errors
ci_upper = predict + critical_value * std_errors
# Plot
ax.plot(dates[llb:], predict[llb:],
label='One-step-ahead predictions')
ci_poly = ax.fill_between(
dates[llb:], ci_lower[llb:], ci_upper[llb:], alpha=0.2
)
ci_label = '$%.3g \\%%$ confidence interval' % ((1 - alpha) * 100)
# Proxy artist for fill_between legend entry
# See e.g. https://matplotlib.org/1.3.1/users/legend_guide.html
p = plt.Rectangle((0, 0), 1, 1, fc=ci_poly.get_facecolor()[0])
# Legend
handles, labels = ax.get_legend_handles_labels()
handles.append(p)
labels.append(ci_label)
ax.legend(handles, labels, loc=legend_loc)
ax.set_title('Predicted vs observed')
# Plot each component
for component, is_plotted in components.items():
if not is_plotted:
continue
ax = fig.add_subplot(k_plots, 1, plot_idx)
plot_idx += 1
try:
component_bunch = getattr(self, component)
title = component.title()
except AttributeError:
# This might be a freq_seasonal component, of which there are
# possibly multiple bagged up in property freq_seasonal
if component.startswith('freq_seasonal_'):
ix = int(component.replace('freq_seasonal_', ''))
big_bunch = getattr(self, 'freq_seasonal')
component_bunch = big_bunch[ix]
title = component_bunch.pretty_name
else:
raise
# Check for a valid estimation type
if which not in component_bunch:
raise ValueError('Invalid type of state estimate.')
which_cov = '%s_cov' % which
# Get the predicted values
value = component_bunch[which]
# Plot
state_label = f'{title} ({which})'
ax.plot(dates[llb:], value[llb:], label=state_label)
# Get confidence intervals
if which_cov in component_bunch:
std_errors = np.sqrt(component_bunch['%s_cov' % which])
ci_lower = value - critical_value * std_errors
ci_upper = value + critical_value * std_errors
ci_poly = ax.fill_between(
dates[llb:], ci_lower[llb:], ci_upper[llb:], alpha=0.2
)
ci_label = ('$%.3g \\%%$ confidence interval'
% ((1 - alpha) * 100))
# Legend
ax.legend(loc=legend_loc)
ax.set_title('%s component' % title)
# Add a note if first observations excluded
if llb > 0:
text = ('Note: The first %d observations are not shown, due to'
' approximate diffuse initialization.')
fig.text(0.1, 0.01, text % llb, fontsize='large')
return fig | Plot the estimated components of the model.
Parameters
----------
which : {'filtered', 'smoothed'}, or None, optional
Type of state estimate to plot. Default is 'smoothed' if smoothed
results are available otherwise 'filtered'.
alpha : float, optional
The confidence intervals for the components are (1 - alpha) %
observed : bool, optional
Whether or not to plot the observed series against
one-step-ahead predictions.
Default is True.
level : bool, optional
Whether or not to plot the level component, if applicable.
Default is True.
trend : bool, optional
Whether or not to plot the trend component, if applicable.
Default is True.
seasonal : bool, optional
Whether or not to plot the seasonal component, if applicable.
Default is True.
freq_seasonal : bool, optional
Whether or not to plot the frequency domain seasonal component(s),
if applicable. Default is True.
cycle : bool, optional
Whether or not to plot the cyclical component, if applicable.
Default is True.
autoregressive : bool, optional
Whether or not to plot the autoregressive state, if applicable.
Default is True.
fig : Figure, optional
If given, subplots are created in this figure instead of in a new
figure. Note that the grid will be created in the provided
figure using `fig.add_subplot()`.
figsize : tuple, optional
If a figure is created, this argument allows specifying a size.
The tuple is (width, height).
Notes
-----
If all options are included in the model and selected, this produces
a 6x1 plot grid with the following plots (ordered top-to-bottom):
0. Observed series against predicted series
1. Level
2. Trend
3. Seasonal
4. Freq Seasonal
5. Cycle
6. Autoregressive
Specific subplots will be removed if the component is not present in
the estimated model or if the corresponding keyword argument is set to
False.
All plots contain (1 - `alpha`) % confidence intervals. | plot_components | python | statsmodels/statsmodels | statsmodels/tsa/statespace/structural.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/structural.py | BSD-3-Clause |
def prepare_data(self):
"""
Prepare data for use in the state space representation
"""
endog = np.require(
np.array(self.data.orig_endog, copy=True), requirements="CW"
).copy()
exog = self.data.orig_exog
if exog is not None:
exog = np.array(exog)
# Base class may allow 1-dim data, whereas we need 2-dim
if endog.ndim == 1:
endog.shape = (endog.shape[0], 1) # this will be C-contiguous
return endog, exog | Prepare data for use in the state space representation | prepare_data | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def initialize_statespace(self, **kwargs):
"""
Initialize the state space representation
Parameters
----------
**kwargs
Additional keyword arguments to pass to the state space class
constructor.
"""
# (Now self.endog is C-ordered and in long format (nobs x k_endog). To
# get F-ordered and in wide format just need to transpose)
endog = self.endog.T
# Instantiate the state space object
self.ssm = SimulationSmoother(endog.shape[0], self.k_states,
nobs=endog.shape[1], **kwargs)
# Bind the data to the model
self.ssm.bind(endog)
# Other dimensions, now that `ssm` is available
self.k_endog = self.ssm.k_endog | Initialize the state space representation
Parameters
----------
**kwargs
Additional keyword arguments to pass to the state space class
constructor. | initialize_statespace | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def clone(self, endog, exog=None, **kwargs):
"""
Clone state space model with new data and optionally new specification
Parameters
----------
endog : array_like
The observed time-series process :math:`y`
k_states : int
The dimension of the unobserved state process.
exog : array_like, optional
Array of exogenous regressors, shaped nobs x k. Default is no
exogenous regressors.
kwargs
Keyword arguments to pass to the new model class to change the
model specification.
Returns
-------
model : MLEModel subclass
Notes
-----
This method must be implemented
"""
raise NotImplementedError('This method is not implemented in the base'
' class and must be set up by each specific'
' model.') | Clone state space model with new data and optionally new specification
Parameters
----------
endog : array_like
The observed time-series process :math:`y`
k_states : int
The dimension of the unobserved state process.
exog : array_like, optional
Array of exogenous regressors, shaped nobs x k. Default is no
exogenous regressors.
kwargs
Keyword arguments to pass to the new model class to change the
model specification.
Returns
-------
model : MLEModel subclass
Notes
-----
This method must be implemented | clone | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def set_filter_method(self, filter_method=None, **kwargs):
"""
Set the filtering method
The filtering method controls aspects of which Kalman filtering
approach will be used.
Parameters
----------
filter_method : int, optional
Bitmask value to set the filter method to. See notes for details.
**kwargs
Keyword arguments may be used to influence the filter method by
setting individual boolean flags. See notes for details.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details.
"""
self.ssm.set_filter_method(filter_method, **kwargs) | Set the filtering method
The filtering method controls aspects of which Kalman filtering
approach will be used.
Parameters
----------
filter_method : int, optional
Bitmask value to set the filter method to. See notes for details.
**kwargs
Keyword arguments may be used to influence the filter method by
setting individual boolean flags. See notes for details.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details. | set_filter_method | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def set_inversion_method(self, inversion_method=None, **kwargs):
"""
Set the inversion method
The Kalman filter may contain one matrix inversion: that of the
forecast error covariance matrix. The inversion method controls how and
if that inverse is performed.
Parameters
----------
inversion_method : int, optional
Bitmask value to set the inversion method to. See notes for
details.
**kwargs
Keyword arguments may be used to influence the inversion method by
setting individual boolean flags. See notes for details.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details.
"""
self.ssm.set_inversion_method(inversion_method, **kwargs) | Set the inversion method
The Kalman filter may contain one matrix inversion: that of the
forecast error covariance matrix. The inversion method controls how and
if that inverse is performed.
Parameters
----------
inversion_method : int, optional
Bitmask value to set the inversion method to. See notes for
details.
**kwargs
Keyword arguments may be used to influence the inversion method by
setting individual boolean flags. See notes for details.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details. | set_inversion_method | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def set_stability_method(self, stability_method=None, **kwargs):
"""
Set the numerical stability method
The Kalman filter is a recursive algorithm that may in some cases
suffer issues with numerical stability. The stability method controls
what, if any, measures are taken to promote stability.
Parameters
----------
stability_method : int, optional
Bitmask value to set the stability method to. See notes for
details.
**kwargs
Keyword arguments may be used to influence the stability method by
setting individual boolean flags. See notes for details.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details.
"""
self.ssm.set_stability_method(stability_method, **kwargs) | Set the numerical stability method
The Kalman filter is a recursive algorithm that may in some cases
suffer issues with numerical stability. The stability method controls
what, if any, measures are taken to promote stability.
Parameters
----------
stability_method : int, optional
Bitmask value to set the stability method to. See notes for
details.
**kwargs
Keyword arguments may be used to influence the stability method by
setting individual boolean flags. See notes for details.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details. | set_stability_method | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def set_conserve_memory(self, conserve_memory=None, **kwargs):
"""
Set the memory conservation method
By default, the Kalman filter computes a number of intermediate
matrices at each iteration. The memory conservation options control
which of those matrices are stored.
Parameters
----------
conserve_memory : int, optional
Bitmask value to set the memory conservation method to. See notes
for details.
**kwargs
Keyword arguments may be used to influence the memory conservation
method by setting individual boolean flags.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details.
"""
self.ssm.set_conserve_memory(conserve_memory, **kwargs) | Set the memory conservation method
By default, the Kalman filter computes a number of intermediate
matrices at each iteration. The memory conservation options control
which of those matrices are stored.
Parameters
----------
conserve_memory : int, optional
Bitmask value to set the memory conservation method to. See notes
for details.
**kwargs
Keyword arguments may be used to influence the memory conservation
method by setting individual boolean flags.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanFilter` class for details. | set_conserve_memory | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def set_smoother_output(self, smoother_output=None, **kwargs):
"""
Set the smoother output
The smoother can produce several types of results. The smoother output
variable controls which are calculated and returned.
Parameters
----------
smoother_output : int, optional
Bitmask value to set the smoother output to. See notes for details.
**kwargs
Keyword arguments may be used to influence the smoother output by
setting individual boolean flags.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanSmoother` class for details.
"""
self.ssm.set_smoother_output(smoother_output, **kwargs) | Set the smoother output
The smoother can produce several types of results. The smoother output
variable controls which are calculated and returned.
Parameters
----------
smoother_output : int, optional
Bitmask value to set the smoother output to. See notes for details.
**kwargs
Keyword arguments may be used to influence the smoother output by
setting individual boolean flags.
Notes
-----
This method is rarely used. See the corresponding function in the
`KalmanSmoother` class for details. | set_smoother_output | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def initialize_known(self, initial_state, initial_state_cov):
"""Initialize known"""
self.ssm.initialize_known(initial_state, initial_state_cov) | Initialize known | initialize_known | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def initialize_approximate_diffuse(self, variance=None):
"""Initialize approximate diffuse"""
self.ssm.initialize_approximate_diffuse(variance) | Initialize approximate diffuse | initialize_approximate_diffuse | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def initialize_stationary(self):
"""Initialize stationary"""
self.ssm.initialize_stationary() | Initialize stationary | initialize_stationary | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def fix_params(self, params):
"""
Fix parameters to specific values (context manager)
Parameters
----------
params : dict
Dictionary describing the fixed parameter values, of the form
`param_name: fixed_value`. See the `param_names` property for valid
parameter names.
Examples
--------
>>> mod = sm.tsa.SARIMAX(endog, order=(1, 0, 1))
>>> with mod.fix_params({'ar.L1': 0.5}):
res = mod.fit()
"""
k_params = len(self.param_names)
# Initialization (this is done here rather than in the constructor
# because param_names may not be available at that point)
if self._fixed_params is None:
self._fixed_params = {}
self._params_index = dict(
zip(self.param_names, np.arange(k_params)))
# Cache the current fixed parameters
cache_fixed_params = self._fixed_params.copy()
cache_has_fixed_params = self._has_fixed_params
cache_fixed_params_index = self._fixed_params_index
cache_free_params_index = self._free_params_index
# Validate parameter names and values
all_fixed_param_names = (
set(params.keys()) | set(self._fixed_params.keys())
)
self._validate_can_fix_params(all_fixed_param_names)
# Set the new fixed parameters, keeping the order as given by
# param_names
self._fixed_params.update(params)
self._fixed_params = {
name: self._fixed_params[name] for name in self.param_names
if name in self._fixed_params}
# Update associated values
self._has_fixed_params = True
self._fixed_params_index = [self._params_index[key]
for key in self._fixed_params.keys()]
self._free_params_index = list(
set(np.arange(k_params)).difference(self._fixed_params_index))
try:
yield
finally:
# Reset the fixed parameters
self._has_fixed_params = cache_has_fixed_params
self._fixed_params = cache_fixed_params
self._fixed_params_index = cache_fixed_params_index
self._free_params_index = cache_free_params_index | Fix parameters to specific values (context manager)
Parameters
----------
params : dict
Dictionary describing the fixed parameter values, of the form
`param_name: fixed_value`. See the `param_names` property for valid
parameter names.
Examples
--------
>>> mod = sm.tsa.SARIMAX(endog, order=(1, 0, 1))
>>> with mod.fix_params({'ar.L1': 0.5}):
res = mod.fit() | fix_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def fit(self, start_params=None, transformed=True, includes_fixed=False,
cov_type=None, cov_kwds=None, method='lbfgs', maxiter=50,
full_output=1, disp=5, callback=None, return_params=False,
optim_score=None, optim_complex_step=None, optim_hessian=None,
flags=None, low_memory=False, **kwargs):
"""
Fits the model by maximum likelihood via Kalman filter.
Parameters
----------
start_params : array_like, optional
Initial guess of the solution for the loglikelihood maximization.
If None, the default is given by Model.start_params.
transformed : bool, optional
Whether or not `start_params` is already transformed. Default is
True.
includes_fixed : bool, optional
If parameters were previously fixed with the `fix_params` method,
this argument describes whether or not `start_params` also includes
the fixed parameters, in addition to the free parameters. Default
is False.
cov_type : str, optional
The `cov_type` keyword governs the method for calculating the
covariance matrix of parameter estimates. Can be one of:
- 'opg' for the outer product of gradient estimator
- 'oim' for the observed information matrix estimator, calculated
using the method of Harvey (1989)
- 'approx' for the observed information matrix estimator,
calculated using a numerical approximation of the Hessian matrix.
- 'robust' for an approximate (quasi-maximum likelihood) covariance
matrix that may be valid even in the presence of some
misspecifications. Intermediate calculations use the 'oim'
method.
- 'robust_approx' is the same as 'robust' except that the
intermediate calculations use the 'approx' method.
- 'none' for no covariance matrix calculation.
Default is 'opg' unless memory conservation is used to avoid
computing the loglikelihood values for each observation, in which
case the default is 'approx'.
cov_kwds : dict or None, optional
A dictionary of arguments affecting covariance matrix computation.
**opg, oim, approx, robust, robust_approx**
- 'approx_complex_step' : bool, optional - If True, numerical
approximations are computed using complex-step methods. If False,
numerical approximations are computed using finite difference
methods. Default is True.
- 'approx_centered' : bool, optional - If True, numerical
approximations computed using finite difference methods use a
centered approximation. Default is False.
method : str, optional
The `method` determines which solver from `scipy.optimize`
is used, and it can be chosen from among the following strings:
- 'newton' for Newton-Raphson
- 'nm' for Nelder-Mead
- 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
- 'lbfgs' for limited-memory BFGS with optional box constraints
- 'powell' for modified Powell's method
- 'cg' for conjugate gradient
- 'ncg' for Newton-conjugate gradient
- 'basinhopping' for global basin-hopping solver
The explicit arguments in `fit` are passed to the solver,
with the exception of the basin-hopping solver. Each
solver has several optional arguments that are not the same across
solvers. See the notes section below (or scipy.optimize) for the
available arguments and for the list of explicit arguments that the
basin-hopping solver supports.
maxiter : int, optional
The maximum number of iterations to perform.
full_output : bool, optional
Set to True to have all available output in the Results object's
mle_retvals attribute. The output is dependent on the solver.
See LikelihoodModelResults notes section for more information.
disp : bool, optional
Set to True to print convergence messages.
callback : callable callback(xk), optional
Called after each iteration, as callback(xk), where xk is the
current parameter vector.
return_params : bool, optional
Whether or not to return only the array of maximizing parameters.
Default is False.
optim_score : {'harvey', 'approx'} or None, optional
The method by which the score vector is calculated. 'harvey' uses
the method from Harvey (1989), 'approx' uses either finite
difference or complex step differentiation depending upon the
value of `optim_complex_step`, and None uses the built-in gradient
approximation of the optimizer. Default is None. This keyword is
only relevant if the optimization method uses the score.
optim_complex_step : bool, optional
Whether or not to use complex step differentiation when
approximating the score; if False, finite difference approximation
is used. Default is True. This keyword is only relevant if
`optim_score` is set to 'harvey' or 'approx'.
optim_hessian : {'opg', 'oim', 'approx'}, optional
The method by which the Hessian is numerically approximated. 'opg'
uses outer product of gradients, 'oim' uses the information
matrix formula from Harvey (1989), and 'approx' uses numerical
approximation. This keyword is only relevant if the
optimization method uses the Hessian matrix.
low_memory : bool, optional
If set to True, techniques are applied to substantially reduce
memory usage. If used, some features of the results object will
not be available (including smoothed results and in-sample
prediction), although out-of-sample forecasting is possible.
Default is False.
**kwargs
Additional keyword arguments to pass to the optimizer.
Returns
-------
results
Results object holding results from fitting a state space model.
See Also
--------
statsmodels.base.model.LikelihoodModel.fit
statsmodels.tsa.statespace.mlemodel.MLEResults
statsmodels.tsa.statespace.structural.UnobservedComponentsResults
"""
if start_params is None:
start_params = self.start_params
transformed = True
includes_fixed = True
# Update the score method
if optim_score is None and method == 'lbfgs':
kwargs.setdefault('approx_grad', True)
kwargs.setdefault('epsilon', 1e-5)
elif optim_score is None:
optim_score = 'approx'
# Check for complex step differentiation
if optim_complex_step is None:
optim_complex_step = not self.ssm._complex_endog
elif optim_complex_step and self.ssm._complex_endog:
raise ValueError('Cannot use complex step derivatives when data'
' or parameters are complex.')
# Standardize starting parameters
start_params = self.handle_params(start_params, transformed=True,
includes_fixed=includes_fixed)
# Unconstrain the starting parameters
if transformed:
start_params = self.untransform_params(start_params)
# Remove any fixed parameters
if self._has_fixed_params:
start_params = start_params[self._free_params_index]
# If all parameters are fixed, we are done
if self._has_fixed_params and len(start_params) == 0:
mlefit = Bunch(params=[], mle_retvals=None,
mle_settings=None)
else:
# Remove disallowed kwargs
disallow = (
"concentrate_scale",
"enforce_stationarity",
"enforce_invertibility"
)
kwargs = {k: v for k, v in kwargs.items() if k not in disallow}
# Maximum likelihood estimation
if flags is None:
flags = {}
flags.update({
'transformed': False,
'includes_fixed': False,
'score_method': optim_score,
'approx_complex_step': optim_complex_step
})
if optim_hessian is not None:
flags['hessian_method'] = optim_hessian
fargs = (flags,)
mlefit = super().fit(start_params, method=method,
fargs=fargs,
maxiter=maxiter,
full_output=full_output,
disp=disp, callback=callback,
skip_hessian=True, **kwargs)
# Just return the fitted parameters if requested
if return_params:
return self.handle_params(mlefit.params, transformed=False,
includes_fixed=False)
# Otherwise construct the results class if desired
else:
# Handle memory conservation option
if low_memory:
conserve_memory = self.ssm.conserve_memory
self.ssm.set_conserve_memory(MEMORY_CONSERVE)
# Perform filtering / smoothing
if (self.ssm.memory_no_predicted or self.ssm.memory_no_gain
or self.ssm.memory_no_smoothing):
func = self.filter
else:
func = self.smooth
res = func(mlefit.params, transformed=False, includes_fixed=False,
cov_type=cov_type, cov_kwds=cov_kwds)
res.mlefit = mlefit
res.mle_retvals = mlefit.mle_retvals
res.mle_settings = mlefit.mle_settings
# Reset memory conservation
if low_memory:
self.ssm.set_conserve_memory(conserve_memory)
return res | Fits the model by maximum likelihood via Kalman filter.
Parameters
----------
start_params : array_like, optional
Initial guess of the solution for the loglikelihood maximization.
If None, the default is given by Model.start_params.
transformed : bool, optional
Whether or not `start_params` is already transformed. Default is
True.
includes_fixed : bool, optional
If parameters were previously fixed with the `fix_params` method,
this argument describes whether or not `start_params` also includes
the fixed parameters, in addition to the free parameters. Default
is False.
cov_type : str, optional
The `cov_type` keyword governs the method for calculating the
covariance matrix of parameter estimates. Can be one of:
- 'opg' for the outer product of gradient estimator
- 'oim' for the observed information matrix estimator, calculated
using the method of Harvey (1989)
- 'approx' for the observed information matrix estimator,
calculated using a numerical approximation of the Hessian matrix.
- 'robust' for an approximate (quasi-maximum likelihood) covariance
matrix that may be valid even in the presence of some
misspecifications. Intermediate calculations use the 'oim'
method.
- 'robust_approx' is the same as 'robust' except that the
intermediate calculations use the 'approx' method.
- 'none' for no covariance matrix calculation.
Default is 'opg' unless memory conservation is used to avoid
computing the loglikelihood values for each observation, in which
case the default is 'approx'.
cov_kwds : dict or None, optional
A dictionary of arguments affecting covariance matrix computation.
**opg, oim, approx, robust, robust_approx**
- 'approx_complex_step' : bool, optional - If True, numerical
approximations are computed using complex-step methods. If False,
numerical approximations are computed using finite difference
methods. Default is True.
- 'approx_centered' : bool, optional - If True, numerical
approximations computed using finite difference methods use a
centered approximation. Default is False.
method : str, optional
The `method` determines which solver from `scipy.optimize`
is used, and it can be chosen from among the following strings:
- 'newton' for Newton-Raphson
- 'nm' for Nelder-Mead
- 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
- 'lbfgs' for limited-memory BFGS with optional box constraints
- 'powell' for modified Powell's method
- 'cg' for conjugate gradient
- 'ncg' for Newton-conjugate gradient
- 'basinhopping' for global basin-hopping solver
The explicit arguments in `fit` are passed to the solver,
with the exception of the basin-hopping solver. Each
solver has several optional arguments that are not the same across
solvers. See the notes section below (or scipy.optimize) for the
available arguments and for the list of explicit arguments that the
basin-hopping solver supports.
maxiter : int, optional
The maximum number of iterations to perform.
full_output : bool, optional
Set to True to have all available output in the Results object's
mle_retvals attribute. The output is dependent on the solver.
See LikelihoodModelResults notes section for more information.
disp : bool, optional
Set to True to print convergence messages.
callback : callable callback(xk), optional
Called after each iteration, as callback(xk), where xk is the
current parameter vector.
return_params : bool, optional
Whether or not to return only the array of maximizing parameters.
Default is False.
optim_score : {'harvey', 'approx'} or None, optional
The method by which the score vector is calculated. 'harvey' uses
the method from Harvey (1989), 'approx' uses either finite
difference or complex step differentiation depending upon the
value of `optim_complex_step`, and None uses the built-in gradient
approximation of the optimizer. Default is None. This keyword is
only relevant if the optimization method uses the score.
optim_complex_step : bool, optional
Whether or not to use complex step differentiation when
approximating the score; if False, finite difference approximation
is used. Default is True. This keyword is only relevant if
`optim_score` is set to 'harvey' or 'approx'.
optim_hessian : {'opg', 'oim', 'approx'}, optional
The method by which the Hessian is numerically approximated. 'opg'
uses outer product of gradients, 'oim' uses the information
matrix formula from Harvey (1989), and 'approx' uses numerical
approximation. This keyword is only relevant if the
optimization method uses the Hessian matrix.
low_memory : bool, optional
If set to True, techniques are applied to substantially reduce
memory usage. If used, some features of the results object will
not be available (including smoothed results and in-sample
prediction), although out-of-sample forecasting is possible.
Default is False.
**kwargs
Additional keyword arguments to pass to the optimizer.
Returns
-------
results
Results object holding results from fitting a state space model.
See Also
--------
statsmodels.base.model.LikelihoodModel.fit
statsmodels.tsa.statespace.mlemodel.MLEResults
statsmodels.tsa.statespace.structural.UnobservedComponentsResults | fit | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def fit_constrained(self, constraints, start_params=None, **fit_kwds):
"""
Fit the model with some parameters subject to equality constraints.
Parameters
----------
constraints : dict
Dictionary of constraints, of the form `param_name: fixed_value`.
See the `param_names` property for valid parameter names.
start_params : array_like, optional
Initial guess of the solution for the loglikelihood maximization.
If None, the default is given by Model.start_params.
**fit_kwds : keyword arguments
fit_kwds are used in the optimization of the remaining parameters.
Returns
-------
results : Results instance
Examples
--------
>>> mod = sm.tsa.SARIMAX(endog, order=(1, 0, 1))
>>> res = mod.fit_constrained({'ar.L1': 0.5})
"""
with self.fix_params(constraints):
res = self.fit(start_params, **fit_kwds)
return res | Fit the model with some parameters subject to equality constraints.
Parameters
----------
constraints : dict
Dictionary of constraints, of the form `param_name: fixed_value`.
See the `param_names` property for valid parameter names.
start_params : array_like, optional
Initial guess of the solution for the loglikelihood maximization.
If None, the default is given by Model.start_params.
**fit_kwds : keyword arguments
fit_kwds are used in the optimization of the remaining parameters.
Returns
-------
results : Results instance
Examples
--------
>>> mod = sm.tsa.SARIMAX(endog, order=(1, 0, 1))
>>> res = mod.fit_constrained({'ar.L1': 0.5}) | fit_constrained | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def filter(self, params, transformed=True, includes_fixed=False,
complex_step=False, cov_type=None, cov_kwds=None,
return_ssm=False, results_class=None,
results_wrapper_class=None, low_memory=False, **kwargs):
"""
Kalman filtering
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
return_ssm : bool,optional
Whether or not to return only the state space output or a full
results object. Default is to return a full results object.
cov_type : str, optional
See `MLEResults.fit` for a description of covariance matrix types
for results object.
cov_kwds : dict or None, optional
See `MLEResults.get_robustcov_results` for a description required
keywords for alternative covariance estimators
low_memory : bool, optional
If set to True, techniques are applied to substantially reduce
memory usage. If used, some features of the results object will
not be available (including in-sample prediction), although
out-of-sample forecasting is possible. Default is False.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
"""
params = self.handle_params(params, transformed=transformed,
includes_fixed=includes_fixed)
self.update(params, transformed=True, includes_fixed=True,
complex_step=complex_step)
# Save the parameter names
self.data.param_names = self.param_names
if complex_step:
kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU
# Handle memory conservation
if low_memory:
kwargs['conserve_memory'] = MEMORY_CONSERVE
# Get the state space output
result = self.ssm.filter(complex_step=complex_step, **kwargs)
# Wrap in a results object
return self._wrap_results(params, result, return_ssm, cov_type,
cov_kwds, results_class,
results_wrapper_class) | Kalman filtering
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
return_ssm : bool,optional
Whether or not to return only the state space output or a full
results object. Default is to return a full results object.
cov_type : str, optional
See `MLEResults.fit` for a description of covariance matrix types
for results object.
cov_kwds : dict or None, optional
See `MLEResults.get_robustcov_results` for a description required
keywords for alternative covariance estimators
low_memory : bool, optional
If set to True, techniques are applied to substantially reduce
memory usage. If used, some features of the results object will
not be available (including in-sample prediction), although
out-of-sample forecasting is possible. Default is False.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details. | filter | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def smooth(self, params, transformed=True, includes_fixed=False,
complex_step=False, cov_type=None, cov_kwds=None,
return_ssm=False, results_class=None,
results_wrapper_class=None, **kwargs):
"""
Kalman smoothing
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
return_ssm : bool,optional
Whether or not to return only the state space output or a full
results object. Default is to return a full results object.
cov_type : str, optional
See `MLEResults.fit` for a description of covariance matrix types
for results object.
cov_kwds : dict or None, optional
See `MLEResults.get_robustcov_results` for a description required
keywords for alternative covariance estimators
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
"""
params = self.handle_params(params, transformed=transformed,
includes_fixed=includes_fixed)
self.update(params, transformed=True, includes_fixed=True,
complex_step=complex_step)
# Save the parameter names
self.data.param_names = self.param_names
if complex_step:
kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU
# Get the state space output
result = self.ssm.smooth(complex_step=complex_step, **kwargs)
# Wrap in a results object
return self._wrap_results(params, result, return_ssm, cov_type,
cov_kwds, results_class,
results_wrapper_class) | Kalman smoothing
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
return_ssm : bool,optional
Whether or not to return only the state space output or a full
results object. Default is to return a full results object.
cov_type : str, optional
See `MLEResults.fit` for a description of covariance matrix types
for results object.
cov_kwds : dict or None, optional
See `MLEResults.get_robustcov_results` for a description required
keywords for alternative covariance estimators
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details. | smooth | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def loglike(self, params, *args, **kwargs):
"""
Loglikelihood evaluation
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
See Also
--------
update : modifies the internal state of the state space model to
reflect new params
Notes
-----
[1]_ recommend maximizing the average likelihood to avoid scale issues;
this is done automatically by the base Model fit method.
References
----------
.. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999.
Statistical Algorithms for Models in State Space Using SsfPack 2.2.
Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023.
"""
transformed, includes_fixed, complex_step, kwargs = _handle_args(
MLEModel._loglike_param_names, MLEModel._loglike_param_defaults,
*args, **kwargs)
params = self.handle_params(params, transformed=transformed,
includes_fixed=includes_fixed)
self.update(params, transformed=True, includes_fixed=True,
complex_step=complex_step)
if complex_step:
kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU
loglike = self.ssm.loglike(complex_step=complex_step, **kwargs)
# Koopman, Shephard, and Doornik recommend maximizing the average
# likelihood to avoid scale issues, but the averaging is done
# automatically in the base model `fit` method
return loglike | Loglikelihood evaluation
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
See Also
--------
update : modifies the internal state of the state space model to
reflect new params
Notes
-----
[1]_ recommend maximizing the average likelihood to avoid scale issues;
this is done automatically by the base Model fit method.
References
----------
.. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999.
Statistical Algorithms for Models in State Space Using SsfPack 2.2.
Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | loglike | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def loglikeobs(self, params, transformed=True, includes_fixed=False,
complex_step=False, **kwargs):
"""
Loglikelihood evaluation
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
See Also
--------
update : modifies the internal state of the Model to reflect new params
Notes
-----
[1]_ recommend maximizing the average likelihood to avoid scale issues;
this is done automatically by the base Model fit method.
References
----------
.. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999.
Statistical Algorithms for Models in State Space Using SsfPack 2.2.
Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023.
"""
params = self.handle_params(params, transformed=transformed,
includes_fixed=includes_fixed)
# If we're using complex-step differentiation, then we cannot use
# Cholesky factorization
if complex_step:
kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU
self.update(params, transformed=True, includes_fixed=True,
complex_step=complex_step)
return self.ssm.loglikeobs(complex_step=complex_step, **kwargs) | Loglikelihood evaluation
Parameters
----------
params : array_like
Array of parameters at which to evaluate the loglikelihood
function.
transformed : bool, optional
Whether or not `params` is already transformed. Default is True.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
See Also
--------
update : modifies the internal state of the Model to reflect new params
Notes
-----
[1]_ recommend maximizing the average likelihood to avoid scale issues;
this is done automatically by the base Model fit method.
References
----------
.. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999.
Statistical Algorithms for Models in State Space Using SsfPack 2.2.
Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | loglikeobs | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def observed_information_matrix(self, params, transformed=True,
includes_fixed=False,
approx_complex_step=None,
approx_centered=False, **kwargs):
"""
Observed information matrix
Parameters
----------
params : array_like, optional
Array of parameters at which to evaluate the loglikelihood
function.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
Notes
-----
This method is from Harvey (1989), which shows that the information
matrix only depends on terms from the gradient. This implementation is
partially analytic and partially numeric approximation, therefore,
because it uses the analytic formula for the information matrix, with
numerically computed elements of the gradient.
References
----------
Harvey, Andrew C. 1990.
Forecasting, Structural Time Series Models and the Kalman Filter.
Cambridge University Press.
"""
params = np.array(params, ndmin=1)
# Setup
n = len(params)
# We cannot use complex-step differentiation with non-transformed
# parameters
if approx_complex_step is None:
approx_complex_step = transformed
if not transformed and approx_complex_step:
raise ValueError("Cannot use complex-step approximations to"
" calculate the observed_information_matrix"
" with untransformed parameters.")
# Get values at the params themselves
params = self.handle_params(params, transformed=transformed,
includes_fixed=includes_fixed)
self.update(params, transformed=True, includes_fixed=True,
complex_step=approx_complex_step)
# If we're using complex-step differentiation, then we cannot use
# Cholesky factorization
if approx_complex_step:
kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU
res = self.ssm.filter(complex_step=approx_complex_step, **kwargs)
dtype = self.ssm.dtype
# Save this for inversion later
inv_forecasts_error_cov = res.forecasts_error_cov.copy()
partials_forecasts_error, partials_forecasts_error_cov = (
self._forecasts_error_partial_derivatives(
params, transformed=transformed, includes_fixed=includes_fixed,
approx_complex_step=approx_complex_step,
approx_centered=approx_centered, res=res, **kwargs))
# Compute the information matrix
tmp = np.zeros((self.k_endog, self.k_endog, self.nobs, n), dtype=dtype)
information_matrix = np.zeros((n, n), dtype=dtype)
d = np.maximum(self.ssm.loglikelihood_burn, res.nobs_diffuse)
for t in range(d, self.nobs):
inv_forecasts_error_cov[:, :, t] = (
np.linalg.inv(res.forecasts_error_cov[:, :, t])
)
for i in range(n):
tmp[:, :, t, i] = np.dot(
inv_forecasts_error_cov[:, :, t],
partials_forecasts_error_cov[:, :, t, i]
)
for i in range(n):
for j in range(n):
information_matrix[i, j] += (
0.5 * np.trace(np.dot(tmp[:, :, t, i],
tmp[:, :, t, j]))
)
information_matrix[i, j] += np.inner(
partials_forecasts_error[:, t, i],
np.dot(inv_forecasts_error_cov[:, :, t],
partials_forecasts_error[:, t, j])
)
return information_matrix / (self.nobs - self.ssm.loglikelihood_burn) | Observed information matrix
Parameters
----------
params : array_like, optional
Array of parameters at which to evaluate the loglikelihood
function.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
Notes
-----
This method is from Harvey (1989), which shows that the information
matrix only depends on terms from the gradient. This implementation is
partially analytic and partially numeric approximation, therefore,
because it uses the analytic formula for the information matrix, with
numerically computed elements of the gradient.
References
----------
Harvey, Andrew C. 1990.
Forecasting, Structural Time Series Models and the Kalman Filter.
Cambridge University Press. | observed_information_matrix | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def opg_information_matrix(self, params, transformed=True,
includes_fixed=False, approx_complex_step=None,
**kwargs):
"""
Outer product of gradients information matrix
Parameters
----------
params : array_like, optional
Array of parameters at which to evaluate the loglikelihood
function.
**kwargs
Additional arguments to the `loglikeobs` method.
References
----------
Berndt, Ernst R., Bronwyn Hall, Robert Hall, and Jerry Hausman. 1974.
Estimation and Inference in Nonlinear Structural Models.
NBER Chapters. National Bureau of Economic Research, Inc.
"""
# We cannot use complex-step differentiation with non-transformed
# parameters
if approx_complex_step is None:
approx_complex_step = transformed
if not transformed and approx_complex_step:
raise ValueError("Cannot use complex-step approximations to"
" calculate the observed_information_matrix"
" with untransformed parameters.")
score_obs = self.score_obs(params, transformed=transformed,
includes_fixed=includes_fixed,
approx_complex_step=approx_complex_step,
**kwargs).transpose()
return (
np.inner(score_obs, score_obs) /
(self.nobs - self.ssm.loglikelihood_burn)
) | Outer product of gradients information matrix
Parameters
----------
params : array_like, optional
Array of parameters at which to evaluate the loglikelihood
function.
**kwargs
Additional arguments to the `loglikeobs` method.
References
----------
Berndt, Ernst R., Bronwyn Hall, Robert Hall, and Jerry Hausman. 1974.
Estimation and Inference in Nonlinear Structural Models.
NBER Chapters. National Bureau of Economic Research, Inc. | opg_information_matrix | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def _score_obs_harvey(self, params, approx_complex_step=True,
approx_centered=False, includes_fixed=False,
**kwargs):
"""
Score
Parameters
----------
params : array_like, optional
Array of parameters at which to evaluate the loglikelihood
function.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
Notes
-----
This method is from Harvey (1989), section 3.4.5
References
----------
Harvey, Andrew C. 1990.
Forecasting, Structural Time Series Models and the Kalman Filter.
Cambridge University Press.
"""
params = np.array(params, ndmin=1)
n = len(params)
# Get values at the params themselves
self.update(params, transformed=True, includes_fixed=includes_fixed,
complex_step=approx_complex_step)
if approx_complex_step:
kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU
if 'transformed' in kwargs:
del kwargs['transformed']
res = self.ssm.filter(complex_step=approx_complex_step, **kwargs)
# Get forecasts error partials
partials_forecasts_error, partials_forecasts_error_cov = (
self._forecasts_error_partial_derivatives(
params, transformed=True, includes_fixed=includes_fixed,
approx_complex_step=approx_complex_step,
approx_centered=approx_centered, res=res, **kwargs))
# Compute partial derivatives w.r.t. likelihood function
partials = np.zeros((self.nobs, n))
k_endog = self.k_endog
for t in range(self.nobs):
inv_forecasts_error_cov = np.linalg.inv(
res.forecasts_error_cov[:, :, t])
for i in range(n):
partials[t, i] += np.trace(np.dot(
np.dot(inv_forecasts_error_cov,
partials_forecasts_error_cov[:, :, t, i]),
(np.eye(k_endog) -
np.dot(inv_forecasts_error_cov,
np.outer(res.forecasts_error[:, t],
res.forecasts_error[:, t])))))
# 2 * dv / di * F^{-1} v_t
# where x = F^{-1} v_t or F x = v
partials[t, i] += 2 * np.dot(
partials_forecasts_error[:, t, i],
np.dot(inv_forecasts_error_cov, res.forecasts_error[:, t]))
return -partials / 2. | Score
Parameters
----------
params : array_like, optional
Array of parameters at which to evaluate the loglikelihood
function.
**kwargs
Additional keyword arguments to pass to the Kalman filter. See
`KalmanFilter.filter` for more details.
Notes
-----
This method is from Harvey (1989), section 3.4.5
References
----------
Harvey, Andrew C. 1990.
Forecasting, Structural Time Series Models and the Kalman Filter.
Cambridge University Press. | _score_obs_harvey | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def score(self, params, *args, **kwargs):
"""
Compute the score function at params.
Parameters
----------
params : array_like
Array of parameters at which to evaluate the score.
*args
Additional positional arguments to the `loglike` method.
**kwargs
Additional keyword arguments to the `loglike` method.
Returns
-------
score : ndarray
Score, evaluated at `params`.
Notes
-----
This is a numerical approximation, calculated using first-order complex
step differentiation on the `loglike` method.
Both args and kwargs are necessary because the optimizer from
`fit` must call this function and only supports passing arguments via
args (for example `scipy.optimize.fmin_l_bfgs`).
"""
(transformed, includes_fixed, method, approx_complex_step,
approx_centered, kwargs) = (
_handle_args(MLEModel._score_param_names,
MLEModel._score_param_defaults, *args, **kwargs))
# For fit() calls, the method is called 'score_method' (to distinguish
# it from the method used for fit) but generally in kwargs the method
# will just be called 'method'
if 'method' in kwargs:
method = kwargs.pop('method')
if approx_complex_step is None:
approx_complex_step = not self.ssm._complex_endog
if approx_complex_step and self.ssm._complex_endog:
raise ValueError('Cannot use complex step derivatives when data'
' or parameters are complex.')
out = self.handle_params(
params, transformed=transformed, includes_fixed=includes_fixed,
return_jacobian=not transformed)
if transformed:
params = out
else:
params, transform_score = out
if method == 'harvey':
kwargs['includes_fixed'] = True
score = self._score_harvey(
params, approx_complex_step=approx_complex_step, **kwargs)
elif method == 'approx' and approx_complex_step:
kwargs['includes_fixed'] = True
score = self._score_complex_step(params, **kwargs)
elif method == 'approx':
kwargs['includes_fixed'] = True
score = self._score_finite_difference(
params, approx_centered=approx_centered, **kwargs)
else:
raise NotImplementedError('Invalid score method.')
if not transformed:
score = np.dot(transform_score, score)
if self._has_fixed_params and not includes_fixed:
score = score[self._free_params_index]
return score | Compute the score function at params.
Parameters
----------
params : array_like
Array of parameters at which to evaluate the score.
*args
Additional positional arguments to the `loglike` method.
**kwargs
Additional keyword arguments to the `loglike` method.
Returns
-------
score : ndarray
Score, evaluated at `params`.
Notes
-----
This is a numerical approximation, calculated using first-order complex
step differentiation on the `loglike` method.
Both args and kwargs are necessary because the optimizer from
`fit` must call this function and only supports passing arguments via
args (for example `scipy.optimize.fmin_l_bfgs`). | score | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def score_obs(self, params, method='approx', transformed=True,
includes_fixed=False, approx_complex_step=None,
approx_centered=False, **kwargs):
"""
Compute the score per observation, evaluated at params
Parameters
----------
params : array_like
Array of parameters at which to evaluate the score.
**kwargs
Additional arguments to the `loglike` method.
Returns
-------
score : ndarray
Score per observation, evaluated at `params`.
Notes
-----
This is a numerical approximation, calculated using first-order complex
step differentiation on the `loglikeobs` method.
"""
if not transformed and approx_complex_step:
raise ValueError("Cannot use complex-step approximations to"
" calculate the score at each observation"
" with untransformed parameters.")
if approx_complex_step is None:
approx_complex_step = not self.ssm._complex_endog
if approx_complex_step and self.ssm._complex_endog:
raise ValueError('Cannot use complex step derivatives when data'
' or parameters are complex.')
params = self.handle_params(params, transformed=True,
includes_fixed=includes_fixed)
kwargs['transformed'] = transformed
kwargs['includes_fixed'] = True
if method == 'harvey':
score = self._score_obs_harvey(
params, approx_complex_step=approx_complex_step, **kwargs)
elif method == 'approx' and approx_complex_step:
# the default epsilon can be too small
epsilon = _get_epsilon(params, 2., None, len(params))
kwargs['complex_step'] = True
score = approx_fprime_cs(params, self.loglikeobs, epsilon=epsilon,
kwargs=kwargs)
elif method == 'approx':
score = approx_fprime(params, self.loglikeobs, kwargs=kwargs,
centered=approx_centered)
else:
raise NotImplementedError('Invalid scoreobs method.')
return score | Compute the score per observation, evaluated at params
Parameters
----------
params : array_like
Array of parameters at which to evaluate the score.
**kwargs
Additional arguments to the `loglike` method.
Returns
-------
score : ndarray
Score per observation, evaluated at `params`.
Notes
-----
This is a numerical approximation, calculated using first-order complex
step differentiation on the `loglikeobs` method. | score_obs | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def _hessian_oim(self, params, **kwargs):
"""
Hessian matrix computed using the Harvey (1989) information matrix
"""
return -self.observed_information_matrix(params, **kwargs) | Hessian matrix computed using the Harvey (1989) information matrix | _hessian_oim | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def _hessian_opg(self, params, **kwargs):
"""
Hessian matrix computed using the outer product of gradients
information matrix
"""
return -self.opg_information_matrix(params, **kwargs) | Hessian matrix computed using the outer product of gradients
information matrix | _hessian_opg | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def _hessian_complex_step(self, params, **kwargs):
"""
Hessian matrix computed by second-order complex-step differentiation
on the `loglike` function.
"""
# the default epsilon can be too small
epsilon = _get_epsilon(params, 3., None, len(params))
kwargs['transformed'] = True
kwargs['complex_step'] = True
hessian = approx_hess_cs(
params, self.loglike, epsilon=epsilon, kwargs=kwargs)
return hessian / (self.nobs - self.ssm.loglikelihood_burn) | Hessian matrix computed by second-order complex-step differentiation
on the `loglike` function. | _hessian_complex_step | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def start_params(self):
"""
(array) Starting parameters for maximum likelihood estimation.
"""
if hasattr(self, '_start_params'):
return self._start_params
else:
raise NotImplementedError | (array) Starting parameters for maximum likelihood estimation. | start_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def param_names(self):
"""
(list of str) List of human readable parameter names (for parameters
actually included in the model).
"""
if hasattr(self, '_param_names'):
return self._param_names
else:
try:
names = ['param.%d' % i for i in range(len(self.start_params))]
except NotImplementedError:
names = []
return names | (list of str) List of human readable parameter names (for parameters
actually included in the model). | param_names | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def state_names(self):
"""
(list of str) List of human readable names for unobserved states.
"""
if hasattr(self, '_state_names'):
return self._state_names
else:
names = ['state.%d' % i for i in range(self.k_states)]
return names | (list of str) List of human readable names for unobserved states. | state_names | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def transform_jacobian(self, unconstrained, approx_centered=False):
"""
Jacobian matrix for the parameter transformation function
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer.
Returns
-------
jacobian : ndarray
Jacobian matrix of the transformation, evaluated at `unconstrained`
See Also
--------
transform_params
Notes
-----
This is a numerical approximation using finite differences. Note that
in general complex step methods cannot be used because it is not
guaranteed that the `transform_params` method is a real function (e.g.
if Cholesky decomposition is used).
"""
return approx_fprime(unconstrained, self.transform_params,
centered=approx_centered) | Jacobian matrix for the parameter transformation function
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer.
Returns
-------
jacobian : ndarray
Jacobian matrix of the transformation, evaluated at `unconstrained`
See Also
--------
transform_params
Notes
-----
This is a numerical approximation using finite differences. Note that
in general complex step methods cannot be used because it is not
guaranteed that the `transform_params` method is a real function (e.g.
if Cholesky decomposition is used). | transform_jacobian | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def transform_params(self, unconstrained):
"""
Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer, to be
transformed.
Returns
-------
constrained : array_like
Array of constrained parameters which may be used in likelihood
evaluation.
Notes
-----
This is a noop in the base class, subclasses should override where
appropriate.
"""
return np.array(unconstrained, ndmin=1) | Transform unconstrained parameters used by the optimizer to constrained
parameters used in likelihood evaluation
Parameters
----------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer, to be
transformed.
Returns
-------
constrained : array_like
Array of constrained parameters which may be used in likelihood
evaluation.
Notes
-----
This is a noop in the base class, subclasses should override where
appropriate. | transform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def untransform_params(self, constrained):
"""
Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer
Parameters
----------
constrained : array_like
Array of constrained parameters used in likelihood evaluation, to
be transformed.
Returns
-------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer.
Notes
-----
This is a noop in the base class, subclasses should override where
appropriate.
"""
return np.array(constrained, ndmin=1) | Transform constrained parameters used in likelihood evaluation
to unconstrained parameters used by the optimizer
Parameters
----------
constrained : array_like
Array of constrained parameters used in likelihood evaluation, to
be transformed.
Returns
-------
unconstrained : array_like
Array of unconstrained parameters used by the optimizer.
Notes
-----
This is a noop in the base class, subclasses should override where
appropriate. | untransform_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def handle_params(self, params, transformed=True, includes_fixed=False,
return_jacobian=False):
"""
Ensure model parameters satisfy shape and other requirements
"""
params = np.array(params, ndmin=1)
# Never want integer dtype, so convert to floats
if np.issubdtype(params.dtype, np.integer):
params = params.astype(np.float64)
if not includes_fixed and self._has_fixed_params:
k_params = len(self.param_names)
new_params = np.zeros(k_params, dtype=params.dtype) * np.nan
new_params[self._free_params_index] = params
params = new_params
if not transformed:
# It may be the case that the transformation relies on having
# "some" (non-NaN) values for the fixed parameters, even if we will
# not actually be transforming the fixed parameters (as they will)
# be set below regardless
if not includes_fixed and self._has_fixed_params:
params[self._fixed_params_index] = (
list(self._fixed_params.values()))
if return_jacobian:
transform_score = self.transform_jacobian(params)
params = self.transform_params(params)
if not includes_fixed and self._has_fixed_params:
params[self._fixed_params_index] = (
list(self._fixed_params.values()))
return (params, transform_score) if return_jacobian else params | Ensure model parameters satisfy shape and other requirements | handle_params | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def update(self, params, transformed=True, includes_fixed=False,
complex_step=False):
"""
Update the parameters of the model
Parameters
----------
params : array_like
Array of new parameters.
transformed : bool, optional
Whether or not `params` is already transformed. If set to False,
`transform_params` is called. Default is True.
Returns
-------
params : array_like
Array of parameters.
Notes
-----
Since Model is a base class, this method should be overridden by
subclasses to perform actual updating steps.
"""
return self.handle_params(params=params, transformed=transformed,
includes_fixed=includes_fixed) | Update the parameters of the model
Parameters
----------
params : array_like
Array of new parameters.
transformed : bool, optional
Whether or not `params` is already transformed. If set to False,
`transform_params` is called. Default is True.
Returns
-------
params : array_like
Array of parameters.
Notes
-----
Since Model is a base class, this method should be overridden by
subclasses to perform actual updating steps. | update | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def _validate_out_of_sample_exog(self, exog, out_of_sample):
"""
Validate given `exog` as satisfactory for out-of-sample operations
Parameters
----------
exog : array_like or None
New observations of exogenous regressors, if applicable.
out_of_sample : int
Number of new observations required.
Returns
-------
exog : array or None
A numpy array of shape (out_of_sample, k_exog) if the model
contains an `exog` component, or None if it does not.
"""
k_exog = getattr(self, 'k_exog', 0)
if out_of_sample and k_exog > 0:
if exog is None:
raise ValueError('Out-of-sample operations in a model'
' with a regression component require'
' additional exogenous values via the'
' `exog` argument.')
exog = np.array(exog)
required_exog_shape = (out_of_sample, self.k_exog)
try:
exog = exog.reshape(required_exog_shape)
except ValueError:
raise ValueError('Provided exogenous values are not of the'
' appropriate shape. Required %s, got %s.'
% (str(required_exog_shape),
str(exog.shape)))
elif k_exog > 0 and exog is not None:
exog = None
warnings.warn('Exogenous array provided, but additional data'
' is not required. `exog` argument ignored.',
ValueWarning)
return exog | Validate given `exog` as satisfactory for out-of-sample operations
Parameters
----------
exog : array_like or None
New observations of exogenous regressors, if applicable.
out_of_sample : int
Number of new observations required.
Returns
-------
exog : array or None
A numpy array of shape (out_of_sample, k_exog) if the model
contains an `exog` component, or None if it does not. | _validate_out_of_sample_exog | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def _get_extension_time_varying_matrices(
self, params, exog, out_of_sample, extend_kwargs=None,
transformed=True, includes_fixed=False, **kwargs):
"""
Get updated time-varying state space system matrices
Parameters
----------
params : array_like
Array of parameters used to construct the time-varying system
matrices.
exog : array_like or None
New observations of exogenous regressors, if applicable.
out_of_sample : int
Number of new observations required.
extend_kwargs : dict, optional
Dictionary of keyword arguments to pass to the state space model
constructor. For example, for an SARIMAX state space model, this
could be used to pass the `concentrate_scale=True` keyword
argument. Any arguments that are not explicitly set in this
dictionary will be copied from the current model instance.
transformed : bool, optional
Whether or not `start_params` is already transformed. Default is
True.
includes_fixed : bool, optional
If parameters were previously fixed with the `fix_params` method,
this argument describes whether or not `start_params` also includes
the fixed parameters, in addition to the free parameters. Default
is False.
"""
# Get the appropriate exog for the extended sample
exog = self._validate_out_of_sample_exog(exog, out_of_sample)
# Create extended model
if extend_kwargs is None:
extend_kwargs = {}
# Handle trend offset for extended model
if getattr(self, 'k_trend', 0) > 0 and hasattr(self, 'trend_offset'):
extend_kwargs.setdefault(
'trend_offset', self.trend_offset + self.nobs)
mod_extend = self.clone(
endog=np.zeros((out_of_sample, self.k_endog)), exog=exog,
**extend_kwargs)
mod_extend.update(params, transformed=transformed,
includes_fixed=includes_fixed)
# Retrieve the extensions to the time-varying system matrices and
# put them in kwargs
for name in self.ssm.shapes.keys():
if name == 'obs' or name in kwargs:
continue
original = getattr(self.ssm, name)
extended = getattr(mod_extend.ssm, name)
so = original.shape[-1]
se = extended.shape[-1]
if ((so > 1 or se > 1) or (
so == 1 and self.nobs == 1 and
np.any(original[..., 0] != extended[..., 0]))):
kwargs[name] = extended[..., -out_of_sample:]
return kwargs | Get updated time-varying state space system matrices
Parameters
----------
params : array_like
Array of parameters used to construct the time-varying system
matrices.
exog : array_like or None
New observations of exogenous regressors, if applicable.
out_of_sample : int
Number of new observations required.
extend_kwargs : dict, optional
Dictionary of keyword arguments to pass to the state space model
constructor. For example, for an SARIMAX state space model, this
could be used to pass the `concentrate_scale=True` keyword
argument. Any arguments that are not explicitly set in this
dictionary will be copied from the current model instance.
transformed : bool, optional
Whether or not `start_params` is already transformed. Default is
True.
includes_fixed : bool, optional
If parameters were previously fixed with the `fix_params` method,
this argument describes whether or not `start_params` also includes
the fixed parameters, in addition to the free parameters. Default
is False. | _get_extension_time_varying_matrices | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def impulse_responses(self, params, steps=1, impulse=0,
orthogonalized=False, cumulative=False, anchor=None,
exog=None, extend_model=None, extend_kwargs=None,
transformed=True, includes_fixed=False, **kwargs):
"""
Impulse response function
Parameters
----------
params : array_like
Array of model parameters.
steps : int, optional
The number of steps for which impulse responses are calculated.
Default is 1. Note that for time-invariant models, the initial
impulse is not counted as a step, so if `steps=1`, the output will
have 2 entries.
impulse : int, str or array_like
If an integer, the state innovation to pulse; must be between 0
and `k_posdef-1`. If a str, it indicates which column of df
the unit (1) impulse is given.
Alternatively, a custom impulse vector may be provided; must be
shaped `k_posdef x 1`.
orthogonalized : bool, optional
Whether or not to perform impulse using orthogonalized innovations.
Note that this will also affect custum `impulse` vectors. Default
is False.
cumulative : bool, optional
Whether or not to return cumulative impulse responses. Default is
False.
anchor : int, str, or datetime, optional
Time point within the sample for the state innovation impulse. Type
depends on the index of the given `endog` in the model. Two special
cases are the strings 'start' and 'end', which refer to setting the
impulse at the first and last points of the sample, respectively.
Integer values can run from 0 to `nobs - 1`, or can be negative to
apply negative indexing. Finally, if a date/time index was provided
to the model, then this argument can be a date string to parse or a
datetime type. Default is 'start'.
exog : array_like, optional
New observations of exogenous regressors for our-of-sample periods,
if applicable.
transformed : bool, optional
Whether or not `params` is already transformed. Default is
True.
includes_fixed : bool, optional
If parameters were previously fixed with the `fix_params` method,
this argument describes whether or not `params` also includes
the fixed parameters, in addition to the free parameters. Default
is False.
**kwargs
If the model has time-varying design or transition matrices and the
combination of `anchor` and `steps` implies creating impulse
responses for the out-of-sample period, then these matrices must
have updated values provided for the out-of-sample steps. For
example, if `design` is a time-varying component, `nobs` is 10,
`anchor=1`, and `steps` is 15, a (`k_endog` x `k_states` x 7)
matrix must be provided with the new design matrix values.
Returns
-------
impulse_responses : ndarray
Responses for each endogenous variable due to the impulse
given by the `impulse` argument. For a time-invariant model, the
impulse responses are given for `steps + 1` elements (this gives
the "initial impulse" followed by `steps` responses for the
important cases of VAR and SARIMAX models), while for time-varying
models the impulse responses are only given for `steps` elements
(to avoid having to unexpectedly provide updated time-varying
matrices).
See Also
--------
simulate
Simulate a time series according to the given state space model,
optionally with specified series for the innovations.
Notes
-----
Intercepts in the measurement and state equation are ignored when
calculating impulse responses.
TODO: add an option to allow changing the ordering for the
orthogonalized option. Will require permuting matrices when
constructing the extended model.
"""
# Make sure the model class has the current parameters
self.update(params, transformed=transformed,
includes_fixed=includes_fixed)
# For time-invariant models, add an additional `step`. This is the
# default for time-invariant models based on the expected behavior for
# ARIMA and VAR models: we want to record the initial impulse and also
# `steps` values of the responses afterwards.
# Note: we don't modify `steps` itself, because
# `KalmanFilter.impulse_responses` also adds an additional step in this
# case (this is so that there isn't different behavior when calling
# this method versus that method). We just need to also keep track of
# this here because we need to generate the correct extended model.
additional_steps = 0
if (self.ssm._design.shape[2] == 1 and
self.ssm._transition.shape[2] == 1 and
self.ssm._selection.shape[2] == 1):
additional_steps = 1
# Get the starting location
if anchor is None or anchor == 'start':
iloc = 0
elif anchor == 'end':
iloc = self.nobs - 1
else:
iloc, _, _ = self._get_index_loc(anchor)
if isinstance(iloc, slice):
iloc = iloc.start
if iloc < 0:
iloc = self.nobs + iloc
if iloc >= self.nobs:
raise ValueError('Cannot anchor impulse responses outside of the'
' sample.')
time_invariant = (
self.ssm._design.shape[2] == self.ssm._obs_cov.shape[2] ==
self.ssm._transition.shape[2] == self.ssm._selection.shape[2] ==
self.ssm._state_cov.shape[2] == 1)
# Get updated time-varying system matrices in **kwargs, if necessary
# (Note: KalmanFilter adds 1 to steps to account for the first impulse)
out_of_sample = max(
iloc + (steps + additional_steps + 1) - self.nobs, 0)
if extend_model is None:
extend_model = self.exog is not None and not time_invariant
if out_of_sample and extend_model:
kwargs = self._get_extension_time_varying_matrices(
params, exog, out_of_sample, extend_kwargs,
transformed=transformed, includes_fixed=includes_fixed,
**kwargs)
# Special handling for matrix terms that are time-varying but
# irrelevant for impulse response functions. Must be set since
# ssm.extend() requires that we pass new matrices for these, but they
# are ignored for IRF purposes.
end = min(self.nobs, iloc + steps + additional_steps)
nextend = iloc + (steps + additional_steps + 1) - end
if ('obs_intercept' not in kwargs and
self.ssm._obs_intercept.shape[1] > 1):
kwargs['obs_intercept'] = np.zeros((self.k_endog, nextend))
if ('state_intercept' not in kwargs and
self.ssm._state_intercept.shape[1] > 1):
kwargs['state_intercept'] = np.zeros((self.k_states, nextend))
if 'obs_cov' not in kwargs and self.ssm._obs_cov.shape[2] > 1:
kwargs['obs_cov'] = np.zeros((self.k_endog, self.k_endog, nextend))
# Special handling for matrix terms that are time-varying but
# only the value at the anchor matters for IRF purposes.
if 'state_cov' not in kwargs and self.ssm._state_cov.shape[2] > 1:
tmp = np.zeros((self.ssm.k_posdef, self.ssm.k_posdef, nextend))
tmp[:] = self['state_cov', :, :, iloc:iloc + 1]
kwargs['state_cov'] = tmp
if 'selection' not in kwargs and self.ssm._selection.shape[2] > 1:
tmp = np.zeros((self.k_states, self.ssm.k_posdef, nextend))
tmp[:] = self['selection', :, :, iloc:iloc + 1]
kwargs['selection'] = tmp
# Construct a model that represents the simulation period
sim_model = self.ssm.extend(np.empty((nextend, self.k_endog)),
start=iloc, end=end, **kwargs)
# Compute the impulse responses
# Convert endog name to index
use_pandas = isinstance(self.data, PandasData)
if type(impulse) is str:
if not use_pandas:
raise ValueError('Endog must be pd.DataFrame.')
impulse = self.endog_names.index(impulse)
irfs = sim_model.impulse_responses(
steps, impulse, orthogonalized, cumulative)
# IRF is (nobs x k_endog); do not want to squeeze in case of steps = 1
if irfs.shape[1] == 1:
irfs = irfs[:, 0]
# Wrap data / squeeze where appropriate
if use_pandas:
if self.k_endog == 1:
irfs = pd.Series(irfs, name=self.endog_names)
else:
irfs = pd.DataFrame(irfs, columns=self.endog_names)
return irfs | Impulse response function
Parameters
----------
params : array_like
Array of model parameters.
steps : int, optional
The number of steps for which impulse responses are calculated.
Default is 1. Note that for time-invariant models, the initial
impulse is not counted as a step, so if `steps=1`, the output will
have 2 entries.
impulse : int, str or array_like
If an integer, the state innovation to pulse; must be between 0
and `k_posdef-1`. If a str, it indicates which column of df
the unit (1) impulse is given.
Alternatively, a custom impulse vector may be provided; must be
shaped `k_posdef x 1`.
orthogonalized : bool, optional
Whether or not to perform impulse using orthogonalized innovations.
Note that this will also affect custum `impulse` vectors. Default
is False.
cumulative : bool, optional
Whether or not to return cumulative impulse responses. Default is
False.
anchor : int, str, or datetime, optional
Time point within the sample for the state innovation impulse. Type
depends on the index of the given `endog` in the model. Two special
cases are the strings 'start' and 'end', which refer to setting the
impulse at the first and last points of the sample, respectively.
Integer values can run from 0 to `nobs - 1`, or can be negative to
apply negative indexing. Finally, if a date/time index was provided
to the model, then this argument can be a date string to parse or a
datetime type. Default is 'start'.
exog : array_like, optional
New observations of exogenous regressors for our-of-sample periods,
if applicable.
transformed : bool, optional
Whether or not `params` is already transformed. Default is
True.
includes_fixed : bool, optional
If parameters were previously fixed with the `fix_params` method,
this argument describes whether or not `params` also includes
the fixed parameters, in addition to the free parameters. Default
is False.
**kwargs
If the model has time-varying design or transition matrices and the
combination of `anchor` and `steps` implies creating impulse
responses for the out-of-sample period, then these matrices must
have updated values provided for the out-of-sample steps. For
example, if `design` is a time-varying component, `nobs` is 10,
`anchor=1`, and `steps` is 15, a (`k_endog` x `k_states` x 7)
matrix must be provided with the new design matrix values.
Returns
-------
impulse_responses : ndarray
Responses for each endogenous variable due to the impulse
given by the `impulse` argument. For a time-invariant model, the
impulse responses are given for `steps + 1` elements (this gives
the "initial impulse" followed by `steps` responses for the
important cases of VAR and SARIMAX models), while for time-varying
models the impulse responses are only given for `steps` elements
(to avoid having to unexpectedly provide updated time-varying
matrices).
See Also
--------
simulate
Simulate a time series according to the given state space model,
optionally with specified series for the innovations.
Notes
-----
Intercepts in the measurement and state equation are ignored when
calculating impulse responses.
TODO: add an option to allow changing the ordering for the
orthogonalized option. Will require permuting matrices when
constructing the extended model. | impulse_responses | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def from_formula(cls, formula, data, subset=None):
"""
Not implemented for state space models
"""
raise NotImplementedError | Not implemented for state space models | from_formula | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def _get_robustcov_results(self, cov_type='opg', **kwargs):
"""
Create new results instance with specified covariance estimator as
default
Note: creating new results instance currently not supported.
Parameters
----------
cov_type : str
the type of covariance matrix estimator to use. See Notes below
kwargs : depends on cov_type
Required or optional arguments for covariance calculation.
See Notes below.
Returns
-------
results : results instance
This method creates a new results instance with the requested
covariance as the default covariance of the parameters.
Inferential statistics like p-values and hypothesis tests will be
based on this covariance matrix.
Notes
-----
The following covariance types and required or optional arguments are
currently available:
- 'opg' for the outer product of gradient estimator
- 'oim' for the observed information matrix estimator, calculated
using the method of Harvey (1989)
- 'approx' for the observed information matrix estimator,
calculated using a numerical approximation of the Hessian matrix.
Uses complex step approximation by default, or uses finite
differences if `approx_complex_step=False` in the `cov_kwds`
dictionary.
- 'robust' for an approximate (quasi-maximum likelihood) covariance
matrix that may be valid even in the presence of some
misspecifications. Intermediate calculations use the 'oim'
method.
- 'robust_approx' is the same as 'robust' except that the
intermediate calculations use the 'approx' method.
- 'none' for no covariance matrix calculation.
"""
from statsmodels.base.covtype import descriptions
use_self = kwargs.pop('use_self', False)
if use_self:
res = self
else:
raise NotImplementedError
res = self.__class__(
self.model, self.params,
normalized_cov_params=self.normalized_cov_params,
scale=self.scale)
# Set the new covariance type
res.cov_type = cov_type
res.cov_kwds = {}
# Calculate the new covariance matrix
approx_complex_step = self._cov_approx_complex_step
if approx_complex_step:
approx_type_str = 'complex-step'
elif self._cov_approx_centered:
approx_type_str = 'centered finite differences'
else:
approx_type_str = 'finite differences'
k_params = len(self.params)
if k_params == 0:
res.cov_params_default = np.zeros((0, 0))
res._rank = 0
res.cov_kwds['description'] = 'No parameters estimated.'
elif cov_type == 'custom':
res.cov_type = kwargs['custom_cov_type']
res.cov_params_default = kwargs['custom_cov_params']
res.cov_kwds['description'] = kwargs['custom_description']
if len(self.fixed_params) > 0:
mask = np.ix_(self._free_params_index, self._free_params_index)
else:
mask = np.s_[...]
res._rank = np.linalg.matrix_rank(res.cov_params_default[mask])
elif cov_type == 'none':
res.cov_params_default = np.zeros((k_params, k_params)) * np.nan
res._rank = np.nan
res.cov_kwds['description'] = descriptions['none']
elif self.cov_type == 'approx':
res.cov_params_default = res.cov_params_approx
res.cov_kwds['description'] = descriptions['approx'].format(
approx_type=approx_type_str)
elif self.cov_type == 'oim':
res.cov_params_default = res.cov_params_oim
res.cov_kwds['description'] = descriptions['OIM'].format(
approx_type=approx_type_str)
elif self.cov_type == 'opg':
res.cov_params_default = res.cov_params_opg
res.cov_kwds['description'] = descriptions['OPG'].format(
approx_type=approx_type_str)
elif self.cov_type == 'robust' or self.cov_type == 'robust_oim':
res.cov_params_default = res.cov_params_robust_oim
res.cov_kwds['description'] = descriptions['robust-OIM'].format(
approx_type=approx_type_str)
elif self.cov_type == 'robust_approx':
res.cov_params_default = res.cov_params_robust_approx
res.cov_kwds['description'] = descriptions['robust-approx'].format(
approx_type=approx_type_str)
else:
raise NotImplementedError('Invalid covariance matrix type.')
return res | Create new results instance with specified covariance estimator as
default
Note: creating new results instance currently not supported.
Parameters
----------
cov_type : str
the type of covariance matrix estimator to use. See Notes below
kwargs : depends on cov_type
Required or optional arguments for covariance calculation.
See Notes below.
Returns
-------
results : results instance
This method creates a new results instance with the requested
covariance as the default covariance of the parameters.
Inferential statistics like p-values and hypothesis tests will be
based on this covariance matrix.
Notes
-----
The following covariance types and required or optional arguments are
currently available:
- 'opg' for the outer product of gradient estimator
- 'oim' for the observed information matrix estimator, calculated
using the method of Harvey (1989)
- 'approx' for the observed information matrix estimator,
calculated using a numerical approximation of the Hessian matrix.
Uses complex step approximation by default, or uses finite
differences if `approx_complex_step=False` in the `cov_kwds`
dictionary.
- 'robust' for an approximate (quasi-maximum likelihood) covariance
matrix that may be valid even in the presence of some
misspecifications. Intermediate calculations use the 'oim'
method.
- 'robust_approx' is the same as 'robust' except that the
intermediate calculations use the 'approx' method.
- 'none' for no covariance matrix calculation. | _get_robustcov_results | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def aic(self):
"""
(float) Akaike Information Criterion
"""
return aic(self.llf, self.nobs_effective, self.df_model) | (float) Akaike Information Criterion | aic | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def aicc(self):
"""
(float) Akaike Information Criterion with small sample correction
"""
return aicc(self.llf, self.nobs_effective, self.df_model) | (float) Akaike Information Criterion with small sample correction | aicc | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def bic(self):
"""
(float) Bayes Information Criterion
"""
return bic(self.llf, self.nobs_effective, self.df_model) | (float) Bayes Information Criterion | bic | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def cov_params_approx(self):
"""
(array) The variance / covariance matrix. Computed using the numerical
Hessian approximated by complex step or finite differences methods.
"""
return self._cov_params_approx(self._cov_approx_complex_step,
self._cov_approx_centered) | (array) The variance / covariance matrix. Computed using the numerical
Hessian approximated by complex step or finite differences methods. | cov_params_approx | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def cov_params_oim(self):
"""
(array) The variance / covariance matrix. Computed using the method
from Harvey (1989).
"""
return self._cov_params_oim(self._cov_approx_complex_step,
self._cov_approx_centered) | (array) The variance / covariance matrix. Computed using the method
from Harvey (1989). | cov_params_oim | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def cov_params_opg(self):
"""
(array) The variance / covariance matrix. Computed using the outer
product of gradients method.
"""
return self._cov_params_opg(self._cov_approx_complex_step,
self._cov_approx_centered) | (array) The variance / covariance matrix. Computed using the outer
product of gradients method. | cov_params_opg | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def cov_params_robust(self):
"""
(array) The QMLE variance / covariance matrix. Alias for
`cov_params_robust_oim`
"""
return self.cov_params_robust_oim | (array) The QMLE variance / covariance matrix. Alias for
`cov_params_robust_oim` | cov_params_robust | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def cov_params_robust_oim(self):
"""
(array) The QMLE variance / covariance matrix. Computed using the
method from Harvey (1989) as the evaluated hessian.
"""
return self._cov_params_robust_oim(self._cov_approx_complex_step,
self._cov_approx_centered) | (array) The QMLE variance / covariance matrix. Computed using the
method from Harvey (1989) as the evaluated hessian. | cov_params_robust_oim | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def cov_params_robust_approx(self):
"""
(array) The QMLE variance / covariance matrix. Computed using the
numerical Hessian as the evaluated hessian.
"""
return self._cov_params_robust_approx(self._cov_approx_complex_step,
self._cov_approx_centered) | (array) The QMLE variance / covariance matrix. Computed using the
numerical Hessian as the evaluated hessian. | cov_params_robust_approx | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def fittedvalues(self):
"""
(array) The predicted values of the model. An (nobs x k_endog) array.
"""
# This is a (k_endog x nobs array; do not want to squeeze in case of
# the corner case where nobs = 1 (mostly a concern in the predict or
# forecast functions, but here also to maintain consistency)
fittedvalues = self.forecasts
if fittedvalues is None:
pass
elif fittedvalues.shape[0] == 1:
fittedvalues = fittedvalues[0, :]
else:
fittedvalues = fittedvalues.T
return fittedvalues | (array) The predicted values of the model. An (nobs x k_endog) array. | fittedvalues | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def hqic(self):
"""
(float) Hannan-Quinn Information Criterion
"""
# return (-2 * self.llf +
# 2 * np.log(np.log(self.nobs_effective)) * self.df_model)
return hqic(self.llf, self.nobs_effective, self.df_model) | (float) Hannan-Quinn Information Criterion | hqic | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def llf_obs(self):
"""
(float) The value of the log-likelihood function evaluated at `params`.
"""
return self.filter_results.llf_obs | (float) The value of the log-likelihood function evaluated at `params`. | llf_obs | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def llf(self):
"""
(float) The value of the log-likelihood function evaluated at `params`.
"""
return self.filter_results.llf | (float) The value of the log-likelihood function evaluated at `params`. | llf | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
def loglikelihood_burn(self):
"""
(float) The number of observations during which the likelihood is not
evaluated.
"""
return self.filter_results.loglikelihood_burn | (float) The number of observations during which the likelihood is not
evaluated. | loglikelihood_burn | python | statsmodels/statsmodels | statsmodels/tsa/statespace/mlemodel.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/statespace/mlemodel.py | BSD-3-Clause |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.