Single equations & tests¶
The classes and functions of the row "Single equations & tests" 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: Least squares, Specification and diagnostic tests, General-to-specific selection and indicator saturation, Instrumental variables, Maximum likelihood, Volatility models (GARCH), Selections and loops, Bootstrap bands and intervals, Quantile regression, Specification sensitivity and the specification curve, Nonparametric estimation, Unit roots and stationarity, Panel data estimators, Robust regression.
How do I: Estimate an equation and test its residuals, Save, reopen and share a project, and replay its script, Run a script in the app, Make a report, Estimate the effect of a policy change like a VAT increase, Check whether a result survives other specifications.
Classes¶
ARCH
dataclass
¶
ARCH(lags: Annotated[int, Widget('', help='lags of the squared residuals tested; a few detect persistent volatility, many dilute power')] = 4)
Bases: Test
Engle's LM test for ARCH effects: do squared residuals depend on their own lags?
The null is no ARCH effects: the squared residuals (standardised residuals when the fit has an ARMA or GARCH error model) are not predictable from their own lags. The statistic is the number of observations times the R-squared of that regression, chi-squared with as many degrees of freedom as lags. A rejection suggests modelling the variance with an ARCH or GARCH model, or at least heteroskedasticity-robust standard errors; on a GARCH fit it checks whether the model has captured the volatility clustering. A misspecified mean equation can also produce a rejection, so check the residuals' autocorrelation first.
Bootstrap
dataclass
¶
Bootstrap(kind: Literal['residual', 'wild', 'block', 'parametric', 'pairs'] = 'residual', draws: int | None = None, block_length: int | None = None, wild_dist: Literal['rademacher', 'mammen', 'normal'] = 'rademacher', seed: int | None = None, bias_correct: bool = False, workers: int | None = None, design: Literal['recursive', 'fixed'] = 'recursive', block_type: Literal['moving', 'stationary'] = 'moving', interval: Literal['percentile', 'hall', 'studentized'] = 'percentile', explosive: Literal['keep', 'redraw'] = 'keep')
How the bands' draws are made: kind residual, wild, block, parametric or pairs; draws replications
(None: the method's draws); block_length for blocks (None: round(5.03 T^(1/4))); wild_dist the wild
bootstrap's multipliers; seed (None: the method's); bias_correct Kilian's correction; workers processes
for the re-estimations; design recursive or fixed; block_type moving or stationary; interval
percentile, hall or studentized (bootstrap-t: coefficients and local projections); explosive keep or redraw
explosive draws.
procedure
¶
The procedure in words, e.g. "wild bootstrap (Rademacher multipliers), recursive design".
BreuschGodfrey
dataclass
¶
BreuschGodfrey(lags: Annotated[int, Widget('', help='order of serial correlation tested against; at least the seasonal period for quarterly or monthly data')] = 4, auxiliary_constant: Annotated[bool, Widget('checkbox', advanced=True, help="add a constant to the auxiliary regression when the equation has none, as statsmodels' acorr_breusch_godfrey does; no effect with a constant")] = False, presample: Annotated[Literal['zero', 'drop'], Widget('choice', advanced=True, help="the first lags' missing lagged residuals: set to zero (EViews, statsmodels), or drop those observations (Stata's nomiss0)")] = 'zero')
Bases: Test
Breusch-Godfrey LM test for serial correlation in the residuals, up to lags.
The null is no serial correlation up to the given lag; the alternative is autoregressive or moving-average errors of that order. The residuals are regressed on the regressors and their own lags (missing initial lags set to zero), and n R-squared is chi-squared with as many degrees of freedom as lags. Unlike Durbin-Watson it stays valid with a lagged dependent variable among the regressors. A rejection means the usual standard errors are wrong and, with a lagged dependent variable, the estimates are inconsistent too: add dynamics to the equation, or, if it is otherwise right, use HAC standard errors. It applies to unweighted least-squares fits.
Convention: the auxiliary regression has exactly the equation's regressors (Breusch 1978, Godfrey 1978; Greene,
Econometric Analysis, 8th ed., chapter 20), all n observations with the missing initial lags of the residuals set to zero,
and R-squared is measured about the residuals' mean. With a constant in the equation statsmodels gives the same
number. Without one, statsmodels' acorr_breusch_godfrey adds a constant to the auxiliary regression, which
changes the statistic; auxiliary_constant=True does the same (it changes nothing when the equation has a
constant).
The details give the F form, as statsmodels' acorr_breusch_godfrey and EViews: the F test that the lags'
coefficients in the auxiliary regression are zero, on lags and n - (regressors + lags) degrees of freedom; it
is more conservative in small samples. presample="drop" drops the first lags observations from the
auxiliary regression instead of setting their missing lagged residuals to zero (Davidson and MacKinnon; Stata's
estat bgodfrey, nomiss0): n is then the observations kept.
BreuschPagan
dataclass
¶
Bases: Test
Breusch-Pagan test, Koenker's studentised form, on the regressors.
Chow
dataclass
¶
Chow(at: Annotated[str, Widget('period', help='first period of the second regime, chosen from outside the data, not by eye')])
Bases: Test
Chow breakpoint test: do the coefficients change from period at?
The null is that all the coefficients are the same before and after the given period. The F statistic compares the sum of squared residuals of the full-sample fit with that of separate fits to the two regimes, assuming the error variance is the same in both; a variance that changes too distorts it. The date must come from outside the data: choosing it where the series seems to break makes the test reject too often, and for an unknown date the Quandt-Andrews test is the right one. Each regime needs more observations than coefficients.
Cluster
dataclass
¶
Cluster-robust covariance by one or two grouping variables or axes.
CochraneOrcutt
dataclass
¶
CochraneOrcutt(iterate: Annotated[bool, Widget('checkbox', help='repeat until rho settles (otherwise one round)')] = True, max_iter: Annotated[int, Widget('number', min=1, max=1000, advanced=True, help='most rounds when iterating; if rho has not settled by then, the fit stops with an error')] = 200, tol: Annotated[float, Widget('number', min=1e-14, max=0.01, advanced=True, help='convergence tolerance for rho')] = 1e-10)
Least squares with AR(1) errors by Cochrane and Orcutt: rho from the residuals, the equation quasi-differenced (the first observation dropped), repeated until rho settles.
Feasible generalised least squares for errors u_t = rho u_t-1 + e_t. It is efficient, with valid standard errors, only if the regressors are strictly exogenous; with a lagged dependent variable among them rho and the coefficients are inconsistent (use ML with ARMA errors, or instruments). The standard errors treat rho as known. Autocorrelated residuals often signal missing dynamics rather than AR(1) errors, so adding lags may be the better model; least squares with hac standard errors keeps the OLS coefficients and corrects only the inference. Dropping the first observation costs efficiency in short samples; Prais-Winsten keeps it. The fit stops with an error if rho reaches 1 in absolute value: difference the series.
CUSUMSQ
dataclass
¶
Bases: Test
CUSUM of squares on recursive residuals; critical values by simulation of the exact null.
Equation
dataclass
¶
Equation(text: str, params: Sequence[str | Param] = (), family: Family = Gaussian(), priors: Mapping[str, Any] = dict(), name: str | None = None, errors: Any = None, variance: Any = None)
An equation written as text: "c ~ y + c[-1]" to estimate, or "y = c + i + g" (an identity).
A ~ equation is linear in its coefficients unless params names them, as in
Equation("x ~ rho*x[-1]", params=["rho"]). Lags are x[-1], and functions such as log, dlog
and d may appear on either side. errors (ARMA(...)) and variance (GARCH(...)) add an error
process. Estimate it with fit.
require_dependent
¶
The dependent variable, or an error when the left-hand side has none or several.
variables
¶
Series the equation uses (fe() and C() arguments are grouping names, not series).
check_names
¶
check_names(data: Dataset) -> None
Every name must be a series in the data or a declared parameter, never both.
fit
¶
fit(data: Dataset, span: tuple[Any, Any] | None = None, where: str | None = None, method: Any = None, weights: str | None = None, missing: Literal['drop', 'raise'] = 'drop') -> FittedEquation
Estimate the equation on data: by least squares unless method says otherwise (OLS(cov="hac"),
IV(...), ML(), Ridge(), ...).
span (first, last) and where (a condition such as "recession == 0") choose the sample; weights
names a weight series; missing="raise" refuses rows with missing values instead of dropping them.
Equations with ARMA errors or a GARCH variance are estimated by maximum likelihood by default.
select_lags
¶
select_lags(data: Dataset, max_lags: int = 8, of: Sequence[str] | None = None, span: tuple[Any, Any] | None = None, method: Any = None) -> Any
Choose how many lags to add, by AIC, BIC and Hannan-Quinn on the sample the largest model allows: lags 1 to
p of each variable in of (by default the left-hand side as written) for p = 0 ... max_lags. Returns
an EquationLagSelection: its table, best and equation("bic").
fit_rolling
¶
fit_rolling(data: Dataset, window: int, span: tuple[Any, Any] | None = None, method: Any = None, step: int = 1) -> Any
Estimate over a moving window of window periods; returns a RollingFit.
fit_recursive
¶
fit_recursive(data: Dataset, min_obs: int | None = None, span: tuple[Any, Any] | None = None, method: Any = None, step: int = 1) -> Any
Estimate over an expanding window starting with min_obs periods; returns a RollingFit.
coefficient_names
¶
Names of the coefficients a linear-form fit will produce (without C() dummies).
residual_expression
¶
lhs - rhs with parameter values substituted; zero when the equation holds.
linear_rhs
¶
The right-hand side of a linear-form equation with its coefficients as parameters.
algebraic
¶
The equation as an economist writes it: cₜ = β₀ + β₁ yₜ + β₂ cₜ₋₁ + εₜ (see pymetrix.notation).
EstimateOf
dataclass
¶
A coefficient of the fit, by the name its summary gives it ("x"; a VAR's "y: r[-1]").
ForecastAt
dataclass
¶
The forecast of variable at the period at, from start (the period after the fit's sample by default).
JarqueBera
dataclass
¶
Bases: Test
Jarque-Bera test of normal residuals, from their skewness and kurtosis.
LjungBox
dataclass
¶
LjungBox(lags: Annotated[int, Widget('', help='autocorrelations tested jointly; about ln(T), a few seasonal cycles for seasonal data')] = 10, squared: Annotated[bool, Widget('checkbox', help='test squared residuals (McLeod-Li: volatility clustering)')] = False)
Bases: Test
Ljung-Box Q test of residual autocorrelation (squared=True: of squared residuals,
the McLeod-Li test). Degrees of freedom are reduced by the number of ARMA terms.
The null is that the residuals (standardised residuals when the fit has an ARMA or GARCH error model) are not autocorrelated up to the given lag; Q is chi-squared and rejects when large. A rejection means dynamics are left in the residuals: add lags or ARMA terms. The number of lags trades off: many dilute the power against correlation at short lags, few miss seasonal correlation. For least-squares residuals with a lagged dependent variable among the regressors, prefer Breusch-Godfrey. The squared version detects volatility clustering; a rejection there points to an ARCH or GARCH model of the variance.
LongRunEffect
dataclass
¶
A long-run multiplier: an equation's sum of the coefficients on variable and its lags over one less the sum
on the dependent variable's lags (with a delta-method standard error); a VAR's or VECM's long-run (cumulated, for a
VAR) response of variable to a shock to shock.
ML
dataclass
¶
ML(cov: Annotated[str | Cluster, Widget('', help='classic: inverse Hessian; white: sandwich, robust to a wrong variance; Cluster(...); opg (logit, probit, Poisson)')] = 'classic', optimizer: Annotated[Literal['newton', 'bhhh'], Widget('choice', advanced=True, help='newton: the Hessian; bhhh: the outer product of the scores (Berndt, Hall, Hall and Hausman); linear logit, probit and Poisson only')] = 'newton', max_iter: Annotated[int, Widget('', min=1, max=10000, advanced=True, help='iterations of the likelihood search; raise it if a fit fails to converge')] = 100, tol: Annotated[float, Widget('', min=1e-14, max=0.01, advanced=True, help='relative change in the estimates and log likelihood at which the search stops (not explicit-form equations)')] = 1e-10, start: Annotated[Mapping[str, float] | None, Widget('', advanced=True, help='starting values for explicit-form equations, e.g. b0=0.5, b1=0.1')] = None)
Maximum likelihood: Logit, Probit, Poisson, negative binomial, zero-inflated Poisson, ordered, multinomial and Tobit families, ARMA errors and GARCH variance.
The estimates are consistent and efficient when the family's likelihood is the right one. Logit and probit
coefficients act on a latent index, so their size is not an effect on the probability: use
fit.marginal_effects() for that, and compare signs and ratios, not levels, across the two. The Poisson
coefficients stay consistent for the conditional mean when the counts are over-dispersed, but then only the
white (sandwich) standard errors are right. The statistics give the log likelihood, McFadden's pseudo
R-squared (one minus its ratio to the intercept-only model's) and the LR test that every slope is zero.
Estimates that grow without bound or a singular information matrix usually mean perfect prediction
(separation) by a regressor. Fixed effects are not supported, since in short panels they bias the other
coefficients (the incidental-parameters problem). ARMA errors and GARCH variance have their own optimiser, so
the optimiser settings below do not apply to them, and their standard errors are classic or white. An
explicit-form equation (y ~ a + b*exp(c*x) as the index) is fitted by quasi-Newton from start; the
optimiser choice does not apply to it.
MonteCarlo
dataclass
¶
MonteCarlo(dgp: Any, estimator: Callable[[Any], Any], reps: int = 1000, seed: int = 0, workers: int = 1, truth: Mapping[str, float] = dict())
A Monte Carlo experiment: reps datasets from dgp (a function of a numpy Generator), each given to
estimator; truth (a mapping of quantity to true value) adds bias and RMSE.
MultiplicativeHeteroskedasticity
dataclass
¶
MultiplicativeHeteroskedasticity(variance: Annotated[Sequence[str], Widget('text', help="the variance's regressors (expressions), e.g. x, log(size)")] = (), max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='most rounds of weighted least squares and scoring before the fit stops with an error')] = 500, tol: Annotated[float, Widget('number', min=1e-14, max=0.01, advanced=True, help='stop when no variance coefficient changes by more than this in a round')] = 1e-10)
Harvey's (1976) multiplicative heteroskedasticity by maximum likelihood.
var(u_i) = exp(g0 + z_i'g): the coefficients by weighted least squares given the variance and the variance by scoring, alternately. The LR test of g = 0 (homoskedasticity) is in the statistics.
Heteroskedasticity does not bias least squares but makes it inefficient and its classic standard errors wrong. Modelling the variance gives efficient weighted estimates if the variance function is right; if it is wrong the coefficients stay consistent but their standard errors, which assume the model, mislead, and least squares with white standard errors is the safer choice. The exponential form keeps the variance positive: a variance coefficient is the proportional change in the variance per unit of its regressor. The variance coefficients and their standard errors are in the notes.
NeuralNetwork
dataclass
¶
NeuralNetwork(units: Annotated[int, Widget('number', min=2, max=50, help='random hidden units (logistic of a random combination of the regressors)')] = 10, components: Annotated[int, Widget('number', min=1, max=10, help='their principal components added (avoiding collinearity)')] = 2, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help="random seed for the hidden units' weights")] = 0)
Bases: Test
Lee, White and Granger's (1993) neural-network test for neglected nonlinearity: hidden units with random weights.
The null is that the conditional mean is linear in the regressors. The standardised regressors pass through hidden logistic units with random weights, and the leading principal components of those units are added to the regression: the F test of their joint significance is reported, with n R-squared (chi-squared) in the details. It has power against a broad range of nonlinearities, but because the weights are random the p-value depends on the seed: check a borderline result with a few seeds. It applies to linear-form least-squares fits.
run
¶
run(fit: FittedEquation) -> TestResult
The regressors (less the constant) standardised; units hidden units psi(g'x), g uniform on [-2, 2] and psi
the logistic, centred; their first components principal components added to the regression: an F test,
and n R^2 of the residuals on everything (chi-squared) in the details.
OLS
dataclass
¶
OLS(cov: str | Cluster = 'classic', hac_lags: int | None = None, start: Annotated[Mapping[str, float] | None, _START] = None, hac_correction: Annotated[bool, Widget('checkbox', advanced=True, help="HAC: multiply by n / (n - k), as EViews and Stata's newey; untick for statsmodels' default")] = True, restrictions: Annotated[str | Sequence[str] | None, _RESTRICTIONS] = None)
Least squares. Explicit-form equations are estimated by nonlinear least squares.
The coefficients are consistent when the regressors are uncorrelated with the error (exogeneity); an omitted variable correlated with a regressor, simultaneity or measurement error in a regressor biases them, and only instruments (IV, GMM) put that right. The standard errors change the inference, not the estimates: classic assumes homoskedastic, serially uncorrelated errors; white allows heteroskedasticity; hac (Newey-West) allows autocorrelation as well, in time series; Cluster(...) allows any correlation within groups, and is needed when the regressor of interest varies only between groups. R-squared measures fit in the sample, not whether the coefficients are causal. Explicit-form equations are solved numerically from the starting values, so check that the estimates do not depend on them.
restrictions=["y + c[-1] = 1"] imposes linear restrictions R b = r on a linear-form equation's coefficients
(restricted least squares): b - (X'X)^-1 R' [R (X'X)^-1 R']^-1 (R b - r), the estimate the restrictions
substituted into the equation would give, with that substitution's covariance (of the chosen kind) and one
residual degree of freedom more per restriction. Coefficients are named as the summary names them.
PraisWinsten
dataclass
¶
PraisWinsten(iterate: Annotated[bool, Widget('checkbox', help='repeat until rho settles (otherwise one round)')] = True, max_iter: Annotated[int, Widget('number', min=1, max=1000, advanced=True, help='most rounds when iterating; if rho has not settled by then, the fit stops with an error')] = 200, tol: Annotated[float, Widget('number', min=1e-14, max=0.01, advanced=True, help='convergence tolerance for rho')] = 1e-10)
Least squares with AR(1) errors by Prais and Winsten: as Cochrane-Orcutt, but the first observation kept, scaled by sqrt(1 - rho^2), so that it is generalised least squares for the AR(1) covariance.
Feasible generalised least squares for errors u_t = rho u_t-1 + e_t. It is efficient, with valid standard errors, only if the regressors are strictly exogenous; with a lagged dependent variable among them rho and the coefficients are inconsistent (use ML with ARMA errors, or instruments). The standard errors treat rho as known. Autocorrelated residuals often signal missing dynamics rather than AR(1) errors, so adding lags may be the better model; least squares with hac standard errors keeps the OLS coefficients and corrects only the inference. Keeping the first observation matters most in short samples and with trending regressors. The fit stops with an error if rho reaches 1 in absolute value: difference the series.
pymetrix.estimation.Beta
dataclass
¶
A beta prior on (0, 1), given by its mean and standard deviation (as Dynare's beta_pdf).
pymetrix.estimation.Calibrated
dataclass
¶
Marks parameters that were set, not estimated.
pymetrix.estimation.Gamma
dataclass
¶
A gamma prior on (0, inf), given by its mean and standard deviation (as Dynare's gamma_pdf).
pymetrix.estimation.InvGamma
dataclass
¶
Inverse gamma of the value itself (Dynare's inv_gamma2_pdf), with this mean and standard deviation.
pymetrix.estimation.InvGamma1
dataclass
¶
Dynare's inverse gamma of type 1 (inv_gamma_pdf), the usual prior on a standard deviation sigma:
density proportional to sigma^-(nu+1) exp(-s / (2 sigma^2)), with nu and s matching the mean and standard
deviation (an infinite standard deviation gives nu = 2).
nu_s
property
¶
The degrees of freedom nu and scale s (Dynare's inverse_gamma_specification), found once for each mean and
standard deviation (a root search: each log density needs them).
QuandtAndrews
dataclass
¶
QuandtAndrews(trim: Annotated[float, Widget('number', min=0.05, max=0.45, step=0.05, help='share of the sample left out at each end; 0.15 is usual, smaller searches nearer the ends')] = 0.15)
Bases: Test
Quandt-Andrews test for a break at an unknown date: the largest Chow F statistic over the candidate dates
in the middle of the sample (all but trim at each end), with Andrews' asymptotic p-value.
The null is that all the coefficients are constant; the alternative is one break at an unknown date. Because the date is the one where the Chow F is largest, the statistic does not have an F distribution: the p-value and critical values come from Andrews' limiting distribution for this number of coefficients and trimming. The date of the peak, in the details, estimates the break date; the exp F and average F statistics are there too, without p-values. The F statistics assume a constant error variance, and Andrews' distribution assumes stationary regressors, so with a time trend or integrated regressors the p-value is only approximate. For more than one break, use Bai-Perron's method.
Quantile
dataclass
¶
Quantile(q: Annotated[float, Widget('number', min=0.01, max=0.99, step=0.05, help='the quantile, e.g. 0.5 for the median')] = 0.5, vcov: Annotated[Literal['robust', 'iid'], Widget('choice', help='robust: sandwich weighting each residual by its sign; iid: assumes identically distributed errors')] = 'robust', kernel: Annotated[Literal['epa', 'gau', 'cos', 'par'], Widget('choice', advanced=True, help='kernel of the error-density estimate behind the standard errors: Epanechnikov, Gaussian, cosine, Parzen')] = 'epa', bandwidth: Annotated[Literal['hsheather', 'bofinger', 'chamberlain'], Widget('choice', advanced=True, help='bandwidth rule of that density estimate (Hall-Sheather, Bofinger or Chamberlain); affects the standard errors only')] = 'hsheather', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict())
Quantile regression at quantile q (0.5: median regression).
A coefficient is the regressor's effect on the q-th quantile of the outcome given the regressors, not on its
mean; estimating several quantiles (quantile_process) shows whether a regressor shifts the whole
distribution or stretches one tail. The estimates are robust to outliers in the dependent variable, not to
outliers in the regressors. The standard errors rest on an estimate of the errors' density at the quantile:
the kernel and the bandwidth rule set that estimate and change the standard errors only, which become less
reliable at extreme quantiles in small samples, where few observations lie beyond the line. The pseudo
R-squared is one minus the ratio of the check loss to that of the quantile alone; it is not comparable with
a least-squares R-squared.
RESET
dataclass
¶
RESET(power: Annotated[int, Widget('number', min=2, max=6, help='highest power of the fitted values added (3 = squares and cubes)')] = 3)
Bases: Test
Ramsey RESET: adds powers 2..power of the fitted values.
The null is that the functional form is right: powers of the fitted values add nothing to the regression. The F test of their joint significance rejects when something is missing, such as a nonlinearity, an omitted variable correlated with the powers, or the wrong transformation (levels rather than logs), but it does not say which. It has little power against omitted variables unrelated to the fitted values. It applies to linear-form least-squares fits without fixed effects or weights.
ResponseAt
dataclass
¶
ResponseAt(shock: str = '', response: str = '', horizon: int | None = None, periods: int | None = None, cumulative: bool = False, draws: int = 0, seed: int = 0)
The impulse response of response to a shock to shock: at horizon, or the whole path to periods
(20 by default) without one. Shocks named differently under different identifications are given as alternatives,
"r|monetary": the first the fit has is used. draws: bootstrap draws for a VAR's or VECM's interval (0: none). A local
projection's response and shock are its own (left empty, or as the projection names them).
RobustLS
dataclass
¶
RobustLS(norm: Annotated[Literal['huber', 'bisquare'], Widget('choice', help='huber: large residuals weighted down; bisquare (Tukey): residuals beyond the tuning constant get no weight')] = 'huber', tuning: Annotated[float | None, Widget('number', min=0.1, max=20, step=0.1, advanced=True, help="the norm's tuning constant, in scaled residuals; empty = 1.345 (Huber) or 4.685 (bisquare), 95% efficient with normal errors; smaller is more robust")] = None, scale: Annotated[float | None, Widget('number', min=0, max=1000000000000.0, advanced=True, help="the errors' scale, held fixed; empty = estimated by the MAD of the residuals and updated each iteration")] = None, max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='iterations of reweighted least squares')] = 200, tol: Annotated[float, Widget('number', min=1e-15, max=0.01, advanced=True, help='convergence: the largest change in the coefficients and the scale, relative to 1 + their size')] = 1e-10)
Robust regression (M-estimation): Huber's norm or Tukey's bisquare, the scale estimated by the MAD.
Large residuals are down-weighted (Huber) or, beyond the tuning constant, given no weight at all (bisquare), so
a few outlying values of the dependent variable do not drive the fit. Huber's estimate is unique; the bisquare's
objective is not convex, so it starts from least squares and finds the nearest solution, which is the usual
practice. Neither protects against outlying regressors (leverage points). With normal errors the default tuning
constants lose about 5% efficiency against least squares. The standard errors (Huber's H1) assume the errors are
independent and symmetric; fit.extra["robust_weights"] gives each observation's final weight, and those near
zero are the outliers.
RollingFit
dataclass
¶
RollingFit(equation: Equation, method: Any, window: int | None, fits: Mapping[Period, FittedEquation], failed: Mapping[Period, str])
One fit per window, keyed by the window's last period.
provenance
property
¶
The windows' provenance gathered (as a backtest gathers its re-estimates'): the sample is the windows' last periods, with the first and the last window's estimation samples; observations are the periods any window used; warnings are each window's, once, with the windows where they arose. None if no window was estimated.
Wald
dataclass
¶
Wald(restriction: Annotated[str, Widget('text', help='restrictions on the coefficients, e.g. b1 + b2 = 1; separate several with commas')])
Bases: Test
Wald test of one or more restrictions, e.g. "b1 + b2 = 1, b3 = 0".
Nonlinear restrictions use the delta method. Coefficients are referred to by name, exactly as restricted least
squares names them: const, a term's label (dlog(y), x[-1], log(P)), an explicit-form parameter or
a column of pymetrix.ols(y, X); a name may be put in backticks (`dlog(y)`), and spaces inside it are
optional.
The null is that all the restrictions hold. The statistic uses the fit's own coefficient covariance (robust or HAC if the fit used one) and is chi-squared with as many degrees of freedom as restrictions; when the fit has residual degrees of freedom the F form (the statistic over the number of restrictions, against the residual degrees of freedom) is in the details and is more conservative in small samples. With nonlinear restrictions the result depends on how they are written (b1 / b2 = 1 and b1 = b2 can give different answers), so prefer the linear form when there is one.
Windows
dataclass
¶
Sample windows over the base's own sample: "rolling" windows of size periods, or "recursive" ones
from its start, the first size periods long, each step periods after the last.
Functions¶
bai_perron
¶
bai_perron(fit: Any, max_breaks: int = 5, trim: float = 0.15) -> StructuralBreaks
Bai-Perron multiple structural breaks in a linear equation (see the module notes).
compare
¶
compare(*fits: FittedEquation, test: Literal['lr', 'hausman'] | None = None, sigma: str = 'efficient') -> Table | TestResult
Without test: a table of fit statistics. test="lr": nested likelihood ratio.
test="hausman": consistent fit first, efficient fit second (see _hausman for sigma).
cox_test
¶
The Cox (1961) test, in Pesaran's (1974) form for linear regressions, that the first model is right against the second: a standard normal statistic, large negative values rejecting.
gets
¶
gets(model: Any, data: Dataset, t_pval: float = 0.05, diagnostics: Sequence[str] | str | None = ('autocorrelation', 'arch'), diag_pval: float = 0.025, keep: Sequence[str] | str | None = ('const',), ic: Literal['bic', 'aic', 'hq'] = 'bic', max_paths: int | None = None, wald_pval: float | None = None, ar_lags: int = 4, arch_lags: int = 4, span: Any = None) -> GetsSelection
General-to-specific selection from the general unrestricted model model (an Equation, a formula, or a fitted equation whose sample is then used; linear in
its coefficients, estimated by least squares on data): a multi-path search that deletes insignificant terms
(t-test at t_pval, the target size) while each reduced model passes the encompassing test against the GUM (at
wald_pval, t_pval unless given) and the diagnostics (at diag_pval), backtracking when a deletion
fails; the final model is the terminal model with the smallest ic. keep names terms never deleted
(the constant by default); max_paths limits the paths (None: one for each insignificant term of the GUM).
ar_lags and arch_lags are the lags of the Breusch-Godfrey and ARCH tests. Returns a GetsSelection:
.fit is the final model (a FittedEquation on the GUM's sample), with the record of the search.
isat
¶
isat(model: Any, data: Dataset, iis: bool = True, sis: bool = False, t_pval: float = 0.001, blocks: int = 2, diagnostics: Sequence[str] | str | None = None, diag_pval: float = 0.025, ic: Literal['bic', 'aic', 'hq'] = 'bic', max_paths: int | None = None, wald_pval: float | None = None, ar_lags: int = 4, arch_lags: int = 4, span: Any = None) -> IndicatorSaturation
Indicator saturation: impulse indicators pulse("date") for every observation (iis) and/or step
indicators step("date") for every date but the first (sis), added to the equation model and selected
by GETS at t_pval in blocks blocks (two: split-half), then across the blocks' retained indicators; the
equation's own terms are kept. Returns an IndicatorSaturation: .fit is the final equation with the
retained indicators as terms, .indicators() lists them (detected outliers and breaks, with dates and
coefficients) and .plot() shows the series, the fit and the breaks. Diagnostics are off by default, as in
gets' isat; t_pval 0.001 as there (about 1/T is a common choice: one indicator retained by chance).
j_test
¶
Davidson and MacKinnon's (1981) J test that the first model is right: the t statistic on the second model's fitted values added to the first. Run it both ways; both, or neither, may reject.
kde
¶
kde(data: Dataset, variable: str, bandwidth: float | Literal['silverman', 'scott', 'cv'] = 'silverman', kernel: Literal['gaussian', 'epanechnikov'] = 'gaussian', points: int = 256, cut: float = 3.0, span: Any = None) -> KernelDensity
A kernel density estimate of variable on points points reaching cut bandwidths beyond the data.
kernel_regression
¶
kernel_regression(data: Dataset, outcome: str, regressors: Sequence[str], kind: Literal['ll', 'lc'] = 'll', bandwidth: Any = 'cv', span: Any = None) -> KernelRegression
Kernel regression of outcome on the regressors series: local linear (kind="ll") or Nadaraya-Watson ("lc"), with
bandwidths by cross-validation, the normal reference rule, or given.
ols
¶
ols(y: Any, X: Any, cov: str | Cluster = 'classic', constant: bool = True, weights: Any = None, clusters: Any = None, hac_lags: int | None = None, hac_correction: bool = True, missing: Literal['drop', 'raise'] = 'drop', names: Sequence[str] | None = None) -> Any
Least squares of y on the columns of X, without a formula or a Dataset: for code running many
regressions. Returns the FittedEquation that Equation("y ~ x1 + x2").fit(data, method=OLS(cov=...))
gives on the same data, with the same numbers, views, tests and provenance.
y is a Series (or a 1-d array, named y); X a DataFrame, a Series, a mapping of names to columns, or a
2-d array (columns named by names, else x1, x2...). Pandas inputs must share their index; a
PeriodIndex (or dates with a frequency) makes the data a time series, as in a dataset, and rows are put in
index order. constant adds the intercept const; weights is a series of weights (weighted least
squares, as fit(weights=...)); missing drops (or refuses) rows with a missing value.
cov is as for OLS: "classic", "white" (HC1), "hc0", "hc2" to "hc5", "hac" (Newey-West, time series; hac_lags
and hac_correction as OLS), or Cluster("a") / Cluster("a", "b") (one- or two-way), the names
being columns of clusters (a Series or DataFrame of group labels) or levels of the index; cov="cluster"
clusters by every column of clusters.
Provenance records vintage_request={"policy": "direct"}: the data were passed directly. In a session the
call is recorded as code; the arrays are saved with a project only if you save them there.
omitted_variables
¶
omitted_variables(eq: Any, data: Any, add: str | Sequence[str], method: Any = None, span: Any = None, where: str | None = None, weights: str | None = None) -> TestResult
Test that the regressors add (expressions, comma-separated or a list) are jointly zero when added to the
linear-form equation eq: Wald F (the headline), Wald chi-squared, likelihood-ratio and LM forms (see the module
docstring). method is the equation's estimation method (OLS when None); both fits use it.
partially_linear
¶
partially_linear(data: Dataset, y: str, linear: Sequence[str], nonparametric: Sequence[str], bandwidth: Any = 'cv', span: Any = None) -> PartiallyLinear
Robinson's (1988) estimator of y = x'b + g(z) + e: b by least squares of y - E[y|z] on x - E[x|z], the conditional means by Nadaraya-Watson (bandwidths by cross-validation on y, or given); g by kernel regression of y - x'b on z.
pymetrix.extension.numerical_hessian
¶
Central-difference Hessian of a scalar function.
pymetrix.extension.point_estimate
¶
point(names: Sequence[str], values: Sequence[float], cov: ndarray | None = None, aliases: Mapping[str, str] | None = None) -> PointEstimate
quantile_process
¶
quantile_process(eq: Equation, data: Dataset, quantiles: Sequence[float] = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9), span: Any = None, vcov: str = 'robust', alpha: float = 0.1) -> QuantileProcess
Quantile regressions at each of quantiles, with least squares for comparison.
specification_grid
¶
specification_grid(base: Any, data: Any, vary: Mapping[str, Any] | None = None, quantity: Any = None, specifications: Sequence[Mapping[str, Any]] | None = None, span: Any = None, method: Any = None, alpha: float = 0.05, criterion: Literal['bic', 'aic'] = 'bic', diagnostics_alpha: float = 0.05, max_lags: int = 8, workers: int | None = None, keep_fits: bool = False) -> SpecificationResults
Fit base again for every combination of the choices in vary (lags, samples, deterministic terms, ranks,
identifications, controls, estimators) and compare one quantity across the fits: see pymetrix.sensitivity.
vary maps each dimension to its choices (every combination is run) or specifications lists them, each a
dict of choices. span and method: the base's sample and estimator, when base is not fitted. alpha:
the intervals' level (1 - alpha); criterion: the information criterion marked; diagnostics_alpha: the diagnostics'
level; max_lags: the largest lag a criterion searches. workers=n: in n processes. keep_fits: keep
each fit (fits).
Results¶
BootstrapReport
dataclass
¶
BootstrapReport(kind: str, procedure: str, requested: int, succeeded: int, failed: int = 0, explosive: int = 0, redrawn: int = 0, handling: str = '', seed: int | None = None, block_length: int | None = None, wild_dist: str | None = None, design: str = 'recursive', bias_correct: bool = False, bias_shrink: float | None = None, interval: str = 'percentile', coverage: float | None = None, workers: int | None = None, messages: tuple[str, ...] = (), rank: int | None = None, rank_kept: int | None = None)
What a bootstrap did: the procedure, the draws requested and used, the failures and how they were handled.
Draws
dataclass
¶
Posterior or bootstrap draws; rows are draws, columns parameters.
FittedEquation
dataclass
¶
FittedEquation(equation: Equation, params: Params, method: Any, resid: Series | None = None, fitted: Series | None = None, stats: Mapping[str, float] = dict(), provenance: Provenance | None = None, design: DataFrame | None = None, weights: str | None = None, extra: Mapping[str, Any] = dict(), backend_result: Any = None)
Bases: BackendResult
plot
¶
Actual, fitted and residuals (time series), or actual against fitted (cross-sections).
qq_plot
¶
The residuals against the normal distribution (a Q-Q plot): they lie along the dashed line if normal.
algebraic
¶
algebraic(style: Literal['unicode', 'latex'] = 'unicode', estimates: bool = False, digits: int = 4) -> str
The equation in algebraic notation; estimates=True puts the estimated values in place of the
coefficients (cₜ = 9.632 + 0.6425 yₜ + 0.1456 cₜ₋₁).
to_frame
¶
One of the result's views as a DataFrame: Coefficients (the default), Statistics, Summary,
Covariance... (the tabs of its window; case does not matter).
from_statsmodels
classmethod
¶
from_statsmodels(res: Any, data: Any = None, command: str | None = None) -> FittedEquation
A FittedEquation from a statsmodels regression result (see pymetrix.interop.from_statsmodels).
breaks
¶
Bai-Perron multiple structural breaks at unknown dates, the number chosen by BIC (stats.breaks).
marginal_effects
¶
marginal_effects(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) -> Table
Marginal effects of a linear equation, logit, probit, Poisson or limited dependent variable model
(estimation.margins): averaged over the sample, at the means, or at chosen values (at={"age": [30, 40]});
discrete changes (change={"income": (10, 20)}); with respect to the variables the terms are built from.
predictive_margins
¶
predictive_margins(at: Literal['average', 'mean'] | Mapping[str, Any] = 'average', alpha: float = 0.05, data: Dataset | None = None, atmeans: bool = False, contrast: bool = False) -> Table
Predictive margins (estimation.margins): the predicted E[y] or probability at each profile of at.
predict
¶
predict(data: Dataset, span: tuple[Any, Any] | None = None, dynamic: bool = False, kind: Literal['response', 'index'] = 'response', unseen: Literal['nan', 'raise'] = 'nan') -> Series
Static: fitted values of the left-hand side (for Logit/Probit/Poisson, the
probability or mean unless kind="index"). Dynamic: simulate the target variable.
With ARMA errors or GARCH variance: the forecast mean of the left-hand side.
C() and fe() terms use the levels the fit saw: a C() level it did not see is an error, and a
fixed effect's level it did not see gives a missing prediction (unseen="nan") or an error
(unseen="raise").
forecast
¶
forecast(data: Dataset, span: tuple[Any, Any], dynamic: bool = False, coverage: float = 0.95, uncertainty: Literal['auto', 'analytic', 'simulation'] = 'auto', draws: int | None = None, seed: int | None = 0, errors: Literal['normal', 'bootstrap'] = 'normal', coefficients: bool = True, unseen: Literal['nan', 'raise'] = 'nan') -> Dataset
Forecasts of the left-hand side with standard errors and a (coverage) interval.
Static forecasts use actual lagged values; their standard errors include residual and parameter uncertainty
(coefficients=False: residual only). Dynamic forecasts use their own earlier forecasts of the target
variable. Their standard errors are analytic where the equation is linear in the target's lags (y ~ y[-1] +
y[-2] + x, a single time series): the shocks through the moving-average weights of the lag polynomial, and
the coefficients' uncertainty by the delta method along the forecast path (coefficients=False: the
shocks only, as statsmodels' AutoReg and ARIMA give). Otherwise (a transformed left-hand side such
as dlog(c), a nonlinear function of a lag, explicit form) they come from a stochastic simulation of the
equation as a one-equation model (Model.solve(draws=...)): draws paths (1,000 unless given), errors
drawn "normal" or "bootstrap" (the residuals resampled: pymetrix.bootstrap's residual kind, for the
shocks only), and with coefficients the coefficients drawn from their normal approximation once a path (not
re-estimated: bootstrap(...) bootstraps the coefficients); the interval is then the draws' quantiles, the same each time for a seed (0 unless
given; None for fresh draws).
uncertainty chooses: "auto" (analytic where it can be), "analytic" or "simulation".
C() and fe() terms use the levels the fit saw: an unseen C() level is an error, an unseen fixed
effect's level gives a missing forecast (unseen="nan") or an error (unseen="raise"); the fixed
effects are taken as known (their estimation error is not in the standard errors).
bootstrap
¶
Bootstrap intervals and standard errors for the coefficients of a linear OLS fit, beside its analytic ones:
a table of the estimates, their standard errors, the bootstrap standard errors and percentile, Hall's and
studentized (bootstrap-t) intervals at 1 - alpha, with the bootstrap's report (.bootstrap).
kind is a Bootstrap(...) or one of: "pairs" (rows drawn with replacement, regressand and regressors
together: valid under heteroskedasticity; with block_length, blocks of rows for time series),
"residual" (fixed design, the centred residuals drawn with replacement: iid errors), "wild" (fixed
design, each residual times a Rademacher, Mammen or normal multiplier: heteroskedasticity of unknown form) and
"block" (fixed design, blocks of consecutive residuals: dependent errors in time series). Each draw is
re-estimated with the fit's own covariance (classic, White, HC or HAC), which the bootstrap-t uses. draws
and seed fill a Bootstrap whose own are None. For OLS without weights, restrictions, absorbed fixed
effects or clustered errors (see pymetrix.bootstrap).
test
¶
test(name: str, *args: Any, **opts: Any) -> TestResult
Run a registered test on this fit by name, e.g. fit.test("breusch_godfrey", lags=4) or
fit.test("chow", at="2008Q1"); tests() lists the ones that apply.
GetsSelection
dataclass
¶
GetsSelection(fit: Any, gum: Any, steps: DataFrame, terminal: DataFrame, gum_diagnostics: DataFrame, kept: tuple[str, ...] = (), deleted: tuple[str, ...] = (), union: tuple[str, ...] = (), settings: dict[str, Any] = dict(), provenance: Any = None)
General-to-specific selection: the final model (fit), the GUM, and the record of the search: each path's
deletions in order with the test that allowed or blocked each one (steps), the terminal models with their
information criteria (terminal), and the diagnostics of the GUM (gum_diagnostics).
stats
property
¶
The final model's statistics, with the search's: terminal models, paths, the GUM's size.
summary
¶
summary() -> Table
The final model, each term with why it was kept; then the terms deleted, and the search in brief.
paths
¶
paths() -> Table
Each path's deletions in order: the term, its t-test p-value, whether it was deleted, and the test that allowed (every check passed) or blocked (the first that failed, with its p-value) the deletion.
terminals
¶
terminals() -> Table
The terminal models: their terms, size, log likelihood and information criteria; the one chosen.
IndicatorSaturation
dataclass
¶
IndicatorSaturation(fit: Any, gum: Any, steps: DataFrame, terminal: DataFrame, gum_diagnostics: DataFrame, kept: tuple[str, ...] = (), deleted: tuple[str, ...] = (), union: tuple[str, ...] = (), settings: dict[str, Any] = dict(), provenance: Any = None, blocks: DataFrame = DataFrame(), retained: DataFrame = DataFrame(), candidates: int = 0)
Bases: GetsSelection
Indicator saturation: the final model with the retained impulse (outliers) and step (breaks) indicators as
terms; blocks records each block's search, retained the indicators kept by the final search.
indicators
¶
indicators() -> Table
The retained indicators: kind (impulse: an outlier; step: a break in the level), date, coefficient, standard error, t and p-value in the final model.
block_record
¶
block_record() -> Table
Each block's search: its indicators, how many it retained and which.
plot
¶
The series with the final model's fitted values, the retained breaks marked by vertical lines and the outliers by points.
KernelDensity
dataclass
¶
KernelDensity(variable: str, grid: ndarray, density: ndarray, bandwidth: float, kernel: str, rule: str, x: ndarray, provenance: Any = None)
A kernel density estimate on a grid.
plot
¶
The density, with the normal of the same mean and variance for comparison.
KernelRegression
dataclass
¶
KernelRegression(y_name: str, x_names: tuple[str, ...], kind: str, bandwidth: ndarray, fitted: Series, gradient: DataFrame, resid: Series, r2: float, bandwidth_rule: str, X: ndarray, y: ndarray, provenance: Any = None)
A kernel regression: fitted conditional means (and local-linear gradients) at the data.
MonteCarloResult
dataclass
¶
MonteCarloResult(spec: MonteCarlo, draws: DataFrame, failures: Mapping[int, str], notes: tuple[str, ...] = (), random_generator: str = 'pcg64')
The outcome of a Monte Carlo experiment: each replication's quantities (draws; failed ones are missing).
PartiallyLinear
dataclass
¶
PartiallyLinear(y_name: str, linear: tuple[str, ...], nonparametric: tuple[str, ...], params: ndarray, cov: ndarray, bandwidth: ndarray, g: Series, resid: Series, Z: ndarray, provenance: Any = None)
Robinson's partially linear model y = x'b + g(z) + e.
PointEstimate
dataclass
¶
PointEstimate(names: tuple[str, ...], values: ndarray, cov: ndarray | None = None, aliases: Mapping[str, str] | None = None)
pymetrix.estimation.QuantileProcess
dataclass
¶
Coefficients across quantiles, with OLS for comparison.
provenance
property
¶
Least squares' provenance (every quantile is fitted on the same sample), with the quantiles as the method and each fit's warnings, once, with the quantiles where they arose.
plot
¶
Each coefficient across quantiles with a (1 - alpha) band, and the OLS estimate as a dashed line.
SemiparametricGARCH
dataclass
¶
SemiparametricGARCH(variable: str, params: ndarray, cov: ndarray, qml: ndarray, qml_se: ndarray, density: KernelDensity, volatility: Series, loglike: float = 0.0, rounds: int = 1, draws: int = 0, provenance: Any = None)
GARCH(1, 1) estimated with the kernel density of its standardised shocks, beside the Gaussian QML fit.
SpecificationResults
dataclass
¶
SpecificationResults(kind: str, quantity: str, dimensions: tuple[str, ...], settings: DataFrame, estimates: ndarray, se: ndarray, lower: ndarray, upper: ndarray, ic: DataFrame, checks: DataFrame, errors: tuple[str | None, ...], base: int | None = None, alpha: float = 0.05, criterion: str = 'bic', horizons: tuple[Any, ...] = (), nobs: tuple[int, ...] = (), samples: tuple[str, ...] = (), fits: tuple[Any, ...] = (), diagnostics_alpha: float = 0.05, choices: Mapping[str, tuple[Any, ...]] = dict(), provenance: Any = None)
Every specification's estimate of one quantity, side by side: see the module docstring.
settings holds each specification's choice in each dimension (as labels), estimates its estimate (a row per
specification; a column per horizon for a path), with se, lower and upper (NaN where the fit gives
none), ic its information criteria and checks its diagnostics. base is the base specification's row,
errors the error of each run that failed (None where it ran).
best
property
¶
The row of the specification with the smallest information criterion (criterion) among those that ran;
marked in the tables and the curve, as one specification among the others, not as the answer.
values
¶
Each specification's estimate, standard error and interval (at horizon for a path: by default the
horizon where the base's response is largest in size).
frame
¶
The settings, the estimate, its standard error, interval and significance, the information criteria, the diagnostics, the observations, which row is the base and which has the smallest criterion, and any error.
robustness
¶
The numbers of summary: the share of the specifications that ran with the base's sign (the median's,
without a base), the share significant, the median, range, and the base's and lowest-criterion estimates.
summary
¶
summary(horizon: Any = None) -> Table
How robust the estimate is: the share of specifications with the base's sign, the share significant, the median and range, and the dimension that moves it most.
dimension_shares
¶
Each dimension's share of the variance of the estimates: the variance of the means by its choices over the total (eta squared), largest first. In a full grid of main effects they add up to one; less, by the interactions.
by_dimension
¶
by_dimension(horizon: Any = None) -> Table
For each dimension and choice: the number of specifications, the mean, median and range of the estimate, the share significant; and each dimension's share of the variance of the estimates.
curve
¶
The specification curve (Simonsohn, Simmons and Nelson 2020): the estimates sorted by size with their intervals, the base and the lowest-criterion specification marked; below, which choice each one uses.
fan
¶
For a path (an impulse response): every specification's path in grey, the base's highlighted, the lowest-criterion one dashed, and the range across the specifications shaded.
StructuralBreaks
dataclass
¶
StructuralBreaks(fit: FittedEquation, trim: float, by_count: DataFrame, chosen: int, breakpoints: tuple[int, ...], index: PeriodIndex, provenance: Any = None)
Bai-Perron multiple breaks in a linear equation: the best dates for each number of breaks, and the number chosen by BIC.
TestResult
dataclass
¶
TestResult(name: str, null: str, statistic: float, df: Any, p_value: float | None, distribution: str = '', critical_values: Mapping[str, float] = dict(), details: Mapping[str, Any] = dict(), provenance: Any = None, backend_call: Any = None)