statspai.postestimation¶
postestimation ¶
Post-estimation tools for StatsPAI.
Provides: - margins(): Average Marginal Effects (AME), Marginal Effects at the Mean (MEM) - marginsplot(): Visualize marginal effects - test(): Wald / F test for linear restrictions (beta1 = beta2, joint significance) - lincom(): Linear combinations of coefficients with inference
Equivalent to Stata's margins, test, lincom commands.
margins_table ¶
margins_table(result, data: Optional[DataFrame] = None, variables: Optional[List[str]] = None, at: Optional[Dict[str, Any]] = None, method: str = 'ame', eps: float = 1e-05, alpha: float = 0.05)
Marginal-effects result that pipes straight into sp.regtable.
Thin adapter over :func:margins: computes the marginal effects
(same kwargs), then wraps the resulting DataFrame in a
:class:_MarginsResult exposing params / std_errors /
tvalues / pvalues / conf_int_* so that
sp.regtable(margins_table(model)) produces a publication-quality
marginal-effects table — closing the "estimator → margins table"
gap that previously required users to hand-build add_rows.
Mirrors the R workflow modelsummary(avg_slopes(model)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
EconometricResults
|
Fitted model — same input |
required |
data
|
Optional[DataFrame]
|
Forwarded verbatim to :func: |
None
|
variables
|
Optional[DataFrame]
|
Forwarded verbatim to :func: |
None
|
at
|
Optional[DataFrame]
|
Forwarded verbatim to :func: |
None
|
method
|
Optional[DataFrame]
|
Forwarded verbatim to :func: |
None
|
eps
|
Optional[DataFrame]
|
Forwarded verbatim to :func: |
None
|
alpha
|
Optional[DataFrame]
|
Forwarded verbatim to :func: |
None
|
Returns:
| Type | Description |
|---|---|
_MarginsResult
|
A duck-typed result object usable directly as a positional
argument to :func: |
Examples:
event_study_table ¶
event_study_table(result, *, regex: Optional[str] = None, label_fmt: str = 't={t}', include_reference: bool = False)
Adapter that turns an event-study fit into a regtable input.
Two extraction paths:
-
CausalResult fast path — when
result.model_infocarries an"event_study"DataFrame (the canonical shape produced by :func:sp.event_study), read itsrelative_time/estimate/se/ci_lower/ci_upper/pvaluecolumns directly. Reference period (estimate==0andse==0) is dropped by default (setinclude_reference=Trueto keep it visible). -
Regex path — when
regexis provided, scanresult.params.indexfor coefficients matching the pattern and use the first capture group as the relative time.
Rows are sorted by relative time (so the rendered table reads
t=-3, t=-2, …, t=+3 regardless of the underlying coefficient
name encoding).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
CausalResult or EconometricResults
|
Fitted model. The CausalResult fast path is used automatically
when |
required |
regex
|
str
|
Pattern with one capture group that matches the relative time
in coefficient names. Required when the CausalResult fast path
is not applicable. Examples: |
None
|
label_fmt
|
str
|
Format string for the row label of each event-time bin. The
|
``"t={t}"``
|
include_reference
|
bool
|
Whether to render the reference period row (typically
|
False
|
Returns:
| Type | Description |
|---|---|
_MarginsResult
|
Duck-typed result accepted directly by :func: |
Examples:
marginsplot ¶
marginsplot(margins_df: DataFrame, ax=None, figsize: tuple = (8, 5), color: str = '#2C3E50', title: Optional[str] = None)
Plot marginal effects with confidence intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
margins_df
|
DataFrame
|
Output from |
required |
ax
|
matplotlib Axes
|
|
None
|
figsize
|
tuple
|
|
(8, 5)
|
color
|
str
|
|
'#2C3E50'
|
title
|
str
|
|
None
|
Returns:
| Type | Description |
|---|---|
(fig, ax)
|
|
margins_at ¶
Compute predictive margins at specific covariate values.
Equivalent to Stata's margins, at(experience=(1 5 10 15 20)).
For each combination of at values, every observation has the at variables set to those values while all other covariates stay at their observed levels. The predicted value is averaged across observations to give the predictive margin at that point, with delta-method SEs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
EconometricResults
|
Fitted model result (must have |
required |
data
|
DataFrame
|
Data to compute margins on. |
required |
at
|
dict
|
Mapping of variable names to lists/arrays of values. If multiple variables are given, the Cartesian product of all value lists is used. Example:: produces 6 grid points. |
required |
alpha
|
float
|
Significance level for confidence intervals. |
0.05
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per grid point with columns for each at variable,
plus |
Examples:
margins_at_plot ¶
margins_at_plot(margins_at_df: DataFrame, x: Optional[str] = None, by: Optional[str] = None, ax=None, figsize: tuple = (8, 5), title: Optional[str] = None, xlabel: Optional[str] = None, ylabel: str = 'Predicted Value', palette: Optional[List[str]] = None)
Plot predictive margins from margins_at() with confidence bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
margins_at_df
|
DataFrame
|
Output from |
required |
x
|
str
|
Variable to place on the x-axis. If None, inferred as the at-variable with the most unique values. |
None
|
by
|
str
|
Variable to produce separate lines for (legend grouping). |
None
|
ax
|
matplotlib Axes
|
|
None
|
figsize
|
tuple
|
|
(8, 5)
|
title
|
str
|
|
None
|
xlabel
|
str
|
|
None
|
ylabel
|
str
|
|
'Predicted Value'
|
palette
|
list of str
|
Colours for each |
None
|
Returns:
| Type | Description |
|---|---|
(fig, ax)
|
|
contrast ¶
contrast(result, data: DataFrame, variable: str, method: str = 'r', reference: Any = None, alpha: float = 0.05) -> DataFrame
Compute contrasts of predictive margins across levels of a variable.
Equivalent to Stata's margins <var>, contrast(ar) / contrast(r).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
EconometricResults
|
Fitted model result. |
required |
data
|
DataFrame
|
Estimation data. |
required |
variable
|
str
|
Categorical variable whose levels are contrasted. |
required |
method
|
str
|
Contrast type:
|
'r'
|
reference
|
scalar
|
Reference level when |
None
|
alpha
|
float
|
Significance level. |
0.05
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: |
Examples:
pwcompare ¶
pwcompare(result, data: DataFrame, variable: str, adjust: str = 'none', alpha: float = 0.05) -> DataFrame
Pairwise comparisons of predictive margins across all levels.
Equivalent to Stata's pwcompare <var>.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
EconometricResults
|
Fitted model result. |
required |
data
|
DataFrame
|
Estimation data. |
required |
variable
|
str
|
Categorical variable whose levels are compared pairwise. |
required |
adjust
|
str
|
P-value adjustment method:
|
'none'
|
alpha
|
float
|
Significance level for (adjusted) confidence intervals. |
0.05
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: |
Examples:
test ¶
Wald test for linear restrictions on coefficients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
EconometricResults or CausalResult
|
Fitted model with |
required |
hypothesis
|
str
|
Hypothesis specification. Examples:
- |
required |
Returns:
| Type | Description |
|---|---|
dict
|
|
Examples:
lincom ¶
Estimate a linear combination of coefficients with inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
EconometricResults or CausalResult
|
Fitted model. |
required |
expression
|
str
|
Linear combination. Examples:
- |
required |
alpha
|
float
|
Significance level. |
0.05
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Examples:
postestimation_contract ¶
postestimation_contract(result: Any, *, data: Optional[DataFrame] = None, include_diagnostics: bool = True) -> Dict[str, Any]
Return the post-estimation actions supported by result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
object
|
Fitted StatsPAI result, estimator, or compatible object. |
required |
data
|
DataFrame
|
Analysis frame available for data-dependent actions. When
supplied, the contract marks |
None
|
include_diagnostics
|
bool
|
Include scalar diagnostics from |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
Machine-readable contract with |