regression.estimate_model()

Estimate a linear model.

Usage

Source

regression.estimate_model(
    data,
    model,
    min_obs=1,
    output="coefficients",
)

Estimates a linear model specified by one or more independent variables. It checks for the presence of the specified independent variables in the dataset and whether the dataset has a sufficient number of observations. Depending on the ‘output’ parameter, it returns the model’s coefficients, t-statistics, residuals, or any combination in a named dict.

Parameters

data: pl.DataFrame

Data frame containing the dependent variable and one or more independent variables.

model: str

Formula string describing the model to be estimated (e.g., ‘ret_excess ~ mkt_excess + hml + smb’). Use ‘y ~ x - 1’ for no-intercept models.

min_obs: int = 1

Minimum number of observations required to estimate the model.

output: str or list of str = "coefficients"
What to return. Must contain one or more of ‘coefficients’, ‘residuals’, and ‘tstats’. If a single value is provided, the corresponding object is returned directly. If multiple values are provided, a dict is returned.

Returns

pl.DataFrame, np.ndarray, or dict
If ‘output’ contains a single value: a data frame of coefficients or t-statistics, or a numeric vector of residuals. If ‘output’ contains multiple values: a dict with the requested elements. Coefficients and t-statistics are returned as one-row data frames with column names corresponding to the model terms (all-null when there are not enough observations). Residuals are returned as a numeric vector of length ‘len(data)’ with NaN for rows with missing data or insufficient observations.

Examples

import numpy as np
import polars as pl
from tidyfinance import estimate_model
rng = np.random.default_rng(42)
data = pl.DataFrame({
    'ret_excess': rng.standard_normal(100),
    'mkt_excess': rng.standard_normal(100),
    'smb': rng.standard_normal(100),
    'hml': rng.standard_normal(100),
})
# Estimate model with a single independent variable
estimate_model(data, 'ret_excess ~ mkt_excess')
# Estimate model with multiple independent variables
estimate_model(data, 'ret_excess ~ mkt_excess + smb + hml')
# Estimate model without intercept
estimate_model(data, 'ret_excess ~ mkt_excess - 1')
# Calculate residuals
estimate_model(
    data, 'ret_excess ~ mkt_excess + smb + hml',
    output='residuals',
)
# Return t-statistics
estimate_model(
    data, 'ret_excess ~ mkt_excess + smb + hml',
    output='tstats',
)
# Return coefficients, t-statistics, and residuals
estimate_model(
    data, 'ret_excess ~ mkt_excess + smb + hml',
    output=['coefficients', 'tstats', 'residuals'],
)