Repository navigation
TST: Close the coverage gaps of regime_switching regression and autoregression - #10978
Merged
Merged
Conversation
…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
marked this pull request as ready for review
November 22, 2026 14:04
This was referenced Nov 22, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Close the coverage gaps of
tsa/regime_switching/markov_regression.pyandmarkov_autoregression.pythrough public paths, and align their docstringswith 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
MarkovRegressionfor everytrend("n", "c", "t", "ct"),switching_trend/switching_exogas abool, list, tuple or ndarray,
switching_variance,exogandexog_tvtp, against a Hamilton filter written out in the test.MarkovAutoregressionof order 1 to 3, with mixedswitching_ar, trend, exog and time-varying transition probabilities,against the filter over the joint state of the current and last
orderregimes.
fitwithem_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_paramsagainst OLS, the interpolation between zero and OLS and thevariance;
param_names;transform_params/untransform_params; theValueError for switching sequences of the wrong length and for too few
observations.
DatetimeIndex, PeriodIndex or RangeIndex, one-column DataFrame, and
ndarray with
dates; exog and exog_tvtp forms; pandas indexes ofpredictions and smoothed probabilities, without the AR presample.
results, notfilter_results, andaccept
cov_kwds; thecov_typedefault is "opg";nobsis an int; theshapes returned by
predict_conditional; 1-dexog; the definition ofthe time trend;
MarkovRegression'sorderis for subclasses.Not changed
regime-specific variance of
MarkovAutoregressionwith order >= 2 usesthe wrong regime (silent);
predictwith a RangeIndex drops the firstpredictions;
trend="C"is ignored; regime suffixes on non-switchingparameter names; pandas exog names lost with a trend;
order=0; lists intransform_params/untransform_params. No test asserts the currentbehaviour of those paths.
Tests
pytest statsmodels/tsa/regime_switching -n 8 -W error: all pass with nowarnings on pandas 3.0.5; the new tests also pass on pandas 2.3.3.
Coverage:
markov_regression.py88.4% → 99.3% lines and 74.1% → 98.3%branches;
markov_autoregression.py92.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.
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