Skip to content

OLS

econometricsmodels.OLS(data, y, x, options=None)

Ordinary Least Squares regression estimator.

Parameters:

Name Type Description Default
data DataFrame

A polars DataFrame containing the dependent and independent variables.

required
y str

Column name of the dependent variable.

required
x list[str]

List of column names of the independent variables.

required
options OLSOptions | None

Estimation options. Defaults to OLSOptions() (classical, with intercept, confidence_level=0.95) when omitted.

None

Examples:

>>> import polars as pl
>>> from econometricsmodels import OLS
>>> df = pl.DataFrame({"y": [1.0, 2.0], "x1": [1.0, 2.0]})
>>> result = OLS(df, y="y", x=["x1"]).fit()
>>> result.params["x1"]

fit()

Estimate the OLS model.

Returns:

Type Description
OLSResults

The estimation results.

Raises:

Type Description
TypeError

An argument has the wrong type (for example x is a string instead of a list of column names). A builtin exception, not a ValidationError.

ValidationError

The input or options are invalid (a column is missing, contains missing values or NaN/infinity, insufficient observations, confidence_level out of range, etc.). A subclass of ValueError.

ComputationError

A problem was detected during computation (e.g. a singular design matrix). A subclass of RuntimeError.

econometricsmodels.OLSOptions

Estimation options for OLS.

See docs/spec/ols-spec.md ("API引数") for the rationale behind each field's meaning and default value.

cluster property

Column name to use as the cluster group key when cov_type="cluster". Refers to a column in data rather than being passed as a separate array. Specifying it with any other cov_type raises ValidationError.

confidence_level property

Confidence level for confidence intervals, in the range (0, 1). Defaults to 0.95 (a 95% confidence interval). Named confidence_level rather than alpha to avoid confusion with the significance level (the 0.05 side).

cov_type property

Standard error type: one of "classical", "hc0", "hc1", "hc2", "hc3", "hac", "cluster". Case-insensitive.

hac_lags property

Number of lags (bandwidth) for HAC (Newey-West) when cov_type="hac". When None, computed automatically via L = floor(4*(n/100)^(2/9)). Specifying it with any other cov_type raises ValidationError.

hac_time property

Column name giving the time order for HAC. Required when cov_type="hac" (omitting it raises ValidationError): the row order of data is never assumed to be the time order. Specifying it with any other cov_type raises ValidationError.

include_intercept property

Whether the engine should automatically add an intercept column. When true, a column of all 1.0 is prepended to the design matrix. If the user's x already contains a constant column while this is true, the resulting perfect collinearity raises ComputationError (singular matrix).

econometricsmodels.OLSResults(raw)

OLS estimation results.

Array-valued properties (params, std_errors, etc.) are exposed as dictionaries keyed by coefficient name (for O(1) lookup of a single parameter). Use coef_table() for a row-oriented listing (see docs/spec/ols-spec.md, "結果構造体").

Parameters:

Name Type Description Default
raw OLSResult

The estimation result object returned by _lib.fit_ols (_lib.OLSResult).

required
Note

Users normally do not construct this directly; it is returned by OLS.fit().

adj_r_squared property

Degrees-of-freedom-adjusted R².

aic property

Akaike Information Criterion (AIC).

bic property

Bayesian Information Criterion (BIC).

conf_int property

Coefficient name to confidence interval (lower, upper).

cov_type property

Standard error type actually used (normalized to lowercase).

dep_var_name property

Column name of the dependent variable.

df_model property

Model degrees of freedom (number of slope coefficients, excluding the intercept).

df_resid property

Residual degrees of freedom (n - k).

f_df_denom property

Denominator degrees of freedom of f_statistic (None when it is NaN). May differ from df_resid, so use this to recompute the p-value from f_statistic.

f_df_num property

Numerator degrees of freedom of f_statistic (None when it is NaN, i.e. there are no slope coefficients).

f_p_value property

P-value of the F-statistic.

f_statistic property

F-statistic.

hac_lags_used property

Number of HAC (Newey-West) lags actually used: the explicit hac_lags if given, otherwise the value chosen automatically, floor(4 * (n / 100) ** (2 / 9)). None unless cov_type="hac".

log_likelihood property

Log-likelihood.

n_obs property

Number of observations.

p_values property

Coefficient name to two-sided p-value.

param_names property

List of coefficient names ("const" first when include_intercept=True).

params property

Coefficient name to coefficient value.

r_squared property

Coefficient of determination (R²).

residuals property

Residuals (in observation order, y - Xβ̂).

stat_df property

Degrees of freedom of the t distribution behind test_stats, or None when stat_dist is "normal". May differ from df_resid (e.g. cluster-robust inference uses G - 1), so use this to recompute p-values from test_stats.

stat_dist property

Distribution of test_stats: "t" (t-statistics) or "normal" (z-statistics).

std_errors property

Coefficient name to standard error.

test_stats property

Coefficient name to test statistic (t-statistic; see stat_dist).

augment(new_data=None)

Source data with the predicted values appended as a column.

Same new_data semantics as predict(), but returns a polars DataFrame (the training data, or new_data when given, plus a new "predicted" column) instead of a row-oriented list. This is the one exception to the project's policy of not returning DataFrames (docs/spec/ols-spec.md, "augment()"): it exists specifically to attach predictions back to their source rows.

Parameters:

Name Type Description Default
new_data DataFrame | None

Same as predict(). If None (default), returns the training data used in fit() with the predicted values appended.

None

Returns:

Type Description
DataFrame

A polars DataFrame: the source data's columns plus

DataFrame

"predicted", in the same row order as the source.

Raises:

Type Description
ValidationError

Same as predict(), or the source data already has a column named "predicted" (which would otherwise be silently overwritten). Also raised for new_data=None when this result has no retained training data (currently only possible for the OLSResults returned by IVResult.first_stage(), which has no single source DataFrame to attach a column to; calling augment(new_data) with an explicit new_data still works normally in that case).

coef_table()

Row-oriented summary table of the coefficients.

Shaped to be usable almost as-is in a REST API response (see docs/spec/ols-spec.md, "結果構造体"). Returned as list[dict] rather than a polars DataFrame, per the project's policy of not using DataFrames for the coefficient table itself.

Returns:

Type Description
list[dict[str, float | str]]

A list of dictionaries, one per coefficient. Keys are

list[dict[str, float | str]]

param, coef, std_err, test_stat, p_value,

list[dict[str, float | str]]

conf_lower, conf_upper.

predict(new_data=None)

Predicted values.

Unified into a single method rather than a separate fitted_values property, to match the naming used by Logit's predict() (docs/spec/ols-spec.md, "predict()").

Parameters:

Name Type Description Default
new_data DataFrame | None

New data to predict on. Must contain columns with the same names as the x columns passed at fit time (matched by name; column order does not matter). If include_intercept=True was used at fit time, the constant column is added automatically and must not be included here. If None (default), returns the fitted values for the training data used in fit().

None

Returns:

Type Description
list[dict[str, float]]

Row-oriented predictions, one dict per observation. Each

list[dict[str, float]]

dict currently has a single key, "predicted".

Raises:

Type Description
ValidationError

new_data is missing a required x column, or a column contains missing/NaN/infinite values.