verify_official: 497/497K forms, per-share layout, candidate re-ranking

- EFTS queries now include 497/497K (many fund families publish their
  per-fund highlights there, not in the consolidated N-CSR) and re-rank
  hits by registrant name match (ticker/brand words), newest first,
  capped at 2 filings per CIK
- new parse_per_share_blocks for the JPMorgan-style 'Per share operating
  performance' table (per-class value blocks; dashes = zero)
- parse_highlights now tolerates row labels split across table cells
  (modernized N-CSRS format, e.g. Calamos 2026)
- region finders: word-flexible name patterns (US vs U.S., class letters),
  self-validating per-share regions (a candidate block must match the
  local series, so a name mention in notes doesn't attribute another
  fund's tables in a combined 58 MB report)
- main() keeps the best result across candidate filings (N-CSRS vs 497
  can round differently) and stops early on 'ok'
- local_series applies the corrections overlay so corrected funds verify
  against their filing

Results: JLPSX and CVSIX now 'ok' (all bounded fiscal years agree with
the official filings); CVSIX also gets a 2023-12-21 0.510 capital-gain
correction. bnd/pmaix still ok (no regression).
This commit is contained in:
gmp
2026-08-31 18:10:39 -04:00
parent 9263283995
commit 1f5720d7db
243 changed files with 6773 additions and 116 deletions
+245 -40
View File
@@ -65,8 +65,8 @@ ROOT = D.DEFAULT_ROOT
REPORT_DIR = Path(__file__).resolve().parent.parent / "reports" / "xcheck_official"
FUNDS = Path(__file__).resolve().parent.parent / "funds.json"
EFTS_URL = "https://efts.sec.gov/LATEST/search-index?q={q}&forms=N-CSR,N-CSRS,10-K,10-Q"
FORMS = ("N-CSR", "N-CSRS", "10-K", "10-Q")
EFTS_URL = "https://efts.sec.gov/LATEST/search-index?q={q}&forms=N-CSR,N-CSRS,10-K,10-Q,497,497K"
FORMS = ("N-CSR", "N-CSRS", "10-K", "10-Q", "497", "497K")
_STOP = {"fund", "funds", "inc", "ltd", "llc", "trust", "company", "the",
"and", "of", "for", "class", "series", "shares", "share", "in",
"on", "at", "to", "a", "an", "with", "portfolio", "portfolios",
@@ -74,6 +74,9 @@ _STOP = {"fund", "funds", "inc", "ltd", "llc", "trust", "company", "the",
"institutional", "etf", "plus", "select", "retail", "wholesale",
"group", "capital", "global", "us", "u.s."}
# 'Financial Highlights' often sits in separate table cells
# ("Financial |Highlights"); tolerate pipes/whitespace between the words
FH = r"Financial[\s|]+Highlights"
TOL_REL = 0.015 # 1.5% per year
TOL_ABS = 0.015 # or $0.015/share (official figures are 3-dp)
NAV_TOL = 0.25 # class match: |local_close - official_nav| / nav
@@ -214,8 +217,12 @@ def parse_highlights(text: str) -> list[dict]:
tag-stripped). A block starts at a 'Net asset value, beginning' row
(both Vanguard's 'Net Asset Value, Beginning of Period' and Victory's
'Net asset value, beginning of period' style)."""
# Row labels are often split across table cells ("Net | asset | value,
# beginning"); pattern searches run on a pipe-flattened copy (1:1
# offsets). Cell-based label extraction below uses the original.
flat = text.replace("|", " ")
starts = [m.start() for m in
re.finditer(r"net\s+asset\s+value,\s*beginning", text, re.I)]
re.finditer(r"net\s+asset\s+value,\s*beginning", flat, re.I)]
blocks = []
for i, s in enumerate(starts):
end = starts[i + 1] if i + 1 < len(starts) else s + 25000
@@ -233,41 +240,41 @@ def parse_highlights(text: str) -> list[dict]:
# "Table of Contents" page footer (its page numbers would be read
# as bare year columns)
h0 = max(0, s - 2000)
toc = text.rfind("Table of Contents", h0, s)
fh = text.rfind("Financial Highlights", h0, s)
toc = flat.rfind("Table of Contents", h0, s)
fh = max([m.end() for m in re.finditer(FH, flat[h0:s])] or [h0]) + h0
h0 = max(h0, toc, fh)
periods = _header_periods(text, h0, s)
periods = _header_periods(flat, h0, s)
if len(periods) < 2:
continue
n = len(periods)
i_end = min(end, text.find("See accompanying", s) if
text.find("See accompanying", s) != -1 else end)
i_end = min(end, flat.find("See accompanying", s) if
flat.find("See accompanying", s) != -1 else end)
def row(pattern: str) -> Optional[list]:
mm = re.search(pattern, text[s:i_end], re.I)
mm = re.search(pattern, flat[s:i_end], re.I)
if not mm:
return None
i0, i1 = s + mm.end(), i_end
for b in [x.start() for x in re.finditer(_ROW_LBL,
text[s:i_end], re.I)]:
flat[s:i_end], re.I)]:
if b > mm.end():
i1 = s + b
break
return _decimals(text, i0, i1, n)
return _decimals(flat, i0, i1, n)
# distribution rows: prefer explicit "from net investment income" /
# "from realized capital gains" labels (Vanguard); otherwise the
# "Distributions to shareholders:" sub-table (Victory), where the
# NII row is the first "Net investment income" after that header
ni = row(r"dividends?\s+from\s+(?:net\s+)?investment\s+income")
cg = row(r"(?:distributions?|dividends?)\s+from\s+(?:net\s+)?realized\s+capital\s+gains?")
cg = row(r"(?:distributions?|dividends?)\s+from\s+(?:net\s+)?realized\s+(?:capital\s+)?gains?")
if ni is None:
dm = re.search(r"distributions?\s+to\s+shareholders", text[s:i_end], re.I)
dm = re.search(r"distributions?\s+to\s+shareholders", flat[s:i_end], re.I)
if dm:
mm = re.search(r"net\s+investment\s+income", text[s + dm.end():i_end], re.I)
mm = re.search(r"net\s+investment\s+income", flat[s + dm.end():i_end], re.I)
if mm:
i0 = s + dm.end() + mm.end()
ni = _decimals(text, i0, i_end, n)
ni = _decimals(flat, i0, i_end, n)
tot = row(r"total\s+distributions?\b")
if ni is None and tot is None:
continue
@@ -286,11 +293,81 @@ def parse_highlights(text: str) -> list[dict]:
return blocks
def _cellnum(c: str) -> Optional[float]:
"""One table cell -> number. Dashes (a zero with a footnote) count as
0.0; footnote-only and junk cells are None."""
c = c.replace("$", "").replace(",", "").replace("&#160;", " ").strip()
if not c:
return None
if c.startswith("—") or c in ("-", "–"):
return 0.0
m = re.fullmatch(r"(\()?(\d+\.\d+|\.\d+)(\))?(\s*\([a-z]\))?", c)
if m:
return -float(m.group(2)) if m.group(1) else float(m.group(2))
return None
def parse_per_share_blocks(text: str) -> list[dict]:
"""JPMorgan-style shareholder-report layout ('Per share operating
performance'): each class block lists, per 'Year Ended <date>' column,
NAV beginning, NII, realized/unrealized gain, total from operations,
distribution NII, distribution capital gain, total distributions.
Cell-based (not _decimals): dash columns are real zeros, and the value
window must not run into the next year's column. Returns blocks
compatible with parse_highlights()."""
cells = [re.sub(r"\s+", " ", c).strip().replace("&#8212;", "—")
.replace("&#8195;", "").replace("&#8201;", "")
for c in text.split("|")]
events: list[tuple] = []
for i, c in enumerate(cells):
m = re.fullmatch(r"Year[s]?\s+Ended\s+(.+)", c)
if m and _parse_date(m.group(1)):
events.append((i, "year", m.group(1)))
elif re.fullmatch(r"Class\s+[A-Z0-9]{1,3}", c):
events.append((i, "class", c))
blocks: list[dict] = []
cur = None
for j, (i, kind, val) in enumerate(events):
if kind == "class":
cur = {"class": val, "periods": [], "nii": [], "capg": [],
"total": [], "nav_begin": [], "nav_end": None}
blocks.append(cur)
continue
if cur is None:
continue
d = _parse_date(val)
stop = events[j + 1][0] if j + 1 < len(events) else len(cells)
vals: list[float] = []
for c in cells[i + 1:stop]:
if re.fullmatch(r"Year[s]?\s+Ended\s+.+", c):
break
v = _cellnum(c)
if v is None:
continue
vals.append(v)
if len(vals) == 7:
break
if len(vals) != 7:
continue
cur["periods"].append({"end": d, "year": d[:4], "kind": "fy"})
cur["nav_begin"].append(abs(vals[0]))
cur["nii"].append(abs(vals[4]))
cur["capg"].append(abs(vals[5]))
cur["total"].append(abs(vals[6]))
return [b for b in blocks if len(b["periods"]) >= 2]
def html_to_cells_text(html: bytes) -> str:
t = re.sub(rb"<\s*(br|/p|/div|/tr|/h[1-6])[^>]*>", b"|\n", html, flags=re.I)
t = re.sub(rb"<[^>]+>", b"|", t)
t = t.decode("utf-8", "replace")
t = re.sub(r"&nbsp;?;", " ", t)
# numeric entities (&#8239; narrow nbsp, &#160; nbsp, ...) break literal
# searches like "Financial Highlights"; keep dashes (zero markers),
# collapse the rest to plain spaces
t = (t.replace("&#8212;", "—").replace("&#8211;", "–")
.replace("&mdash;", "—").replace("&ndash;", "–"))
t = re.sub(r"&#\d+;", " ", t)
t = re.sub(r"&[a-z]+;", " ", t)
return t
@@ -301,14 +378,20 @@ def _efits(q: str) -> list[dict]:
d = json.loads(edgar.sec_get(EFTS_URL.format(q=urllib.parse.quote(q)))
.decode("utf-8", "replace"))
out, seen = [], set()
for h in d.get("hits", {}).get("hits", [])[:20]:
# EFTS returns up to 100; small filings (497K notices) rank above the
# large combined reports, so keep the whole page and let the
# find_filings re-ranking pick the real thing
for h in d.get("hits", {}).get("hits", [])[:100]:
src = h.get("_source", {})
acc, _, doc = h.get("_id", "").partition(":")
if acc in seen or not doc.lower().endswith((".htm", ".html")):
continue
seen.add(acc)
out.append({"accession": acc, "doc": doc,
"period_end": src.get("period_ending") or "",
# 497s carry no period_ending; file_date keeps them
# orderable
"period_end": src.get("period_ending")
or src.get("file_date") or "",
"display": src.get("display_names", ["?"])[0],
"ciks": src.get("ciks", []),
"score": h.get("_score", 0)})
@@ -316,11 +399,25 @@ def _efits(q: str) -> list[dict]:
return out
def _brand(name: str) -> Optional[str]:
"""First distinctive word of the fund name, usually the family brand
(iShares, Fidelity, JPMorgan, SPDR, Invesco...)."""
for w in re.findall(r"[A-Za-z][A-Za-z\-'.]{2,}", name):
if w.lower() not in _STOP:
return w
return None
def find_filings(ticker: str, name: str, limit: int = 6) -> list[dict]:
"""Candidate filings, best first. A bare ticker matches hundreds of
unrelated documents, so: (1) the full fund name as one phrase (it only
appears in the fund's own filings), (2) ticker + distinctive name
words, (3) the bare ticker."""
unrelated documents, so: (1) the full fund name as one phrase, (2)
ticker + family brand, (3) ticker + distinctive name words, (4) the
bare ticker. Results are then ranked: a registrant whose display name
contains the ticker (single-fund trusts like 'SPDR GOLD TRUST (GLD)')
or the brand words (families like iShares Trust) ranks first, newest
filing first within a registrant. EFTS itself scores bag-of-words,
so unrelated prospectuses often outrank the fund's own 10-K — this
re-ranking is what makes ETF verification possible."""
def merge(f: list[dict]) -> None:
for x in f:
if x["accession"] not in {y["accession"] for y in out}:
@@ -328,14 +425,43 @@ def find_filings(ticker: str, name: str, limit: int = 6) -> list[dict]:
out: list[dict] = []
words = [w for w in re.findall(r"[A-Za-z][A-Za-z\-'.]{2,}", name)
if w.lower() not in _STOP]
brand = _brand(name)
if len(words) >= 4:
merge(_efits('"' + name + '"'))
if brand:
merge(_efits('"' + ticker + '" AND "' + brand + '"'))
if len(out) < limit and words:
merge(_efits('"' + ticker + '" AND ' +
" AND ".join('"' + w + '"' for w in words[:3])))
if len(out) < limit:
merge(_efits('"' + ticker + '"'))
return out[:limit]
name_words = {w.lower() for w in re.findall(r"[A-Za-z][A-Za-z\-'.]{3,}",
name)
if w.lower() not in _STOP}
scored = []
for f in out:
disp = f["display"].lower()
s = 4 * (1 if ticker.lower() in disp else 0) \
+ sum(1 for w in name_words if w in disp)
scored.append((s, f["period_end"], f))
scored.sort(key=lambda t: (t[0], t[1]), reverse=True)
per_cik: dict = {}
res = []
for s, pe, f in scored:
key = tuple(f["ciks"]) or (f["display"],)
if per_cik.get(key, 0) >= 2: # at most 2 filings per registrant
continue
per_cik[key] = per_cik.get(key, 0) + 1
res.append(f)
if len(res) >= limit:
break
return res
def _flex(s: str) -> str:
"""A word pattern that tolerates pipes/whitespace between words
(fund names often sit in one cell per word)."""
return r"[\s|]+".join(re.escape(w) for w in s.split())
def _title_runs(seg: str) -> list[str]:
@@ -376,13 +502,71 @@ def fund_region(text: str, ticker: str, name: str) -> Optional[str]:
if len(words) < 4:
continue
for tail_n in range(len(words), 3, -1):
anchor = " ".join(words[-tail_n:])
for m in re.finditer(re.escape(anchor), text, re.I):
fh = text.find("Financial Highlights", m.start(), m.start() + 4000)
if fh == -1:
anchor = _flex(" ".join(words[-tail_n:]))
for m in re.finditer(anchor, text, re.I):
fhm = re.search(FH, text[m.start():m.start() + 4000])
if not fhm:
continue
fh = m.start() + fhm.start()
reg = text[fh:fh + 150000]
if parse_highlights(reg):
if parse_highlights(reg) or parse_per_share_blocks(reg):
return reg
return None
def _name_pats(name: str) -> list[str]:
"""Pipe-tolerant name patterns. Yahoo longNames and filing names differ
("JPMorgan US Large Cap Core Plus I" vs "JPMorgan U.S. Large Cap Core
Plus Fund"), so match on runs of 3-4 distinctive words, dots optional.
Trailing single-letter / RC# class designators are dropped."""
if not name:
return []
words = [re.sub(r"\.", "", w) for w in name.split()]
while words and (len(words[-1]) <= 2 and words[-1].isalpha()):
words.pop()
pats = []
def mk(ws: list[str]) -> str:
# optional dots between letters: "US" matches "U.S." and vice versa
return r"[\s|]+".join(r"(?:" + r"\.?".join(re.escape(ch) for ch in w)
+ r"\.?)" for w in ws)
# tail runs (the distinctive part) and the head (brand + next words)
for n in (4, 3):
if len(words) >= n:
pats.append(mk(words[-n:]))
if len(words) > n:
pats.append(mk(words[:n]))
pats.append(mk(words))
return pats
def region_per_share(text: str, ticker: str, name: str,
loc: Optional[dict] = None) -> Optional[str]:
"""Region finder for the 'Per share operating performance' layout
(JPMorgan-style shareholder reports). Anchors on the fund name or
ticker; when `loc` (local series) is given, a candidate region is only
accepted if one of its class blocks actually matches the local
distributions — name mentions in notes/TOC of a 58 MB combined report
would otherwise attribute another fund's tables."""
pats = _name_pats(name)
pats.append(rf"(?<![A-Z0-9]){re.escape(ticker)}(?![A-Z0-9])")
for p in pats:
for m in re.finditer(p, text, re.I):
reg = text[m.start():m.start() + 400000]
blocks = parse_per_share_blocks(reg)
if not blocks:
continue
if loc is None:
return reg
for b in blocks:
errs = []
for i in range(len(b["periods"]) - 1):
off = abs(b["total"][i])
lc = _window_sum(loc["dist"], b["periods"][i + 1]["end"],
b["periods"][i]["end"])
if off < 0.01 and lc < 0.01:
continue
errs.append(abs(off - lc) / max(off, lc, 1e-9))
if errs and sum(errs) / len(errs) < 0.15:
return reg
return None
@@ -398,7 +582,7 @@ def region_by_name(text: str, name: str, min_shared: int = 3):
best word-overlap candidate with a parseable region."""
target = _wordset(name)
best = None
for m in re.finditer(r"Financial Highlights", text):
for m in re.finditer(FH, text):
pre = re.sub(r"&#\w+;", " ", text[max(0, m.start() - 400):m.start()])
pre = re.sub(r"[\s|]+", " ", pre).strip()
runs = re.findall(r"[A-Z][A-Za-z0-9'\u2019\-]*"
@@ -410,7 +594,7 @@ def region_by_name(text: str, name: str, min_shared: int = 3):
if shared < min_shared:
continue
reg = text[m.start():m.start() + 150000]
if not parse_highlights(reg):
if not (parse_highlights(reg) or parse_per_share_blocks(reg)):
continue
if best is None or shared > best[0]:
best = (shared, reg, cand)
@@ -420,7 +604,10 @@ def region_by_name(text: str, name: str, min_shared: int = 3):
# ---------------------------------------------------------------- compare
def local_series(sym: str, root: Path, frozen: Path) -> dict:
"""Local (date, amount) distributions and close series; frozen copies
shadow the data root."""
shadow the data root, and the overrides/corrections overlay (confirmed
official fixes, see overrides/corrections/) is applied on top so a
corrected fund verifies against its filing rather than the raw dump."""
import pandas as pd
def read(sfx: str):
p = frozen / f"{sym}-{sfx}.csv"
if not p.exists():
@@ -432,7 +619,12 @@ def local_series(sym: str, root: Path, frozen: Path) -> dict:
parts = line.split(",")
if len(parts) >= 2:
out.append((parts[0][:10], float(parts[1])))
return out
ser = pd.Series({pd.Timestamp(d): v for d, v in out}, dtype=float)
try:
ser = D._apply_corrections(sym, sfx, ser)
except Exception:
pass
return [(ts.strftime("%Y-%m-%d"), float(v)) for ts, v in ser.items()]
dist = sorted(read("dividend") + read("capitalGain"))
p = frozen / f"{sym}-history.csv"
if not p.exists():
@@ -575,6 +767,8 @@ def main() -> int:
raise RuntimeError("json-only")
cands = find_filings(sym.upper(), name)
rec = {"symbol": sym, "name": name}
loc = local_series(sym, ROOT, D.FROZEN_DIR)
best = None
for filing in cands:
try:
doc = edgar.sec_get(
@@ -593,23 +787,34 @@ def main() -> int:
rb = region_by_name(text, name)
if rb:
region, how = rb[1], f"name:{rb[2]} (shared={rb[0]})"
if region is None:
rp = region_per_share(text, sym.upper(), name, loc)
if rp:
region, how = rp, "per-share-data"
if region is None:
continue # wrong document; try next candidate
rec["filing"] = filing
rec["how"] = how
rec["n_bytes"] = len(doc)
blocks = parse_highlights(region)
loc = local_series(sym, ROOT, D.FROZEN_DIR)
blocks = (parse_highlights(region)
or parse_per_share_blocks(region))
res = compare(sym, blocks, loc)
rec.update(res)
rec["verdict"] = res["verdict"]
break
res.update({"symbol": sym, "name": name, "filing": filing,
"how": how, "n_bytes": len(doc)})
# different official docs can disagree by a cent or two
# (N-CSRS vs 497 rounding); keep the best match but stop
# early on a clean "ok"
key = (res["verdict"] != "ok", res.get("mean_rel_err", 1.0))
if best is None or key < (best["verdict"] != "ok",
best.get("mean_rel_err", 1.0)):
best = res
if res["verdict"] == "ok":
break
if best is not None:
rec.update(best)
else:
rec["verdict"] = "not-found"
rec["detail"] = ("no candidate filing contained this fund "
f"({len(cands)} tried)")
except Exception as e:
rec = {"symbol": sym, name: name, "verdict": "error",
rec = {"symbol": sym, "name": name, "verdict": "error",
"detail": str(e)[:300]}
out.write_text(json.dumps(rec, indent=1))
summary.append(rec)