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 *
data = generate_panel_data()
model_robust = fit_linearmodels(
formula="y ~ x1 + EntityEffects",
data=data.data,
engine=PanelOLS,
kwargs_fit={'cov_type': 'robust'}
)
predictions(model_robust)Notes
The fitted model includes additional attributes:
data: The processed data after listwise deletionformula: The original formula stringformula_engine: Set to “linearmodels”model: The fitted linearmodels model object