Skip to content

TST: Close the coverage gaps of regime_switching regression and autoregression - #10978

Merged
bashtage merged 4 commits into
statsmodels:mainfrom
bashtage:wip-tsa-cov-c7b
Nov 22, 2026
Merged

bashtage merged 4 commits into
statsmodels:mainfrom
bashtage:wip-tsa-cov-c7b

Conversation

@bashtage

Copy link
Copy Markdown
Member

Close the coverage gaps of tsa/regime_switching/markov_regression.py and
markov_autoregression.py through public paths, and align their docstrings
with the code. The tests compare at fixed parameters with references written
out in the tests: the Hamilton (1989) filter, least squares and closed
forms. The source changes are docstrings only.

Changes

  • The log-likelihood and conditional means of MarkovRegression for every
    trend ("n", "c", "t", "ct"), switching_trend/switching_exog as a
    bool, list, tuple or ndarray, switching_variance, exog and
    exog_tvtp, against a Hamilton filter written out in the test.
  • The same for MarkovAutoregression of order 1 to 3, with mixed
    switching_ar, trend, exog and time-varying transition probabilities,
    against the filter over the joint state of the current and last order
    regimes.
  • One EM update (fit with em_iter=1, maxiter=0) against the M-step:
    mean(y**2) without regressors, OLS when no coefficient switches,
    weighted least squares from the smoothed probabilities, the two-step
    update for mixed switching, and the identity between the common and the
    regime-specific variance updates of the AR model.
  • start_params against OLS, the interpolation between zero and OLS and the
    variance; param_names; transform_params/untransform_params; the
    ValueError for switching sequences of the wrong length and for too few
    observations.
  • Contract tests: endog as list, tuple, (n, 1), int64, Series with a
    DatetimeIndex, PeriodIndex or RangeIndex, one-column DataFrame, and
    ndarray with dates; exog and exog_tvtp forms; pandas indexes of
    predictions and smoothed probabilities, without the AR presample.
  • Docstrings: the results classes take results, not filter_results, and
    accept cov_kwds; the cov_type default is "opg"; nobs is an int; the
    shapes returned by predict_conditional; 1-d exog; the definition of
    the time trend; MarkovRegression's order is for subclasses.

Not changed

  • No behaviour changes. Bugs found in the audit are fixed separately: the
    regime-specific variance of MarkovAutoregression with order >= 2 uses
    the wrong regime (silent); predict with a RangeIndex drops the first
    predictions; trend="C" is ignored; regime suffixes on non-switching
    parameter names; pandas exog names lost with a trend; order=0; lists in
    transform_params/untransform_params. No test asserts the current
    behaviour of those paths.

Tests

  • pytest statsmodels/tsa/regime_switching -n 8 -W error: all pass with no
    warnings on pandas 3.0.5; the new tests also pass on pandas 2.3.3.

  • Coverage: markov_regression.py 88.4% → 99.3% lines and 74.1% → 98.3%
    branches; markov_autoregression.py 92.0% → 98.8% and 75.0% → 90.0%.
    What remains is unreachable or reachable only with order=0.

  • Mutation check: 20 single-line changes to the covered code, each caught by
    a new test.

  • tests added / passed.

  • code/documentation is well formatted.

  • properly formatted commit message. See
    NumPy's guide.

AI Disclosure

Contributions must comply with the statsmodels AI Policy.

Tick exactly one of the following. If AI tools were used, replace the <...>
placeholders in the second option with the tool name(s) and how the tool's output was
used.

  • No AI tools were used to develop this pull request.
  • AI tools were used.
    Tool(s): Claude Code (Claude Opus 5.5).
    Used for: writing the tests and docstring fixes from a contract audit, and checking them (references independent of the code, mutation check).
    I have personally read, understood, and can explain every line of this diff, and
    have verified the statistical/numerical correctness of the change.

🤖 Generated with Claude Code

…ters

Close the coverage gaps in markov_regression.py and
markov_autoregression.py through public paths, checking each result
against a reference written out independently of the model code:

- the log-likelihood and conditional means for every trend ("n", "c",
  "t", "ct"), switching_trend/switching_exog/switching_ar as a bool and
  as a list, tuple or ndarray, switching_variance, exog and exog_tvtp,
  against a Hamilton (1989) filter written out in the tests (over the
  joint state of the current and the last `order` regimes for the AR
  model, with time-varying transition probabilities)
- one EM update (fit with em_iter=1 and maxiter=0) against the M-step:
  closed forms (mean(y**2), OLS when no coefficient switches) and
  weighted least squares from the smoothed regime probabilities, plus
  the identity between the common and the regime-specific variance
  updates of the AR model
- start_params against OLS on the regressors and the lags, the
  documented interpolation between zero and OLS, and the variance
- param_names, transform_params/untransform_params (logistic,
  stationary AR polynomials, round trip), and the ValueError for
  switching sequences of the wrong length and too few observations
- the documented input forms: endog as list, tuple, (nobs, 1) column,
  int64, Series with a DatetimeIndex, PeriodIndex or RangeIndex,
  one-column DataFrame, or ndarray with dates; exog and exog_tvtp as
  list, ndarray, Series and DataFrame
- MarkovRegressionResults and MarkovAutoregressionResults: the
  constructor argument is `results`, not `filter_results`; document
  `cov_kwds` and the 'opg' default of `cov_type`; `nobs` is an int, and
  for the AR model it excludes the `order` presample observations.
- `predict_conditional`: give the shape of the returned array and the
  meaning of each axis, (k_regimes, 1, nobs) for the regression model
  and (k_regimes,) * (order + 1) + (nobs,) for the AR model.
- `exog` may also be 1-d for a single regressor.
- `trend`: the time trend is 1, ..., nobs; in the AR model it counts the
  presample observations too.
- MarkovRegression `order`: it is for subclasses; the likelihood of a
  Markov switching regression does not depend on previous regimes, so it
  should be left at 0.
assert_allclose broadcasts a length-one axis, so check the shapes given in
the docstrings, (k_regimes, 1, nobs) for MarkovRegression and
(k_regimes,) * (order + 1) + (nobs,) for MarkovAutoregression, explicitly.
@bashtage
bashtage marked this pull request as ready for review November 22, 2026 14:04
@bashtage
bashtage merged commit 74e15fd into statsmodels:main Nov 22, 2026
10 of 11 checks passed
@bashtage
bashtage deleted the wip-tsa-cov-c7b branch November 22, 2026 14:05
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 23, 2026
Remove code in tsa/regime_switching that no public path reaches, found
in the coverage audit of the module (statsmodels#10977, statsmodels#10978). Results do not
change.

markov_switching.py:
- `_logistic` and `_partials_logistic`: not used anywhere (only their
  own tests, which are removed).
- `initial_probabilities`: the "Invalid initialization method" branch;
  only "steady-state" and "known" can be selected.
- `_filter` and `_smooth`: the `regime_transition` argument, which no
  caller passes.
- `_fit_em`: the results-object branch and its `cov_type`, `cov_kwds`,
  `full_output`, `return_params` and `**kwargs` arguments; fit and the
  start-parameter search only use the returned parameters. It now
  always returns them (the existing EM tests call it directly and now
  evaluate the log-likelihood of the returned parameters).
- `_start_params_search`: the `start_params=None` default; fit always
  passes start parameters.
- `MarkovSwitchingResults`: the `hasattr(self, "cov_kwds")` guard
  (never set before), the `k_params == 0` branch (a model always has
  transition parameters), the code after `raise NotImplementedError` in
  `_get_robustcov_results`, the rank update in `cov_params_robust`
  (`cov_params_opg`, computed first, has always set it), and in
  `summary` the `hasattr(self, "cov_type")` guards and the `if etext`
  guard (the covariance description or the singular-matrix note is
  always added).

markov_regression.py: the `tmp is None` branch of `_em_variance`, whose
callers always pass `tmp`.

markov_autoregression.py: the `_index is not None` guard
(TimeSeriesModel always sets an index), the never-passed `tmp` argument
of `_em_autoregressive` and its `_k_exog > 0` guard (it is only called
with exog), and an array that the loop always replaces.
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 25, 2026
Remove code in tsa/regime_switching that no public path reaches, found
in the coverage audit of the module (statsmodels#10977, statsmodels#10978). Results do not
change.

markov_switching.py:
- `_logistic` and `_partials_logistic`: not used anywhere (only their
  own tests, which are removed).
- `initial_probabilities`: the "Invalid initialization method" branch;
  only "steady-state" and "known" can be selected.
- `_filter` and `_smooth`: the `regime_transition` argument, which no
  caller passes.
- `_fit_em`: the results-object branch and its `cov_type`, `cov_kwds`,
  `full_output`, `return_params` and `**kwargs` arguments; fit and the
  start-parameter search only use the returned parameters. It now
  always returns them (the existing EM tests call it directly and now
  evaluate the log-likelihood of the returned parameters).
- `_start_params_search`: the `start_params=None` default; fit always
  passes start parameters.
- `MarkovSwitchingResults`: the `hasattr(self, "cov_kwds")` guard
  (never set before), the `k_params == 0` branch (a model always has
  transition parameters), the code after `raise NotImplementedError` in
  `_get_robustcov_results`, the rank update in `cov_params_robust`
  (`cov_params_opg`, computed first, has always set it), and in
  `summary` the `hasattr(self, "cov_type")` guards and the `if etext`
  guard (the covariance description or the singular-matrix note is
  always added).

markov_regression.py: the `tmp is None` branch of `_em_variance`, whose
callers always pass `tmp`.

markov_autoregression.py: the `_index is not None` guard
(TimeSeriesModel always sets an index), the never-passed `tmp` argument
of `_em_autoregressive` and its `_k_exog > 0` guard (it is only called
with exog), and an array that the loop always replaces.
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 25, 2026
Remove code in tsa/regime_switching that no public path reaches, found
in the coverage audit of the module (statsmodels#10977, statsmodels#10978). Results do not
change.

markov_switching.py:
- `_logistic` and `_partials_logistic`: not used anywhere (only their
  own tests, which are removed).
- `initial_probabilities`: the "Invalid initialization method" branch;
  only "steady-state" and "known" can be selected.
- `_filter` and `_smooth`: the `regime_transition` argument, which no
  caller passes.
- `_fit_em`: the results-object branch and its `cov_type`, `cov_kwds`,
  `full_output`, `return_params` and `**kwargs` arguments; fit and the
  start-parameter search only use the returned parameters. It now
  always returns them (the existing EM tests call it directly and now
  evaluate the log-likelihood of the returned parameters).
- `_start_params_search`: the `start_params=None` default; fit always
  passes start parameters.
- `MarkovSwitchingResults`: the `hasattr(self, "cov_kwds")` guard
  (never set before), the `k_params == 0` branch (a model always has
  transition parameters), the code after `raise NotImplementedError` in
  `_get_robustcov_results`, the rank update in `cov_params_robust`
  (`cov_params_opg`, computed first, has always set it), and in
  `summary` the `hasattr(self, "cov_type")` guards and the `if etext`
  guard (the covariance description or the singular-matrix note is
  always added).

markov_regression.py: the `tmp is None` branch of `_em_variance`, whose
callers always pass `tmp`.

markov_autoregression.py: the `_index is not None` guard
(TimeSeriesModel always sets an index), the never-passed `tmp` argument
of `_em_autoregressive` and its `_k_exog > 0` guard (it is only called
with exog), and an array that the loop always replaces.
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 25, 2026
Remove code in tsa/regime_switching that no public path reaches, found
in the coverage audit of the module (statsmodels#10977, statsmodels#10978). Results do not
change.

markov_switching.py:
- `_logistic` and `_partials_logistic`: not used anywhere (only their
  own tests, which are removed).
- `initial_probabilities`: the "Invalid initialization method" branch;
  only "steady-state" and "known" can be selected.
- `_filter` and `_smooth`: the `regime_transition` argument, which no
  caller passes.
- `_fit_em`: the results-object branch and its `cov_type`, `cov_kwds`,
  `full_output`, `return_params` and `**kwargs` arguments; fit and the
  start-parameter search only use the returned parameters. It now
  always returns them (the existing EM tests call it directly and now
  evaluate the log-likelihood of the returned parameters).
- `_start_params_search`: the `start_params=None` default; fit always
  passes start parameters.
- `MarkovSwitchingResults`: the `hasattr(self, "cov_kwds")` guard
  (never set before), the `k_params == 0` branch (a model always has
  transition parameters), the code after `raise NotImplementedError` in
  `_get_robustcov_results`, the rank update in `cov_params_robust`
  (`cov_params_opg`, computed first, has always set it), and in
  `summary` the `hasattr(self, "cov_type")` guards and the `if etext`
  guard (the covariance description or the singular-matrix note is
  always added).

markov_regression.py: the `tmp is None` branch of `_em_variance`, whose
callers always pass `tmp`.

markov_autoregression.py: the `_index is not None` guard
(TimeSeriesModel always sets an index), the never-passed `tmp` argument
of `_em_autoregressive` and its `_k_exog > 0` guard (it is only called
with exog), and an array that the loop always replaces.
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 27, 2026
Remove code in tsa/regime_switching that no public path reaches, found
in the coverage audit of the module (statsmodels#10977, statsmodels#10978). Results do not
change.

markov_switching.py:
- `_logistic` and `_partials_logistic`: not used anywhere (only their
  own tests, which are removed).
- `initial_probabilities`: the "Invalid initialization method" branch;
  only "steady-state" and "known" can be selected.
- `_filter` and `_smooth`: the `regime_transition` argument, which no
  caller passes.
- `_fit_em`: the results-object branch and its `cov_type`, `cov_kwds`,
  `full_output`, `return_params` and `**kwargs` arguments; fit and the
  start-parameter search only use the returned parameters. It now
  always returns them (the existing EM tests call it directly and now
  evaluate the log-likelihood of the returned parameters).
- `_start_params_search`: the `start_params=None` default; fit always
  passes start parameters.
- `MarkovSwitchingResults`: the `hasattr(self, "cov_kwds")` guard
  (never set before), the `k_params == 0` branch (a model always has
  transition parameters), the code after `raise NotImplementedError` in
  `_get_robustcov_results`, the rank update in `cov_params_robust`
  (`cov_params_opg`, computed first, has always set it), and in
  `summary` the `hasattr(self, "cov_type")` guards and the `if etext`
  guard (the covariance description or the singular-matrix note is
  always added).

markov_regression.py: the `tmp is None` branch of `_em_variance`, whose
callers always pass `tmp`.

markov_autoregression.py: the `_index is not None` guard
(TimeSeriesModel always sets an index), the never-passed `tmp` argument
of `_em_autoregressive` and its `_k_exog > 0` guard (it is only called
with exog), and an array that the loop always replaces.
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 27, 2026
Remove code in tsa/regime_switching that no public path reaches, found
in the coverage audit of the module (statsmodels#10977, statsmodels#10978). Results do not
change.

markov_switching.py:
- `_logistic` and `_partials_logistic`: not used anywhere (only their
  own tests, which are removed).
- `initial_probabilities`: the "Invalid initialization method" branch;
  only "steady-state" and "known" can be selected.
- `_filter` and `_smooth`: the `regime_transition` argument, which no
  caller passes.
- `_fit_em`: the results-object branch and its `cov_type`, `cov_kwds`,
  `full_output`, `return_params` and `**kwargs` arguments; fit and the
  start-parameter search only use the returned parameters. It now
  always returns them (the existing EM tests call it directly and now
  evaluate the log-likelihood of the returned parameters).
- `_start_params_search`: the `start_params=None` default; fit always
  passes start parameters.
- `MarkovSwitchingResults`: the `hasattr(self, "cov_kwds")` guard
  (never set before), the `k_params == 0` branch (a model always has
  transition parameters), the code after `raise NotImplementedError` in
  `_get_robustcov_results`, the rank update in `cov_params_robust`
  (`cov_params_opg`, computed first, has always set it), and in
  `summary` the `hasattr(self, "cov_type")` guards and the `if etext`
  guard (the covariance description or the singular-matrix note is
  always added).

markov_regression.py: the `tmp is None` branch of `_em_variance`, whose
callers always pass `tmp`.

markov_autoregression.py: the `_index is not None` guard
(TimeSeriesModel always sets an index), the never-passed `tmp` argument
of `_em_autoregressive` and its `_k_exog > 0` guard (it is only called
with exog), and an array that the loop always replaces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant