security-master / recipe /quality.py
ZipLime's picture
Update the security master
ed5ee12 verified
Raw History Blame Contribute Delete
8.8 kB
"""Checks that decide whether a build may be published.
A security master fails quietly. A wrong ticker does not raise; it silently
sends a backtest to another company's price series, and the result looks
plausible. So the checks here are about identity: that a ticker current for one
filer is not simultaneously current for another, that intervals are ordered,
that the CUSIP bridge resolves the names everyone actually looks up.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import polars as pl
from .store import read_table
# Floors measured on the corpus, set below what it gives so a regression fails
# and noise does not.
MIN_TICKER_COVERAGE = 0.70
# Weighted by how often a CUSIP appears in settlement records, and counting
# only instruments that could resolve. A plain count of matched CUSIPs is the
# wrong measure: two thirds of the CUSIPs ever traded are one-off warrants,
# foreign lines and delisted shells, and exchange-traded funds -- which settle
# like shares and file nothing -- can never resolve at all. By count the bridge
# looks 37% complete; it covers 88% of the position value actually held in 13F.
MIN_CUSIP_WEIGHTED_MATCH = 0.60
MIN_ISSUERS = 15_000
# A ticker genuinely belongs to two filers at once only in odd cases -- a
# reorganisation mid-transfer, a dual filer. Above this share it means the
# ticker history is being stitched to the wrong companies.
MAX_AMBIGUOUS_CURRENT_TICKERS = 0.02
@dataclass
class QualityReport:
errors: list[str] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
metrics: dict[str, Any] = field(default_factory=dict)
def error(self, message: str) -> None:
self.errors.append(message)
def warn(self, message: str) -> None:
self.warnings.append(message)
def metric(self, name: str, value: Any) -> None:
self.metrics[name] = value
@property
def ok(self) -> bool:
return not self.errors
def as_dict(self) -> dict[str, Any]:
return {
"ok": self.ok,
"generated_at": datetime.now(UTC).isoformat(),
"errors": self.errors,
"warnings": self.warnings,
"metrics": self.metrics,
}
def write(self, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(self.as_dict(), indent=2, default=str), encoding="utf-8")
def validate(data_dir: Path) -> QualityReport:
report = QualityReport()
data_dir = Path(data_dir)
observations = read_table(data_dir, "observations").collect()
identifiers = read_table(data_dir, "identifiers").collect()
issuers = read_table(data_dir, "issuers").collect()
cusip_map = read_table(data_dir, "cusip_map").collect()
pit = read_table(data_dir, "pit").collect()
for name, frame in (
("observations", observations), ("identifiers", identifiers),
("issuers", issuers), ("cusip_map", cusip_map), ("pit", pit),
):
report.metric(f"rows_{name}", frame.height)
if issuers.is_empty():
report.error("issuers table is empty")
return report
if issuers.height < MIN_ISSUERS:
report.error(f"only {issuers.height} issuers, below the {MIN_ISSUERS} floor")
for column in ("cik", "kind", "value", "observed_on", "source"):
nulls = observations[column].null_count()
if nulls:
report.error(f"observations.{column}: {nulls} nulls")
reversed_spans = identifiers.filter(pl.col("valid_to") < pl.col("valid_from")).height
if reversed_spans:
report.error(f"identifiers: {reversed_spans} spans end before they start")
duplicates = identifiers.height - identifiers.select("cik", "kind", "value").unique().height
if duplicates:
report.error(f"identifiers: {duplicates} duplicate (cik, kind, value) rows")
if issuers["cik"].n_unique() != issuers.height:
report.error("issuers: duplicate CIKs")
with_ticker = issuers.filter(pl.col("primary_ticker").is_not_null()).height
coverage = with_ticker / issuers.height
report.metric("issuers_with_ticker", round(coverage, 4))
active = issuers.filter(pl.col("is_active"))
report.metric("issuers_active", active.height)
if not active.is_empty():
active_coverage = active.filter(pl.col("primary_ticker").is_not_null()).height / active.height
report.metric("active_issuers_with_ticker", round(active_coverage, 4))
if active_coverage < MIN_TICKER_COVERAGE:
report.error(
f"only {active_coverage:.1%} of active issuers have a ticker, "
f"below the {MIN_TICKER_COVERAGE:.0%} floor"
)
# The check that matters most: a ticker current for two filers at once means
# somebody's history has been attached to the wrong company.
current = identifiers.filter((pl.col("kind") == "ticker") & pl.col("is_current"))
if not current.is_empty():
ambiguous = (
current.group_by("value").agg(pl.col("cik").n_unique().alias("filers"))
.filter(pl.col("filers") > 1)
)
share = ambiguous.height / current["value"].n_unique()
report.metric("ambiguous_current_tickers", ambiguous.height)
report.metric("ambiguous_current_ticker_share", round(share, 4))
if share > MAX_AMBIGUOUS_CURRENT_TICKERS:
report.error(
f"{ambiguous.height} tickers are current for more than one filer "
f"({share:.1%}) — histories are being stitched to the wrong companies"
)
if not cusip_map.is_empty():
matched = cusip_map.filter(pl.col("cik").is_not_null()).height
report.metric("cusip_rows", cusip_map.height)
report.metric("cusip_matched_share", round(matched / cusip_map.height, 4))
resolvable = cusip_map.filter(~pl.col("looks_like_fund").fill_null(False))
weight = resolvable["observations"].sum() or 1
rate = resolvable.filter(pl.col("cik").is_not_null())["observations"].sum() / weight
report.metric("cusip_weighted_match", round(rate, 4))
report.metric("cusip_fund_rows", cusip_map.height - resolvable.height)
report.metric(
"cusip_by_confidence",
{
row["match_confidence"]: row["n"]
for row in cusip_map.group_by("match_confidence")
.agg(pl.len().alias("n")).iter_rows(named=True)
},
)
if rate < MIN_CUSIP_WEIGHTED_MATCH:
report.error(
f"only {rate:.1%} of non-fund CUSIP traffic resolved to a filer, "
f"below the {MIN_CUSIP_WEIGHTED_MATCH:.0%} floor"
)
if cusip_map.select("cusip", "ticker").unique().height != cusip_map.height:
report.error("cusip_map: duplicate (cusip, ticker) rows")
# A fund family shares one CUSIP prefix, so a fund inheriting its filer
# from that prefix means one accidental ticker collision has named every
# fund under it. This is how IVV, IWM and EFA came to be ICF International.
inherited_funds = cusip_map.filter(
pl.col("looks_like_fund").fill_null(False)
& (pl.col("match_method") == "cusip6_inherited")
).height
report.metric("cusip_fund_rows_inherited", inherited_funds)
if inherited_funds:
report.error(
f"cusip_map: {inherited_funds} fund rows took a filer from their CUSIP "
f"prefix — a fund family's prefix names no operating company"
)
report.metric(
"cusip_name_conflicts",
cusip_map.filter(pl.col("match_method") == "name_conflict").height,
)
if not pit.is_empty():
if pit.height != identifiers.height:
report.error(
f"pit has {pit.height} events for {identifiers.height} identifier spans"
)
for column in ("entity_id", "event_date", "knowledge_date"):
if pit[column].null_count():
report.error(f"pit.{column}: {pit[column].null_count()} nulls")
bounds = observations.select(
pl.col("observed_on").min().alias("first"), pl.col("observed_on").max().alias("last")
).row(0)
report.metric("coverage_first_observation", str(bounds[0]))
report.metric("coverage_last_observation", str(bounds[1]))
report.metric(
"observations_by_source",
{
row["source"]: row["n"]
for row in observations.group_by("source").agg(pl.len().alias("n")).iter_rows(named=True)
},
)
return report
__all__ = ["QualityReport", "validate"]