Fix Yahoo total-distribution double count (1,957 syms)

Yahoo's dividend endpoint returns the fund's TOTAL per-share distribution
(dividend + capital gain) for many share classes while the capitalGains
endpoint returns the cap-gain portion separately; summing both double-counted
cap gains and broke pre/post-tax comparability (after-tax engine could beat
the adj-based pre-tax return: impossible).

Add _fix_total_distributions to the bundle-assembly invariants
(layout-agnostic, survives re-downloads): on same-date div>capg events, the
exact Yahoo-adj implied distribution (d = P - Q*A_{t-1}/A_t) must match the
div-file amount (not the sum) on >=3 dates before rewriting div -= capg.
Self-validating: genuine separate same-date distributions are untouched.
Rewrote 17,900 cells on 1,957 symbols.

Pool check (scripts/check_adj_consistency.py): all 14 symbols now
TR(close+events) == TR(adj) to 0.01pt and post < pre with plausible drags.

Tests: rewrite case, no-rewrite case, idempotency (tests/test_data.py).
This commit is contained in:
gmp
2026-09-01 16:23:03 -04:00
parent 6c147cc850
commit 5e5a10d725
4 changed files with 301 additions and 2 deletions
+60
View File
@@ -220,9 +220,69 @@ def main() -> int:
D.CORRECTIONS_DIR = real_corr
finally:
shutil.rmtree(tmp, ignore_errors=True)
test_total_distributions()
print(f"\n{PASS} passed, {FAIL} failed")
return 1 if FAIL else 0
def test_total_distributions() -> None:
"""Yahoo 'dividend file = total distribution' invariant (unit level)."""
n = 8
idx = pd.DatetimeIndex([f"2024-01-{i + 1:02d}" for i in range(n)])
def close_from(start: float, total_by_i: dict[int, float]) -> list[float]:
# price drops by the distribution on ex-dates (+0.05 drift)
c = [start]
for i in range(1, n):
d = total_by_i.get(i, 0.0)
c.append(c[-1] - d + 0.05)
return c
def adj_from(closes: list[float], total_by_i: dict[int, float]) -> list[float]:
# Yahoo convention: A_i = A_{i-1} * Q_i / (P_{i-1} - d)
a = [closes[0]]
for i in range(1, n):
d = total_by_i.get(i, 0.0)
a.append(a[-1] * closes[i] / (closes[i - 1] - d) if d else a[-1])
return a
def mk(vals: dict[int, float]) -> pd.Series:
s = pd.Series({idx[i]: v for i, v in vals.items()}, dtype=float)
return s.reindex(idx).fillna(0.0)
# tot: div file carries the TOTAL, capg file the cap-gain part
tot_div = {1: 1.0, 3: 2.0, 5: 1.5}
tot_cap = {1: 0.4, 3: 0.8, 5: 0.5}
# sep: genuine separate same-date distributions (adj matches the SUM)
sep_div = {1: 0.9, 3: 1.4, 5: 1.2}
sep_cap = {1: 0.4, 3: 0.3, 5: 0.2}
tot_close = close_from(100.0, tot_div)
sep_close = close_from(100.0, {i: sep_div[i] + sep_cap[i] for i in sep_div})
close_df = pd.DataFrame({"tot": tot_close, "sep": sep_close}, index=idx)
adj_df = pd.DataFrame({
"tot": pd.Series(adj_from(tot_close, tot_div), index=idx),
"sep": pd.Series(adj_from(sep_close, {i: sep_div[i] + sep_cap[i]
for i in sep_div}), index=idx),
})
div_df = pd.DataFrame({"tot": mk(tot_div), "sep": mk(sep_div)}, index=idx)
capg_df = pd.DataFrame({"tot": mk(tot_cap), "sep": mk(sep_cap)}, index=idx)
fixed = D._fix_total_distributions(div_df, capg_df, close_df, adj_df)
check("total-dist: only 'tot' rewritten", fixed == ["tot"])
check("total-dist: tot div -= capg (sum preserved)",
all(abs(div_df.at[idx[i], "tot"] - (tot_div[i] - tot_cap[i])) < 1e-12
for i in tot_div)
and all(abs(div_df.at[idx[i], "tot"] + capg_df.at[idx[i], "tot"]
- tot_div[i]) < 1e-12 for i in tot_div))
check("total-dist: 'sep' (adj matches sum) untouched",
all(div_df.at[idx[i], "sep"] == sep_div[i] for i in sep_div))
# idempotent: second pass changes nothing (mask now div>cap still true but
# adj already reflects the total -> rewrite would break the match)
div2 = div_df.copy()
fixed2 = D._fix_total_distributions(div2, capg_df, close_df, adj_df)
check("total-dist: idempotent (no double subtraction)",
fixed2 == [] and (div2["tot"] == div_df["tot"]).all())
if __name__ == "__main__":
sys.exit(main())