Repository navigation
Conversation
bashtage
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 22, 2026 14:05
b32aa5e to
98e2a14
Compare
bashtage
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 23, 2026 19:15
98e2a14 to
c9d5664
Compare
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.
4 of 5 tasks
bashtage
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 24, 2026 16:15
d74387a to
16ef9cd
Compare
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
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 25, 2026 12:11
16ef9cd to
af46501
Compare
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
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 25, 2026 12:51
af46501 to
d819afd
Compare
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
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 25, 2026 18:41
d819afd to
e3882b6
Compare
| # Setup covariance matrix notes dictionary | ||
| if not hasattr(self, "cov_kwds"): | ||
| self.cov_kwds = {} | ||
| self.cov_kwds = {} |
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
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 27, 2026 00:32
e3882b6 to
f97b0c7
Compare
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
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 27, 2026 23:07
f97b0c7 to
4742c7c
Compare
The EM step for the transition probabilities of the Markov switching
models (_em_regime_transition, used by fit with em_iter, the default
start, and by the start-parameter search with search_iter) estimated
p[i->j] = sum_t Pr[S_t = j, S_{t-1} = i | T] / sum_t Pr[S_t = i | T].
The M-step divides by sum_t Pr[S_{t-1} = i | T] (Hamilton, 1990). The two
sums differ by Pr[S_{T-1} = i | T] - Pr[S_{-1} = i | T], up to one
observation in each regime, so the estimates were off by about 1/nobs:
by 0.35% at the start parameters of fedfunds[-10:], and by 1.4% to 13% in
the new tests, whose short series (18 and 20 observations) end in another
regime than they start. The rows of the estimated matrix need not sum
to one, which is what the "Invalid regime transition probabilities"
rescaling was there for.
Changes
- Divide by the sum of the smoothed joint probabilities over S_t, that is
sum_t Pr[S_{t-1} = i | T]. The rows sum to one.
- versionchanged in the em_iter docstring of fit.
Results change. Of the 11 test_fit_em regression values (statsmodels'
own EM with its default settings, no external reference), 8 rise, for
example -745.83654 to -745.82796 (areturns) and -508.65852 to -508.65687
(fedfunds). Two fall slightly because the EM stops on its tolerance at
another point of its path: TestHamiltonAR4 by 1.9e-5 (3 iterations) and
TestFedFundsConstL1Exog by 6.8e-5 (run to the end, both versions reach
-229.25616). TestHamiltonAR2Short (10 observations) falls from -8.886 to
-49.95, because the last M-step of the AR coefficients jumps to explosive
values. Fitted results change where the optimizer starts from the EM
parameters and stops at another point: the 10-observation fedfunds model
now reaches a degenerate maximum (llf 5.127, one regime for the first
observation and a variance near zero) instead of -7.855, the 10-observation
AR(2) another local maximum (-5.096 instead of -4.052), and the Hamilton
switching AR(2) -179.386805 instead of -179.386841.
Not changed
- The EM steps of the other parameters, and models with time-varying
transition probabilities (the EM does not update them).
- The rescaling when a row sums to more than one. With the fixed
denominator, it can only happen by rounding; no test reaches it now.
Tests
- test_em_transition_m_step (MarkovRegression with 2 and 3 regimes,
MarkovAutoregression of order 2): one EM iteration through
fit(em_iter=1, maxiter=0) gives the transition probabilities computed in
the test from the smoothed joint probabilities at the start parameters.
Fails on main.
- The 11 test_fit_em values are recomputed (10 fail on main; AR4 was
within the tolerance), with a comment that they are regression values.
- test_fit of TestHamiltonAR2Short, TestFedFundsConstShort and
TestHamiltonAR2Switch passes the start parameters that 5 EM iterations
gave on main (em_iter=0), so they keep checking the same optimum.
…form MarkovSwitching.untransform_params inverted the logistic transform of the transition probabilities with scipy's root finder for three or more regimes, and raised "Could not untransform parameters." whenever it did not converge. It does not converge when a probability out of a regime is (nearly) zero, in particular the implied probability of moving to the last regime, one minus the sum of the others, which rounds to zero or to noise of about 1e-16. With the corrected EM step of statsmodels#11066, 20 EM iterations drive such a probability to zero, and MarkovRegression(y, 3).fit(em_iter=20) raised in 55 of 400 simulated samples (65 with em_iter=50). The same failure was reachable on main with start parameters such as p[0->0] = 0.3, p[0->1] = 0.7. The transform has a closed-form inverse: p[i->j] = exp(x_j) / (1 + sum_l exp(x_l)) gives x_j = log(p[i->j]) - log(p[i->k-1]), with p[i->k-1] = 1 - sum_j p[i->j]. This is also what the two-regime branch computed. Changes - untransform_params uses the closed form for any number of regimes. A probability of zero, including an implied last probability that is zero or slightly negative after rounding, is replaced by the smallest positive normal float (np.finfo(np.float64).tiny, about 2.2e-308) before taking logs, so the unconstrained parameters are finite (about 708 in size) and transform_params gives back the probabilities. Documented in the Notes, with a versionchanged directive. - Negative or NaN probabilities, or probabilities out of a regime that sum to more than one by more than 1e-8 (the tolerance of initialize_known), raise ValueError with a message that says so. With three or more regimes they raised "Could not untransform parameters." before; with two regimes they gave NaN. - The private _untransform_logistic, used only by the root finder, is removed; test_exog_tvtp computed the logits with it and now computes them directly. Fits that ran change only where the optimizer stops. On fedfunds (2 and 3 regimes), areturns (3 regimes), the Hamilton AR(4) and 40 simulated 3-regime samples, the unconstrained start parameters after the EM steps agree with those of the root finder to 6e-11 (relative) and the log-likelihood there to 5e-13; from them, the optimizer stops at another point of a flat likelihood in 4 of the 45 fits (log-likelihoods up to 8e-5 apart, parameters up to 3e-5 apart). With two regimes, a probability of exactly zero or one gave an infinite unconstrained parameter (one transformed back to NaN); they are finite now. Tests - Round trips untransform(transform(x)) and transform(untransform(p)) to rtol 1e-12 for 2, 3 and 4 regimes, with ordinary probabilities and with probabilities of 1e-22 and 1e-304. Fail on the base for 3 and 4 regimes ("Could not untransform parameters." with the tiny probabilities, and up to 4e-12 apart with the ordinary ones, the accuracy of the root finder). - Zero probabilities (explicit, implied, and a sum exceeding one by 1e-9) give finite unconstrained values that transform back to the probabilities; invalid ones (negative, NaN, a sum exceeding one by 1e-7) raise. - fit(em_iter=20, maxiter=0) for two simulated samples where the EM drives p[0->2] to zero (exactly, and to 8e-13) returns the EM parameters. Fails on the base ("Could not untransform parameters.").
…params The zero-probability test also compares the unconstrained values with log(p[i->j]) - log(p[i->k-1]) computed by hand, with zero probabilities replaced by the documented floor, the smallest positive normal float (2.2250738585072014e-308), so a different floor for the implied last probability fails the test.
test_fit_em_zero_transition relied on 20 EM iterations driving p[0->2] to
zero (p[0->0] + p[0->1] one up to 1e-12). With the newest versions
(Python 3.15, NumPy 2.5.5) the EM steps for seed 10 take the re-scaling
path instead (EstimationWarning, which also leaked), so the precondition
failed. The test now builds the start parameters with p[0->2] exactly zero
and zero up to 8e-13, and checks that fit without EM steps or optimizer
iterations returns them (through untransform_params and transform_params);
it fails without the closed form ("Could not untransform parameters.").
MarkovSwitchingResults popped "approx_complex_step" and "approx_centered" from the cov_kwds dict passed to fit, filter or smooth, so the caller's dict lost those keys, and then ignored them: the 'approx', 'opg' and 'robust' covariance matrices always used complex-step derivatives and the covariance description always said so. The results now work on a copy of cov_kwds and use the keys: approx_complex_step=False computes the Hessian and the scores by finite differences (forward differences, or centered ones with approx_centered=True), and the description names the method. The keys are documented in fit. The default, complex-step differentiation, does not change; covariance matrices of calls that set approx_complex_step to False change (at the level of the finite-difference error). Tests: the caller's dict is unchanged; with approx_complex_step=False, the 'approx', 'opg' and 'robust' covariance matrices with forward and centered differences against the matrices built from the finite-difference Hessian and scores, their agreement with the complex-step matrices up to the truncation error, and the description.
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.
The summary of Markov switching results warns that the covariance matrix is singular when the results' _rank is below the number of parameters. With cov_type="robust", _rank was the rank of the outer product of gradients (OPG) matrix: cov_params_robust computes cov_params_opg first, which sets the rank, so the robust matrix's own rank update could never run (statsmodels#11010 removes it as unreachable). The robust matrix, pinv(H pinv(OPG) H), squares the conditioning of the Hessian and the OPG matrix, and can have a lower rank. For MarkovRegression(fedfunds[-10:], k_regimes=2) at the parameters of TestFedFundsConstShort, where regime 1 has a smoothed probability below 4e-5 in every period, the OPG matrix has rank 5 (smallest singular value 9e-13 of the largest), and the robust matrix rank 3, but the summary did not warn. Changes - cov_params_robust sets _rank to the rank of the robust matrix when no rank is set yet, that is when it is the covariance matrix of the results, as cov_params_approx and cov_params_opg do for theirs. Results with another cov_type keep the rank of their own matrix when cov_params_robust is computed later. - versionchanged in the cov_params_robust docstring. The summary of robust results can now warn that the covariance matrix is singular (or stop warning, if the OPG rank was lower, which cannot happen in exact arithmetic). Not changed - The covariance matrices and standard errors. - The rank and warning of results with cov_type "approx", "opg", "none" and "custom". Tests - test_summary_singular_warning_follows_cov_type: for robust results with a robust matrix of rank 3 the summary warns (fails on statsmodels#11010's branch and on main); for OPG and approx results of the same model (rank 5 each, also after computing their robust matrix of rank 3) and for robust results of the full series (rank 5) it does not. The ranks are computed in the test from cov_params().
Docstring fixes in tsa/regime_switching/markov_switching.py found by a
contract audit of the public names, each checked against the code:
- cy_hamilton_filter_log returns six arrays (also the log predicted and
filtered joint probabilities used by the smoother), joint_loglikelihoods
is log f(y_t | Y_{t-1}), and the time of initial_probabilities is
stated with the first observation at t = 1.
- cy_kim_smoother_log takes log probabilities, and a transition matrix
with nobs + order periods.
- The MarkovSwitchingParams example gave wrong indexes.
- MarkovSwitching: the shapes accepted by initial_probabilities and the
exog_tvtp of regime_transition_matrix, predict returns only in-sample
predictions (out of sample raises NotImplementedError), filter and
smooth use 'opg' by default and return the raw output with
return_raw=True, Returns sections for loglikeobs, loglike, score,
score_obs and hessian, and fit returns an array with
return_params=True, ignores em_iter with time-varying transition
probabilities, draws search variates uniformly within half of
search_scale, and full_output=False is deprecated.
- HamiltonFilterResults, KimSmootherResults and MarkovSwitchingResults:
the attributes and their shapes and types (DataFrames for pandas
data), the results parameter, expected_durations, llf_obs is an array,
the shapes of fittedvalues, resid and predict, and forecast always
raises NotImplementedError.
Close the coverage gaps of tsa/regime_switching/markov_switching.py
through public paths, with every value checked against something
independent of the code under test:
- The Hamilton filter and Kim smoother written out in probability space
for a two-regime model at Stata's fedfunds estimates: predicted,
filtered and smoothed marginal probabilities, the joint probabilities
of (S_t, S_{t-1}), loglikeobs and loglike as the sum of the log
predicted densities, the ergodic initial probabilities, expected
durations 1 / (1 - p_ii) and the information criteria; Stata's
published predicted and filtered probabilities (unused until now).
- The same with time-varying transition probabilities from the logistic
closed form, including time-varying expected durations, and for
cy_hamilton_filter_log and cy_kim_smoother_log with an order-0
likelihood (with and without time-varying transitions).
- A subclass that only provides the conditional loglikelihoods gets the
base results class; known initial probabilities against the
recursions; summary tables of a model without switching parameters.
- initial_probabilities against the closed form (two regimes) and the
unit-eigenvalue eigenvector (three regimes), with a given 2-d or 3-d
transition matrix; regime_transition_matrix for new exog_tvtp data
against the multinomial logistic.
- predict with start and end (integers and dates), filter with
untransformed parameters, the results_class arguments, filter results
with pandas data, the raw filter and smoother output against Stata.
- Every cov_type: the covariance used, the summary note, the OPG
covariance against central-difference scores, the defaults of filter,
smooth and fit, and cov_type="custom".
- fit with given start parameters (transformed or not) and
return_params; the random start search with per-parameter scales
against the candidates it draws, a wrong-size scale, and with
time-varying transitions against the closed-form EM step.
- transform_params and untransform_params (logistic, multinomial
logistic, no solution, time-varying), the summary sample with dates,
start and model_name, the singular covariance note, and the
MarkovSwitchingParams docstring example.
Contract tests: endog as list, tuple, (n, 1) column, Series with a
DatetimeIndex, PeriodIndex or RangeIndex, DataFrame and int dtype give
the ndarray results and keep the index; dates and freq with an ndarray;
missing="drop" and "raise"; exog_tvtp as list, DataFrame, 1-d array and
Series.
… test The CodeQL check failed with two "Unhashable object hashed" errors at params[[0, 2]] and params[[1, 3]] in test_filter_smoother_tvtp_fixed_params: the analysis does not know that np.r_ returns an ndarray, so it takes the list index as a dictionary key (the same false positive as for np.r_[[...]] on main). Select the same coefficients with the slices params[0:4:2] and params[1:4:2], as the test already does with params[4:6].
bashtage
force-pushed
the
wip-tsa-cov-c7a
branch
from
November 28, 2026 21:36
4742c7c to
ead100d
Compare
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.
Stacked on #11068, which is stacked on #11010, #11002, #11183 and #11066: merge those first (this PR adds three commits). The stack was rebuilt on 2026-11-25 so that it merges without conflicts in this order; notes about conflicts with PRs of the same stack no longer apply.
Close the coverage gaps of
tsa/regime_switching/markov_switching.pythrough public paths, and align the docstrings with what the code does. The
tests compare with references independent of the code: the Hamilton filter
and Kim smoother written out in probability space, Stata's published
probabilities, and closed forms. The source changes are docstrings only.
Changes
constant and time-varying transition probabilities, against the
recursions written out in the test: predicted, filtered and smoothed
marginal probabilities and the joint probabilities of (S_t, S_{t-1});
loglikeobsandloglike; the ergodic initial probabilities, expecteddurations 1/(1-p_ii) and the information criteria; Stata's predicted and
filtered probabilities (unused until now).
cy_hamilton_filter_logandcy_kim_smoother_logwith an order-0likelihood, through a subclass that only supplies the conditional
log-likelihoods, with known initial probabilities.
initial_probabilitiesagainst the closed form and the unit-eigenvalueeigenvector;
regime_transition_matrixwith newexog_tvtpdata againstthe multinomial logistic;
predictwith integer and datestart/end;filterwith untransformed parameters; theresults_classarguments;the raw filter and smoother output.
cov_type, the OPG covariance against central-difference scores(to a tolerance that allows for the numerical derivatives), and the
cov_typedefaults offilter,smoothandfit.fitwith given start parameters andreturn_params, the random startsearch with per-parameter scales against the candidates it draws, and the
search with time-varying transitions against the closed-form EM step. No
test asserts where the optimizer stops.
transform_params/untransform_params; the summary sample,start,model_nameand the singular-covariance note.DatetimeIndex, PeriodIndex or RangeIndex, DataFrame and int;
dates/freq;missing; theexog_tvtpforms.inputs of the smoother; the corrected
MarkovSwitchingParamsexample; theaccepted shapes of
initial_probabilitiesandregime_transition_matrix; Returns sections for the likelihood, scoreand Hessian methods and the
return_raw/return_paramsresults; theopgdefault offilter/smooth;full_output,em_iterandsearch_scaleoffit; the attributes, shapes and pandas types of theresults classes;
forecastand out-of-samplepredictraiseNotImplementedError.
Not changed
predictwith arrayprobabilities; conditional predictions withstart/end(silent) and on pandas results;summary(display_params= False)is ignored; lists intransform_params/untransform_params;underflow in the compiled filter (an extreme observation gives a -inf
log-likelihood);
cov_kwdsis mutated and itsapprox_*keys ignored;complex transitions with real conditional log-likelihoods. No test
asserts the current behaviour of those paths.
Tests
pytest statsmodels/tsa/regime_switching -n 8: all pass with no warningson pandas 3.0.5; the new tests also pass on pandas 2.3.3.
Coverage:
markov_switching.py94.7% → 97.6% lines and 85.0% → 95.5%branches. What remains is reachable only through private calls, a LAPACK
failure, the bugs above, or not at all.
Mutation check: 25 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