Panels & microeconometrics¶
The classes and functions of the row "Panels & microeconometrics" of Analytical tools, with what calls return (the results and their methods: forecasts, impulse responses, tests). Import them from pymetrix (from pymetrix import ...) unless a heading names another module. Parameters and return types are in each signature; the text says what each does.
Help topics: Marginal effects and margins, Dynamic panels: Arellano-Bond and system GMM, Interactive fixed effects, Conditional logit, Survival analysis, Maximum likelihood, Nested and mixed logit, Panel data estimators, Cointegration and VECMs, Unit roots and stationarity.
Classes¶
ArellanoBond
dataclass
¶
ArellanoBond(gmm: Annotated[str, Widget('text', help='variables instrumented by their own lags (endogenous); empty = the dependent variable')] = '', lags: Annotated[str, Widget('text', help='lags used as instruments, first:last, e.g. 2:4; 2: = all from the second')] = '2:', system: Annotated[bool, Widget('checkbox', help='add the levels equation (Blundell-Bond system GMM)')] = False, two_step: Annotated[bool, Widget('checkbox', help='two-step GMM with Windmeijer-corrected standard errors')] = True, collapse: Annotated[bool, Widget('checkbox', help='one instrument column per lag, not per period and lag (fewer instruments)')] = False, time_effects: Annotated[bool, Widget('checkbox', help='period dummies, instrumenting themselves: absorb common shocks that would correlate the errors across entities')] = True)
Dynamic panel GMM: difference GMM (Arellano-Bond); system=True for system GMM (Blundell-Bond).
The lags are valid instruments only if the errors are serially uncorrelated in levels. Then the differenced
residuals show first-order correlation but not second-order: a small AR(2) p-value invalidates lag 2 of the
gmm variables, so start the lags at 3. System GMM also assumes that the differences of the gmm variables are
uncorrelated with the entity effects (a mean-stationary start). Without collapse the instrument count grows
with the square of the number of periods; too many instruments overfit the endogenous variables, pull the
estimates towards least squares and weaken the Hansen test, whose p-value near 1 is then a warning rather than
reassurance. Keep the instruments fewer than the groups by collapsing or capping the lags. As a check, the
coefficient on the lagged dependent variable should lie between its within estimate (biased down) and its
pooled least-squares one (biased up).
Between
dataclass
¶
Between(cov: str | Cluster = 'classic', reweight: Annotated[bool, _adv('weight entities by their number of observations')] = False, debiased: Annotated[bool, _adv('small-sample (n-k) correction of the covariance')] = True, backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())
Bases: _Wrapped
Between estimator: OLS on entity means.
Breitung
dataclass
¶
Breitung(variable: str, lags: Annotated[int, advanced(help='lagged differences removed from each series first (prewhitening), the same for all; 0 = none')] = 0, trend: Annotated[Literal['c', 'ct'], Widget('', help="each entity's own terms: c a constant, ct a constant and trend (trending series)")] = 'c', robust: Annotated[bool, advanced(help="Breitung and Das's statistic, robust to cross-sectional dependence")] = False)
Bases: Test
Breitung's unbiased panel unit-root test, optionally robust to cross-sectional dependence.
Breitung (2000); the robust version is Breitung and Das's (2005), standard normal as both N and T grow: with ten entities it rejects a true null about 8-11% of the time at 5%, against 40% or more for the standard statistic under a strong common factor.
The null is that every series has a unit root; the alternative, as for Levin, Lin and Chu, is that all are stationary with a common coefficient. The statistic rejects when large and negative. Because it needs no bias adjustment it keeps more power than Levin-Lin-Chu when each series has its own trend. It needs a balanced panel, and the robust statistic needs more periods than entities; use it when a common shock is likely.
CIPS
dataclass
¶
CIPS(variable: str, lags: Annotated[int, advanced(help='lagged differences in each CADF regression, the same for every entity; too few distort the size')] = 0, trend: Annotated[Literal['c', 'ct', 'n'], Widget('', help="each entity's own terms: c a constant, ct a constant and trend (trending series), n none")] = 'c', truncated: Annotated[bool, advanced(help='truncate each CADF statistic (CIPS*), which matters only in very short panels')] = False, draws: Annotated[int, advanced(help="simulations of the null distribution for this panel's N, T and lags")] = 10000, seed: Annotated[int, advanced()] = 0)
Bases: Test
Pesaran's CIPS test: cross-sectionally augmented ADF regressions, for panels with a common factor.
The null is that every series has a unit root; the alternative is that some are stationary. Each entity's ADF regression adds the cross-section means' lagged level and differences, which absorb a single unobserved common factor, so the test stays valid where IPS, Levin-Lin-Chu and Fisher-type tests reject too often; several factors are not fully absorbed. The statistic is the average CADF t-ratio and rejects when large and negative; critical values and the p-value are simulated for the panel's N, T and lags. The lag is fixed and the same for every entity: too few leave serial correlation that distorts the size, so check that the result survives a few values. The entities' own CADF statistics are in the details.
CLogLog
dataclass
¶
0/1 outcomes with the complementary log-log link: P(y = 1) = 1 - exp(-exp(x b)), asymmetric where the logit and
probit are symmetric (the probability approaches 1 faster than it leaves 0). EViews' extreme-value binary model
(binary(d=x)), Stata's cloglog and R's binomial(link = "cloglog").
FamaMacBeth
dataclass
¶
FamaMacBeth(cov: str | Cluster = 'classic', hac_lags: int | None = None, debiased: Annotated[bool, _adv('small-sample (n-k) correction of the covariance')] = True, backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())
Bases: _Wrapped
Fama-MacBeth: cross-section regressions each period, averaged.
FirstDifference
dataclass
¶
FirstDifference(cov: str | Cluster = 'classic', debiased: Annotated[bool, _adv('small-sample (n-k) correction of the covariance')] = True, backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())
Bases: _Wrapped
First-difference estimator (the constant drops out).
FisherADF
dataclass
¶
FisherADF(variable: str, lags: Annotated[str | int, advanced(help='lagged differences in each ADF regression, or aic / bic to choose entity by entity')] = 'aic', trend: Annotated[Literal['c', 'ct', 'n'], Widget('', help="each entity's own terms: c a constant, ct a constant and trend (trending series), n none")] = 'c', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other arguments of each statsmodels adfuller')] = dict())
Bases: Test
Fisher-type panel unit-root test: ADF tests entity by entity, combined (Maddala-Wu chi-squared; Choi Z).
Each entity's ADF test is run on its own (MacKinnon p-values) and the p-values are combined. The null is that every series has a unit root; the alternative is that at least one is stationary, so a rejection does not say how many are: the details count the entities rejecting at 5%. Entities may have their own lags and sample lengths, which suits unbalanced panels. The combination assumes the entities' tests are independent; a common shock makes it reject too often, and then CIPS or Breitung's robust statistic is the better choice. Choi's inverse-normal and logit statistics are in the details.
Hadri
dataclass
¶
Hadri(variable: str, trend: Annotated[Literal['c', 'ct'], Widget('', help='the null: each series stationary around its own level (c) or linear trend (ct)')] = 'c', heteroskedastic: Annotated[bool, advanced(help='each series its own error variance (default), or one pooled variance')] = True, lags: Annotated[str | int, advanced(help="Bartlett lags for a long-run variance when errors are autocorrelated; 0 = none (Hadri's original), auto = 4(T/100)^(2/9)")] = 0)
Bases: Test
Hadri LM test: the null is that every series is stationary (the panel counterpart of KPSS).
The null is that every series is stationary around its own level (c) or trend (ct); the alternative is that some have a unit root. The statistic averages the entities' KPSS-type LM statistics, standardised to N(0, 1), and rejects when large. With Lags 0 (Hadri's original) each series' variance is its residual variance, valid only for serially uncorrelated errors: with persistent but stationary data that version rejects far too often, so give Bartlett lags or auto. It needs a balanced panel and assumes independent entities; cross-sectional dependence also makes it reject too often. Read it with a test whose null is a unit root (IPS, CIPS).
Heckman
dataclass
¶
Heckman(selection: Annotated[str, Widget('text', help='the selection equation: a 0/1 variable on its regressors, e.g. inlf ~ educ + kids')] = '', estimator: Annotated[Literal['twostep', 'ml'], Widget('choice', help='two-step (probit, then least squares with lambda) or maximum likelihood')] = 'twostep', cov: Annotated[str | Cluster, Widget('', help="ml: classic (inverse Hessian) or white (sandwich); the two-step uses Heckman's corrected covariance")] = 'classic', max_iter: Annotated[int, Widget('', min=1, max=10000, advanced=True, help='maximum likelihood only: Newton steps after the quasi-Newton search, which may take 20 times as many')] = 100, tol: Annotated[float, Widget('', min=1e-14, max=0.01, advanced=True, help='maximum likelihood only: relative change in the estimates and likelihood that stops it')] = 1e-10)
Heckman's sample-selection model, for an outcome observed only where selection is 1.
The outcome equation allows for the selection's correlation with the outcome. twostep: a probit of the
selection, then least squares with the inverse Mills ratio (lambda), with Heckman's corrected covariance;
ml: full maximum likelihood (rho and sigma estimated).
Least squares on the selected observations alone is biased when the unobservables that decide selection also move the outcome (rho not zero, e.g. wage offers seen only for those who work). The correction rests on joint normality of the two errors; it is credible only with an exclusion restriction, a variable in the selection equation that is not in the outcome equation. Without one, identification comes from the probit's nonlinearity alone, lambda is nearly collinear with the regressors and the estimates are fragile. The coefficient on lambda (rho times sigma) measures the selection: a significant one says the uncorrected regression would be biased. The outcome coefficients describe the whole population, not only the selected. Maximum likelihood is more efficient if normality holds; the two-step is simpler and a useful check.
ImPesaranShin
dataclass
¶
ImPesaranShin(variable: str, lags: Annotated[str | int, advanced(help='lagged differences in each ADF regression, or aic / bic to choose entity by entity')] = 'aic', trend: Annotated[Literal['c', 'ct'], Widget('', help="each entity's own terms: c a constant, ct a constant and trend (trending series)")] = 'c', draws: Annotated[int, advanced(help='random walks simulated for the null mean and variance of each t-statistic; more, less simulation error')] = 100000, seed: Annotated[int, advanced()] = 0)
Bases: Test
Im-Pesaran-Shin test: the average of the entities' ADF t-statistics (t-bar), standardised (W t-bar).
The null is that every series has a unit root. The alternative lets the autoregressive coefficient differ across entities and needs only some of the series to be stationary, so a rejection does not mean that all are. Each entity keeps its own lags and sample length; W t-bar is standard normal under the null and rejects when large and negative. It assumes independent entities: a common factor makes it reject too often, and CIPS, which allows one, is then the better choice. Power is low when T is short, and lower still with trends.
Kao
dataclass
¶
Kao(variables: Annotated[str, Widget('', help='the series, comma-separated; the first is regressed on the others, pooled with entity constants')], lags: Annotated[int, advanced(help='lagged differences in the pooled ADF regression of the residuals')] = 1, bandwidth: Annotated[str | int, advanced(help='Bartlett lags for the long-run covariance; auto = 4 (T / 100)^(2/9)')] = 'auto')
Bases: Test
Kao's panel cointegration tests: Dickey-Fuller and ADF tests on the residuals of the pooled within regression.
The null is no cointegration. The within regression gives each entity its own constant but the same slopes, so the alternative is cointegration with a common cointegrating vector; when the slopes may differ by entity, Pedroni's or Westerlund's tests suit better. There is no trend option. The statistic shown is the ADF one; the four Dickey-Fuller statistics are in the details, all standard normal under the null and rejecting when large and negative. DF rho, DF t and ADF use the long-run covariances to allow endogenous regressors and serially correlated errors; DF rho and DF t assume neither. It needs a balanced panel and assumes independent entities.
LevinLinChu
dataclass
¶
LevinLinChu(variable: str, lags: Annotated[str | int, advanced(help='lagged differences in each ADF regression, or aic / bic to choose entity by entity')] = 'aic', trend: Annotated[Literal['c', 'ct', 'n'], Widget('', help="each entity's own terms: c a constant, ct a constant and trend (trending series), n none")] = 'c')
Bases: Test
Levin-Lin-Chu test: a pooled ADF regression with a common autoregressive coefficient, adjusted to N(0, 1).
The null is that every series has a unit root; the alternative is that all are stationary with the same autoregressive coefficient. That is a strong restriction: when only some series may be stationary, IPS or the Fisher-type tests suit better. Lags and deterministic terms are each entity's own; the adjusted t-statistic is standard normal under the null and rejects when large and negative. It needs a balanced panel and assumes independent entities (a common factor makes it reject too often). The adjustments are tabulated from 25 periods (after lags) up: shorter panels get those for 25, and the test is best suited to moderate panels.
Multinomial
dataclass
¶
Unordered outcomes (multinomial logit): coefficients for each outcome against the base (default: the first).
NegativeBinomial
dataclass
¶
Counts with more variance than the Poisson allows: NB2, Var(y) = mu + alpha mu^2.
OrderedCLogLog
dataclass
¶
Ordered outcomes with extreme-value errors: P(y <= j) = 1 - exp(-exp(cut_j - x b)), the complementary log-log
link (EViews' ordered(d=x); statsmodels' OrderedModel with distr=scipy.stats.gumbel_l).
OrderedLogit
dataclass
¶
Ordered outcomes (ratings, grades): P(y <= j) = logistic(cut_j - x b), with cut points in place of a constant.
Pedroni
dataclass
¶
Pedroni(variables: Annotated[str, Widget('', help='the series, comma-separated; in each entity the first is regressed on the others')], trend: Annotated[Literal['c', 'ct', 'n'], Widget('', help="each entity's terms in its cointegrating regression: c constant, ct constant and trend, n none")] = 'c', lags: Annotated[str | int, advanced(help="lagged differences in the ADF statistics' regressions, or aic / bic to choose entity by entity")] = 'aic', bandwidth: Annotated[str | int, advanced(help='Bartlett lags for the long-run variances; auto = 4 (T / 100)^(2/9)')] = 'auto', draws: Annotated[int, advanced(help='simulated entities for the moments under the null')] = 20000, seed: Annotated[int, advanced()] = 0)
Bases: Test
Pedroni's panel cointegration tests: four within-dimension (panel) and three between-dimension (group) statistics of the residuals of each entity's cointegrating regression.
The null is no cointegration in any entity; each entity has its own cointegrating coefficients. The four panel statistics pool the residuals' autoregressive coefficient, so their alternative is cointegration in every entity with a common coefficient; the three group statistics average entity by entity and let it differ. The statistic shown is group ADF t; all seven, standardised to N(0, 1), are in the details. Panel v rejects when large, the other six when large and negative, and they can disagree in short panels. The entities are assumed independent: a common shock makes the tests reject too often. Up to seven regressors.
RandomEffects
dataclass
¶
RandomEffects(cov: str | Cluster = 'classic', small_sample: Annotated[bool, _adv('small-sample adjustment of the variance components')] = False, debiased: Annotated[bool, _adv('small-sample (n-k) correction of the covariance')] = True, backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())
Bases: _Wrapped
Random-effects (GLS) panel estimator.
StochasticFrontier
dataclass
¶
StochasticFrontier(cost: Annotated[bool, Widget('checkbox', help="a cost frontier (y = x'b + v + u) rather than a production one")] = False)
The normal-half-normal stochastic frontier by maximum likelihood (Aigner, Lovell and Schmidt 1977).
y = x'b + v - u for a production frontier (+ u for a cost frontier), v normal and u >= 0 half-normal inefficiency. Reports
sigma_v, sigma_u, lambda = sigma_u / sigma_v and the mean technical efficiency E[exp(-u)]; each observation's
inefficiency E[u | e] (Jondrow, Lovell, Materov and Schmidt 1982) is in fit.extra["inefficiency"].
Inefficiency is told apart from noise only by the assumed distributions: it shows up as skewness of the least-squares residuals, negative for a production frontier and positive for a cost one. Skewed the wrong way, sigma_u goes to zero and the frontier is least squares. The LR test of no inefficiency is one-sided (half a chi-squared(1)); a small lambda says that deviations from the frontier are mostly noise. Each observation's efficiency is a conditional mean, not a consistent estimate of that unit's own, so rank units with care; and the results can change with the distribution chosen for u.
Tobit
dataclass
¶
A regression censored at left and/or right (None: no limit): values at a limit stand for any beyond it.
Westerlund
dataclass
¶
Westerlund(variables: Annotated[str, Widget('', help='the series, comma-separated; the first is the one whose error correction is tested')], trend: Annotated[Literal['c', 'ct', 'n'], Widget('', help="each entity's terms in its error-correction regression: c constant, ct constant and trend, n none")] = 'c', lags: Annotated[int, advanced(help="lagged differences of every variable in each entity's error-correction regression")] = 1, leads: Annotated[int, advanced(help="leads of the regressors' differences, absorbing their correlation with the errors; 0 = none")] = 0, bandwidth: Annotated[str | int, advanced(help='Bartlett lags for the long-run variances; auto = 4 (T / 100)^(2/9)')] = 'auto', draws: Annotated[int, advanced(help='simulated entities for the moments under the null')] = 20000, seed: Annotated[int, advanced()] = 0)
Bases: Test
Westerlund's error-correction panel cointegration tests: the group mean (Gt, Ga) and pooled (Pt, Pa) tests that the error-correction coefficient is zero.
Each entity's error-correction regression explains the change in the first variable by its own lagged level, the others' lagged levels, lags of its change and leads and lags of the others' changes. The null is that the coefficient on the lagged level is zero in every entity: no error correction, so no cointegration. The group-mean statistics Gt and Ga let each entity have its own coefficient and reject when some entities error-correct; the pooled Pt and Pa reject when the panel as a whole does. All four are standardised to N(0, 1) and reject when large and negative; Gt is shown, the others are in the details. The regressors are assumed weakly exogenous. Westerlund's bootstrap for cross-sectionally dependent panels is not computed, so the p-values assume independent entities.
ZeroInflatedPoisson
dataclass
¶
Counts with extra zeros: a structural zero with probability logistic(inflate terms), else a Poisson count.
inflate lists the regressors of that probability ("" = a constant only).
Functions¶
cce
¶
cce(data: Dataset, outcome: str, regressors: Sequence[str], pooled: bool = False) -> PanelMeanGroup
Pesaran's common correlated effects: each unit's regression with the cross-section averages of outcome and regressors
added; mean group (default) or pooled. The averages' coefficients are not reported.
choice_logit
¶
choice_logit(data: Dataset, choice: str, regressors: Sequence[str] = (), case: str | None = None, alternative: str | None = None, alternative_constants: bool = False, case_variables: Sequence[str] = (), base: Any = None, cov: Literal['hessian', 'cluster'] = 'hessian') -> FittedConditionalLogit
McFadden's conditional logit for choice data in long form, one row per case and alternative: choice is 1
for the chosen alternative, regressors vary across alternatives (cost, time). case and alternative
name the series or axes identifying them (default: the dataset's first two entity axes). With
alternative_constants a constant for each alternative but base (default the first); case_variables
enter interacted with the alternatives' indicators.
choice_margins
¶
choice_margins(fit: Any, at: Mapping[str, Any] | None = None, dydx: Sequence[str] | None = None, change: Mapping[str, Any] | None = None, alternative: Any = None, predict: bool = False, contrast: bool = False, atmeans: bool = False, alpha: float = 0.05) -> Table
Effects on the choice probabilities at chosen values (Stata's margins, at() after cmclogit) after
choice_logit, nested_logit or mixed_logit: at={"cost": [2, 4]} sets the variable in every case (an
attribute for every alternative, or only for alternative), one profile per value (every combination of
several). At each profile the derivatives of each alternative's probability in each variable of dydx (default
all), or with change={"cost": (2, 4)} (from a to b) or {"cost": 1} (by an amount) the discrete change;
predict=True gives the probabilities themselves. Averaged over the cases with the other variables as observed,
or at their means (atmeans, not for the mixed logit, whose probabilities are simulated with the fit's draws).
contrast=True adds each profile less the first. Delta-method standard errors.
clogit_effects
¶
clogit_effects(fit: Any, at: Literal['average', 'mean'] = 'average', fixed_effect: float | None = None, alpha: float = 0.05, dummy: bool = False, changes: Mapping[str, Any] | None = None) -> ConditionalLogitEffects
Marginal effects and elasticities after choice_logit: own and cross derivatives of the probabilities in
each attribute, and derivatives in each characteristic of the case, averaged over the cases (at="average")
or at the means ("mean"), with delta-method standard errors. After conditional_logit (fixed effects):
odds ratios, and with fixed_effect the effects on the probability of a unit with that fixed effect.
Discrete changes (measure "discrete change"), beside the derivatives: with dummy=True for every 0/1 variable
(all values 0 or 1, as statsmodels' get_margeff(dummy=True)) the change in the probabilities when it goes
from 0 to 1, and for each variable in changes={name: delta} the change when it goes from its value to the
value plus delta ({name: (a, b)}: from a to b, Stata's at() pair). For an attribute, one alternative's value changes at a time (own and cross changes, as the
derivatives); for a characteristic, the case's. The panel logit has them only at a fixed_effect.
conditional_logit
¶
conditional_logit(data: Dataset, outcome: str, regressors: Sequence[str], group: str | None = None, cov: Literal['hessian', 'cluster'] = 'hessian') -> FittedConditionalLogit
Chamberlain's fixed-effects logit: the 0/1 outcome on regressors, conditioning on each group's number of
ones, which removes the group's own intercept. group is the panel's unit axis unless named (a series or an
axis); cov the inverse Hessian or errors clustered by group.
cox_ph
¶
cox_ph(data: Dataset, duration: str, event: str, regressors: Sequence[str], entry: str | None = None, strata: str | None = None, ties: Literal['breslow', 'efron'] = 'breslow', cov: Literal['hessian', 'robust', 'cluster'] = 'hessian', cluster: str | None = None, id: str | None = None) -> FittedCoxPH
Cox's proportional hazards regression of duration (event 1 for the event, 0 censored) on
regressors, by partial likelihood with ties "breslow" or "efron"; entry for left truncation and
strata for a baseline hazard per stratum. cov: the inverse Hessian, "robust" (each subject its own
cluster) or "cluster" (by cluster). With entry, a subject is at risk in (entry, duration], as R's coxph and
Stata's stcox (an entry must be before the end), and robust or clustered errors are Lin and Wei's sandwich from
those risk sets.
Time-varying covariates: give the data in counting-process form, a row per subject and spell of constant
covariates, with entry the spell's start, duration its stop and event 1 only if the event ends it, and
id the subject. Each row is at risk in (start, stop], as R's coxph and Stata's stcox (so a spell starting at
an event time is not at risk then); a subject's spells must not overlap; "robust" clusters on the subject.
cox_survival_curves
¶
cox_survival_curves(fit: FittedCoxPH, at: Any = None, alpha: float = 0.05, interval: Literal['log-log', 'log', 'plain'] = 'log-log') -> CoxSurvivalCurves
Survival curves after Cox's model at covariate profiles: S(t | x) = exp(-H0(t) exp(x'beta)), H0 Breslow's
baseline cumulative hazard (right-continuous), with pointwise intervals on the interval scale from Tsiatis'
variance of H(t | x) = exp(x'beta) H0(t), which the delta method takes over beta and the baseline hazard:
Var H(t | x) = exp(2 x'beta) sum_{t_j <= t} d_j / W_j^2 + q(t)' V q(t),
q(t) = exp(x'beta) sum_{t_j <= t} (x - xbar_j) d_j / W_j,
W_j the risk set's sum of exp(x_i'beta), xbar_j its weighted mean of x, V the fit's covariance of beta. at:
{regressor: value or list}, every combination a profile, the others at their sample means; a DataFrame of
profiles; or None (the means). With strata, a curve per profile and stratum.
cumulative_incidence
¶
cumulative_incidence(data: Dataset, duration: str, event: str, group: str | None = None, entry: str | None = None, alpha: float = 0.05) -> FittedCumulativeIncidence
Competing risks: the Aalen-Johansen cumulative incidence function of each cause, F_k(t), the probability of
failing from cause k by t when other causes compete. event codes the cause: 0 censored, each other value a
cause. By group; entry for left truncation. Delta-method (Greenwood-type) standard errors (Marubini and
Valsecchi, as Stata's stcompet and lifelines' AalenJohansenFitter) and pointwise log(-log) intervals.
duration_model
¶
duration_model(data: Dataset, duration: str, event: str, regressors: Sequence[str] = (), dist: Literal['exponential', 'weibull', 'lognormal', 'loglogistic'] = 'weibull', form: Literal['aft', 'ph'] = 'aft', entry: str | None = None) -> FittedDurationModel
A parametric duration (survival) regression of duration (event 1 for the event, 0 censored) on
regressors and a constant, by maximum likelihood: dist "exponential", "weibull", "lognormal" or
"loglogistic"; form "aft" (accelerated failure time, log T = x'beta + sigma e) or, for the exponential and
Weibull, "ph" (proportional hazards, h(t | x) = p t^(p-1) exp(x'b)); entry for delayed entry (left
truncation). See the module docstring for the parametrisations.
hausman_mcfadden
¶
hausman_mcfadden(fit: Any, drop: Any, coefficients: Sequence[str] | None = None) -> TestResult
Hausman and McFadden's test of IIA after choice_logit: the model refitted without the alternatives in
drop (one, or a list; the cases that chose them dropped), and Hausman's quadratic form in the difference of
the coefficients the two fits share (or those named in coefficients), chi-squared with the rank of the
difference of their covariances as degrees of freedom. A difference that is not positive definite is handled as
Stata's hausman does: a generalised inverse, reported in the result.
interactive_fe
¶
interactive_fe(data: Dataset, outcome: str, regressors: Sequence[str], factors: int | Literal['auto'] = 1, effects: Literal['none', 'unit', 'time', 'twoway'] = 'none', cov: Literal['homoskedastic', 'robust', 'cluster'] = 'robust', bias_correction: bool = False, max_factors: int = 8, criterion: str = 'icp1', tol: float = 1e-09, max_iter: int = 10000) -> FittedInteractiveFE
Bai's (2009) interactive fixed effects: outcome on regressors with factors unobserved common factors
with unit-specific loadings ("auto": chosen by Bai and Ng's criterion up to max_factors), after
removing additive effects; a balanced panel.
kaplan_meier
¶
kaplan_meier(data: Dataset, duration: str, event: str, group: str | None = None, entry: str | None = None, strata: str | None = None, alpha: float = 0.05, interval: Literal['log-log', 'log', 'plain'] = 'log-log', bands: bool = False, test: Literal['logrank', 'wilcoxon', 'tarone-ware'] = 'logrank') -> FittedKaplanMeier
Kaplan-Meier survival curves of duration (event 1 for the event, 0 censored), one per value of
group, with the log-rank test of equal survival across groups (test: "logrank", "wilcoxon"
(Gehan-Breslow) or "tarone-ware"; within strata if given). entry: entry times (left truncation).
Pointwise intervals on the interval scale; bands: Hall-Wellner simultaneous bands too (95% only).
knn_weights
¶
knn_weights(data: Dataset, coordinates: Sequence[str], k: int = 5) -> ndarray
Binary k-nearest-neighbour weights from the coordinates columns (Euclidean distance), rows in the data's order.
marginal_effects
¶
marginal_effects(fit: FittedEquation, at: Literal['average', 'mean'] | Mapping[str, Any] = 'average', alpha: float = 0.05, data: Dataset | None = None, dydx: Sequence[str] | None = None, change: Mapping[str, Any] | None = None, atmeans: bool = False, contrast: bool = False, terms: bool = False) -> Any
The change in E[y] (linear, counts, Tobit: the censored mean), the probability (logit, probit) or each outcome's
probability (ordered, multinomial) for a unit change in each variable: averaged over the sample (at="average"),
at the variables' means ("mean"), or at chosen values (Stata's at(): at={"age": [30, 40], "female": 1},
one row per profile, the other variables at their observed values, or at their means with atmeans=True). A 0/1
variable's effect is the change from 0 to 1; change={"income": (10, 20), "educ": 1, "age": "sd"} gives the
change between two values, by an amount or by one standard deviation instead. dydx picks the variables;
contrast=True adds each profile's effects less the first's (the effect of x at z = 1 less at z = 0). Effects
are with respect to the variables the terms are built from (x through x, x^2 and x*z); data= (the estimation
data) is needed for a variable that is not a term of its own (log(x) alone), and terms=True varies each term on
its own instead. Delta-method standard errors.
mean_group
¶
mean_group(data: Dataset, outcome: str, regressors: Sequence[str], trend: bool = False) -> PanelMeanGroup
Pesaran and Smith's mean group: least squares of outcome on regressors (a constant, and a trend with trend) unit by
unit, the coefficients averaged.
mixed_logit
¶
mixed_logit(data: Dataset, choice: str, regressors: Sequence[str] = (), random: Mapping[str, str] | None = None, case: str | None = None, alternative: str | None = None, panel: str | None = None, alternative_constants: bool = False, case_variables: Sequence[str] = (), base: Any = None, correlated: bool = False, draws: int = 500, draw_type: Literal['halton', 'random', 'scrambled_halton', 'sobol'] = 'halton', seed: int = 0, cov: Literal['hessian', 'cluster'] = 'hessian') -> FittedMixedLogit
A mixed (random-parameters) logit by simulated maximum likelihood, for choice data in long form as
choice_logit takes it. random maps regressors to "normal" or "lognormal" (others are fixed);
correlated estimates the Cholesky factor of their covariance; panel names the decision maker whose
choices share one draw. draws per decision maker: Halton (deterministic), pseudo-random (seed), or
scrambled Halton or Sobol sequences (scipy.stats.qmc, scrambled from seed).
cov: the inverse Hessian, or clustered by decision maker (by case without a panel).
nested_logit
¶
nested_logit(data: Dataset, choice: str, regressors: Sequence[str] = (), nests: str | Mapping[Any, Sequence[Any]] = '', case: str | None = None, alternative: str | None = None, alternative_constants: bool = False, case_variables: Sequence[str] = (), base: Any = None, dissimilarity: Literal['free', 'equal', 'one'] = 'free', cov: Literal['hessian', 'cluster'] = 'hessian') -> FittedNestedLogit
A nested logit by full-information maximum likelihood for choice data in long form (one row per case and
alternative), as choice_logit takes it. nests is a series (or axis) giving each row's nest, constant for an
alternative, or a mapping {nest: [alternatives]}. dissimilarity: "free" (one lambda per nest), "equal" (one
lambda shared by the nests) or "one" (every lambda 1: the conditional logit). The form is McFadden's,
consistent with utility maximisation (RU2); nests of one alternative have lambda fixed at 1. cov: the
inverse Hessian, or clustered by case.
pooled_mean_group
¶
pooled_mean_group(data: Dataset, outcome: str, regressors: Sequence[str], lags: int = 1) -> PooledMeanGroup
The pooled mean group estimator of an ARDL(lags, lags) in error-correction form, by concentrated maximum likelihood.
predictive_margins
¶
predictive_margins(fit: FittedEquation, at: Literal['average', 'mean'] | Mapping[str, Any] = 'average', alpha: float = 0.05, data: Dataset | None = None, atmeans: bool = False, contrast: bool = False) -> Any
Predictive margins (Stata's margins without dydx): the predicted E[y] or probability, averaged over the
sample with the variables in at set to each profile's values (at={"age": [30, 40, 50]}), or at the means
(at="mean", or atmeans=True with a profile). contrast=True adds each profile's margin less the first's.
Terms built from a variable (x^2, x*z, log(x)) are rebuilt from its value; data= is needed for a variable that is
not a term of its own. Delta-method standard errors.
spatial_diagnostics
¶
spatial_diagnostics(data: Dataset, outcome: str, regressors: Sequence[str], W: Any, row_standardise: bool = True) -> Table
Moran's I of the OLS residuals and Anselin's LM tests for a spatial lag and a spatial error, with robust forms.
spatial_regression
¶
spatial_regression(data: Dataset, outcome: str, regressors: Sequence[str], W: Any, model: Literal['lag', 'error'] = 'lag', row_standardise: bool = True) -> SpatialModel
The spatial lag (y = rho W y + X b + e) or spatial error (u = lambda W u + e) model by maximum likelihood.
Results¶
ConditionalLogitEffects
dataclass
¶
ConditionalLogitEffects(kind: str, outcome: str, at: str, frame: DataFrame, alternatives: tuple[Any, ...] = (), regressors: tuple[str, ...] = (), case_variables: tuple[str, ...] = (), fixed_effect: float | None = None, alpha: float = 0.05, cases: int = 0, discrete: dict[str, str] = dict(), provenance: Any = None, model: str = 'conditional logit')
Marginal effects and elasticities after McFadden's choice logit (kind="choice"), or odds ratios (and
effects at a chosen fixed effect) after Chamberlain's panel logit (kind="panel"). frame holds every
number: one row per variable, measure, probability and the alternative whose attribute changes.
table
¶
table(variable: str, measure: Literal['derivative', 'elasticity', 'discrete change'] = 'derivative', values: str = 'estimate') -> DataFrame
The effects of variable: for an attribute, alternatives by alternatives (row j, column k: the change in
P(j) for a change in the attribute of k); for a characteristic of the case, one row per alternative.
measure "derivative", "elasticity" or "discrete change" (for the variables in discrete); values
"estimate" or "std err".
CoxSurvivalCurves
dataclass
¶
CoxSurvivalCurves(duration: str, profiles: DataFrame, table: DataFrame, alpha: float = 0.05, interval: str = 'log-log', strata: str | None = None, provenance: Any = None)
Survival curves after Cox's model at covariate profiles, with pointwise intervals (the delta method).
survival_at
¶
S(t | x) and its interval at chosen times (right-continuous steps), by profile and stratum.
medians
¶
Median survival at each profile (the first time S(t | x) is at or below 0.5) and its interval (where the interval's limits reach 0.5); NaN where the curve, or a limit, stays above 0.5.
DurationCurves
dataclass
¶
DurationCurves(duration: str, dist: str, profiles: DataFrame, table: DataFrame, alpha: float = 0.05, provenance: Any = None)
Survival and hazard curves of a parametric duration model at covariate profiles, with pointwise intervals.
FittedConditionalLogit
dataclass
¶
FittedConditionalLogit(kind: str, outcome: str, names: tuple[str, ...], values: ndarray, cov: ndarray, loglike: float = 0.0, loglike_null: float = 0.0, groups: int = 0, dropped_groups: int = 0, nobs: int = 0, cov_type: str = 'hessian', group: str = '', alternative: str | None = None, probabilities: Series | None = None, iterations: int = 0, converged: bool = True, provenance: Any = None, design: Any = None)
A conditional logit: Chamberlain's fixed-effects logit (kind="panel") or McFadden's choice model ("choice").
marginal_effects
¶
marginal_effects(at: Literal['average', 'mean'] = 'average', fixed_effect: float | None = None, alpha: float = 0.05, dummy: bool = False, changes: Any = None) -> Any
Marginal effects and elasticities of the choice probabilities (choice data), or odds ratios (and, with
fixed_effect, effects at that value of the fixed effect) for the panel logit; discrete changes for 0/1
variables (dummy=True) and for changes={name: delta}: clogit_effects.
FittedCoxPH
dataclass
¶
FittedCoxPH(duration: str, event: str, names: tuple[str, ...], values: ndarray, cov: ndarray, loglike: float = 0.0, loglike_null: float = 0.0, nobs: int = 0, events: int = 0, ties: str = 'breslow', cov_type: str = 'hessian', cluster: str | None = None, strata: str | None = None, entry: str | None = None, baseline: DataFrame | None = None, schoenfeld: DataFrame | None = None, naive_cov: ndarray | None = None, km: Series | None = None, provenance: Any = None, design: dict[str, Any] | None = None, id: str | None = None, subjects: int = 0)
Cox's proportional hazards regression by partial likelihood (statsmodels' PHReg).
survival_curves
¶
survival_curves(at: Any = None, alpha: float = 0.05, interval: Literal['log-log', 'log', 'plain'] = 'log-log') -> CoxSurvivalCurves
Survival curves S(t | x) = exp(-H0(t) exp(x'beta)) at covariate profiles, with pointwise intervals by the delta
method over beta and the baseline hazard (Tsiatis' variance). at: {regressor: value or list of values},
every combination a profile ({"age": [40, 60], "treated": [0, 1]}: four); regressors not given at their
sample means; None: one profile at the means. Also a DataFrame, a row per profile. See cox_survival_curves.
ph_test
¶
ph_test(transform: Literal['km', 'rank', 'identity', 'log'] = 'km') -> Table
Grambsch and Therneau's test of proportional hazards for each regressor and globally: the scaled Schoenfeld
residuals against transform of the event times (the approximation of R's cox.zph before version 3, and
lifelines'). A small p-value says the regressor's effect changes over time.
FittedCumulativeIncidence
dataclass
¶
FittedCumulativeIncidence(duration: str, event: str, table: DataFrame, causes: tuple[Any, ...], group: str | None = None, alpha: float = 0.05, entry: str | None = None, provenance: Any = None)
FittedDurationModel
dataclass
¶
FittedDurationModel(duration: str, event: str, dist: str, form: str, names: tuple[str, ...], values: ndarray, cov: ndarray, theta: ndarray, theta_cov: ndarray, regressors: tuple[str, ...] = (), loglike: float = 0.0, nobs: int = 0, events: int = 0, entry: str | None = None, converged: bool = True, alpha: float = 0.05, X: ndarray | None = None, provenance: Any = None)
A parametric duration (survival) regression by maximum likelihood.
ancillary
¶
ancillary() -> Table
The scale sigma of log time and the shape 1/sigma (the Weibull's p; lifelines' rho or beta), with delta-method standard errors; for the exponential both are 1, fixed.
hazard_ratios
¶
exp(coefficient) with its interval: hazard ratios in PH form, time ratios in AFT form (no constant or ancillary).
predict
¶
predict(data: Any = None, what: Literal['median', 'mean', 'survival', 'hazard', 'linear'] = 'median', t: float | None = None, quantile: float = 0.5) -> Series
Predictions for each row of data (default: the estimation sample): "median" (or another quantile)
and "mean" duration, S(t) ("survival") or h(t) ("hazard") at time t, or "linear" x'beta (AFT).
curves
¶
curves(at: Any = None, times: Sequence[float] | None = None, alpha: float = 0.05) -> DurationCurves
Survival and hazard curves at covariate profiles (at as for Cox's curves: {regressor: values}, every
combination, others at their means; None: the means), on times (default 100 points up to the longest
duration), with pointwise intervals by the delta method (survival on the log(-log) scale, the hazard on the
log scale).
FittedInteractiveFE
dataclass
¶
FittedInteractiveFE(outcome: str, regressors: tuple[str, ...], factors: int, effects: str, cov_type: str, beta: ndarray, cov: ndarray, beta_uncorrected: ndarray, F: DataFrame, loadings: DataFrame, resid: Series, fitted: Series, criteria: DataFrame | None = None, criterion: str | None = None, bias_correction: bool = False, sigma2: float = 0.0, units: int = 0, periods: int = 0, iterations: int = 0, converged: bool = True, provenance: Any = None)
A panel regression with interactive fixed effects: beta, the estimated factors and loadings.
FittedKaplanMeier
dataclass
¶
FittedKaplanMeier(duration: str, event: str, table: DataFrame, groups: DataFrame, group: str | None = None, test: Any = None, alpha: float = 0.05, interval: str = 'log-log', bands: bool = False, entry: str | None = None, provenance: Any = None, hazard: DataFrame | None = None)
Kaplan-Meier estimates, one curve per group, with the test of equal survival across groups (test).
cumulative_hazard
¶
The Nelson-Aalen cumulative hazard H(t) = sum_{t_i <= t} d_i / n_i at each event time (of one group, or all), with Aalen's standard error sqrt(sum d_i / n_i^2) and pointwise intervals on the log scale.
plot_hazard
¶
The Nelson-Aalen cumulative hazards, by group, with their pointwise intervals (step layers).
survival_table
¶
The estimates at each event time (of one group, or all).
survival_at
¶
S(t) and its interval at chosen times (the step function: the last event time at or before t), by group.
FittedMixedLogit
dataclass
¶
FittedMixedLogit(outcome: str, names: tuple[str, ...], values: ndarray, cov: ndarray, random: dict[str, str] = dict(), correlated: bool = False, draws: int = 0, draw_type: str = 'halton', loglike: float = 0.0, loglike_logit: float = 0.0, loglike_null: float = 0.0, cases: int = 0, people: int = 0, dropped_cases: int = 0, nobs: int = 0, cov_type: str = 'hessian', case: str = '', alternative: str = '', panel: str | None = None, probabilities: Series | None = None, individual: DataFrame | None = None, iterations: int = 0, converged: bool = True, provenance: Any = None, design: Any = None)
A mixed logit by simulated maximum likelihood: the fixed coefficients and the random coefficients' means
(of the underlying normal for a lognormal one), then their standard deviations (sd.x) or, correlated, the
Cholesky factor of their covariance (chol.x.y).
random_coefficients
¶
random_coefficients() -> Table
Each random coefficient's distribution: mean, median and standard deviation of the coefficient itself (for a lognormal one, from the underlying normal's), and, correlated, the correlations of the underlying normals; delta-method standard errors.
marginal_effects
¶
marginal_effects(at: Literal['average'] = 'average', alpha: float = 0.05, dummy: bool = False, changes: Mapping[str, Any] | None = None) -> Any
Derivatives and elasticities of the choice probabilities, averaged over the cases, each integrated over the
random coefficients with the estimation's draws: dP_j/dx_k = E_beta[beta L_j (delta_jk - L_k)] and the
elasticity x_k / P_j times that (Train 2009, chapter 6); with delta-method standard errors
(ConditionalLogitEffects). Discrete changes as clogit_effects gives them (dummy, changes),
from the simulated probabilities with the same draws. Effects at chosen values: choice_margins.
predict
¶
predict(data: Dataset, case: str | None = None, alternative: str | None = None, panel: str | None = None, seed: int | None = None, draws: int | None = None) -> Series
The simulated choice probabilities for new choice data in long form (one row per case and alternative, as
the fit took): the same attributes and characteristics, alternatives among the fit's, no choice series needed.
By default the draws are made as the fit's were (the same kind, number and seed, one set per decision maker in
the order of their ids, so the estimation data give the fitted probabilities); with seed (and draws,
default the fit's number) new pseudo-random draws instead. panel (default the fit's, when the data have
it) names the decision maker whose cases share a draw. One probability per row, in the data's index.
FittedNestedLogit
dataclass
¶
FittedNestedLogit(outcome: str, names: tuple[str, ...], values: ndarray, cov: ndarray, nests: dict[Any, str] = dict(), dissimilarity: str = 'free', loglike: float = 0.0, loglike_logit: float = 0.0, loglike_null: float = 0.0, iia_test: Any = None, cases: int = 0, dropped_cases: int = 0, nobs: int = 0, cov_type: str = 'hessian', case: str = '', alternative: str = '', probabilities: Series | None = None, fixed_nests: tuple[str, ...] = (), iterations: int = 0, converged: bool = True, provenance: Any = None, design: Any = None)
A nested logit by FIML in the form consistent with random utility maximisation (RU2): coefficients, then
each nest's dissimilarity parameter lambda (one shared, with dissimilarity="equal").
lambdas
property
¶
Each nest's dissimilarity parameter (1 for a nest of one alternative).
nest_table
¶
nest_table() -> Table
The nests, their alternatives and their lambdas, with a Wald test of lambda = 1 for each free one.
marginal_effects
¶
marginal_effects(at: Literal['average', 'mean'] = 'average', alpha: float = 0.05, dummy: bool = False, changes: Mapping[str, Any] | None = None) -> Any
Derivatives and elasticities of the choice probabilities in each attribute of each alternative and each
characteristic of the case, averaged over the cases or at the means, with delta-method standard errors
(ConditionalLogitEffects, as after the conditional logit). Discrete changes as clogit_effects gives
them: dummy=True for every 0/1 variable (0 to 1), changes={name: delta} from each value to the value
plus delta, or {name: (a, b)} from a to b. Effects at chosen values (at() profiles):
choice_margins.
predict
¶
predict(data: Dataset, case: str | None = None, alternative: str | None = None) -> Series
The choice probabilities for new choice data in long form (one row per case and alternative, as the fit took): the same attributes and characteristics, alternatives among the fit's (each in its nest), no choice series needed. One probability per row, in the data's index.
PanelMeanGroup
dataclass
¶
PanelMeanGroup(method: str, y_name: str, names: tuple[str, ...], params: ndarray, cov: ndarray, units: DataFrame, nobs: int = 0, provenance: Any = None)
A mean-group or CCE estimate: average coefficients with their standard errors, and each unit's coefficients.
PooledMeanGroup
dataclass
¶
PooledMeanGroup(y_name: str, x_names: tuple[str, ...], theta: ndarray, theta_cov: ndarray, phi: Series, short_run: DataFrame, mg_theta: ndarray, mg_theta_cov: ndarray, loglike: float = 0.0, lags: int = 1, nobs: int = 0, provenance: Any = None)
The pooled mean group: a common long run, unit-specific adjustment and short run.
hausman
¶
Hausman's test of a common long run: the PMG theta (efficient under it) against the mean group of the units' own long runs (consistent either way).
SpatialModel
dataclass
¶
SpatialModel(model: str, y_name: str, names: tuple[str, ...], params: ndarray, cov: ndarray, sigma2: float = 0.0, loglike: float = 0.0, nobs: int = 0, resid: ndarray = None, provenance: Any = None)
A spatial lag or spatial error model estimated by maximum likelihood.