Files
global-live/src/data/qmj.py
T
2026-08-12 16:40:47 -07:00

932 lines
37 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Paper-faithful Asness-Frazzini-Pedersen (AFP) "Quality Minus Junk" score.
Construction reference: `notes/tier-1/asness-frazzini-pedersen.md` §4-§5.
CRITICAL FRAMING — this is an OUT-OF-SAMPLE test (window 2018-2026, after AFP's
2012 sample end). The construction matches the paper EXACTLY; there are no
"improvements" or neutralizations. ROE is computed pure-paper (NI / BE) even
when book equity is negative — the rank-z + 6-measure averaging + buyback-
rewarding Payout pillar structurally outvote the single pathological measure
(see `project_qmj_diagnostic_track.md`). Negative-equity names (MCD/HD/AZO/...)
are handled BY the construction: LEV is debt/assets, Altman-Z uses *market*
equity, Ohlson-O has the OENEG dummy — no bespoke patch.
Quality = z(average of available pillar scores). The shipped live/default
variant adds R&D expense / market equity as a fifth optional pillar.
Core standardisation (AFP §5): for a raw measure x over a cross-section,
z(x) = (rank(x) - mean(rank)) / std(rank) # z-score the RANK, not x
ascending so HIGH = good. Each pillar = re-z-score of the simple average of its
member z-scores. Missing-data rule: average over the AVAILABLE member z-scores
per stock (do NOT zero-fill). Min-coverage gate: a stock needs >= 1 non-missing
member in EACH of the 4 pillars (and >= 10 of the ~16 fundamental measures
overall) to receive a Quality score; below that it gets NaN Quality and drops
out of the QMJ cross-section while staying in the price universe.
FLOW vs STOCK (AFP appendix A1): "unless specified, XpressFeed data items refer
to ANNUAL items." FLOW variables (net_income, revenue, cogs, depreciation,
capex, operating_income, pretax_income) are therefore aggregated to TTM (a
trailing-4-quarter sum, requiring 4 consecutive quarters else NaN). STOCK
variables (total_assets, equity, retained_earnings, total_liabilities,
current/{assets,liabilities}, cash, short_term_debt, lt_debt, minority_interest,
preferred_stock) are used point-in-time (latest quarter). EVOL is the one
exception: it uses QUARTERLY ROE.
Fidelity caveats (flagged for review — see CAVEAT comments inline):
- BAB / IVOL: computed by src/data/qmj_risk.py from daily returns + the market
proxy as the real Frazzini-Pedersen ex-ante beta (rho * sigma_i/sigma_m on
3-day overlapping returns) and the residual-vol IVOL (std of beta-adjusted
residual, skip last day). There is NO panel-column/total-vol fallback for
the Safety members.
- FUTL (Ohlson): AFP FUTL = pretax_income / total_liabilities (PT/LT only).
- CPI: Ohlson-O deflates adjusted assets by a CPI index. The real series
(FRED CPIAUCSL) is loaded from data/raw/macro/cpiaucsl.csv if present;
absent, a constant fallback (=100) is used with a logged warning. The
deflator enters O only through a log term, so a constant is a level shift
that the cross-sectional rank-z absorbs — but it is NOT the faithful series.
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import pandas as pd
from src.data.fundamentals import (
extract_pit_shares,
lag_to_monthly,
parse_fundamentals_response,
)
logger = logging.getLogger(__name__)
_QUARTERS_PER_YEAR = 4
_GROWTH_LAG_Q = 20 # 5 years
_PIT_LAG_DAYS = 90
_PIT_LAG_DAYS_ANNUAL = 180 # FF 6-month convention for annual accounting
# freq -> periods-per-year (PPY). 4 = quarterly (TTM = 4-period sum, current
# default); 1 = annual (the annual flow IS the TTM, so the "TTM" is identity).
_PPY_BY_FREQ = {"quarterly": 4, "annual": 1}
# Member -> pillar membership. The averaging respects only non-missing members.
_PROFITABILITY = ["gpoa", "roe", "roa", "cfoa", "gmar", "acc"]
_GROWTH = ["g_gpoa", "g_roe", "g_roa", "g_cfoa", "g_gmar", "g_acc"]
_SAFETY = ["bab", "ivol", "lev", "o_score", "z_score", "evol"]
_PAYOUT = ["eiss", "diss", "npop"]
_RD = ["rd_me"]
_ALL_MEASURES = _PROFITABILITY + _GROWTH + _SAFETY + _PAYOUT
# pillar-name -> member list, for the config-driven coverage gate.
_PILLAR_MEMBERS = {
"profitability": _PROFITABILITY,
"growth": _GROWTH,
"safety": _SAFETY,
"payout": _PAYOUT,
"rd": _RD,
}
_STRICT_REQUIRE_PILLARS: tuple[str, ...] = ("profitability", "growth", "safety", "payout")
# LIVE coverage gate (shipped 2026-06-07): Growth is OPTIONAL. A name missing the
# ENTIRE Growth pillar (no 5-year history — typically recent listings or gappy
# fundamentals) is still scored on the other three pillars. This was the original
# design intent; a strict-vs-relaxed US-only A/B (notes/diagnostics/
# qmj_gate_relax_growth_2026-06-07.md) showed relaxed ~0.06 Sortino / 0.9pt CAGR
# BELOW strict on the 2018-26 window with identical MaxDD — shipped on project owner
# green-light over the A/B (coverage/intent call: +71k scores, +15.1% coverage).
# _STRICT_REQUIRE_PILLARS is kept for the strict-gate regression + as the all-4
# reference. The Quality COMPOSITE is unchanged: it still averages all available
# pillars (Growth included when present); only the eligibility gate is relaxed.
_LIVE_REQUIRE_PILLARS: tuple[str, ...] = ("profitability", "safety", "payout")
_MIN_MEASURES_OVERALL = 10 # >= ~10 of the ~16 fundamental measures
# Fama-French financial-sector exclusion (shipped 2026-06-10). Fama-French exclude
# SIC 6000-6999 (financials) from factor portfolios because the accounting-based
# measures are undefined or distorted for banks/insurers/holding companies: there
# is no COGS (gross-profit measures), no current/non-current split (working-capital
# accruals, Altman-Z), and debt/assets leverage + Ohlson-O are meaningless when
# deposits/reserves are not "debt". We follow the convention via the modern GICS
# analogue (GicSector == "Financials"; Real Estate is its own GICS sector and is
# NOT excluded here). Excluded names get NaN quality (the veto NaN-keeps them) and
# are labelled "na_financial" in the live picks. Set False to restore scoring of
# financials (the prior behaviour, where they mostly fell out via the coverage gate).
_EXCLUDE_FINANCIALS = True
_FINANCIAL_GIC_SECTOR = "Financials"
def gic_sector(data: dict) -> str | None:
"""GICS sector tag from an EODHD fundamentals payload (General.GicSector)."""
general = data.get("General") or {}
sector = general.get("GicSector")
return str(sector) if sector else None
def is_financial(data: dict) -> bool:
"""True when the name is a GICS Financials member (Fama-French exclusion)."""
return gic_sector(data) == _FINANCIAL_GIC_SECTOR
def _ppy_for_freq(freq: str) -> int:
ppy = _PPY_BY_FREQ.get(freq)
if ppy is None:
raise ValueError(f"QMJ: unknown freq {freq!r} (expected 'quarterly' or 'annual')")
return ppy
def _coverage_gate(
z: pd.DataFrame,
require_pillars: tuple[str, ...],
min_measures_overall: int,
all_measures: list[str] | None = None,
) -> pd.Series:
"""Paper-faithful coverage gate: required-pillar presence AND a measure floor.
`require_pillars` is the set of pillars that must each have >=1 non-missing
member z-score; an empty set imposes no per-pillar requirement (pure-paper:
average whatever is available). `min_measures_overall` is the overall
non-missing-member floor. The strict default reproduces the historical gate
(all four pillars + 10 measures) byte-for-byte.
"""
measures = all_measures or _ALL_MEASURES
n_measures = z[measures].notna().sum(axis=1)
gate = n_measures >= min_measures_overall
for pillar in require_pillars:
members = _PILLAR_MEMBERS[pillar]
gate = gate & z[members].notna().any(axis=1)
return gate
@dataclass
class QMJConfig:
"""Injectable knobs for QMJ construction.
daily_returns_path / market_proxy_path feed the real Frazzini-Pedersen
beta + residual IVOL (src/data/qmj_risk.py). bab_ivol lets a caller inject a
precomputed [date, ticker, bab, ivol] frame (tests/sanity) to skip the
daily-return scan.
"""
start: str = "2018-01-01"
freq: str = "quarterly" # "quarterly" (PPY=4, default) or "annual" (PPY=1)
pit_lag_days: int = _PIT_LAG_DAYS
daily_returns_path: str = "data/processed/daily_returns.parquet"
market_proxy_path: str = "data/processed/market_proxy_daily.parquet"
cpi_csv: str = "data/raw/macro/cpiaucsl.csv"
min_measures_overall: int = _MIN_MEASURES_OVERALL
# Growth-optional live gate (2026-06-07). Pass _STRICT_REQUIRE_PILLARS to
# restore the all-4 strict gate.
require_pillars: tuple[str, ...] = _LIVE_REQUIRE_PILLARS
universe: list[str] | None = field(default=None) # None => all panel US names
bab_ivol: pd.DataFrame | None = field(default=None)
# Shipped live/default variant: add positive R&D expense / market equity as
# a fifth optional pillar. Set False to reproduce paper-faithful AFP QMJ.
add_rd_pillar: bool = True
# ---------------------------------------------------------------------------
# Rank-z standardisation (AFP §5)
# ---------------------------------------------------------------------------
def rank_z(x: pd.Series) -> pd.Series:
"""z(x) = (rank(x) - mean(rank)) / std(rank), ascending, HIGH = good.
Ranks are average-rank (ties shared). NaN inputs stay NaN and are excluded
from the rank mean/std. A degenerate cross-section (<2 finite obs or zero
rank dispersion) returns all-NaN.
"""
r = x.rank(method="average", na_option="keep")
finite = r.dropna()
if len(finite) < 2:
return pd.Series(np.nan, index=x.index)
mu = finite.mean()
sd = finite.std(ddof=1)
if not np.isfinite(sd) or sd == 0:
return pd.Series(np.nan, index=x.index)
return (r - mu) / sd
def _pillar_score(z_members: pd.DataFrame, members: list[str]) -> pd.Series:
"""Average available member z-scores per row, then re-rank-z the average.
Available-member average: do NOT zero-fill missing members (AFP missing-data
rule). Rows with no available member get NaN, which propagates out of the
re-z step.
"""
present = [m for m in members if m in z_members.columns]
if not present:
return pd.Series(np.nan, index=z_members.index)
avg = z_members[present].mean(axis=1, skipna=True)
return rank_z(avg)
# ---------------------------------------------------------------------------
# CPI loader (Ohlson-O deflator)
# ---------------------------------------------------------------------------
def load_cpi(cpi_csv: str | Path) -> pd.Series:
"""Load a date-indexed CPI series from a CSV (columns: date,value).
Returns a monotone date-indexed float Series. If the file is absent a
constant-100 stub is returned with a warning — the deflator enters Ohlson-O
only inside a log term, so a constant is a level shift the cross-sectional
rank-z absorbs, but it is NOT the faithful FRED CPIAUCSL series.
"""
path = Path(cpi_csv)
if not path.exists():
logger.warning(
"load_cpi: CPI file %s absent — using constant=100 fallback "
"(NON-FAITHFUL; source FRED CPIAUCSL into this path). TODO",
path,
)
idx = pd.date_range("1990-01-01", "2030-01-01", freq="MS")
return pd.Series(100.0, index=idx, name="cpi")
df = pd.read_csv(path)
cols = {c.lower(): c for c in df.columns}
date_col = cols.get("date", df.columns[0])
val_col = cols.get("value", df.columns[-1])
s = pd.Series(
pd.to_numeric(df[val_col], errors="coerce").to_numpy(),
index=pd.to_datetime(df[date_col]),
name="cpi",
)
return s[s.index.notna()].sort_index()
def _cpi_at(cpi: pd.Series, when: pd.Timestamp) -> float:
"""As-of CPI value (last observation <= when); first obs if before start."""
prior = cpi[cpi.index <= when]
if len(prior):
return float(prior.iloc[-1])
return float(cpi.iloc[0]) if len(cpi) else 100.0
# ---------------------------------------------------------------------------
# Per-ticker quarterly measure computation
# ---------------------------------------------------------------------------
def _ttm(values: np.ndarray, periods_per_year: int = _QUARTERS_PER_YEAR) -> np.ndarray:
"""Trailing-1-year SUM (TTM) over `periods_per_year` consecutive periods.
Input is one ticker's per-period series in chronological order. The first
(PPY-1) periods are NaN (insufficient history); a NaN in any component
period propagates to NaN. PPY=1 (annual) is the identity: the annual flow
already IS the trailing-year sum.
"""
s = pd.Series(values)
return s.rolling(periods_per_year, min_periods=periods_per_year).sum().to_numpy()
def _lag(values: np.ndarray, k: int) -> np.ndarray:
"""k-period lag with NaN padding at the head."""
out = np.full(len(values), np.nan)
if len(values) > k:
out[k:] = values[:-k]
return out
def _div(n: np.ndarray, d: np.ndarray) -> np.ndarray:
with np.errstate(invalid="ignore", divide="ignore"):
r = n / d
r[~np.isfinite(d) | (d == 0)] = np.nan
return r
def compute_quarterly_measures(
quarterly: pd.DataFrame, periods_per_year: int = _QUARTERS_PER_YEAR
) -> pd.DataFrame:
"""Compute all per-period, ticker-local QMJ measures (pre cross-section).
`periods_per_year` (PPY) parameterises the accounting frequency: 4 =
quarterly (default, current behaviour), 1 = annual. FLOW inputs (net_income,
revenue, cogs, depreciation, capex, operating_income, pretax_income) are
aggregated to TTM (trailing-PPY-period sum; PPY=1 is the identity); STOCK
inputs are point-in-time. Working capital uses the AFP-refined definition and
ΔWC is the trailing-year (PPY-period) change. Growth uses a 5*PPY-period lag,
NPOP a 5*PPY-period window, DISS a PPY-period lag. EVOL is frequency-aware:
quarterly uses std of quarterly ROE (60q, >=12 obs; else annual ROE 5y),
annual uses std of annual ROE over the last 5 fiscal years (>=5 obs).
Columns are oriented HIGH = good. The cross-sectional / ME-dependent measures
(o_score, z_score) are completed in build_qmj_panel once ME is available.
"""
if quarterly.empty:
return quarterly.copy()
ppy = periods_per_year
growth_lag = 5 * ppy
npop_window = 5 * ppy
df = quarterly.copy().sort_values(["ticker", "quarter_end"]).reset_index(drop=True)
if "research_development" not in df.columns:
df["research_development"] = np.nan
# STOCK (point-in-time) inputs.
ta = df["total_assets"].to_numpy(float)
eq = df["equity"].to_numpy(float)
pref = df["preferred_stock"].to_numpy(float)
minint = df["minority_interest"].to_numpy(float)
lt_debt = df["lt_debt"].to_numpy(float)
st_debt = df["short_term_debt"].to_numpy(float)
ca = df["current_assets"].to_numpy(float)
cl = df["current_liabilities"].to_numpy(float)
cash = df["cash"].to_numpy(float)
# book_equity = shareholders' equity - preferred (PURE PAPER, as-is even <0).
book_equity = eq - pref
df["book_equity"] = book_equity
# TTM FLOW aggregates, computed per ticker (4 consecutive quarters).
ttm_cols = {
"ttm_net_income": "net_income",
"ttm_revenue": "revenue",
"ttm_cogs": "cogs",
"ttm_depreciation": "depreciation",
"ttm_capex": "capex",
"ttm_operating_income": "operating_income",
"ttm_pretax_income": "pretax_income",
"ttm_research_development": "research_development",
}
for out_c in ttm_cols:
df[out_c] = np.nan
# Refined working capital (TXP omitted: not in EODHD) and its ANNUAL change.
# WC = current_assets - current_liabilities - cash + short_term_debt
wc_refined = ca - cl - cash + st_debt
df["_wc_refined"] = wc_refined
df["wc_refined"] = wc_refined # carried through lag_to_monthly for Altman-Z
df["_dwc"] = np.nan # ΔWC = WC_t - WC_{t-4q} (ANNUAL change)
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
for out_c, src in ttm_cols.items():
df.loc[idx, out_c] = _ttm(grp[src].to_numpy(float), ppy)
df.loc[idx, "_dwc"] = grp["_wc_refined"].to_numpy(float) - _lag(
grp["_wc_refined"].to_numpy(float), ppy
)
ttm_ni = df["ttm_net_income"].to_numpy(float)
ttm_rev = df["ttm_revenue"].to_numpy(float)
ttm_cogs = df["ttm_cogs"].to_numpy(float)
ttm_dep = df["ttm_depreciation"].to_numpy(float)
ttm_capex = df["ttm_capex"].to_numpy(float)
dwc = df["_dwc"].to_numpy(float)
ttm_gp = ttm_rev - ttm_cogs # TTM gross profit
capex_abs = np.abs(ttm_capex)
cf = ttm_ni + ttm_dep - dwc - capex_abs # CFOA numerator
mwcpd = ttm_dep - dwc # ACC numerator (DP - ΔWC), HIGH = good
df["_gp"] = ttm_gp
df["_cf"] = cf
df["_mwcpd"] = mwcpd
# --- Profitability (TTM flows / point-in-time stocks; HIGH = good) ---
df["gpoa"] = _div(ttm_gp, ta)
df["roe"] = _div(ttm_ni, book_equity) # PURE PAPER even when BE < 0
df["roa"] = _div(ttm_ni, ta)
df["cfoa"] = _div(cf, ta)
df["gmar"] = _div(ttm_gp, ttm_rev)
# ACC = (DP - ΔWC)/AT, HIGH = good (AFP: high accruals quality = good).
df["acc"] = _div(mwcpd, ta)
# --- Growth (5yr = 5*PPY-period prior): Δnumerator / lagged denominator. ---
g_cols = {
"g_gpoa": (ttm_gp, ta),
"g_roe": (ttm_ni, book_equity),
"g_roa": (ttm_ni, ta),
"g_cfoa": (cf, ta),
"g_gmar": (ttm_gp, ttm_rev),
"g_acc": (mwcpd, ta),
}
for name in g_cols:
df[name] = np.nan
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
n = len(idx)
if n <= growth_lag:
continue
for name, (num, den) in g_cols.items():
sub_num = num[idx]
sub_den = den[idx]
lagged_num = _lag(sub_num, growth_lag)
lagged_den = _lag(sub_den, growth_lag)
with np.errstate(invalid="ignore", divide="ignore"):
g = (sub_num - lagged_num) / lagged_den
g[~np.isfinite(lagged_den) | (lagged_den == 0)] = np.nan
df.loc[idx, name] = g
# --- Safety: LEV = -(LT + ST + minority + preferred)/AT (HIGH = good). ---
total_debt = lt_debt + st_debt + minint + pref
df["_total_debt"] = total_debt
df["lev"] = -_div(total_debt, ta)
# TOTD for DISS = LT + ST + minority + preferred (same aggregate as LEV num).
df["_totd"] = total_debt
# --- Safety: EVOL (frequency-aware). Quarterly (PPY=4): -std(QUARTERLY ROE,
# trailing 60q, >=12 obs); else -std(ANNUAL ROE over trailing 5 fiscal years,
# >=5 obs). Annual (PPY=1): -std(ANNUAL ROE over the last 5 fiscal-year rows,
# >=5 obs) — the paper's explicit annual branch. Per-period ROE uses
# per-period net income / book_equity (NOT ttm).
df["evol"] = np.nan
q_roe = _div(df["net_income"].to_numpy(float), book_equity)
df["_q_roe"] = q_roe
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
roe_q = grp["_q_roe"].to_numpy(float)
out = np.full(len(idx), np.nan)
for i in range(len(idx)):
if ppy == 1:
ann = roe_q[max(0, i - 4) : i + 1]
ann = ann[np.isfinite(ann)]
if len(ann) >= 5:
out[i] = -np.std(ann, ddof=1)
continue
window = roe_q[max(0, i - 59) : i + 1]
window = window[np.isfinite(window)]
if len(window) >= 12:
out[i] = -np.std(window, ddof=1)
else:
ann = roe_q[max(0, i - 19) : i + 1 : ppy]
ann = ann[np.isfinite(ann)]
if len(ann) >= 5:
out[i] = -np.std(ann, ddof=1)
df.loc[idx, "evol"] = out
# --- Payout: EISS computed in build_qmj_panel (PIT shares). DISS / NPOP. ---
# DISS = -1yr % change in TOTD (PPY-period lag).
df["diss"] = np.nan
df["npop"] = np.nan
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
totd = grp["_totd"].to_numpy(float)
n = len(idx)
if n > ppy:
lag_totd = _lag(totd, ppy)
with np.errstate(invalid="ignore", divide="ignore"):
pct = (totd - lag_totd) / lag_totd
pct[~np.isfinite(lag_totd) | (lag_totd == 0)] = np.nan
df.loc[idx, "diss"] = -pct
# NPOP = Σ_5y(per-period NI - ΔBE) / Σ_5y(per-period gross profit), the
# 5*PPY-period window.
ni_q = grp["net_income"].to_numpy(float)
gp_q = grp["revenue"].to_numpy(float) - grp["cogs"].to_numpy(float)
be_q = grp["book_equity"].to_numpy(float)
dbe = np.full(n, np.nan)
dbe[1:] = np.diff(be_q)
net_payout = ni_q - dbe
npop = np.full(n, np.nan)
for i in range(n):
lo = i - npop_window + 1
if lo < 0:
continue
np_win = net_payout[lo : i + 1]
gp_win = gp_q[lo : i + 1]
if np.isfinite(np_win).sum() < npop_window // 2:
continue
denom = np.nansum(gp_win)
if denom != 0 and np.isfinite(denom):
npop[i] = np.nansum(np_win) / denom
df.loc[idx, "npop"] = npop
return df
# ---------------------------------------------------------------------------
# Ohlson-O & Altman-Z (need market cap / CPI — computed at monthly cross-section)
# ---------------------------------------------------------------------------
def ohlson_o_score(
total_assets: float,
total_liabilities: float,
short_term_debt: float,
lt_debt: float,
current_assets: float,
current_liabilities: float,
ttm_net_income: float,
ttm_net_income_prior: float,
ttm_pretax_income: float,
book_equity: float,
market_cap: float,
cpi: float,
) -> float:
"""AFP/Ohlson(1980) O-Score. Returns the RAW O (high = high bankruptcy prob).
The Safety member is -O (negated in build_qmj_panel). Coefficients are the
exact Ohlson(1980) values per the AFP appendix.
AFP definitions: ADJASSET = TA + 0.1*(ME - BE); TLTA = DEBT(DLC+DLTT)/ADJASSET
(DEBT, not total liabilities); WCTA = (CA - CL)/ADJASSET (simple WC here);
NITA = TTM NI / TA (NOT /ADJASSET); FUTL = TTM pretax income / total
liabilities (PT/LT only, no depreciation); INTWO = 1 if TTM NI < 0 both years.
"""
if not np.isfinite(total_assets) or total_assets == 0:
return np.nan
ta_adj = total_assets + 0.1 * (market_cap - book_equity)
if not np.isfinite(ta_adj) or ta_adj <= 0 or cpi <= 0:
return np.nan
if not np.isfinite(total_liabilities) or total_liabilities == 0:
return np.nan
if not np.isfinite(current_assets) or current_assets == 0:
return np.nan
debt = short_term_debt + lt_debt
if not np.isfinite(debt):
return np.nan
tlta = debt / ta_adj
wcta = (current_assets - current_liabilities) / ta_adj
clca = current_liabilities / current_assets
oeneg = 1.0 if total_liabilities > total_assets else 0.0
nita = ttm_net_income / total_assets
futl = ttm_pretax_income / total_liabilities
intwo = 1.0 if (ttm_net_income < 0 and ttm_net_income_prior < 0) else 0.0
denom_chin = abs(ttm_net_income) + abs(ttm_net_income_prior)
chin = (ttm_net_income - ttm_net_income_prior) / denom_chin if denom_chin != 0 else 0.0
o = (
-1.32
- 0.407 * np.log(ta_adj / cpi)
+ 6.03 * tlta
- 1.43 * wcta
+ 0.0757 * clca
- 1.72 * oeneg
- 2.37 * nita
- 1.83 * futl
+ 0.285 * intwo
- 0.521 * chin
)
return float(o)
def altman_z_score(
working_capital: float,
retained_earnings: float,
ttm_operating_income: float,
market_cap: float,
ttm_revenue: float,
total_assets: float,
) -> float:
"""AFP form of Altman(1968) Z-Score. HIGH = safe.
Z = (1.2*WC + 1.4*RE + 3.3*EBIT + 0.6*ME + Sales) / TA
WC = refined working capital (CA - CL - cash + ST debt); RE = retained
earnings; EBIT = TTM operating income; ME = market cap; Sales = TTM revenue;
TA = total assets. (Altman-canonical uses simple CA - CL; AFP/this build
pass the refined WC consistent with the profitability section.)
"""
if not np.isfinite(total_assets) or total_assets == 0:
return np.nan
z = (
1.2 * working_capital
+ 1.4 * retained_earnings
+ 3.3 * ttm_operating_income
+ 0.6 * market_cap
+ ttm_revenue
) / total_assets
return float(z)
# ---------------------------------------------------------------------------
# Market-cap derivation (ME = month-end close × PIT shares)
# ---------------------------------------------------------------------------
def derive_market_cap(
pit_shares: pd.Series,
monthly_dates: pd.DatetimeIndex,
close_by_date: pd.Series,
pit_lag_days: int = _PIT_LAG_DAYS,
) -> pd.Series:
"""ME at each monthly date = month-end close × PIT-aligned shares.
Shares are PIT-aligned with the same lag convention as fundamentals: a
shares observation dated quarter_end becomes known after pit_lag_days, then
forward-filled. close_by_date is a date-indexed close series for one ticker.
Returns a date-indexed ME Series over monthly_dates (NaN where unknown).
"""
out = pd.Series(np.nan, index=pd.DatetimeIndex(monthly_dates), name="me")
if pit_shares.empty:
return out
known_from = pit_shares.index + pd.Timedelta(days=pit_lag_days)
sh = pd.Series(pit_shares.to_numpy(), index=known_from).sort_index()
for d in out.index:
visible = sh[sh.index <= d]
if visible.empty:
continue
shares = visible.iloc[-1]
close = close_by_date.get(d, np.nan)
if np.isfinite(close) and np.isfinite(shares):
out.loc[d] = close * shares
return out
# ---------------------------------------------------------------------------
# Assembly
# ---------------------------------------------------------------------------
def _us_universe(panel: pd.DataFrame, cfg: QMJConfig) -> list[str]:
if cfg.universe is not None:
return list(cfg.universe)
tickers = panel.loc[panel["ticker"].str.endswith(".US"), "ticker"].unique()
return sorted(tickers)
def _load_bab_ivol(cfg: QMJConfig, panel: pd.DataFrame) -> pd.DataFrame:
"""Real FP beta -> bab and residual-vol -> ivol per (date, ticker).
If cfg.bab_ivol is supplied it is used directly (tests / sanity injection).
Otherwise daily_returns + market_proxy are read and qmj_risk computes the
members for the panel's (date, ticker) cross-section.
"""
if cfg.bab_ivol is not None:
bi = cfg.bab_ivol.copy()
bi["date"] = pd.to_datetime(bi["date"])
return bi[["date", "ticker", "bab", "ivol"]]
from src.data.qmj_risk import compute_fp_beta_ivol
daily = pd.read_parquet(cfg.daily_returns_path, columns=["date", "ticker", "ret_d"])
daily["date"] = pd.to_datetime(daily["date"])
market = pd.read_parquet(cfg.market_proxy_path)
market["date"] = pd.to_datetime(market["date"])
pairs = panel[["date", "ticker"]].drop_duplicates()
return compute_fp_beta_ivol(daily, market, pairs)
def build_qmj_panel(
panel_path: str = "data/processed/panel_monthly.parquet",
fundamentals_dir: str = "data/raw/eodhd/fundamentals",
out_path: str | None = "data/processed/qmj_monthly.parquet",
cfg: QMJConfig | None = None,
start: str | None = None,
) -> pd.DataFrame:
"""Build the monthly QMJ quality panel and (optionally) persist it.
Output columns: [date, ticker, qmj_profitability, qmj_growth, qmj_safety,
qmj_payout, qmj_rd, qmj_quality, qmj_n_measures] when the R&D pillar is
enabled; otherwise qmj_rd/rd_me are omitted.
"""
cfg = cfg or QMJConfig()
if start is not None:
cfg.start = start
ppy = _ppy_for_freq(cfg.freq)
all_measures = _ALL_MEASURES + (_RD if cfg.add_rd_pillar else [])
panel = pd.read_parquet(panel_path)
panel["date"] = pd.to_datetime(panel["date"])
panel = panel[panel["date"] >= pd.Timestamp(cfg.start)]
universe = _us_universe(panel, cfg)
monthly_dates = pd.DatetimeIndex(sorted(panel["date"].unique()))
cpi = load_cpi(cfg.cpi_csv)
# Real Frazzini-Pedersen beta -> bab and residual-vol -> ivol (no fallback).
bab_ivol = _load_bab_ivol(cfg, panel)
fdir = Path(fundamentals_dir)
# Per-ticker monthly measure frames accumulate here.
monthly_frames: list[pd.DataFrame] = []
for ticker in universe:
fpath = fdir / f"{ticker}.json"
if not fpath.exists():
continue
try:
data = json.loads(fpath.read_text(encoding="utf-8"))
except (ValueError, OSError):
logger.debug("QMJ: unreadable fundamentals for %s", ticker)
continue
# Fama-French convention: financials are excluded from the quality
# cross-section entirely (so they neither receive a score nor distort the
# rank-z of non-financials). They are NaN-kept downstream by the veto.
if _EXCLUDE_FINANCIALS and is_financial(data):
logger.debug("QMJ: %s excluded (GICS Financials)", ticker)
continue
quarterly = parse_fundamentals_response(data, ticker, freq=cfg.freq)
if quarterly.empty:
continue
measures = compute_quarterly_measures(quarterly, periods_per_year=ppy)
pit_shares = extract_pit_shares(data)
tk_panel = panel[panel["ticker"] == ticker]
if tk_panel.empty:
continue
close_by_date = tk_panel.set_index("date")["close"]
me = derive_market_cap(pit_shares, monthly_dates, close_by_date, cfg.pit_lag_days)
# PIT-lag the per-quarter measures + the raw inputs needed for O/Z to
# monthly month-ends via the shared lag_to_monthly helper.
keep = [
"ticker",
"quarter_end",
*_PROFITABILITY,
*_GROWTH,
"lev",
"evol",
"diss",
"npop",
# raw inputs for O / Z scored at the monthly cross-section:
"total_assets",
"total_liabilities",
"short_term_debt",
"lt_debt",
"current_assets",
"current_liabilities",
"wc_refined",
"book_equity",
"retained_earnings",
"ttm_net_income",
"ttm_pretax_income",
"ttm_operating_income",
"ttm_revenue",
"ttm_research_development",
]
keep = [c for c in keep if c in measures.columns]
m_monthly = lag_to_monthly(measures[keep], monthly_dates, pit_lag_days=cfg.pit_lag_days)
if m_monthly.empty:
continue
# EISS = -1yr % change split-adjusted shares (from PIT shares aligned to
# monthly). Use the same PIT-lag forward-fill, then 12-month % change.
sh_monthly = _shares_monthly(pit_shares, monthly_dates, cfg.pit_lag_days)
m_monthly = m_monthly.merge(
sh_monthly.rename("_shares").reset_index().rename(columns={"index": "date"}),
on="date",
how="left",
)
m_monthly["eiss"] = -m_monthly["_shares"].pct_change(12, fill_method=None)
# Attach ME and the real FP bab / ivol (qmj_risk) by (date, ticker).
m_monthly = m_monthly.merge(
me.rename("me").reset_index().rename(columns={"index": "date"}),
on="date",
how="left",
)
if cfg.add_rd_pillar:
with np.errstate(invalid="ignore", divide="ignore"):
rd_me = m_monthly["ttm_research_development"] / m_monthly["me"]
m_monthly["rd_me"] = rd_me.where(
(m_monthly["ttm_research_development"] > 0) & (m_monthly["me"] > 0)
)
tk_bi = bab_ivol[bab_ivol["ticker"] == ticker][["date", "bab", "ivol"]]
m_monthly = m_monthly.merge(tk_bi, on="date", how="left")
# Prior-year TTM net income (for Ohlson INTWO / CHIN). ttm_net_income is
# forward-filled quarterly, so a 12-month shift gives the TTM NI known
# one fiscal year earlier.
m_monthly = m_monthly.sort_values("date")
m_monthly["_ttm_ni_prior"] = m_monthly["ttm_net_income"].shift(12)
monthly_frames.append(m_monthly)
if not monthly_frames:
logger.warning("build_qmj_panel: no tickers produced measures")
cols = [
"date",
"ticker",
"qmj_profitability",
"qmj_growth",
"qmj_safety",
"qmj_payout",
"qmj_quality",
"qmj_n_measures",
]
empty = pd.DataFrame(columns=cols)
if out_path:
empty.to_parquet(out_path)
return empty
panel_m = pd.concat(monthly_frames, ignore_index=True)
# Compute O / Z per (date, ticker) row now that ME + prior-NI are present.
panel_m["o_raw"] = panel_m.apply(_row_ohlson, axis=1, cpi=cpi)
panel_m["o_score"] = -panel_m["o_raw"] # high O = bad → negate
panel_m["z_score"] = panel_m.apply(_row_altman, axis=1)
# Cross-sectional rank-z per date for every measure, then pillars, gate.
out_rows: list[pd.DataFrame] = []
for date, grp in panel_m.groupby("date"):
g = grp.copy()
z = pd.DataFrame(index=g.index)
for m in all_measures:
z[m] = rank_z(g[m]) if m in g.columns else np.nan
prof = _pillar_score(z, _PROFITABILITY)
grow = _pillar_score(z, _GROWTH)
safe = _pillar_score(z, _SAFETY)
pay = _pillar_score(z, _PAYOUT)
rd = _pillar_score(z, _RD) if cfg.add_rd_pillar else None
n_measures = z[all_measures].notna().sum(axis=1)
gate = _coverage_gate(
z, cfg.require_pillars, cfg.min_measures_overall, all_measures=all_measures
)
pillar_cols = [prof, grow, safe, pay]
if rd is not None:
pillar_cols.append(rd)
pillar_avg = pd.concat(pillar_cols, axis=1).mean(axis=1, skipna=True)
quality = rank_z(pillar_avg.where(gate))
out = pd.DataFrame(
{
"date": date,
"ticker": g["ticker"].to_numpy(),
"qmj_profitability": prof.to_numpy(),
"qmj_growth": grow.to_numpy(),
"qmj_safety": safe.to_numpy(),
"qmj_payout": pay.to_numpy(),
"qmj_quality": quality.to_numpy(),
"qmj_n_measures": n_measures.to_numpy(),
}
)
if rd is not None:
out["qmj_rd"] = rd.to_numpy()
out["rd_me"] = g.get("rd_me", pd.Series(np.nan, index=g.index)).to_numpy()
out_rows.append(out)
result = pd.concat(out_rows, ignore_index=True)
result = result.dropna(subset=["qmj_quality"]).reset_index(drop=True)
result = result.sort_values(["date", "ticker"]).reset_index(drop=True)
logger.info(
"build_qmj_panel: %d (date, ticker) quality scores over %d tickers, %s..%s",
len(result),
result["ticker"].nunique(),
result["date"].min().date() if len(result) else "n/a",
result["date"].max().date() if len(result) else "n/a",
)
if out_path:
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
result.to_parquet(out_path)
return result
def _shares_monthly(
pit_shares: pd.Series, monthly_dates: pd.DatetimeIndex, pit_lag_days: int
) -> pd.Series:
out = pd.Series(np.nan, index=pd.DatetimeIndex(monthly_dates))
if pit_shares.empty:
return out
known_from = pit_shares.index + pd.Timedelta(days=pit_lag_days)
sh = pd.Series(pit_shares.to_numpy(), index=known_from).sort_index()
for d in out.index:
visible = sh[sh.index <= d]
if not visible.empty:
out.loc[d] = visible.iloc[-1]
return out
def _row_ohlson(row: pd.Series, cpi: pd.Series) -> float:
try:
ni_prior = row.get("_ttm_ni_prior")
if not np.isfinite(ni_prior):
ni_prior = row.get("ttm_net_income")
return ohlson_o_score(
total_assets=row.get("total_assets", np.nan),
total_liabilities=row.get("total_liabilities", np.nan),
short_term_debt=row.get("short_term_debt", np.nan),
lt_debt=row.get("lt_debt", np.nan),
current_assets=row.get("current_assets", np.nan),
current_liabilities=row.get("current_liabilities", np.nan),
ttm_net_income=row.get("ttm_net_income", np.nan),
ttm_net_income_prior=ni_prior,
ttm_pretax_income=row.get("ttm_pretax_income", np.nan),
book_equity=row.get("book_equity", np.nan),
market_cap=row.get("me", np.nan),
cpi=_cpi_at(cpi, pd.Timestamp(row["date"])),
)
except (ZeroDivisionError, ValueError, TypeError, FloatingPointError):
return np.nan
def _row_altman(row: pd.Series) -> float:
try:
return altman_z_score(
working_capital=row.get("wc_refined", np.nan),
retained_earnings=row.get("retained_earnings", np.nan),
ttm_operating_income=row.get("ttm_operating_income", np.nan),
market_cap=row.get("me", np.nan),
ttm_revenue=row.get("ttm_revenue", np.nan),
total_assets=row.get("total_assets", np.nan),
)
except (ZeroDivisionError, ValueError, TypeError, FloatingPointError):
return np.nan