Chapter 14 — Fama-MacBeth and the OLS utilities¶
Part III of the assayinganomalies tutorial. Prerequisite chapters: 1–13. Python modules covered:
analytics/regressions.py,analytics/ols.py,ops.py.
What this chapter answers¶
- What each argument of
run_fama_macbethdoes, including the units ofy(the function does not scale returns). - Which winsorization rule the monthly clip follows.
- How
xis assembled: by position, so two regressors that share a name both reach the fit. - How each month is solved: column-scaled least squares on a packed dates × stocks array, with rank-deficient months left NaN rather than given made-up slopes.
- How
_maybe_fill_low_frequencydecides a regressor is low-frequency, and how far it carries each value forward. - Which Newey–West lag
_nw_se_of_meanuses by default: 0, i.e. OLS standard errors of the mean; there is no automatic bandwidth. - What
nanols/OlsRes/prtprovide for ad-hoc regressions. - Why
aa.logexists: it returns NaN for non-positive or non-finite inputs instead of warning or raising.
Where this sits in the pipeline¶
Chapter 12 loads (date, permno) panels. Chapter 13 sorts them into portfolios.
This chapter is the other cross-sectional workhorse: regress next month’s
return on characteristics, average the slopes over time, and report t-stats.
flowchart TD
LOAD["aa.load ret, me, signals"]
XIN["_regressor_frame: x by position"]
WIN["_winsor_or_trim_by_date"]
FILL["_maybe_fill_low_frequency"]
LAG["_calendar_lag_panel on RHS (and WLS weights)"]
LOOP["_cross_section_fits: pack to dates x stocks, per-date lstsq if n >= min_obs"]
AVG["mean of betas; OLS or NW SE of the mean"]
OUT["RegressionResult"]
LOAD --> XIN --> WIN --> FILL --> LAG --> LOOP --> AVG --> OUT
y and the regressors are long (date, permno) Series. The lag is a
calendar-month lag, computed with the same _calendar_lag_positions helper
Chapter 13 uses inside calc_ptf_rets. For the two steps that work one month
at a time — the winsor clip and the monthly regressions — the long panel is
packed into a dates × stocks array (session_cache.pack_layout).
run_fama_macbeth is also called by protocol builders
(make_anom_benchmark_results, make_close_anom_results — Chapter 17) and by
the quickstart notebook
(the quickstart). The
make_fmb_res builder in Chapter 17 is a different Fama-MacBeth — a
rolling combination signal (eret) over the anomaly zoo — that reuses
_calendar_lag_panel but runs its own monthly loop and does not call
run_fama_macbeth.
Argument map: run_fama_macbeth¶
y and x are pandas objects; dates live on the MultiIndex, so there is no
dates argument.
| Python | Default | Shape / dtype | Notes |
|---|---|---|---|
y |
required | Series, (date, permno) |
Not scaled: pass 100 * ret for percent coefficients; intercept units are whatever you pass. |
x |
required | DataFrame, Series, list of Series, or {name: Series} |
One column per regressor, unlagged. |
| (index) | — | month-end Timestamp in level date |
Dates come from the index. |
num_lags |
1 |
int ≥ 0 | Lag of RHS only. 0 means you already lagged. |
min_obs |
100 |
int | Skip the month if complete-case n is smaller. |
weight_matrix |
None (OLS) |
Series, (date, permno) |
Non-None turns on WLS; weights are lagged 1 month regardless of num_lags. |
newey_west_lags |
0 |
int ≥ 0 | 0 = OLS SE of the mean. >0 = Bartlett HAC with that lag. No automatic bandwidth. |
print_results |
False |
bool | Print the coefficient table. |
time_period |
full sample | int YYYYMM, (YYYYMM, YYYYMM), a datetime, or a datetime pair |
A scalar means start through last date. |
trim_indicator |
False |
bool | True → trim tails to NaN; False → winsorize (clip). |
winsor_trim_pct |
1.0 |
float in [0, 50) |
0 skips the clip. |
no_const |
False |
bool | True suppresses the intercept. |
labels |
Const/var 1/… |
sequence of length k |
Must include the intercept name when no_const=False. |
fill_low_frequency |
True |
bool | False skips the low-frequency forward fill. |
Typical call:
res = aa.run_fama_macbeth(
100 * df["ret"],
[aa.log(df["me"]), df["R12_2"]],
time_period=196307,
labels=["Const", "log(me)", "R"],
)
Python does not scale returns for you. Pass 100 * ret yourself, as Chapter
2’s tour snippet does.
Execution order¶
run_fama_macbeth walks these steps:
- Put
xin one DataFrame, one column per requested regressor, by position (_regressor_frame). Internally the columns are then renamedx1 … xK, so no regressor name can collide withyorw. - Require a
(date, permno)MultiIndex ony,x, and weights. - Winsorize or trim each RHS column by date.
- Optionally fill low-frequency regressors forward.
- Lag RHS by
num_lags(default 1) in calendar months. - If WLS, lag the weight panel by 1.
- Subset
time_period. - Pack
y,x(andw) into dates × stocks arrays. For each date: complete-case mask; skip ifn < min_obs; column-scaled least squares (OLS, or WLS onsqrt(w)-weighted rows); a rank-deficient month stays NaN. Adjusted R² comes from the same packed arrays. - Average coefficients over months where every beta is finite. t-stat = mean / SE, with SE from OLS or Newey–West.
- Optionally print.
x = _winsor_or_trim_by_date(x, pct=winsor_trim_pct, trim=trim_indicator)
# (optional) fill low-frequency regressors forward (Pythonic approximation)
if fill_low_frequency:
x = _maybe_fill_low_frequency(x)
# lag RHS by num_lags (MATLAB default is 1). MATLAB's `lag(thisX, n, nan)`
# shifts rows of a rectangular months x stocks grid, so a stock missing from
# the panel last month contributes nothing; a per-permno shift would instead
# carry its last *observed* value across the gap.
if num_lags > 0:
x = _calendar_lag_panel(x, num_lags)
wls = False
w = None
if weight_matrix is not None:
w = pd.to_numeric(weight_matrix, errors="coerce")
w = _calendar_lag_panel(w, 1)
wls = True
RegressionResult¶
Signature — dataclass fields, not a constructor you call.
Returns (this is the return type of run_fama_macbeth)
| Field | Shape |
|---|---|
beta |
DataFrame, dates × coefficients, float64. Months that fail min_obs stay NaN. |
bhat |
Series of time-series means, indexed by coefficient labels. |
t |
Series of t-stats on those means. |
rbar2 |
Series of monthly adjusted R². |
mean_r2 |
float, nanmean of rbar2. |
metadata |
dict of the options actually used. |
Dates are on beta.index (month-end Timestamps, not YYYYMM ints).
print_results prints a banner, 25-character left-aligned labels, and
%12.3f coefficients and t-stats (no column headers).
def print_results(self) -> None:
labels = list(self.bhat.index)
print("----------------------------------------------------------------------")
print(" Results from Fama - MacBeth regressions")
print("----------------------------------------------------------------------")
for lab in labels:
b = self.bhat.loc[lab]
tt = self.t.loc[lab]
b_str = f"{b:12.3f}" if pd.notna(b) else f"{'NaN':>12}"
t_str = f"{tt:12.3f}" if pd.notna(tt) else f"{'NaN':>12}"
print(f"{lab:<25}{b_str}{t_str}")
print("----------------------------------------------------------------------")
RegressionResult is in analytics.regressions.__all__ but is not
re-exported from the package __init__.
run_fama_macbeth(y, x, *, ...)¶
Signature — see the argument map above. x goes through
_regressor_frame first, which places each regressor by position:
base = [
f"x{i}" if (nm is None or nm == "") else str(nm)
for i, nm in enumerate(raw, start=1)
]
names = _dedupe_names(base)
# `keys=` labels the columns in list order; `join="outer"` is concat's
# default and matches the old dict-of-Series concat.
frame = pd.concat(items, axis=1, keys=names)
return frame, names
A list [aa.log(me), R] becomes a two-column DataFrame whose names come from
each Series (so aa.log’s log(me) name is how you get a readable column
before labels= overrides the printed rows). Unnamed Series become x1,
x2, … by position. A repeated name is suffixed (_dedupe_names:
["a", "a", "a_2"] → ["a", "a_3", "a_2"]), so [x, x * x] — where both
Series keep x.name — gives two regressors, not one. A dict uses its keys; a
one-column DataFrame inside a list counts as one regressor; a DataFrame whose
own column labels repeat is rejected. pd.concat aligns on the union of
indexes — a stock present in me but not in R gets NaN on that column.
The names survive in metadata["regressor_names"].
Returns — RegressionResult as above.
What it does — after the shared preprocess (winsor, fill, lag, time subset),
y, the regressors and the weights are stacked, packed into a dates × stocks
array, and handed to _cross_section_fits:
pieces = [df["y"].to_numpy(dtype=float)[:, None]]
if x_cols:
pieces.append(df[x_cols].to_numpy(dtype=float))
if wls:
pieces.append(pd.to_numeric(df["w"], errors="coerce").to_numpy(dtype=float)[:, None])
stacked = np.concatenate(pieces, axis=1)
packed, unique_dates, _, _ = _panel_to_date_stock(stacked, df.index)
dates = pd.Index(unique_dates)
y_mat = packed[:, :, 0]
x_mat = packed[:, :, 1 : 1 + n_x] if n_x else packed[:, :, 1:1]
w_mat = packed[:, :, -1] if wls else None
beta_arr, rbar_arr = _cross_section_fits(
y_mat, x_mat, no_const=no_const, w=w_mat, min_obs=min_obs
)
# ...
# Average betas and compute t-stats (OLS or NW) on the mean.
valid_rows = beta_ts.notna().all(axis=1)
bhat = beta_ts[valid_rows].mean(axis=0)
A stock-month counts toward a month's regression only if y, every x, and
w are finite and w >= 0 (the complete-case mask in _cross_section_fits).
Each month is solved with _lstsq_full_rank (see
The monthly solve); it does not call
analytics.ols.nanols on the cross-section. Averaging keeps a month only when
every coefficient is finite (notna().all(axis=1)), which is also what drops a
rank-deficient month.
time_period handling: a single int is YYYYMM start through
the last date in y. A pair of ints is
[start, end]. A datetime / Timestamp is normalized with
MonthEnd(0) so datetime(1963, 8, 1) becomes 1963-08-31, matching the
panel.
There is no option to silence warnings globally; Python warnings behave as usual.
Winsorize vs trim¶
With winsor_trim_pct = p > 0, each regressor is treated month by month:
Winsorize (trim_indicator=False, the default) — for each month, compute
the p and 100 - p percentiles of the cross-section, then clip: values
below the lower bound become the lower bound, values above the upper bound
become the upper bound. Months with no finite values are skipped.
Trim (trim_indicator=True) — same percentiles, but tails are set to
NaN instead of clipped.
The percentiles use the plot-position rule (i - 0.5)/n, not
Series.quantile. This follows the original MATLAB toolkit, whose prctile
uses that rule.
_winsor_or_trim_by_date(x, *, pct, trim)¶
Signature
x— DataFrame,(date, permno)× regressors.pct—winsor_trim_pct;<= 0is a no-op;>= 50raises.trim—trim_indicator.
Returns — DataFrame, same index and columns, float64 values.
What it does
layout = pack_layout(x.index)
mats = [
pack_column(
pd.to_numeric(x[c], errors="coerce").to_numpy(dtype="float64"),
layout,
name=c,
)
for c in cols
]
mat = np.stack(mats, axis=-1)
# ...
lo_hi = np.array([pct, 100.0 - pct], dtype=float)
for j in range(mat.shape[2]):
col = mat[:, :, j]
bounds = _matlab_prctile_rows_finite(col, lo_hi)
lo = bounds[:, 0:1]
hi = bounds[:, 1:2]
finite_b = np.isfinite(lo[:, 0]) & np.isfinite(hi[:, 0])
if not finite_b.any():
continue
if trim:
drop = (col < lo) | (col > hi)
col = np.where(finite_b[:, None] & drop, np.nan, col)
else:
clipped = np.clip(col, lo, hi)
col = np.where(finite_b[:, None], clipped, col)
mat[:, :, j] = col
out_vals = mat[date_codes, within, :]
Each regressor is packed into a dates × stocks matrix, so the per-month tails
are one row-wise percentile plus a clip, without a pandas groupby. The
results are scattered back to the original rows by (date_codes, within), so
the output keeps the input’s row order. _matlab_prctile_rows_finite computes
the percentile row by row with plot positions (i - 0.5)/n, the same rule as
sorts._matlab_prctile
(Ch 13; three copies
catalogued in Ch 9).
Non-finite values are set aside before the sort, so ±Inf does not move the
tails. Pandas quantile uses (i-1)/(n-1) and was measured to move FM
coefficients in the 4th digit.
Each column is forced through pd.to_numeric(...).to_numpy(dtype="float64")
before packing. DuckDB / Chen–Zimmerman integer-like signals often arrive as
nullable Int64, which cannot be clipped to float bounds. np.stack
returns a new array, so the clip never touches the caller’s data.
make_fmb_res has a sibling _winsorize_xs_1pct (Chapter 17) that is the
same clip on a single cross-section.
_maybe_fill_low_frequency(x)¶
This is the accounting-data frequency fix. It is the easiest function in the file to misread.
Signature — x: DataFrame of unlagged RHS columns.
Returns — DataFrame, same shape; a column classified as low-frequency has
each stock’s values carried forward for at most freq - 1 calendar months.
What it does
def _maybe_fill_low_frequency(x: pd.DataFrame) -> pd.DataFrame:
"""
Carry sparse regressors forward for one observation interval, no further.
...
"""
from .sorts import _calendar_ffill, _date_codes_and_months
out = x.copy()
for col in out.columns:
s = pd.to_numeric(out[col], errors="coerce")
obs = s.notna().groupby(level="date").any()
idx = obs.index[obs.to_numpy()].sort_values()
if len(idx) < 3 or pd.Series(idx).diff().median() <= pd.Timedelta(days=40):
out[col] = s
continue
_, _, months = _date_codes_and_months(idx)
gaps = pd.Series(np.diff(months)).value_counts()
freq = int(gaps[gaps == gaps.max()].index.min())
out[col] = _calendar_ffill(s, freq - 1)
return out
Two separate decisions:
- Is the column low-frequency? Find the dates on which any stock has a value. If there are at least 3 and their median calendar gap is more than 40 days, yes.
- How far to carry?
freqis the most common gap between those dates in calendar months (the smallest on ties):1= monthly,3= quarterly,12= annual._calendar_ffill(s, freq - 1)then carries each stock’s last value at mostfreq - 1calendar months forward. Rows absent from the panel count toward that limit rather than stretching it.
With June-only annual data, freq = 12 and a value lasts June through May.
A stock missing one June has no value for that year, whatever it had the June
before — the carry is per stock, not a cross-sectional fill. The carry also
stops freq - 1 months after the last observed date and after an irregular
gap; it never stretches to the next observation or to the end of the sample.
This is the case you get from the database by default: aa.load returns
annual Compustat columns (bm, at, gp, …) with values in June only
(Ch 12), so a regressor built from them is carried June through May here.
_calendar_ffill is the routine behind aa.fill_months, so the result is the
same as filling the regressor yourself with aa.fill_months(x) or loading
with fill_annual=True; a regressor that already has values every month is
left alone. With fill_low_frequency=False a June-only regressor stays
June-only and enters one cross-section a year. Each column is classified and
filled on its own, so a June-only column next to a monthly one is fine; a
single column computed from both (say be / me with monthly me) has values
in June only and is carried as a whole.
| Case | Median gap | Fills? |
|---|---|---|
| Monthly (~28–31 day gaps) | ~30 < 40 days | no |
| Quarterly | ~90 days | yes, 2 months forward |
| Annual (June-only) | ~365 days | yes, 11 months forward |
| Monthly with a few missing months | still ~30 days | no |
| Fewer than 3 dates with any observation | — | skips |
_calendar_lag_panel(obj, lag)¶
Signature — obj is a (date, permno) Series or DataFrame; lag is a
non-negative int.
Returns — same type and original index order; cells whose
(date − lag months, permno) row is missing are NaN. Dates must be
month-ends and (date, permno) keys unique, or it raises ValueError.
What it does — sort stably (skipped when the index is already sorted),
convert dates to calendar-month ordinals, then reuse Chapter 13’s
_calendar_lag_positions / _take_lagged.
groupby("permno").shift(lag) is the wrong
tool here: it reaches back to that stock’s last observed month, which may
be 13 months earlier. The calendar lag finds no row for “last calendar
month”, so the lagged value is NaN. The lag counts calendar months, not panel
dates, so a month missing from the whole panel leaves the following month NaN
for every stock. _calendar_lag_panel serves both the RHS and the WLS
weights.
The monthly solve¶
Each month's cross-section is solved by OLS, or by WLS when weight_matrix
is given, after the weights are normalized to sum to one. Only the
coefficients and the adjusted R² are kept. There is no standalone
analytics.ols.nanwls; weighted least squares for Fama-MacBeth lives only
here.
Five helpers, outermost first:
| Helper | Role |
|---|---|
_cross_section_fits(y, x, *, no_const, w, min_obs) |
Builds the packed design (intercept column of ones on occupied cells unless no_const), the complete-case mask (y, every x and w finite, w >= 0), and dispatches to OLS or WLS. Returns (beta, rbar) with shapes (T, k) and (T,). |
_batched_ols_beta_rbar(y, x, mask, min_obs) |
For every date with at least min_obs valid rows, solves that date's rows with _lstsq_full_rank. |
_batched_wls_beta_rbar(y, x, w, mask, min_obs) |
Same, on rows multiplied by sqrt(w / sum(w)). Dates whose valid weights sum to zero stay NaN. |
_lstsq_full_rank(a, b) |
One cross-section: column-scaled SVD least squares; all NaN unless the design has full column rank. |
_rbar_from_packed(y, x, beta, mask, eligible) |
Adjusted R² for every date at once from the packed arrays. |
What it does
def _lstsq_full_rank(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Least-squares coefficients of ``b`` on ``a``; all NaN if ``a`` lacks full column rank.
...
"""
k = a.shape[1]
nan = np.full(k, np.nan, dtype=np.float64)
if a.shape[0] < k:
return nan
scale = np.abs(a).max(axis=0)
if not (scale > 0).all():
return nan
c, _, rank, _ = np.linalg.lstsq(a / scale, b, rcond=None)
if rank < k:
return nan
return c / scale
Three choices here matter for the numbers.
- Least squares, not the normal equations. Forming
X'Xsquares the condition number. With nearly collinear regressors a solve of(X'X) b = X'yreturns finite but wrong slopes.np.linalg.lstsqworks onXitself through an SVD. WLS uses the same solver onsqrt(w) * [X, y]rather thanX'WX. A Python loop over dates costs well under a millisecond per month. - Column scaling. Each column is divided by its largest absolute value
before the solve, and the coefficients are scaled back. This leaves the
least-squares solution unchanged but makes the rank decision independent of
units. Without it,
lstsq’s default cutoff (eps * max(n, k)times the largest singular value) treated a market-cap column in dollars next to a ratio around1e-4as rank deficient and set its slope to zero. - Rank-deficient months are NaN. A month whose design lacks full column rank — an all-zero column, two identical regressors, fewer rows than coefficients — has no identified coefficients. It is left NaN and drops out of the averages through the “every beta finite” rule.
Adjusted R² (_rbar_from_packed) is
1 - (SSR/(n-k)) / (SST/(n-1)), NaN when n <= k + 1. For WLS it uses
unweighted residuals and unweighted y - mean(y) — not a weighted
R². This follows the original MATLAB toolkit, whose weighted regression
reports the unweighted R². Normalizing the weights to sum to one per date
does not change the coefficients.
Non-finite or negative weights are dropped by the mask (they do not count
toward min_obs), and the month is NaN if the remaining weight mass is 0.
The older per-date kernels _ols_beta_rbar(y, X) and _wls_beta_rbar(y, X, w)
are still in the module. run_fama_macbeth does not call them; they serve as
a per-date reference for the batched solve. _wls_beta_rbar still
solves the normal equations, so do not reuse it on ill-conditioned designs.
This is not analytics.ols.nanols. The public nanols uses pinv,
returns a full OlsRes, and is what nanols(y, ones)
mean/t-stat calls go through. The FM loop keeps only beta and R̄².
_nw_se_of_mean(x, lags)¶
For each coefficient series, the standard error of its time-series mean comes from a regression on a constant:
newey_west_lags == 0(default) → OLS standard error of the mean.newey_west_lags > 0→ Newey–West (Bartlett) standard error with that lag.
Signature — x 1-D coefficient path; lags is newey_west_lags.
Returns — float, SE of the sample mean.
Lag selection. Nothing picks a lag from T. The default is
newey_west_lags=0. Zero means do not run Newey–West: use
std(x, ddof=1) / sqrt(T), which is the OLS standard error of the mean —
algebraically the same as nanols(y, ones).bstd. There is no Andrews /
Newey–West automatic bandwidth (floor(4*(T/100)^(2/9)) or similar). When
you pass a positive L, that L is used as-is.
What it does when lags > 0
def _nw_se_of_mean(x: np.ndarray, lags: int) -> float:
x = x.astype(float)
x = x[np.isfinite(x)]
T = x.shape[0]
if T == 0:
return np.nan
if lags <= 0:
return float(np.std(x, ddof=1) / np.sqrt(T)) if T > 1 else np.nan
u = x - x.mean()
gamma0 = (u @ u) / T
s = gamma0
for ell in range(1, min(lags, T - 1) + 1):
w = 1 - ell / (lags + 1)
gamma = (u[ell:] @ u[:-ell]) / T
s += 2 * w * gamma
var_mean = s / T
return float(np.sqrt(var_mean)) if var_mean >= 0 else np.nan
The Bartlett kernel is w = 1 - ℓ/(L+1) (the standard Newey–West weights,
not 1 - ℓ/L). For a regression on a constant, the HAC sandwich
V = (X'X)^{-1} G (X'X)^{-1} with X'X = T reduces to G / T^2, where G
is the Bartlett-weighted sum of autocovariances of u_t. Here gamma
divides by T once and var_mean = s/T divides again — so
se = sqrt(G)/T. Non-finite entries are dropped inside the helper, although
the caller has already removed incomplete months.
analytics/ols.py¶
Public OLS for ad-hoc regressions — notably the nanols(y, ones) idiom
(mean and t-stat of a return series) — and its printer prt(res).
Re-exported as aa.nanols and aa.prt. This is not the kernel inside the
FM monthly loop and not transforms.betas._nanols (Chapter 10).
OlsRes¶
Signature — dataclass.
| Field | Role |
|---|---|
beta, tstat, bstd |
coefficients, t-stats, SEs |
resid, yhat |
residual and fitted, complete-case length |
sige |
e'e / (n-k) |
rsqr, rbar |
R² and adjusted R² |
nobs, nvar |
after NaN drop |
labels |
printed names (used by prt) |
On an empty sample rsqr and sige are NaN.
nanols(y, x, labels=None)¶
Signature
y— array-like, coerced withpd.Series(y).astype(float)so a Series keeps order and NaNs.x— 1-D or 2-D; 1-D becomes a single column. No intercept is added — pass a column of ones yourself.labels— optional; defaultx1, x2, ….
Returns — OlsRes. If n < 2 after the NaN drop, betas/t-stats/SEs are
NaN and nobs=0.
What it does — drop any row with a non-finite value in y or x (so
±Inf is dropped as well as NaN). Then:
XtX_inv = np.linalg.pinv(X.T @ X)
beta = XtX_inv @ (X.T @ y)
yhat = X @ beta
resid = y - yhat
sige = float(resid @ resid) / (n - k)
bstd = np.sqrt(np.diag(sige * XtX_inv))
tstat = beta / bstd
ss_tot = float(((y - y.mean()) ** 2).sum())
rsqr = 1 - float(resid @ resid) / ss_tot if ss_tot > 0 else np.nan
rbar = 1 - (1 - rsqr) * (n - 1) / (n - k) if np.isfinite(rsqr) and n > k else np.nan
pinv keeps the solve safe on rank-deficient designs. Residual variance is
e'e/(n-k) and bstd = sqrt(sige * diag((X'X)^{-1})). With x a column of
ones, beta is the sample mean and tstat its t-statistic, which is how
%/mo means are computed throughout the quickstart notebook.
Relationship to the other OLS kernels
| Kernel | Where | Solve | Min n |
Returns |
|---|---|---|---|---|
analytics.ols.nanols |
this chapter | pinv(X'X) |
n < 2 → empty result |
OlsRes |
transforms.betas._nanols |
Chapter 10 | solve(X'X) |
n < k+1 |
(beta, se) |
sorts._ols |
Chapter 13 | (local) | — | beta, t, R² for factor regs |
_lstsq_full_rank |
FM loop | column-scaled lstsq (SVD) |
rank < k → NaN; rbar NaN if n <= k+1 |
beta |
Chapter 10 already flagged unifying the first two. A third and fourth copy
live in sorts and in the FM loop. None of them import each other. Several
protocol builders compute their %/mo rows through nanols (Chapter 17).
prt(res, title="Ordinary Least-squares Estimates")¶
Signature — res: OlsRes; title sets the header line.
Returns — None; prints to stdout.
What it does
def prt(res: OlsRes, title: str = "Ordinary Least-squares Estimates") -> None:
"""Port of the jplv7 ``prt`` display for an OLS result."""
print(title)
print(f"R-squared = {res.rsqr:8.4f}")
print(f"Rbar-squared = {res.rbar:8.4f}")
print(f"sigma^2 = {res.sige:8.4f}")
print(f"Nobs, Nvars = {res.nobs:6d}, {res.nvar:4d}")
print("***********************************************")
print(f"{'Variable':<14}{'Coefficient':>14}{'t-statistic':>14}")
for lab, b, t in zip(res.labels, res.beta, res.tstat):
print(f"{lab:<14}{b:14.6f}{t:14.6f}")
It prints R², adjusted R², residual variance, sample size, and a coefficient / t-statistic table. There is no Durbin–Watson statistic, no p-value column, and no option to write to a file.
ops.py¶
One public function. Imported in the package __init__ as aa.log.
log(x, *, min_positive=0.0)¶
Signature
x—pd.Series(typically(date, permno)).min_positive— threshold; values<=this become NaN. Default0.0means strictly positive.
Returns — Series, same index, name log(<original name>) or log(x).
What it does
def log(x: pd.Series, *, min_positive: float = 0.0) -> pd.Series:
s = pd.to_numeric(x, errors="coerce")
s = s.where(np.isfinite(s))
s = s.where(s > min_positive)
out = np.log(s)
base = x.name if getattr(x, "name", None) else "x"
out.name = f"log({base})"
return out
Python np.log on a float Series yields -Inf at 0 and NaN plus a
RuntimeWarning at negatives; math.log raises. Masking first means
-Inf is never produced, numpy stays quiet, and non-positive market caps
simply drop out of the regression as missing values. The Series name is
log(me), which gives readable default column names on the
x=[aa.log(me), R] convenience path.
Small helpers¶
| Name | Role |
|---|---|
_ensure_panel_index |
Raises unless index.names[:2] == ["date", "permno"]. Called on y, x, and weight_matrix. |
_as_regressor |
One list or dict entry: a Series, or a one-column DataFrame squeezed to one; anything else raises. |
_regressor_frame |
Puts the regressors in one DataFrame by position; returns (frame, names). See run_fama_macbeth. |
_dedupe_names |
Suffixes repeated regressor names (_2, _3, …) without taking a name requested elsewhere. |
_panel_to_date_stock |
Packs a long panel into a dates × stocks array (ragged months NaN-padded); returns the codes to scatter back. |
_matlab_prctile_rows_finite |
Row-wise plot-position percentile ((i - 0.5)/n) on the finite entries of each row. See _winsor_or_trim_by_date. |