plm: panel regression (spreg, linearmodels, R)

The user guide of this module: plm.

class apatools.plm.PanelData(y, x, ent, tim, w, N, T, entities, times)[source]

Bases: object

Balanced panel in the long layout used by spreg: T consecutive blocks (periods) of N rows (entities), the entities in the order of the rows of the weights w.

Usually created by make_panel() (called by plm(), which stores the instance on every fitted model as plm_panel).

y

Dependent variable (float), MultiIndex (entity, time) with level names "entity" and "time", sorted by period first and then by entity.

Type:

pandas.Series

x

Predictors (float, without constant), same index.

Type:

pandas.DataFrame

ent, tim

Entity / period position (0..N-1 / 0..T-1) of every row.

Type:

numpy.ndarray

w

Weights aligned with the entities (w.n == N), or None.

Type:

libpysal.weights.W or None

N, T

Number of entities and of periods; len(y) == N * T.

Type:

int

entities, times

Labels of the entities (in layout order) and of the periods (sorted).

Type:

list

subset(keep)[source]

Panel restricted to the rows keep (boolean mask). Must remove whole entities and/or whole periods so that the panel stays balanced; w is restricted accordingly.

Parameters:

keep (array-like of bool) – Mask with one element per row of the panel.

Returns:

PanelData – New panel (the positions ent / tim are renumbered from 0; w is restricted with the original weight values kept, and the original transformation re-applied).

Raises:

ValueError – If the kept rows do not form a balanced rectangle (entities x periods).

apatools.plm.make_panel(data, y=None, x=None, entity=None, time=None, w=None, formula=None, dropna=True, balance='error', w_ids=None)[source]

Convert a long DataFrame into a PanelData in the layout needed by spreg.

The rows are sorted by period first and then by entity; the entities are ordered like the rows of w (with w) or sorted (without w; in order of appearance if they cannot be sorted). Rows with a missing entity or period label are dropped.

Parameters:
  • data (pandas.DataFrame) – Long data. The index must be unique if formula is used.

  • y (str) – Dependent variable (ignored if formula is given).

  • x (list of str) – Predictors, without constant (ignored if formula is given).

  • entity (str, optional) – Columns (or index levels) identifying entity and period. Pass both or none; if both are None, the index must be a two-level (entity, time) MultiIndex.

  • time (str, optional) – Columns (or index levels) identifying entity and period. Pass both or none; if both are None, the index must be a two-level (entity, time) MultiIndex.

  • w (libpysal.weights.W, optional) – Spatial weights. The entity values must be the ids w.id_order (or w_ids); entities missing in the data are removed from w (with a UserWarning).

  • formula (str, optional) – patsy formula ("y ~ x1 + x2"); the intercept is dropped (spreg and linearmodels handle constants themselves). Rows with NAs are always dropped by patsy.

  • dropna (bool, default True) – Drop rows with missing values in y/x (not used with formula).

  • balance ({"error", "drop"}, default "error") – What to do with entities that are not observed in every period: raise a ValueError or drop these entities (with a UserWarning).

  • w_ids (sequence, optional) – Entity labels in the row order of w. Default: w.id_order.

Returns:

PanelData – The balanced panel (N entities, T periods, N * T rows).

Raises:
  • ValueError – For an invalid balance / entity / time combination, a MultiIndex of the wrong shape, duplicated (entity, time) pairs, an unbalanced panel with balance="error", entities that are not ids of w, or missing y/x.

  • KeyError – If entity / time is neither a column nor an index level.

apatools.plm.base_metrics(r, panel=None)[source]

Fit metrics of a fitted panel model of either backend.

Keys (where available): model, backend, r_sq and r_sq_type ("ols": pooled R², "within": R² of the within-transformed data of an FE model, "overall": R² of a RE model with linearmodels, "pseudo": spreg pseudo R², the squared correlation of observed and predicted y), r_sq_adj, f_stat, f_pvalue, df_model, df_resid (FE: N·T - N - k), aic, bic, llf (spreg: they do not count the N fixed effects), n_obs (= N·T), n_entities, n_periods, n_params (slope coefficients), mae and mad (median absolute deviation of the residuals).

Residuals (mae, mad) follow the estimator: for non-spatial FE models (both backends) they are the residuals of the within model, i.e. they include the estimated entity effects; for pooled and RE models they are y - x·β (spreg) or the backend’s residuals (linearmodels). spreg’s own PanelFE reports y - x·β and a pseudo R² that ignore the effects, so the within R² and the residuals are recomputed here. spreg’s FE standard errors use N·T - N instead of N·T - N - k degrees of freedom (slightly too small), and its confidence intervals / p-values are normal-based.

Parameters:
  • r (fitted model) – A result of plm() (spreg panel model or linearmodels PanelEffectsResults / PanelResults).

  • panel (PanelData, optional) – Not used (kept so that base_metrics(r, panel) has the same call as the other helpers).

Returns:

dict – See above. f_stat / f_pvalue / df_model / df_resid are missing for spatial and random-effects models (and for the linearmodels random-effects model); r_sq_adj exists for pooled OLS and non-spatial FE models only; aic / bic exist only for spreg models that report them, llf if the backend provides a finite log-likelihood.

Notes

The F test of an FE model compares the within R² with df_model = k and df_resid = N·T - N - k. With period effects (effects="time" or "twoway" of plm(), both backends) R² is the within R² after removing all effects and df_resid = N·T - A - k with A the number of effects estimated away (N + T - 1 for two-way, T for time effects with the constant). The linearmodels F statistic follows the covariance type of the fit (robust version if the covariance is not "Unadjusted").

apatools.plm.pred_metrics(results, panel, backend='spreg', group='entity', exclude_neighbors=False, **kwargs)[source]

Leave-one-group-out prediction metrics (R²pred, MAEpred, MADpred) for panel models.

Leave-one-observation-out is not meaningful for panels: the other periods of the same entity leak into the training sample. Instead whole groups are held out in turn, the model (and the weights) are refitted without them and their rows are predicted:

  • group="entity": one entity at a time (all its periods). Predicts a new entity, so it is not possible for fixed-effects models (an entity effect cannot be estimated); their metrics are nan with a warning.

  • group="time": one period at a time (all entities). Works for every model; fixed effects are estimated from the remaining periods.

Predictions are x·β plus the constant, plus ρ·(Wy) for spatial lag models (observed y of the neighbours in the same period, original weights) and plus the entity effect for FE models. Random-effects models use the population-average predictor (no entity effect). Models with slx_lags are not supported.

Warning

With spatial data the neighbours of a held-out entity stay in the training sample, which makes group="entity" optimistic (see apatools.slm.pred_metrics()). exclude_neighbors=True additionally removes the neighbours of the held-out entity from the training sample (only for group="entity"; needs w).

Cost: one refit per group and model.

Parameters:
  • results (list) – Fitted models (from plm()), whose type determines the model names.

  • panel (PanelData) – The panel the models were fitted on (results[i].plm_panel).

  • backend ({"spreg", "linearmodels"}, default "spreg") – Estimation package used to refit the models.

  • group ({"entity", "time"}, default "entity") – Which groups are held out in turn.

  • exclude_neighbors (bool, default False) – Also remove the neighbours (according to panel.w) of the held-out entity from the training sample; needs group="entity" and weights (ValueError otherwise).

  • **kwargs – The model arguments passed to plm() (<model>_model_<argument> etc.). slx_lags > 0 raises NotImplementedError.

Returns:

list of dict – One dict per model with pred_loo_r_sq (clipped to [-1, 1]), pred_loo_mae and pred_loo_mad (median absolute deviation of the prediction errors); all nan for models that could not be refitted (FE models with group="entity", or every refit failed). Refits that fail are skipped and reported in a UserWarning; another warning reports training weights with islands.

Notes

A cross-validation-style metric (leave-one-group-out). With e the prediction errors of all held-out rows, pred_loo_r_sq = 1 - Σ e² / Σ (y - ȳ)² (ȳ: mean of all y, the sums run over the predicted rows), pred_loo_mae = mean(|e|) and pred_loo_mad = median(|e - median(e)|).

References

Roberts, D. R., Bahn, V., Ciuti, S., Boyce, M. S., Elith, J., Guillera-Arroita, G., Hauenstein, S., Lahoz-Monfort, J. J., Schröder, B., Thuiller, W., Warton, D. I., Wintle, B. A., Hartig, F., & Dormann, C. F. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913-929. https://doi.org/10.1111/ecog.02881

apatools.plm.plm(data, y=None, x=None, w=None, entity=None, time=None, model='fe', formula=None, backend='spreg', **kwargs)[source]

Fit panel regressions (pooled, fixed effects, random effects, optionally spatial).

The data are converted with make_panel() (balanced panel in the layout of spreg) and every requested model is fitted on it. Spatial models: spatial lag with fixed or random effects (Elhorst, 2003, 2014), spatial error with pooled, fixed or random effects by maximum likelihood (Anselin, 1988) or the generalized-moments estimator of Kapoor, Kelejian and Prucha (2007).

Parameters:
  • data (pandas.DataFrame) – Long panel data with an entity and a time column (or an (entity, time) index).

  • y (str) – Dependent variable; ignored if formula is given.

  • x (list of str) – Predictors (no constant); ignored if formula is given.

  • w (libpysal.weights.W, optional) – Spatial weights (required for the slm_* / sem_* models). The entity values must be its ids (w.id_order), or pass w_ids. See make_panel().

  • entity (str, optional) – Entity and period columns (or index levels). Both None: use the two-level index.

  • time (str, optional) – Entity and period columns (or index levels). Both None: use the two-level index.

  • model (str or list of str) – Any of pooled, fe, re, slm_fe, slm_re, sem_pooled, sem_fe, sem_re, sem_pooled_gm, sem_re_gm (see the module docstring); linearmodels supports pooled, fe, re.

  • formula (str, optional) – patsy formula; overrides y/x.

  • backend ({"spreg", "linearmodels", "splm"}) – Estimation package. "linearmodels" is an optional dependency and allows e.g. fe_fit_cov_type="clustered" or fe_fit_cluster_entity=True, and time or two-way fixed effects (effects). "splm" uses R (packages plm, splm, spdep) through Rscript; the results are apatools.r.splm.SplmFit objects instead of spreg or linearmodels results.

  • **kwargs – Function options (below) and arguments for the backend named <model>_model_<argument> (passed to the model class, e.g. slm_fe_model_method="LU"; with "splm" to plm::plm / splm::spml, e.g. slm_fe_model_zero.policy=True) or <model>_fit_<argument> (passed to .fit(), linearmodels only), where <model> is one of the names above.

  • effects ({"entity", "time", "twoway"}, default "entity") –

    Effects of the fixed-effects models (fe, slm_fe, sem_fe): entity (the usual within model), time (period) or both (two-way fixed effects); the other models ignore it. Where each is available:

    model

    spreg

    linearmodels

    splm (R)

    fe

    entity, time, twoway

    entity, time, twoway

    entity, time, twoway

    slm_fe

    entity, twoway

    not available

    entity, time, twoway

    sem_fe

    entity, time, twoway

    not available

    entity, time, twoway

    all other models

    ignored

    ignored

    ignored

    linearmodels: sets its arguments entity_effects and time_effects (fe_model_entity_effects / fe_model_time_effects still work and take precedence). splm: sets the argument effect of R’s plm / spml (fe_model_effect takes precedence). spreg has no such option, so the period effects are period dummies added to the regressors (time[<period>] in r.summary; hidden by plm_report()), valid for any spatial weights; "time" is then the pooled model with the dummies (fe and sem_fe; there is no pooled spatial lag model, so not slm_fe), and slx_lags is not available. plm_tests() compares models with period effects by F / likelihood-ratio tests (no Hausman test), and they have no pred_* metrics. The standard errors of spreg’s entity-effects models use N·T - N degrees of freedom (see base_metrics()), so with "twoway" they are slightly too small. The standard errors of rho / lambda come from spreg’s analytic information matrix and understate the sampling spread somewhat in small panels (the within ML estimator is biased towards zero).

  • rscript (str, optional) – backend="splm": path of Rscript (default: the environment variable APATOOLS_RSCRIPT, the PATH and the usual install locations). r_timeout limits the time of every R run (seconds).

  • verbose (bool, default True) – Print the panel dimensions and the model summaries.

  • dropna (bool, default True) – Drop rows with missing values.

  • balance ({"error", "drop"}, default "error") – Entities not observed in all periods: raise an error or drop them.

  • w_ids (sequence, optional) – Entity labels in the row order of w (default w.id_order).

  • slx_lags (int, default 0) – Number of spatial lags of the predictors (spreg models that support it; not with linearmodels).

  • base_metrics (bool, default True) – Compute base_metrics().

  • pred_metrics (bool, default False) – Add leave-one-group-out prediction metrics, see pred_metrics().

  • pred_group ({"entity", "time"}, default "entity") – Group that is held out.

  • pred_exclude_neighbors (bool, default False) – Also hold out the neighbours of the held-out entity (needs w).

Returns:

  • results (list) – One fitted model per entry of model (spreg or linearmodels objects, or SplmFit for R). Each has the attributes plm_panel (the PanelData used) and plm_spec (backend and fitting options), which mundlak() and plm_tests() need.

  • metrics (list of dict) – See base_metrics() (plus pred_loo_* if requested). Empty if neither base_metrics nor pred_metrics is requested.

Raises:
  • ValueError – For an unknown backend or spatial model without w (and the errors of make_panel()).

  • NotImplementedError – For an unknown model name, a spatial model / slx_lags with backend="linearmodels", slx_lags or a GMM model with backend="splm".

  • ImportError – If backend="linearmodels" and linearmodels is not installed, or an R package is missing with backend="splm".

  • RuntimeError – If R is not found or fails (backend="splm").

References

Anselin, L. (1988). Spatial econometrics: Methods and models. Kluwer Academic. https://doi.org/10.1007/978-94-015-7799-1

Elhorst, J. P. (2003). Specification and estimation of spatial panel data models. International Regional Science Review, 26(3), 244-268. https://doi.org/10.1177/0160017603253791

Elhorst, J. P. (2014). Spatial econometrics: From cross-sectional data to spatial panels. Springer. https://doi.org/10.1007/978-3-642-40340-8

Kapoor, M., Kelejian, H. H., & Prucha, I. R. (2007). Panel data models with spatially correlated error components. Journal of Econometrics, 140(1), 97-130. https://doi.org/10.1016/j.jeconom.2006.09.004

Baltagi, B. H. (2021). Econometric analysis of panel data (6th ed.). Springer. https://doi.org/10.1007/978-3-030-53953-5

Examples

>>> results, metrics = plm(
...     df, "y", ["x1", "x2"], w=w, entity="county", time="year",
...     model=["pooled", "fe", "re", "slm_fe"],
...     verbose=True, balance="error", slx_lags=0,
...     base_metrics=True, pred_metrics=True, pred_group="time",
...     slm_fe_model_method="LU",
... )
apatools.plm.plm_report(results, metrics=None, format_pval=True, add_stars=True, decimal=3, add_ftest=True, add_aic=True, add_bic=True, add_llf=True, add_mae=True, add_mad=True, add_pred_loo_mae=True, add_pred_loo_mad=True, add_n_obs=True, add_panel_dims=True, intercept_name='Intercept')[source]

Build one APA-style coefficient table per model from plm() output.

Columns: coef, se, z (or t), p-value, cil, cir (95% CI), optional sig stars. The first row’s model column holds a fit summary such as R²within = .36, R²adj = .34, F(2, 123) = 35.1, p < .001, MAE = ..., N = 150, n = 25, T = 6; R²pred, MAEpred and MADpred appear if plm() was run with pred_metrics=True. R²within is the R² of the within-transformed data (FE), R²overall the overall R² of a random-effects model (linearmodels), R²pseudo the squared correlation of observed and predicted y (spreg, spatial and RE models) and a plain R² is the pooled OLS R². The spatial parameters (rho = ρ of the lag models, lambda = λ of the error models) and the variance parameters of spreg (e.g. phi, sigma2_v) are rows of the table.

Parameters:
  • results (list) – Fitted models (first value returned by plm()).

  • metrics (list of dict, optional) – Metrics (second value returned by plm()), matched with results by position; without them the tables have no model column.

  • format_pval (bool or callable, default True) – False keeps the numeric p-values. True replaces them by APA strings without the p = prefix (".009", "<.001"; apatools.format.format_p()). A callable is applied to every p-value and its return value is used. The stars are always computed from the numeric p-values.

  • add_stars (bool or callable, default True) – False: no sig column. True: add a sig column with significance stars (*** p < .001, ** p < .01, * p < .05, ⁺ p < .10, otherwise an empty string; apatools.format.get_stars()). A callable maps one p-value to the marker.

  • decimal (int or None, default 3) – Round the columns coef, se, cil and cir to this many decimals (the statistic and the p-values are not rounded here). None or 0: no rounding.

  • add_ftest (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_aic (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_bic (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_llf (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_pred_loo_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_pred_loo_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_n_obs (bool, default True) – Include the corresponding part (F test, AIC, BIC, LL, MAE, MAD, MAEpred, MADpred, N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.

  • add_panel_dims (bool, default True) – Append the number of entities and periods, n = ..., T = ....

  • intercept_name (str, default "Intercept") – Row label of the constant (CONSTANT of spreg, const of linearmodels); other labels are unchanged.

Returns:

list of pandas.DataFrame – One table per model, indexed by the coefficient names, with the columns coef, se, z (spreg models other than pooled OLS) or t (pooled OLS and linearmodels), p-value, cil / cir (limits of the 95% confidence interval, confidence level 0.95: normal approximation coef ∓ 1.96 · se for spreg, the interval of linearmodels otherwise), sig (if add_stars) and model (fit summary, first row only, if metrics are given). Fixed effects are not listed as coefficients.

apatools.plm.plm_effects(results, w=None, inference='simulation', n_draws=1000, seed=13, conf_level=0.95, traces='auto', n_probes=50, format_pval=False, add_stars=False, decimal=None)[source]

Direct, indirect and total effects of the regressors of the spatial lag panel models fitted with plm().

In a spatial lag model (slm_fe, slm_re; every backend that fits them: spreg and splm; with spreg also the Durbin model of slx_lags) the coefficient of a regressor is not its effect: a change in one entity also changes its neighbours through ρWy, and their neighbours in turn. LeSage & Pace (2009) summarize the effect matrix by three averages, which Elhorst (2014) uses for panels as well (the weights W of the entities apply in every period): the direct effect (the change of an entity caused by a change of its own regressor, including the feedback through its neighbours), the total effect (the change of an entity caused by a unit change of the regressor in all entities) and the indirect effect, their difference (the spillover). The averages are computed from the traces of the powers of W, without inverting I - ρW; for the Durbin model the effect matrix is (I - ρW)⁻¹ (β_k I + θ_k W).

Parameters:
  • results (list) – Fitted models from plm(). Only the spatial lag models have these effects; the others are skipped with a warning (the coefficients of the spatial error models already are the direct and total effects).

  • w (libpysal.weights.W, optional) – The weights of the entities; by default those stored with the results (the panel’s).

  • inference ({"simulation", "analytic"}, default "simulation") – How the standard errors, z values, p-values and confidence intervals are obtained. "simulation": LeSage & Pace’s simulation, n_draws draws of the coefficients and ρ from their estimated joint normal distribution; the standard error is the standard deviation of the effects of the draws and the confidence interval is made of their percentiles (so it can be asymmetric). "analytic": the delta method with the gradient of the trace series (the interval is estimate ± z · se).

  • n_draws – As in apatools.slm.slm_effects().

  • seed – As in apatools.slm.slm_effects().

  • conf_level – As in apatools.slm.slm_effects().

  • traces – As in apatools.slm.slm_effects().

  • n_probes – As in apatools.slm.slm_effects().

  • format_pval – As in apatools.slm.slm_effects().

  • add_stars – As in apatools.slm.slm_effects().

  • decimal – As in apatools.slm.slm_effects().

Returns:

pandas.DataFrame – One row per model, regressor and effect: the columns model (the model name; a repeated one gets the suffix _2, …), variable, effect ("Direct", "Indirect", "Total"), estimate, se, z, p-value, cil, cir and optionally sig.

Notes

The constant has no effect and is left out, as are the period effects of effects="time" / "twoway" (they are not regressors). The standard errors use the covariance matrix of the coefficients and ρ of the backend: spreg’s covers the coefficients and ρ jointly, that of splm treats ρ as uncorrelated with the coefficients, so the standard errors of the indirect and total effects differ somewhat between the backends. spreg’s estimates of an entity-effects model are those of the within estimator.

The delta method (inference="analytic") treats the effects as linear in the estimates. That holds when ρ is estimated precisely; with few units and a large ρ the standard errors of the indirect and total effects can be far too small (in a 64-unit example with ρ = 0.6 the analytic standard error of an indirect effect was 0.44, against 1.48 by simulation with 100,000 draws and 1.43 in R’s impacts), so prefer the simulation then. The direct effect is much less sensitive. The simulated standard errors of the indirect and total effects are noisy in the same situation, because a few draws of ρ near its bound give huge effects: in that example the standard error of the indirect effect was 1.03 with 5000 draws and 1.48 with 100,000 (R’s own simulation behaves the same way). Raise n_draws and check that the result is stable with another seed.

References

LeSage, J., & Pace, R. K. (2009). Introduction to spatial econometrics. CRC Press. https://doi.org/10.1201/9781420064254 https://doi.org/10.1201/9781420064254

Elhorst, J. P. (2014). Spatial econometrics: From cross-sectional data to spatial panels. Springer. https://doi.org/10.1007/978-3-642-40340-8 https://doi.org/10.1007/978-3-642-40340-8

Examples

>>> results, metrics = plm(df, "y", ["x1", "x2"], w=w, entity="county", time="year", model="slm_fe")
>>> plm_effects(results, inference="analytic", decimal=3)
apatools.plm.hausman(r_fe, r_re)[source]

Hausman test of a fixed- against a random-effects model with the same spatial structure.

Compares the common slope coefficients: H = d' (V_fe - V_re)⁻¹ d ~ χ²(k). Works for both backends. Returns (statistic, df, p-value); statistic and p-value are nan (with a warning) if V_fe - V_re is not positive definite. This is common when the effects are correlated with the predictors (the random-effects variance is then too large), i.e. exactly when the test should reject; use mundlak() in that case.

Parameters:
  • r_fe (fitted models) – Fixed- and random-effects results from plm() of the same backend and spatial structure (e.g. fe and re, or slm_fe and slm_re). The statistic uses the slope coefficients (not the constant, rho, lambda or variance parameters) present in both.

  • r_re (fitted models) – Fixed- and random-effects results from plm() of the same backend and spatial structure (e.g. fe and re, or slm_fe and slm_re). The statistic uses the slope coefficients (not the constant, rho, lambda or variance parameters) present in both.

Returns:

  • statistic (float) – The Hausman statistic H.

  • df (int) – Degrees of freedom, the number of compared slope coefficients.

  • p_value (float) – P(χ²(df) > H).

Raises:

ValueError – If there is no common slope coefficient.

References

Hausman, J. A. (1978). Specification tests in econometrics. Econometrica, 46(6), 1251-1271. https://doi.org/10.2307/1913827

apatools.plm.mundlak(r_re)[source]

Mundlak test of correlated entity effects for a random-effects model.

The model is refitted with the entity means of the (time-varying) predictors added; a Wald test checks that their coefficients are jointly zero. Under the null the random-effects estimator is consistent. The test is the regression-based equivalent of the Hausman test for the slope coefficients, but it stays defined when V_fe - V_re is not positive definite, which is typical when the effects are correlated with the predictors (the random-effects variance is then inflated), and it works for all random-effects models.

Parameters:

r_re (fitted random-effects model (re, slm_re, sem_re_gm, …)) – Must come from plm(), which stores the panel and the fitting options on it.

Returns:

  • statistic (float) – Wald statistic b' V⁻¹ b of the coefficients b (covariance V) of the added <x>_mean regressors; only predictors that vary within entities get a mean.

  • df (int) – Number of added regressors.

  • p_value (float) – P(χ²(df) > statistic).

Raises:

ValueError – If the model does not come from plm() or no predictor varies over time.

References

Mundlak, Y. (1978). On the pooling of time series and cross section data. Econometrica, 46(1), 69-85. https://doi.org/10.2307/1913646

apatools.plm.plm_tests(results, w=None, format_pval=False, add_stars=False, decimal=None)[source]

Specification tests for the models fitted with plm(), as a tidy DataFrame.

Computed where the required models are among results:

  • Hausman FE vs RE (fe/re, slm_fe/slm_re, sem_fe/sem_re) for the common slope coefficients. Null: random effects are consistent. Omitted (with a warning) when V_fe - V_re is not positive definite, see hausman().

  • Mundlak test for every random-effects model, see mundlak(). Null: the effects are uncorrelated with the predictors (random effects are consistent).

  • F test of entity effects (fe vs pooled, non-spatial, same backend). Null: no entity effects.

  • Models with period effects (effects="time" / "twoway"; Hausman and Mundlak need random-effects models with period effects, which are not available): F tests of period effects (twoway vs fe, time vs pooled), of entity effects given period effects (twoway vs time) and of both (twoway vs pooled), for the non-spatial models of the same backend that are among results; likelihood-ratio test of period effects (slm_fe / sem_fe with twoway vs without, T - 1 degrees of freedom). The Baltagi-Song-Koh and Anselin LM tests are available for the pooled model only. The likelihood-ratio statistic is multiplied by the residual degrees of freedom over N·T (the within likelihood counts N·T observations; unscaled it rejects 12-16 % of the time at the 5 % level in simulations with N = 36-100 and T = 6, scaled 6-7 %). Note: the F test of time effects against pooled is conservative when the data have strong entity effects, because they inflate the pooled residuals (in simulations with N = 36, T = 6: 0 % rejections of true nulls at the 5 % level and 87 % power for time effects with an SD of half the error SD, against 7 % and 97 % for twoway vs fe); with entity effects in the data prefer that entity-conditional test.

  • Baltagi-Song-Koh LM tests (spreg, from pooled; need weights): marginal random effects (LM1), marginal spatial error (LM2) and their joint test (LMJ), and the Anselin LM tests for a spatial lag / error (and their robust versions).

Parameters:
  • results (list) – Fitted models from plm().

  • w (libpysal.weights.W, optional) – Weights for the LM tests; by default those stored with the results.

  • format_pval (bool or callable, optional) – True turns the p-values into APA strings (.633, <.001); a callable is used to format each p-value; False (default) keeps the numeric p-values.

  • add_stars (bool or callable, optional) – True adds a sig column with significance stars; a callable maps a p-value to the marker; False (default) adds no column. Computed from the numeric p-values.

  • decimal (int, optional) – Rounds the statistic column to this many decimals; None or 0 (default) keeps the full precision. The report strings are not affected.

Returns:

pandas.DataFrame – Columns test, model, statistic, df, df_denom, p-value (strings unless format_pval=False), optionally sig, and an APA-style string report. The table is empty (with these columns) if none of the tests applies to results. Use format_pval=False, add_stars=False, decimal=None for the raw numbers.

Notes

The model column holds the compared models ("fe vs re") or the model name. df is None for the LM tests with one degree of freedom reported as LM; df_denom is set only for the F test. The Baltagi-Song-Koh and Anselin LM tests need spreg and w. The Baltagi-Song-Koh tests come from spreg (spreg.diagnostics_panel); the Anselin tests are computed here for the stacked pooled model (spreg’s panel versions differ from the textbook statistics). Both agree with R (plmtest, splm::slmtest).

References

Hausman, J. A. (1978). Specification tests in econometrics. Econometrica, 46(6), 1251-1271. https://doi.org/10.2307/1913827

Mundlak, Y. (1978). On the pooling of time series and cross section data. Econometrica, 46(1), 69-85. https://doi.org/10.2307/1913646

Baltagi, B. H., Song, S. H., & Koh, W. (2003). Testing panel data regression models with spatial error correlation. Journal of Econometrics, 117(1), 123-150. https://doi.org/10.1016/s0304-4076(03)00120-9

Breusch, T. S., & Pagan, A. R. (1980). The Lagrange multiplier test and its applications to model specification in econometrics. The Review of Economic Studies, 47(1), 239-253. https://doi.org/10.2307/2297111

Anselin, L., Le Gallo, J., & Jayet, H. (2008). Spatial panel econometrics. In L. Mátyás & P. Sevestre (Eds.), The econometrics of panel data (pp. 625-660). Springer. https://doi.org/10.1007/978-3-540-75892-1_19