fit_linearmodels()
Fit a linearmodels model with output that is compatible with pymarginaleffects.
This function streamlines the process of fitting linearmodels panel models by:
- Parsing panel effects from the formula
- Handling missing values
- Creating model matrices
- Fitting the model with specified options
Parameters
formula
: (str) Model formula with optional panel effects terms.
- Supported effects are:
- EntityEffects: Entity-specific fixed effects
- TimeEffects: Time-specific fixed effects
- FixedEffects: Alias for EntityEffects
- Example:
"y ~ x1 + x2 + EntityEffects"
data
: (pandas.DataFrame) Panel data with MultiIndex (entity, time) or regular DataFrame with entity and time columns.
engine
: (callable) linearmodels model class (e.g., PanelOLS, BetweenOLS, FirstDifferenceOLS)
kwargs_engine
: (dict, default={}) Additional arguments passed to the model initialization.
- Example:
{'weights': weights_array}
kwargs_fit
: (dict, default={}) Additional arguments passed to the model’s fit method.
- Example:
{'cov_type': 'robust'}
Returns
(ModelLinearmodels) A fitted model wrapped in the ModelLinearmodels class for compatibility with marginaleffects.
Examples
from linearmodels.panel import PanelOLS
from linearmodels.panel import generate_panel_data
from marginaleffects import *
= generate_panel_data()
data = fit_linearmodels(
model_robust ="y ~ x1 + EntityEffects",
formula=data.data,
data=PanelOLS,
engine={'cov_type': 'robust'}
kwargs_fit
)
predictions(model_robust)
Notes
The fitted model includes additional attributes: - data: The processed data after listwise deletion - formula: The original formula string - formula_engine: Set to “linearmodels” - model: The fitted linearmodels model object (PanelEffectsResults)