Compare commits

...
26 Commits
Author SHA1 Message Date
gmp 4236ca1866 AGENTS.md: document the 8599 hot-reload trap (app.py reloads, imported modules don't) + server relaunch recipe 2026-09-02 07:25:47 -04:00
gmp bdb887dee8 Statistics tab: use the BIL daily total return as rf (Fund Lab convention)
- No fixed risk-free rate: the statistics page now nets Sharpe, Sortino
  and CAPM alpha against BIL (SPDR 1-3 Month T-Bill) daily total
  returns from the data bundle — the same reference the Fund Lab uses
  for all its alphas (pre-2007 dates fill 0, as in fundlab.decompose).
- metrics: sharpe/sortino/beta_alpha/summary accept a daily rf SERIES
  (or scalar annual rate as before) via a shared excess() helper.
- Also fixes a latent double-count: the old scalar-rf alpha subtracted
  rf twice (once in the returns, once in the intercept term); alpha is
  now mean(excess fund) - beta * mean(excess bench), the standard CAPM
  intercept on excess returns.
- Page caption states the T-bill reference (or warns if BIL is absent).
- Tests: series-rf identities (sharpe/sortino/beta/alpha), benchmark
  self-row beta 1 / alpha 0, caption check.
2026-09-02 07:03:17 -04:00
gmp d5a7bb70b0 Statistics tab: fix benchmark alignment + rf-adjusted Sharpe/Sortino/alpha
- Pass the benchmark's DAILY price series to metrics.summary() instead of
  a month-end-resampled one; summary() derives daily returns and
  annualizes with 252d, so the old resample made beta/alpha regress the
  fund's month-end daily returns against whole-month benchmark returns
  (and skewed ann_return_bench).
- New sidebar setting 'Risk-free rate %' (default 4%, persisted) passed
  through to summary(), so Sharpe, Sortino and CAPM alpha are computed
  in excess of rf; noted in the page caption and stats help.
2026-09-02 06:53:36 -04:00
gmp d7302b1646 Add LCRIX proxy portfolio (Leuthold Core, from 2026-03-31 N-CSRS asset mix) 2026-09-01 21:42:49 -04:00
gmp 9f657dc9f4 Tax engine: apply NIIT + state/local to the equity path (not just recorded taxes)
The full rate stack (federal + NIIT + state) was used for the recorded
tax columns and for realized gains at rebalances, but the equity path
itself deducted only the FEDERAL rate in two places:

1. distribution reinvestment kept (1 - div_rate)/(1 - lt_rate) instead of
   (1 - div_rate - niit - sl_rate);
2. the per-date liquidation tax ('sell everything today') passed bare
   (lt_rate, st_rate) to _liquidation_tax.

Symptom: FLCSX 10Y showed a 1.4pt after-tax drag instead of the true
~2.8pt. Fix: d_keep/c_keep factors and stacked liquidation rates.

Regression tests pin the equity path: reinvested net with NIIT+state,
ST and LT liquidation tax at the full stack (all fail on the old code).

Corrected 2015-2026 NYC after-tax: SPY 13.82->11.23, IVV 13.81->11.22,
JLPSX 13.68->9.18 (previously reported 12.51/12.50/11.31, superseded).
2026-09-01 17:22:04 -04:00
gmp 5e5a10d725 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).
2026-09-01 16:23:03 -04:00
gmp 6c147cc850 gitignore notes/ (personal tax profile); README pointer 2026-09-01 12:42:25 -04:00
gmp 19b33d5a18 Add NIIT + state/local rates to the after-tax model (NYC support)
NYC residents pay, on a capital-gain distribution, roughly 20% federal
+ 3.8% NIIT + 6.85-9.65% NY + 3.876% NYC = ~34-37% — the old model's
flat 20% understated the real after-tax drag of high-distribution
funds for this user by ~15 points on exactly the flows that matter.

tax.py: new niit + sl_rate params (decimals). sl_rate is the
state+local marginal rate applied at ORDINARY rates to every flow —
state and local have NO preferential cap-gain rate, so the composite
is lt_rate+niit+sl_rate on cap-gain dists, div_rate+niit+sl_rate on
dividends, and (st/lt_rate)+niit+sl_rate on realized gains.

app.py: two new sidebar fields (persisted in settings.json), wired
through _compute_portfolio's cache key.

tests/test_tax.py: 3 new cases (capg and div composite rates,
net-taxed realized ST gains/losses at st+NIIT+SL).

README: NYC rate note with the 2025 IT-201 schedule values (NYC 3.876%
over $50k; NY 6.85% at $215,400-$1.077M, 9.65% at $1.077M-$5M,
single filer) and the composite example.
2026-09-01 09:37:58 -04:00
gmp 576d9fba97 Fix after-tax model: raw prices + reinvestment (was 2.7x over-taxing)
The old model valued holdings in ADJ (total-return index) units but
computed distribution flows as raw per-share dollars — so every
distribution, and its tax, was overstated by the raw/adj ratio
(JLPSX: 30.10/11.25 = 2.7x; the Dec-2020 cap-gain tax showed as 12.1%
of the account instead of the true 4.5%). The wiggle in the after-tax
curve was this bug, not a convention issue.

tax.py now:
- values holdings in RAW share units on close prices (bundle.close);
- receives the per-share distribution on its event date, pays the tax
  (recorded in TaxResult.taxes), and reinvests the after-tax remainder
  at the same day's raw close — the tax's effect lives in the (smaller)
  reinvested units and is NOT also deducted from cash (double-count
  caught and fixed in review);
- recomputes market value after the reinvestment so equity[t] is the
  post-event liquidation value.

With the fix, the 'as-if-liquidated' equity on JLPSX's ex-div day drops
by exactly the true tax cost (4.72% vs 12.1% before); the -22.9% price
drop is offset by the distribution kept.

Also:
- app.py passes bundle.close to the after-tax model (pre-tax
  portfolio_returns still uses adj);
- JLPSX/JLPYX: the 2020-12-11 6.824 capital-gain distribution is moved
  to the true ex-div date 2020-12-14 (remove/add correction ops), so
  the reinvestment prices at the post-drop close;
- tests/test_tax.py: 8 synthetic regression tests (tax magnitude,
  reinvestment MV, no double-count, ex-div equity step, per-component
  rates); run_tests.sh now runs it.
2026-08-31 23:58:15 -04:00
gmp 43ddd3ec7f Repair Yahoo adj-close/event-date misalignment (JLPSX, JLPYX)
JLPSX showed a bogus +29.3%/-22.9% 3-day wiggle in Dec 2020: Yahoo dated
the 6.824 year-end cap-gain distribution on the 12-11 record date but the
market went ex-div on 12-14 (close 30.10 -> 23.22), so the raw Adj Close
column pre-applied the adjustment 3 days before the price actually fell.

New 'history' correction op ({date: {col: value}}) patches individual OHLC
cells at bundle assembly (full build, incremental, and correction-changed
recompute paths); check_corrections validates dates/columns; 4 new tests.

scripts/scan_adj_misalign.py finds the artifact set-wide: 481 hits on 278
symbols, overwhelmingly December year-end distributions of value funds
(JLPSX's class of fund). scripts/fix_adj_misalign.py repairs it
arithmetic-only (rescale adj in [event, ex-div) by (1-f); cumulative
returns unchanged, cross-checked implied dist vs the price drop). Applied
to the only curated-fund hit (JLPSX) and its sister class JLPYX (implied
dist 6.824 both = official amount; ex-div 2020-12-14). The remaining ~276
symbols are reported in reports/adj_misalign/scan.md for a bulk run.
2026-08-31 23:08:42 -04:00
gmp 3c5bee96ce Clean multi-vintage 'ctime' files: 1,065 files, 2.2M stale rows
Some dump files carry a trailing 'ctime' column: an older pipeline
appended a FULL re-download of the symbol per download (up to ~28
vintages per date, 2019-2022). The consumer keeps the last row per date,
so it silently used stale (~2021) vintages where Yahoo later revised
values. scripts/clean_multivintage.py keeps, per date, the rows from the
newest ctime (event files keep distinct same-day amounts; history/split
keep the single newest row), drops the ctime column, sorts by date.
Applied to the data root and overrides/frozen (which carried the same
artifact): 1,065 files, 2,202,712 stale rows dropped.

Also: stripped 3 UTF-8 BOMs (teg/lo/krft), refreshed the event backup
with the cleaned files, and re-ran the double-listing scan: category C
(83 symbols, 18,636 repeated within-file rows) is fully explained by the
multi-vintage artifact and is now gone; A (6,589 pairs, corrected) and
B (12,366 pairs, open review list) are unchanged. Whole-set structural
QC after cleaning: 0 duplicate dates, 3 syms/15 rows of OHLC invariant
violations, 15 syms/2,897 rows of non-positive prices (mostly
long-delisted tickers), 8 unsorted files (reader sorts).
2026-08-31 22:25:02 -04:00
gmp bb8e39605e Event-history protection: backup dir, empty-download fallback, docs
Yahoo's 2026 event-feed change (capitalGain events dropped for some
funds; no events at all for terminated tickers) can wipe good event
history on re-download. Defense in depth:

- overrides/event-backup/: last-known-good copy of every dividend/
  capitalGain file (8,192 files, 58 MB); refresh with
  scripts/backup_events.py after each dump update
- data.py event_file(): frozen > data-root (while populated) > backup;
  used by panel reads, verify_official, and the double-listing scanner
- README: capital-gain files are mutual-fund-only in this dump; Yahoo
  has no LT/ST split (tax.py taxes capg at lt_rate; the per-fund split
  would come from fund-company annual tax statements or commercial feeds)
- tests: exact Timestamp .loc keys (pandas 3.x string matching returns a
  Series on large DatetimeIndex)
2026-08-31 21:59:25 -04:00
gmp e20b2e30cb Double-listing: layout-agnostic invariants, whole-dump sweep, bulk corrections
Yahoo changed the shape of its event feed between downloads: a 2026-08
re-download of CVIX/JLPSX shows it no longer returns capitalGain events at
all (the dividend stream still carries the year-end rows), while stale
tickers now return no events at all. File-specific remove ops therefore
break silently on the next re-download, so the double-listing fix is now
expressed as layout-agnostic invariants applied at bundle assembly
(idempotent, hold for full and incremental builds):

  dedup: [[date, amount]]      keep at most one copy of a same-date/
      same-amount cross-file pair (the capitalGain copy when both present)
  drop_capg_copy: [date]       the capitalGain row on that date is the
      spurious copy of the dividend row

- data.py: apply_invariants() at bundle assembly + pure dedupe_event_rows()
  shared with verify_official and tests (8 new test cases, 22 passing)
- JLPSX/CVSIX corrections rewritten with the invariants (2019-08-08 now
  keeps the dividend amount per the verified same-date pattern)
- scripts/scan_double_listing.py: whole-dump sweep -> reports/double_listing/
  6,421 symbols scanned: 1,218 with same-amount pairs (6,589), 1,631 with
  differing-amount pairs (12,366, reported only - not distinguishable from
  legitimate same-day div+capg without per-fund official data), 83 with
  repeated within-file rows (ingest keep-last already collapses them)
- scripts/apply_dedup_corrections.py: bulk 'dedup' corrections for the
  1,218 same-amount symbols (1,212 new files; the 6 verified funds keep
  their explicit, official-verified corrections)
- scripts/check_corrections.py: integrity check for every correction op
  against the actual (frozen) files - caught a mis-filed CVSIX entry
2026-08-31 21:00:36 -04:00
gmp 08bc63a2ef README: update the remaining data gaps after the double-listing corrections 2026-08-31 19:50:52 -04:00
gmp e15cb51390 Corrections: resolve the 7 stale mismatches via the Yahoo double-listing pattern
Scanning the verified funds for same-date div/capg pairs showed the Yahoo
double-listing mechanism in every one of the 7 'mismatch' stale funds, and
the official fiscal-year totals pin down which amount is true:

- identical-amount pairs (JLPSX, GDEUX, GSOUX, FAEVX, CVSIX, FZAGX): the
  year-end distribution is in both files; keep the capitalGain copy,
  remove the dividend copy (GDEUX: FY2021-08 1.73 = 1.625+0.115 and
  FY2022-08 0.39 = 0.348+0.036 after; JLPSX/GSOUX/FAEVX/CVSIX same)
- differing-amount pairs (OTCRX, SHXIX, FZAGX, FGIZX, CVSIX): the
  dividend-file amount is the true one in every officially-verified case
  (OTCRX FY2023 0.85 = 0.852488, SHXIX FY2023 1.01 = 1.0078, FZAGX all
  four FYs exact); the capitalGain row is the spurious copy

After corrections GDEUX/SHXIX/CVSIX/JLPSX verify 'ok' against their
filings. The same pattern is extended to these funds' pre-2021 history
(marked mechanism-inferred in the correction notes). Remaining residuals:
FAEVX and FGIZX are also missing regular quarterly dividend rows in the
Yahoo dump (official FY totals exceed local even after dedup) - needs the
funds' per-date distribution archives; FIKAX's official extraction is
ambiguous (systematic ~0.12/yr offset = wrong class table in the
500-fund consolidated Fidelity N-CSRS).
2026-08-31 19:50:18 -04:00
gmp 1f5720d7db 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).
2026-08-31 18:10:39 -04:00
gmp 9263283995 Corrections overlay: per-symbol distribution fixes survive re-downloads
overrides/corrections/{SYM}.json (git-tracked, with as_of/source/note)
holds remove/replace/add ops on the dividend and capital-gain series.
data.py applies them on top of whatever the data root (or the frozen
snapshot) provides, in both the full build and the incremental refresh
path, and the corrections dir joins the cache manifest so a change
invalidates the cache. A goget re-download of the base CSV can never
clobber a confirmed correction. Format and usage documented in data.py.
2026-08-31 14:49:39 -04:00
gmp 6536c9903e Tier-3 verification: cross-check distributions against SEC filings
scripts/verify_official.py locates each fund's latest N-CSR/N-CSRS/10-K/10-Q
via EDGAR full-text search (full fund-name phrase first, then ticker +
name words, then bare ticker), extracts the fund's Financial Highlights
tables (both Vanguard-style and Victory-style layouts, calendar and
non-calendar fiscal years, M/D/YY and month-name headers), matches the
share class by per-share distribution series + NAV magnitude, and
compares per period window against the local Yahoo CSVs (frozen copies
for stale tickers). Per-symbol JSONs + SUMMARY.md land in
reports/xcheck_official/; results are cached per fund.

Run on the 29 curated funds: 8 ok (exact to 3dp, e.g. VTSAX 2021-2026H1),
1 mismatch (CVSIX FY2009: local 1.104 vs official 0.81 - the Yahoo
2008-12-18 row of 0.292 looks spurious), 3 weak-match (uncovered doc
formats, e.g. Leuthold), 17 not-found (mostly ETF families whose
10-K layouts aren't covered yet).
2026-08-31 14:41:03 -04:00
gmp 02aa750a06 Freeze stale (Yahoo-empty) tickers: snapshot final series in overrides/frozen/
230 tickers whose Yahoo chart responses now come back without a timestamp
array (terminated/merged funds): goget overwrites the .json on every pass
while ohlc.Conv skips the write, leaving the old CSVs as the last known
series. Snapshot them into overrides/frozen/ (git-tracked, audited in
reports/stale-funds.md) and make data.py prefer the frozen copies and
ignore any future data-root rewrite/delete for those symbols, so the
final series survives future goget runs. The cache manifest now covers
the overrides dir too; incremental refresh skips data-root files of
frozen symbols.
2026-08-31 13:23:24 -04:00
gmp 2bbe4e58ec Style-tilt battery + commentary in the fund report pipeline
fundlab/styletilt.py: 22 style/asset sleeves regressed on excess-of-T-bill
returns (full history + 5y); BIC forward selection identifies the tilt
stack; residual-alpha verdict ('factor exposure, not skill' when t<1.75);
data-driven English commentary with sign-specific phrasing. Rendered as a
'Style tilts' block (factor table + prose) in both the app and the HTML
report. All 24 pre-built + 8 ad-hoc fund reports rebuilt.
2026-08-30 20:36:04 -04:00
gmp d2ff607c79 On-demand per-fund reports for standalone Symbol-box funds
Any symbol that stands alone in the Symbol box (not a comma-joined
portfolio component) now gets a full report, built on demand and cached
in reports/report_data_adhoc.json. Rendered at the top of the Fund Lab
Summary as group 'A'; pointer at the top of the page. Rendering logic
extracted into render_fund_report() shared by pre-built and on-demand
entries. ~0.3-0.9 s per new fund after one-time panel warmup; instant
afterwards (memory + disk cache).
2026-08-30 18:35:42 -04:00
gmp e28f8fcf85 Report charts: re-basing-on-zoom widget (same as Equity tab); layout fixes
- per-fund report charts now use chart_widget.equity_chart_html
  (st.iframe) instead of static st.plotly_chart: every visible window
  re-bases each line to 1.0 at its left edge, so fund/reference/index
  compare in any zoom level - same semantics as the Equity curves tab
- removed 'expand all' checkbox (24 expanded sections drowned the page)
- added 'rest of Fund Lab continues below' marker after the report
  section; the other Fund Lab sections (alpha search, clusters, N-PORT,
  drawdown, tax, CEF) were never deleted and are unchanged
2026-08-30 18:15:11 -04:00
gmp 3fbf332b31 Per-fund report: app Summary page + narrative engine + mix_series beta fix
- fundlab/narrative.py: data-driven English prose per fund (performance,
  drivers tiered by fit, explicit 'what we do NOT know', bottom line)
- fundlab/reportdata.py: static build -> reports/report_data.json
- app.py Fund Lab Summary: at-a-glance table + per-fund expanders
  (narrative, equity curve, period table with fund-ref gap, drivers,
  reference mix, tax, cluster peers)
- fundlab/report.py: narrative in the HTML report; forward-selected
  reference (weak-fit funds anchor to cash); SLEEVE_DESC exposure
  explanations
- BUG: mix_series() never applied the betas (reference curves were raw
  sleeve sums; JLPSX 'reference' +407% vs fund +123%) - fixed and all
  reference curves/tables regenerated
- reports/fund_report.html + report_data.json regenerated
2026-08-30 17:36:58 -04:00
gmp 328855a926 Fund report: 11 candidates + 13 shortlist funds, self-contained HTML
fundlab/report.py -> reports/fund_report.html (20 MB, plotly inlined,
opens offline). Per fund: max-history equity curve (fund vs fitted
reference vs IVV); performance table (full/5y/1y, the 5 market
episodes, calendar years) with the fund-minus-reference period-alpha
column; drivers (reference-model R²/alpha/t + 34-sleeve signature +
curated decomposition verdict and N-PORT cross-check notes); the
reference mix explained sleeve-by-sleeve (what each exposure actually
is, plus net-cash/net-levered read); tax character + taxable/IRA
placement; and a peer table of the 4 best funds in the same k=30
return-driver cluster with computed advantages/disadvantages.

Weak-fit (R²<0.5) funds anchor their tables to CASH rather than the
statistically-thin forward-selected mix (which can be an offsetting
VIX/duration spec combination whose path is meaningless); the loadings
are still shown with a 'weak fit' caveat.
2026-08-30 17:00:41 -04:00
gmp 89674c24dd Compute all alphas in excess of the 3-mo T-bill rate (BIL)
Raw-intercept alphas absorbed the T-bill yield on uninvested/levered
portions (582 well-fitted funds >2%/yr off; sum-of-betas polluted by
level-matching). Now fund AND sleeves are netted against BIL daily
total return before every regression; a cash position contributes
exactly zero.

- decompose: rf_series()/excess(); shv+bil dropped from regressors
  (~0 columns in excess space); FULL_WINDOW -> 2007-06-01 (BIL
  inception; mixing raw pre-2007 with excess breaks the fit).
- factors: same excess treatment; shv out of DRIVERS.
- CASH axis redefined: alpha/cash_yield -> net cash position = 1 -
  sum(betas) (label 'cash (net posn)').
- CANDIDATE list 250 -> 11: the old list was mostly under-invested
  funds whose 'alpha' was cash yield, not skill.
- refback.py: per-fund fitted reference (forward-selected sleeves)
  stored as ref_5y/ref_full in search_all.json; app alpha-search
  table gains a 'reference (5y)' column - the answer to 'what is
  alpha computed against' (the fund's OWN fitted sleeve mix, not one
  index).
- App captions updated; raw-alpha-era results backed up as
  *_rawalpha.json (not deleted).
2026-08-30 15:50:15 -04:00
gmp 9f666538c3 Add CASH axis: money-market/cash-equivalents as a return driver
A fund's yield is a near-constant in return space, so OLS puts it in
the intercept (alpha_ann), not in the shv/bil betas (which only
measure rate-CHANGE sensitivity). Cash funds therefore showed no
dominant driver.

- factors: cash_yield() (shv trailing-1y total return = local
  stand-in for the 13-wk T-bill / 0-3m Treasury index), AXES =
  DRIVERS + ['cash'] (alpha_ann / cash_yield, 1.0 = earns the cash
  rate); a display/clustering axis, not a regressor.
- cluster: cash column in the loading matrix; k-means distances use
  the cash-2x-emphasized matrix (a pure cash fund's level axis was
  otherwise swallowed by the low-exposure cloud); labels use raw
  values; label() cash-aware (0.25 threshold, 1.5x runner-up).
- app: cluster view over AXES with the emphasized distance.

The 331-fund 'no dominant driver' grab-bag now splits into
'cash (yield) +0.64' (n=187, MM + ultra-short) and 'cash (yield)
+1.26' (n=59 pure). 123/123 tests.
2026-08-30 13:27:41 -04:00
10563 changed files with 1130449 additions and 696 deletions
+2
View File
@@ -9,3 +9,5 @@ fundlab/nport_cache/raw/
fundlab/universe_cache/
fundlab/xcheck_run.log
fundlab/streamlit.log
reports/report_data_adhoc.json
notes/
+54
View File
@@ -0,0 +1,54 @@
# Project notes for agents
## Relaunch the Streamlit server after changing ANY module other than app.py
The UI server runs on the **fixed port 8599** (started by `run.sh` or
`fundlab/server_watchdog.sh`, which keeps it alive every 5 min).
**Streamlit hot-reloads `app.py` on edit, but imported modules
(`metrics.py`, `data.py`, `portfolio.py`, `tax.py`, `fundlab/*`, ...)
stay cached in `sys.modules` for the process's whole lifetime.**
After editing any of those, the live server keeps running the OLD code
paired with the NEW `app.py` — a classic symptom is a cryptic TypeError
/ AttributeError on the page even though `tests/test_app.py` passes
(it spins up a fresh AppTest process).
After touching anything `app.py` imports, relaunch the server:
```bash
cd /mnt/Backup/prog/f
pkill -f 'streamlit run app\.py'; sleep 3
setsid nohup .venv/bin/streamlit run app.py --server.port 8599 \
--server.headless true --browser.gatherUsageStats false \
>> fundlab/streamlit.log 2>&1 < /dev/null & disown
# wait for health:
curl -s http://127.0.0.1:8599/_stcore/health # -> ok
```
(Or just `pkill` it and let the watchdog relaunch within 5 min.)
Note: `setsid ... &` from a short-lived shell may die with the shell in
some harnesses — if the health check never answers, retry the relaunch
from a longer-lived command.
Verify on the LIVE server with the browser test (server must be running):
```bash
.venv/bin/python tests/test_e2e_browser.py
```
## Tests
- `.venv/bin/python tests/test_app.py` — AppTest suite (no server needed).
- `.venv/bin/python tests/test_e2e_browser.py` — Playwright against the
live 8599 server.
- Both back up / restore `settings.json`; neither starts the server
(e2e) or needs it (test_app).
## Conventions
- **Risk-free rate = BIL (SPDR 1-3 Month T-Bill) daily total return**
from the data bundle — the single tool-wide convention for rf
(`fundlab/decompose.rf_series()` is the reference). Statistics tab
Sharpe/Sortino/alpha are in excess of it (`metrics.excess()`). Do not
introduce fixed/constant rf rates elsewhere.
- Data root is `~/prog/fin/stocks`; symbols in the bundle are lowercase.
+112 -1
View File
@@ -24,12 +24,117 @@ partial refresh takes seconds instead of a full ~1 min rebuild.
| `data.py` | Ingest `{sym}-history/dividend/capitalGain.csv` -> cached parquet panels (date x symbol), with manifest-based incremental refresh when the data dir changes. `Adj Close` already includes distributions, so it drives pre-tax total returns. |
| `metrics.py` | Total/annualized return, vol, Sharpe, Sortino, max drawdown, Calmar, CAPM beta/alpha. Pure pandas, all transparent. |
| `portfolio.py` | Weighted portfolios with drift and periodic rebalancing to target weights (`1W/1ME/QE/YE`), one-way cost in bps. Spec grammar: commas join the elements of ONE portfolio (`SYM` or `SYM:w`, bare = equal weight), spaces separate DISTINCT symbols/portfolios (`parse_items`). |
| `tax.py` | Simplified DAS after-tax engine: FIFO lots, 365-day long/short split, separate LT/ST/dividend rates. Headline curve = what you keep if you **sell everything today** (unrealized gains taxed daily by lot age). |
| `tax.py` | Simplified DAS after-tax engine: FIFO lots, 365-day long/short split, separate LT/ST/dividend rates plus federal NIIT and a state+local marginal rate (applied at ordinary rates — state/local have no preferential cap-gain rate). Headline curve = what you keep if you **sell everything today** (unrealized gains taxed daily by lot age). |
| `chart_widget.py` | Self-contained plotly.js chart in an iframe: mouse zoom/pan, x clamped to the data, view edges snapped to first/last data points with day-precise labels, y tight-fit, every line re-based to 1.0 at the left edge. |
| `portfolios.py` | Saved portfolio definitions in `portfolios.json` (name, spec, scheme, cost). |
| `settings.json` | Persisted UI inputs (symbol/benchmark specs, scheme, costs, tax rates, period, curve/window mode) — restored on every page load and server restart; delete to reset. |
| `app.py` | Streamlit UI: single "symbol or portfolio" spec field (page updates as soon as the input is valid; unknown symbols get click-to-fix "did you mean" suggestions) + a benchmark box with the same grammar (one benchmark per line; a line is a single symbol or a comma-joined portfolio, simulated with the same scheme/cost/tax rules — pre- and after-tax curves, first one drives beta/alpha), scheme/costs/tax rates, save + load/compare/delete portfolios (overlaid pre/after-tax curves), curve toggle (both / pre-tax only / after-tax only), stats table, allocation, per-year tax detail. |
## Data verification (Tier 3: against official filings)
Notes on the data itself:
- **Capital gains in this dump are mutual funds only.** The
dividend/capitalGain event files exist only for open-end mutual funds
(spot-checked: no ETFs, CEFs, BDCs or individual stocks carry them —
CEF/BDC distribution components are lumped into their dividend stream
by Yahoo). For total returns only the distribution TOTAL matters, which
is what Yahoo provides and what the corrections above fix.
- **There is no long-term/short-term split anywhere in the Yahoo data**
(an event is just a per-share amount), and the corrections never used
one either — the official checks compare total distributions. `tax.py`
therefore taxes capital-gain distributions at the long-term rate
(`lt_rate`), a simplification: fund cap-gain distributions are
predominantly long-term, but the per-fund LT/ST split would come from
the fund company's annual tax statement (1099-DIV detail: boxes 2a/2b),
the shareholder-report body, or a commercial feed (Lipper/Morningstar).
- **NYC residents: add the state+local layer.** The sidebar's two extra
rate fields exist for this. Set `NIIT %` to 3.8 if your MAGI is over
the threshold, and `State + local %` to your NY+NYC MARGINAL rate sum
(2025 single, from the Form IT-201 rate schedules): NYC is 3.876%
above $50k of city taxable income; NY is 6.85% at $215,400-$1.077M of
state taxable income and 9.65% at $1.077M-$5M. So a typical NYC
household pays, on a capital-gain distribution, roughly
20% federal + 3.8% NIIT + 6.85-9.65% NY + 3.876% NYC = ~34-37% —
which is exactly why high-distribution open-end funds lose so much
more to tax than ETFs for NYC residents (see the per-year tax detail
tab). Note: NY/NYC tax capital gains at ORDINARY rates (no
preferential cap-gain rate), which the single `State + local %` field
models correctly; the federal `Long-term gains %` field stays the
preferential 0/15/20%.
`~/prog/fin/stocks` is a Yahoo dump and gets re-downloaded (overwritten),
so fixes must live outside it. Pipeline:
1. `scripts/audit_stale.py` — finds tickers whose latest history row is
old and whose fresh Yahoo download is empty (delisted/merged funds,
tickers Yahoo no longer serves). Snapshots their final
`{history,dividend,capitalGain}.csv` + `longName` into
`overrides/frozen/{SYM}.{ext|json}`. `data.py` shadows the data root
with the frozen copies, so a re-download can't clobber them.
1b. `overrides/event-backup/` — backup of every dividend/capitalGain file
(refresh with `scripts/backup_events.py` after each dump update).
Yahoo changed its event feed in 2026: for some funds it no longer
returns `capitalGains` events at all, and terminated funds return no
events, so a re-download can empty or orphan good event history. The
data-root file wins while it is populated; an emptied/missing one
falls back to the backup (`data.py event_file`). The `ohlc` converter
likewise refuses to overwrite a populated event CSV with an empty
download. (Yahoo omits the whole `capitalGains` JSON key when there
are no events, so plain re-downloads in place usually leave old files
untouched — the backup is the second line of defense.)
2. `scripts/verify_official.py [syms | --stale]` — finds the fund's
shareholder report (EDGAR EFTS for `"TICKER"`, forms N-CSR/N-CSRS/
N-14/N-2/497) and parses the per-class *Financial Highlights* (or
JPMorgan-style *Per share operating performance*) tables: period-by-
period distribution totals compared against local
dividends + capital-gains over the same windows, plus a spot check of
the NAV-per-share row against the local close. Verdicts per symbol in
`reports/xcheck_official/{sym}.json`: **ok** (all bounded fiscal
years agree), **mismatch** (class matched, some year off — the
report tells you which), **weak-match** (best class fit too poor to
trust), **not-found** (fund not in any candidate filing). The local
side applies the corrections overlay, so a corrected fund verifies
against its filing. When several filings parse (e.g. the 497 annual
and the N-CSRS, which can round differently), the best match wins.
3. Confirmed findings go into `overrides/corrections/{SYM}.json` as
auditable deltas (`remove`/`replace`/`add` of distribution rows, each
entry dated and valued — amounts are what Yahoo reports, not the
official filing's). `data.py` applies them on cache build. Examples:
- **CVSIX** — 2008-12-18 0.292 duplicate of the same day's 0.641
(official FY09 = 0.81 balances without it); 2023-12-21 0.510
capital-gain row duplicated next to the day's 0.691 dividend
(official FY2024-10 = 0.79 balances without it).
- **JLPSX** — 13 year-end capital-gain distributions duplicated into
the dividend file (FY2021–2025 all match the JPMorgan 497 after
removal).
Remaining known data gaps (need the fund company's per-date
distribution archive; fiscal-year totals alone can't reconstruct them):
FAEVX and FGIZX — the Yahoo dump is missing the funds' regular quarterly
dividend rows (official fiscal-year totals exceed local even after the
double-listing dedup above); FIKAX — the official extraction is ambiguous
(the 500-fund consolidated Fidelity N-CSRS has multiple near-identical
sub-fund tables, and the best match is a systematic ~0.12/yr offset,
i.e. the wrong share class).
**Whole-dump double-listing sweep.** `scripts/scan_double_listing.py`
scans every symbol's effective event files for the pattern and writes
`reports/double_listing/scan.{md,json}`. On the 2026-08 dump (6,421
symbols with event files): 1,218 symbols had same-date/same-amount
cross-file pairs (6,589 pairs, 80% in December / fiscal year-end), 1,631
had same-date differing-amount pairs (12,366), and 83 had repeated
same-date rows within one file (Yahoo repeating a row up to ~35x; the
ingest already keeps the last). The same-amount pairs were corrected in
bulk by `scripts/apply_dedup_corrections.py` (1,212 correction files,
`dedup` invariant, mechanism-inferred and individually revertible). The
differing-amount pairs are reported but NOT auto-corrected: without a
per-fund official schedule they can't be distinguished from a legitimate
same-day dividend + capital-gain pairing — that's the open review list
(scan.md, category B). `scripts/check_corrections.py` verifies every
correction op against the actual files (a remove that matches nothing is
a silent no-op — it caught a mis-filed entry in CVSIX).
## Development
- **Run**: `./run.sh` → http://localhost:8599 (fixed port; no-ops if a
@@ -65,3 +170,9 @@ partial refresh takes seconds instead of a full ~1 min rebuild.
Ideas: vectorbt sweeps over rebalance schemes, NiceGUI/Textual frontend,
empyrical-reloaded metrics, monthly (not yearly) loss netting, tax-loss
harvesting simulation.
## Local notes
`notes/tax.md` (gitignored) holds the personal tax profile, verified rate tables,
inherited-IRA rules/strategy, and the vehicle plan for this account. Update it when
tax facts change.
+254 -55
View File
@@ -60,6 +60,12 @@ if not up_to_date(Path(root)):
# data symbols are stored lowercase; input is resolved case-insensitively
_LOWER2SYM = {s.lower(): s for s in bundle.adj.columns}
# risk-free rate for the statistics page: BIL (SPDR 1-3 Month T-Bill)
# daily total return — the same convention as the Fund Lab (alphas in
# excess of the 3-mo T-bill, cash earns exactly the rf rate)
_bil = _LOWER2SYM.get("bil")
rf = m.daily_returns(bundle.adj[_bil]) if _bil is not None else None
def _resolve_weights(w: dict) -> dict:
"""Map parsed symbols onto the data's symbol case (insensitive match)."""
@@ -129,6 +135,14 @@ st_rate = st.sidebar.number_input("Short-term gains %", 0.0, 49.0,
float(_settings.get("st_rate", 15.0))) / 100
div_rate = st.sidebar.number_input("Dividends %", 0.0, 49.0,
float(_settings.get("div_rate", 15.0))) / 100
niit = st.sidebar.number_input(
"NIIT % (federal 3.8% on investment income if MAGI over the "
"threshold; 0 otherwise)", 0.0, 5.0,
float(_settings.get("niit", 0.0))) / 100
sl_rate = st.sidebar.number_input(
"State + local % (NY+NYC: capital gains taxed at ORDINARY rates, "
"no preferential cap-gain rate)", 0.0, 49.0,
float(_settings.get("sl_rate", 0.0))) / 100
# statistics available in the Statistics tab (names = metrics.summary keys)
_STATS_VALID = ("total_return", "return", "vol", "sharpe", "sortino",
@@ -158,8 +172,10 @@ stats_order = st.sidebar.text_input(
help=("Which statistics to show on the Statistics tab, in the order they "
"appear.\n"
"Available: " + ", ".join(_STATS_VALID) + "\n"
"beta, alpha_ann and ann_return_bench only have a value when a "
"benchmark is set. Empty field = show all, default order."))
"beta, alpha and ann_return_bench only have a value when a "
"benchmark is set. Sharpe, Sortino and alpha are computed in "
"excess of the 3-mo T-bill (BIL daily total return), as in the "
"Fund Lab. Empty field = show all, default order."))
_stats_cols = [_STATS_RENAME.get(s.strip(), s.strip())
for s in stats_order.split(",") if s.strip()]
_unknown_stats = [s for s in _stats_cols if s not in _STATS_VALID]
@@ -217,7 +233,8 @@ if _end_ts == "bad":
# remember the sidebar inputs now, before any validation st.stop()
_remember(spec=spec, bench_spec=bench_spec, scheme_index=_scheme_labels.index(scheme),
cost_bps=cost_bps, lt_rate=lt_rate * 100, st_rate=st_rate * 100,
div_rate=div_rate * 100, period=period, stats_order=stats_order,
div_rate=div_rate * 100, niit=niit * 100, sl_rate=sl_rate * 100,
period=period, stats_order=stats_order,
date_window=win, range_start=range_start, range_end=range_end)
if not spec.strip():
@@ -286,19 +303,19 @@ if saved:
@st.cache_data(show_spinner=False)
def _compute_portfolio(w_key: tuple, scheme: str | None, cost_bps: float,
start: str, lt: float, st_r: float, div: float,
root: str, gen: int):
n: float, sl: float, root: str, gen: int):
w = dict(w_key)
r = portfolio_returns(bundle.adj, w, rebalance=scheme, cost_bps=cost_bps, start=start)
t = after_tax_portfolio(bundle.adj, bundle.div, bundle.capg, w, rebalance=scheme,
t = after_tax_portfolio(bundle.close, bundle.div, bundle.capg, w, rebalance=scheme,
cost_bps=cost_bps, lt_rate=lt, st_rate=st_r,
div_rate=div, start=start)
div_rate=div, niit=n, sl_rate=sl, start=start)
return r, t
def build_result(name: str, w: dict, scheme: str | None, cost: float) -> dict:
r, t = _compute_portfolio(tuple(sorted(w.items())), scheme, cost, start,
lt_rate, st_rate, div_rate, str(root),
generation(Path(root)))
lt_rate, st_rate, div_rate, niit, sl_rate,
str(root), generation(Path(root)))
return {"name": name, "weights": w, "res": r, "tax": t}
results = []
@@ -338,8 +355,8 @@ for i, item in enumerate(bench_spec.split(), 1):
continue
try:
r, t = _compute_portfolio(tuple(sorted(w.items())), freq, cost_bps, start,
lt_rate, st_rate, div_rate, str(root),
generation(Path(root)))
lt_rate, st_rate, div_rate, niit, sl_rate,
str(root), generation(Path(root)))
except ValueError as e:
st.sidebar.warning(f"Benchmark {i} ignored: {e}")
continue
@@ -364,7 +381,11 @@ else:
if len(results) > 1:
st.caption(f"Comparing: {', '.join(r['name'] for r in results)}")
st.caption(f"{scheme} · start {start} · cost {cost_bps} bps · "
f"tax LT/ST/div {lt_rate:.0%}/{st_rate:.0%}/{div_rate:.0%}"
f"tax LT/ST/div {lt_rate:.0%}/{st_rate:.0%}/{div_rate:.0%} "
+ (" · Sharpe/Sortino/alpha in excess of the 3-mo T-bill (BIL)"
if rf is not None
else " · no T-bill (BIL) in the data — "
"Sharpe/Sortino/alpha unadjusted")
+ (f" · benchmark: {' ; '.join(b['label'] for b in benchmarks)}"
if benchmarks else ""))
@@ -403,6 +424,17 @@ def rng(s):
"""Clip a price/return series (or frame) to the display range."""
return s[(s.index >= lo) & (s.index <= hi)]
# standalone symbols in the Symbol box (not portfolio components) get a
# full per-fund report, built on demand - point the user at it
_standalone = [s for w in items if len(w) == 1 for s in w]
if _standalone:
st.info(
f"Full report(s) generated for: "
f"{', '.join(s.upper() for s in _standalone)} — see the "
f"**Fund Lab** tab, top of the Summary section. (Only symbols "
f"that stand alone in the Symbol box get a report; portfolio "
f"components do not.)")
tab_stats, tab_equity, tab_alloc, tab_tax, tab_corr, tab_fundlab = st.tabs(
["Statistics", "Equity curves", "Allocation", "Tax detail",
"Correlation", "Fund Lab"])
@@ -419,8 +451,9 @@ with tab_stats:
if bench is not None:
rows.append((f"benchmark: {bench['label']}", rng(bench["price"]),
rng(bench["after"])))
bm = (rng(bench["price"]).resample("ME").last()
if bench is not None else None)
# daily price series — metrics.summary() computes daily returns
# and annualizes with 252 days/yr, so never pre-resample
bm = rng(bench["price"]) if bench is not None else None
def pick(d: dict) -> dict:
# user-configured selection + order; skip columns the summary
@@ -434,12 +467,12 @@ with tab_stats:
summaries = {}
for name, pre, after in rows:
if both:
summaries[f"{name} (pre-tax)"] = pick(m.summary(pre, bm))
summaries[f"{name} (after-tax)"] = pick(m.summary(after, bm))
summaries[f"{name} (pre-tax)"] = pick(m.summary(pre, bm, rf))
summaries[f"{name} (after-tax)"] = pick(m.summary(after, bm, rf))
elif show_pre:
summaries[name] = pick(m.summary(pre, bm))
summaries[name] = pick(m.summary(pre, bm, rf))
else:
summaries[name] = pick(m.summary(after, bm))
summaries[name] = pick(m.summary(after, bm, rf))
st.dataframe(m.format_summary_table(summaries), width='stretch')
if benchmarks:
@@ -576,6 +609,110 @@ with tab_corr:
# ---------------------------------------------------------------- fund lab
# per-fund report mockup from N-PORT schedules of investments (fundlab)
def render_fund_report(_f: dict) -> None:
"""Render one per-fund report entry (narrative, re-basing equity
chart, period table, drivers, reference mix, tax, cluster peers).
Used by the Summary section for both the pre-built 24 and the
on-demand reports generated for standalone Symbol-box funds."""
_m, _st = _f["meta"], _f.get("stats", {})
_grp = {"candidate": "C", "shortlist": "S"}.get(_m["group"], "A")
# ad-hoc entries carry negative sort orders (they sort first) - show
# the absolute number; and skip the name when it just repeats the
# ticker (ETFs have no fund name on file)
_num = abs(int(_m["order"]))
_nm = _m["name"] if _m["name"].upper() != _m["sym"].upper() else None
_title = (f"{_grp}{_num:02d} · {_m['sym'].upper()}"
+ (f" — {_nm}" if _nm else ""))
if _m.get("verdict"):
_title += f" [{_m['verdict'][:44]}]"
with st.expander(_title):
if _f.get("narrative"):
st.markdown("\n\n".join(_f["narrative"]))
# same re-basing-on-zoom widget as the Equity curves tab: every
# visible window re-bases each line to 1.0 at its left edge, so
# fund/reference/index are comparable no matter where you zoom
_c = _f.get("chart", {})
if _c.get("dates"):
from chart_widget import equity_chart_html
_ds = pd.to_datetime(_c["dates"])
_series = {_m["sym"].upper(): pd.Series(_c["fund"], _ds)}
if _c.get("ref"):
_series["fitted reference"] = pd.Series(
_c["ref"], pd.to_datetime(_c["ref_dates"]))
if _c.get("ivv"):
_series["S&P 500 (IVV)"] = pd.Series(
_c["ivv"], pd.to_datetime(_c["ivv_dates"]))
st.iframe(equity_chart_html(
{k: s / s.iloc[0] for k, s in _series.items()},
_ds, height=460, ytitle="growth (1.0 = start)",
styles={
_m["sym"].upper(): {"width": 2},
"fitted reference": {"width": 1, "dash": "dash",
"opacity": 0.8},
"S&P 500 (IVV)": {"width": 1, "dash": "dot",
"opacity": 0.5},
}), height=490)
if _f.get("perf"):
st.dataframe(pd.DataFrame(
_f["perf"],
columns=["period", "fund", "reference",
"S&P 500", "fund − reference"]),
width="stretch", hide_index=True)
st.caption(
"fund − reference = period alpha/timing (the part of "
"that period the fitted mix does not explain). For "
"cash-anchored funds the reference is the T-bill rate "
"itself.")
if _f.get("drivers"):
st.markdown("\n\n".join(_f["drivers"]))
_sty = _f.get("style")
if _sty and _sty.get("full"):
_f5 = {x["sym"]: x for x in _sty.get("rec5", {}).get("factors", [])}
_srows = []
for x in _sty["full"]["factors"]:
y5 = _f5.get(x["sym"], {})
if abs(x["t"]) < 2 and abs(y5.get("t", 0) or 0) < 2:
continue
_srows.append([
x["name"], f"{x['beta']:+.2f}", f"{x['t']:+.1f}",
(f"{y5['beta']:+.2f}" if y5 else "—"),
(f"{y5['t']:+.1f}" if y5 else "—"),
"✓" if x["sym"] in _sty.get("identified", []) else ""])
st.markdown("**Style tilts** (22 style/asset sleeves regressed "
"on the fund's excess returns; US funds proxy the "
"global factors; 'identified' = survived the BIC "
"forward-selection gate on the full history)")
st.dataframe(pd.DataFrame(
_srows,
columns=["factor", "β full", "t full", "β 5y", "t 5y",
"identified"]),
width="stretch", hide_index=True)
st.markdown("\n\n".join(_sty.get("commentary", [])))
_ref = _f.get("reference")
if _ref and _ref.get("rows"):
st.markdown(f"**Reference mix** ({_ref['netcash']})")
st.dataframe(pd.DataFrame(
_ref["rows"],
columns=["loading", "what it is",
"what it exposes you to"]),
width="stretch", hide_index=True)
st.caption(_ref["text"])
if _f.get("tax"):
st.markdown(f"**Tax** — {_f['tax']}")
_pe = _f.get("peers")
if _pe and _pe.get("rows"):
st.markdown(
f"**Peers — cluster: {_pe['cluster']}** "
f"(n={_pe['n']})")
st.dataframe(pd.DataFrame(
_pe["rows"],
columns=["fund", "5y", "CAGR", "maxDD",
"R² 5y", "alpha 5y", "tax"]),
width="stretch", hide_index=True)
st.caption(_pe["proscons"])
with tab_fundlab:
try:
_FUNDS = json.loads((Path(__file__).parent / "funds.json").read_text())
@@ -595,25 +732,74 @@ with tab_fundlab:
_DR = json.loads(_dc.RESULTS.read_text())
except Exception:
_DR = {}
with st.expander(f"Summary — all {len(_FL_LABELS)} funds"):
_sum_rows = []
for _s in _ORDER:
_d = _DR.get(_s, {})
_rec = _d.get("recent", {})
_comp = ", ".join(f"{c['sym']} {c['beta']:+.2f}"
for c in _rec.get("components", [])[:4]) or \
", ".join(f"{c['sym']} {c['beta']:+.2f}"
for c in _d.get("components", [])[:4])
_sum_rows.append({
"fund": _FL_LABELS.get(_s, _s),
"verdict": _d.get("verdict", "n/a"),
"R² 5y": round(_rec["r2"], 3) if "r2" in _rec else None,
"alpha 5y": (f"{_rec['alpha_ann']*100:+.1f}% "
f"(t={_rec['alpha_t']:+.1f})")
if "alpha_ann" in _rec else None,
"components": _comp or "—",
})
st.dataframe(pd.DataFrame(_sum_rows), width="stretch")
# --- per-fund report: narrative + performance + drivers + peers ----
# static build (fundlab.reportdata) so the page stays fast
_RD = Path(__file__).parent / "reports" / "report_data.json"
if not _RD.exists():
with st.expander("Summary - per-fund reports (not built yet)"):
st.info("Run `.venv/bin/python -m fundlab.reportdata` in the "
"project root, then refresh.")
else:
try:
_rd = json.loads(_RD.read_text())
_rfunds = _rd["funds"]
except Exception as _e: # noqa: BLE001
st.warning(f"report data unreadable: {_e}")
_rfunds = {}
# on-demand reports: a symbol that stands ALONE in the Symbol box
# (not a component of a comma-joined portfolio) gets a full
# report, so any fund can be examined; results are cached on
# disk (reports/report_data_adhoc.json) so re-loading is instant
from fundlab import reportdata as _rdata
_standalone = [s for w in items if len(w) == 1 for s in w]
_new = [s for s in _standalone if s not in _rfunds]
if _new:
with st.spinner(
f"Building report(s) for {', '.join(s.upper() for s in _new)}"
" (first time for a fresh server: up to ~1 min for the "
"driver panel; cached afterwards)"):
_built = _rdata.ensure_adhoc(_new)
_rfunds = {**_built, **_rfunds} # ad-hoc entries first
for _i, (_s, _f) in enumerate(_built.items(), 1):
_f["meta"]["order"] = -_i # ad-hoc block sorts first
_rorder = sorted(_rfunds,
key=lambda s: _rfunds[s]["meta"]["order"])
if _rfunds:
st.subheader(f"Summary - per-fund reports "
f"({len(_rfunds)} funds)")
st.caption(
f"Generated {_rd['generated']}. Each fund: a narrative "
"discussion first (the performance, what drives it, and "
"what we do NOT know), then the equity curve, the period "
"table (fund vs fitted reference vs S&P 500, with the "
"fund-minus-reference gap), the return drivers, the "
"reference mix explained sleeve by sleeve, tax placement, "
"and the best peers from the same return-driver cluster. "
"All alphas are in excess of the 3-mo T-bill rate.")
_ag = []
for _s in _rorder:
_f = _rfunds[_s]
_m, _st = _f["meta"], _f.get("stats", {})
_ag.append({
"fund": (f"{_m['sym'].upper()}"
if _m["name"].upper() == _m["sym"].upper()
else f"{_m['sym'].upper()} — {_m['name'][:44]}"),
"group": _m["group"],
"5y": _st.get("t5y", "—"),
"CAGR": _st.get("cagr", "—"),
"maxDD": _st.get("mdd", "—"),
"R² 5y": _st.get("r2_5y", "—"),
"alpha 5y": _st.get("alpha_5y", "—"),
"cluster": (_f.get("peers") or {}).get("cluster", ""),
})
st.dataframe(pd.DataFrame(_ag), width="stretch",
hide_index=True)
for _s in _rorder:
render_fund_report(_rfunds[_s])
st.caption("← the rest of the Fund Lab continues below: "
"alpha search, return-driver clusters, N-PORT "
"cross-check, drawdown resilience, tax location, "
"and the CEF ranking.")
# --- alpha search: all screened funds (shortlist + longlist + harvest)
with st.expander("Alpha search — all screened funds, ranked"):
@@ -660,6 +846,7 @@ with tab_fundlab:
else "—"),
"alpha 5y": (f"{_a5*100:+.1f}% (t={_v['alpha_t_5y']:+.1f})"
if isinstance(_a5, (int, float)) else "—"),
"reference (5y)": _v.get("ref_5y") or "—",
"corr port": (f"{_v['corr_portfolio']:.2f}"
if isinstance(_v.get("corr_portfolio"),
(int, float)) else "—"),
@@ -670,14 +857,18 @@ with tab_fundlab:
})
st.dataframe(pd.DataFrame(_tbl), width="stretch")
st.caption(
"Screen: daily total returns vs 21 broad sleeve axes (same "
"set for every fund); 'alpha 5y' = OLS intercept over the "
"last 5 years (t-stat); 'corr port' = correlation with your "
"current qspnx/pmaix portfolio; '6m + %' = share of rolling "
"6-month windows where the fund beat its fitted sleeve mix. "
"CANDIDATE = R²5y < 0.6 (or < 0.85 with strong residual "
"alpha), t5y ≥ 2, t-full ≥ 1.25, ≥ 45% positive windows, "
"portfolio correlation < 0.3.")
"Screen: daily total returns IN EXCESS OF THE 3-MO T-BILL "
"RATE (BIL) vs 21 broad sleeve axes (same set for every "
"fund); 'alpha 5y' = OLS intercept of the excess returns "
"over the last 5 years (t-stat) — i.e. outperformance vs "
"the fund's OWN fitted sleeve mix (the 'reference' column), "
"not vs one index; a cash position earns exactly the t-bill "
"rate and adds zero alpha. 'corr port' = correlation with "
"your current qspnx/pmaix portfolio; '6m + %' = share of "
"rolling 6-month windows where the fund beat its fitted "
"sleeve mix. CANDIDATE = R²5y < 0.6 (or < 0.85 with strong "
"residual alpha), t5y ≥ 2, t-full ≥ 1.25, ≥ 45% positive "
"windows, portfolio correlation < 0.3.")
# --- return-driver clusters: k-means on 35-sleeve loading vectors ---
with st.expander(
@@ -691,7 +882,11 @@ with tab_fundlab:
_syms, _V = _cl.loading_matrix()
_fr = json.loads((_dc.RESULTS.parent /
"factor_results.json").read_text())
_lab = _cl.kmeans(_V, _ck)
# distance on the cash-emphasized matrix (a pure cash fund's
# level axis is otherwise swallowed by the low-exposure cloud);
# labels below use the raw _V values
_lab = _cl.kmeans(_cl.emphasized(_V, _fac.AXES.index("cash")),
_ck)
_sumrows = []
for c in range(_ck):
idx = [i for i, l in enumerate(_lab) if l == c]
@@ -699,7 +894,7 @@ with tab_fundlab:
continue
med = _np.median(_V[idx], 0)
top = _np.argsort(-_np.abs(med))[:4]
prof = {_fac.DRIVERS[t]: float(med[t]) for t in top
prof = {_fac.AXES[t]: float(med[t]) for t in top
if abs(med[t]) >= 0.08}
lab = _cl.label(prof)
t5s = [_fr[_syms[i]].get("alpha_t_5y") for i in idx]
@@ -736,7 +931,7 @@ with tab_fundlab:
continue
med = _np.median(_V[idx], 0)
top = _np.argsort(-_np.abs(med))[:4]
prof = {_fac.DRIVERS[t]: float(med[t]) for t in top
prof = {_fac.AXES[t]: float(med[t]) for t in top
if abs(med[t]) >= 0.08}
if _cl.label(prof) == _target:
_members = [(i, idx[0]) for i in idx]
@@ -767,11 +962,14 @@ with tab_fundlab:
r.pop("_t")
st.dataframe(pd.DataFrame(_rows), width="stretch")
st.caption(
"Each fund's daily returns are regressed on 35 sleeve axes "
"(equity styles/sizes/intl/EM, the duration ladder, IG/HY/"
"muni/MBS/preferred/EM-debt credit, sectors, gold/oil/"
"commodities, CTA); the 35-d loading vector is the fund's "
"'return-driver signature' and k-means groups similar "
"Each fund's daily total returns IN EXCESS OF THE 3-MO "
"T-BILL RATE (BIL) are regressed on 34 sleeve axes (equity "
"styles/sizes/intl/EM, the duration ladder, IG/HY/muni/MBS/"
"preferred/EM-debt credit, sectors, gold/oil/commodities, "
"CTA); the loading vector is the fund's 'return-driver "
"signature' — the betas are its NET INVESTED mix — plus a "
"virtual CASH axis = 1 − Σβ (net cash/T-bill position; 1 = "
"fully in cash, < 0 = levered). k-means groups similar "
"signatures. 'corr port' is shown for reference only - "
"high-corr funds are REPLACEMENTS for current holdings, "
"not rejections.")
@@ -1092,9 +1290,10 @@ with tab_fundlab:
if _dr.get("note"):
st.markdown("**Holdings cross-check:** " + _dr["note"])
st.caption(
"Method: daily total returns; greedy forward selection on BIC "
"(add only if ΔBIC ≥ 2 and |t| > 2); candidate sleeves curated per "
"fund from the strategy text + N-PORT. β = exposure, not a literal "
"Method: daily total returns IN EXCESS OF THE 3-MO T-BILL RATE "
"(BIL); greedy forward selection on BIC (add only if ΔBIC ≥ 2 and "
"|t| > 2); candidate sleeves curated per fund from the strategy "
"text + N-PORT. β = exposure, not a literal "
"holding weight; 'drift' = mean |rolling 1y β − full β| relative to "
"the full β. High-R² + low drift ≈ static mix; low R² with positive "
"alpha ≈ market-neutral/alpha strategy.")
+337 -12
View File
@@ -24,10 +24,197 @@ import time
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import pandas as pd
DEFAULT_ROOT = Path("~/prog/fin/stocks").expanduser()
CACHE_DIR = Path(__file__).parent / ".cache"
# Frozen overrides: stale (Yahoo-empty) tickers whose final series is
# snapshotted here by scripts/audit_stale.py. For symbols that have a
# frozen copy, the data-root files are ignored so a future goget
# re-download can never clobber the last known-good series.
FROZEN_DIR = Path(__file__).parent / "overrides" / "frozen"
# Backup of the dividend/capitalGain event files, used as a fallback when a
# re-download no longer carries those events. In 2026 Yahoo changed its event
# feed: for some funds it stopped returning capitalGain events entirely and
# for terminated funds it returns no events at all, so a plain re-download
# overwrites good historical event CSVs with empty ones. The backup holds
# the last known-good content; see scripts/backup_events.py.
EVENT_BACKUP_DIR = Path(__file__).parent / "overrides" / "event-backup"
# Corrections: per-symbol distribution fixes confirmed against official
# sources (see scripts/verify_official.py). Applied on top of whatever the
# data root / frozen dir says, so re-downloads can never clobber them.
# Format, one file per symbol in overrides/corrections/:
# {"dividends": {"remove": [["2008-12-18", 0.292], ...],
# "replace": {"2008-12-18": 0.0},
# "add": [["2007-12-18", 0.292], ...]},
# "capitalGains": {...same ops...},
# "dedup": [["2022-12-13", 4.841], ...],
# "drop_capg_copy": ["2023-12-21", ...],
# "as_of": "2026-08-31", "source": "<filing URL>", "note": "..."}
#
# The two cross-file ops express the Yahoo double-listing invariant and are
# LAYOUT-AGNOSTIC (applied at bundle assembly, idempotent): Yahoo has changed
# which file carries a distribution between downloads (e.g. in 2026 it stopped
# returning capitalGain events entirely for some funds while the dividend
# stream kept the year-end row), so file-specific removes would silently break
# on the next re-download.
# dedup: [[date, amount]] the (date, amount) row may appear in
# both files; keep at most one (the capitalGain copy if both present).
# drop_capg_copy: [date] the capitalGain row on that date is a
# spurious copy of the dividend row; drop it (any amount).
CORRECTIONS_DIR = Path(__file__).parent / "overrides" / "corrections"
_corr_cache: dict = {}
def _load_corrections(sym: str) -> dict:
f = CORRECTIONS_DIR / f"{sym.upper()}.json"
if f.exists():
try:
if f not in _corr_cache or _corr_cache[f][0] != f.stat().st_mtime_ns:
_corr_cache[f] = (f.stat().st_mtime_ns,
json.loads(f.read_text()))
return _corr_cache[f][1]
except Exception:
return {}
return {}
def dedupe_event_rows(corr: dict, div: list[tuple[str, float]],
capg: list[tuple[str, float]]
) -> tuple[list[tuple[str, float]], list[tuple[str, float]]]:
"""Pure list-level version of apply_invariants (no file access), shared
by verify_official and unit tests."""
dups = corr.get("dedup") or []
drops = corr.get("drop_capg_copy") or []
if not dups and not drops:
return div, capg
ck = {(d, round(v, 9)) for d, v in capg}
# dedup: drop the dividend copy only when the capitalGain copy is present
out_div = [r for r in div
if not any(r[0] == d and round(r[1], 9) == round(a, 9)
and (d, round(a, 9)) in ck
for d, a in dups)]
# drop_capg_copy: the capg row on that date is the spurious one
out_capg = [r for r in capg if r[0] not in drops]
return out_div, out_capg
def _fix_total_distributions(div: pd.DataFrame, capg: pd.DataFrame,
close: pd.DataFrame, adj: pd.DataFrame) -> list[str]:
"""Fix Yahoo's "dividend file carries the TOTAL distribution" quirk.
For many fund share classes Yahoo's dividend endpoint reports the fund's
TOTAL per-share distribution (dividend + capital gain) while the
capitalGains endpoint reports the cap-gain portion separately; summing
both files double-counts the cap-gain part and breaks pre/post-tax
comparability (the after-tax engine can even beat the adj-based pre-tax
return, which is impossible for consistent data).
Detection is layout-agnostic and self-validating: on dates where both
files have an event and the dividend amount strictly exceeds the cap-gain
amount, Yahoo's adj factor steps by an implicit total distribution (the
close/adj ratio only steps on distribution dates). If that implicit
amount matches the dividend-file amount (not the sum) on most overlap
dates, the dividend file is the total and we rewrite div -= capg there,
leaving div+capg == total. Symbols with genuine separate same-date
distributions (adj matches the sum) are left untouched.
Returns the list of rewritten symbols.
"""
fixed: list[str] = []
for sym in div.columns:
if sym not in capg.columns or sym not in close.columns or sym not in adj.columns:
continue
dv = div[sym]
cg = capg[sym].reindex(div.index).fillna(0.0)
mask = (dv > 0) & (cg > 0) & (dv > cg * 1.001)
n = int(mask.sum())
if n < 3:
continue
c, a = close[sym], adj[sym]
if (a.fillna(0) == 0).all() or (c.fillna(0) == 0).all():
continue
# Yahoo adj convention: A_t = A_{t-1} * Q_t / (P_{t-1} - d) =>
# exact implied total distribution: d = P - Q * (A_{t-1} / A_t)
imp = (c.shift(1) - c * (a.shift(1) / a)).reindex(div.index)
d_s = dv[mask]
g_s = cg[mask]
imp = imp[mask]
ref = np.maximum(imp.abs(), d_s.abs())
ref = ref.replace(0, np.nan)
m_tot = (imp - d_s).abs() <= 0.05 * ref
m_both = (imp - (d_s + g_s)).abs() <= 0.05 * ref
if int(m_tot.sum()) >= 3 and int(m_tot.sum()) > int(m_both.sum()):
div.loc[mask, sym] = d_s - g_s
fixed.append(sym)
return fixed
def apply_invariants(div: pd.DataFrame, capg: pd.DataFrame,
adj: pd.DataFrame | None = None,
close: pd.DataFrame | None = None) -> None:
"""Cross-file correction invariants (Yahoo double-listing), applied at
bundle assembly so they hold for full and incremental builds and survive
re-downloads that move a row between the dividend/capitalGain files.
Idempotent: panels keep the pre-invariant state, this re-derives it."""
for f in sorted(CORRECTIONS_DIR.glob("*.json")):
sym = f.stem.lower()
try:
corr = json.loads(f.read_text())
except Exception:
continue
dups = corr.get("dedup") or []
drops = corr.get("drop_capg_copy") or []
if not dups and not drops:
continue
if sym in capg.columns:
for d in drops:
ts = pd.Timestamp(d)
if ts in capg.index and abs(capg.at[ts, sym]) > 1e-9:
capg.at[ts, sym] = 0.0
if sym in div.columns and sym in capg.columns:
for d, a in dups:
ts = pd.Timestamp(d)
if ts in div.index and ts in capg.index and \
abs(div.at[ts, sym] - a) < 1e-9 and \
abs(capg.at[ts, sym] - a) < 1e-9:
div.at[ts, sym] = 0.0
if adj is not None and close is not None:
_fix_total_distributions(div, capg, close, adj)
def _apply_corrections(sym: str, suffix: str, ser: pd.Series,
col: str | None = None) -> pd.Series:
if suffix == "history":
# {date: {col: value}} — patch individual OHLC cells (e.g. a
# misaligned Yahoo adj-close spike). Only touches the requested col.
ops = _load_corrections(sym).get("history")
if not ops or col is None:
return ser
d = {ts: float(v) for ts, v in ser.items()}
for dstr, cells in ops.items():
ts = pd.Timestamp(dstr)
if ts in d and col in cells:
d[ts] = float(cells[col])
return pd.Series(d).sort_index()
key = {"dividend": "dividends", "capitalGain": "capitalGains"}.get(suffix)
ops = _load_corrections(sym).get(key) if key else None
if not ops:
return ser
d = {ts: float(v) for ts, v in ser.items()}
for r in ops.get("remove", []):
ts = pd.Timestamp(r[0])
amt = r[1] if len(r) > 1 else None
if ts in d and (amt is None or abs(d[ts] - amt) < 1e-9):
del d[ts]
for ts_s, amt in ops.get("replace", {}).items():
d[pd.Timestamp(ts_s)] = float(amt)
for r in ops.get("add", []):
ts = pd.Timestamp(r[0])
d[ts] = d.get(ts, 0.0) + float(r[1])
if not d:
return pd.Series(dtype=float)
return pd.Series(d).sort_index()
_SUFFIXES = ("history", "dividend", "capitalGain")
_PANELS = ("adj", "close", "div", "capg")
@@ -50,16 +237,77 @@ def _read_csv_clean(f: Path) -> pd.DataFrame:
return df
def frozen_syms() -> set:
"""Symbols with a frozen history copy in the overrides dir."""
if not FROZEN_DIR.is_dir():
return set()
return {f.stem[: -len("-history")] for f in FROZEN_DIR.glob("*-history.csv")}
def _has_data_rows(p: Path) -> bool:
"""True if the csv has at least one row beyond the header."""
try:
with open(p, errors="replace") as fh:
if not fh.readline():
return False
return fh.readline() != ""
except OSError:
return False
def event_file(sym: str, sfx: str, root: Path) -> Path:
"""Effective event file (dividend/capitalGain): frozen copy, else the
data-root file while it still carries rows, else the backup, else the
(possibly emptied by a re-download) data-root file."""
fr = FROZEN_DIR / f"{sym}-{sfx}.csv"
if fr.exists():
return fr
rt = root / f"{sym}-{sfx}.csv"
if _has_data_rows(rt):
return rt
bk = EVENT_BACKUP_DIR / f"{sym}-{sfx}.csv"
if bk.exists() and _has_data_rows(bk):
return bk
return rt
def _panel_paths(root: Path, suffix: str) -> list[tuple[str, Path]]:
"""(symbol, path) for every panel file; frozen copies shadow data-root,
and for event files the backup dir is the fallback (see event_file)."""
frozen = frozen_syms()
if suffix in ("dividend", "capitalGain"):
syms = sorted({f.name[: -len(f"-{suffix}.csv")]
for f in root.glob(f"*-{suffix}.csv")}
| ({f.name[: -len(f"-{suffix}.csv")]
for f in EVENT_BACKUP_DIR.glob(f"*-{suffix}.csv")}
if EVENT_BACKUP_DIR.is_dir() else set())
| ({f.name[: -len(f"-{suffix}.csv")]
for f in FROZEN_DIR.glob(f"*-{suffix}.csv")}
if FROZEN_DIR.is_dir() else set()))
return [(sym, event_file(sym, suffix, root))
for sym in syms if sym not in frozen
or (FROZEN_DIR / f"{sym}-{suffix}.csv").exists()]
out = []
for f in sorted(root.glob(f"*-{suffix}.csv")):
sym = f.name[: -len(f"-{suffix}.csv")]
if sym in frozen:
continue
out.append((sym, f))
for f in sorted(FROZEN_DIR.glob(f"*-{suffix}.csv")) if FROZEN_DIR.is_dir() else []:
out.append((f.name[: -len(f"-{suffix}.csv")], f))
return out
def _read_panel(root: Path, suffix: str, col: str) -> pd.DataFrame:
cols, syms = [], []
for f in sorted(root.glob(f"*-{suffix}.csv")):
for sym, f in _panel_paths(root, suffix):
try:
df = _read_csv_clean(f)
except Exception:
continue
if col in df.columns:
cols.append(df[col])
syms.append(f.name[: -len(f"-{suffix}.csv")])
cols.append(_apply_corrections(sym, suffix, df[col], col))
syms.append(sym)
if not cols:
return pd.DataFrame()
out = pd.concat(cols, axis=1)
@@ -96,13 +344,26 @@ REFRESH_CADENCE = 30.0 # min seconds between actual cache rebuilds
_watchers: dict[tuple, threading.Thread] = {}
_gen: dict[tuple, int] = {} # (root, cache) -> bundle generation counter
def _scan_files(root: Path) -> dict:
"""{filename: (mtime_ns, size)} for every csv/json file in the data root."""
"""{filename: (mtime_ns, size)} for every csv/json file in the data root
plus the frozen overrides (namespaced under 'frozen/')."""
out = {}
with os.scandir(root) as it:
for e in it:
if e.is_file() and e.name.endswith((".csv", ".json")):
st = e.stat()
out[e.name] = (st.st_mtime_ns, st.st_size)
if FROZEN_DIR.is_dir():
with os.scandir(FROZEN_DIR) as it:
for e in it:
if e.is_file() and e.name.endswith((".csv", ".json")):
st = e.stat()
out["frozen/" + e.name] = (st.st_mtime_ns, st.st_size)
if CORRECTIONS_DIR.is_dir():
with os.scandir(CORRECTIONS_DIR) as it:
for e in it:
if e.is_file() and e.name.endswith(".json"):
st = e.stat()
out["corrections/" + e.name] = (st.st_mtime_ns, st.st_size)
return out
@@ -154,27 +415,84 @@ def _apply_changes(root: Path, cache: Path, old: dict, new: dict) -> None:
return sfx, fname[: -len(f"-{sfx}.csv")]
return None, None
def _path(fname: str) -> Path:
# frozen/ namespaced files live in the overrides dir
return FROZEN_DIR / fname[8:] if fname.startswith("frozen/") else root / fname
updates: dict[str, dict] = {k: {} for k in _PANELS} # panel -> {sym: series}
drops: set[str] = set()
authoritative: set[str] = set() # corrections-derived series: replace,
# don't combine (deletions must stick)
# data-root files of frozen symbols are ignored: their canonical series
# lives in the overrides dir, which is tracked in the same scan
frozen = frozen_syms()
def _recompute_corrected(symfile: str) -> None:
"""corrections/{SYM}.json changed: re-derive the symbol's
dividend/capital-gain series from the base file + corrections."""
for sfx, colname, key in (("history", "Adj Close", "adj"),
("history", "Close", "close"),
("dividend", "Dividends", "div"),
("capitalGain", "Capital Gains", "capg")):
sym = None
p = None
for case in (symfile[:-5].lower(), symfile[:-5].upper()):
for base in (FROZEN_DIR, root):
q = base / f"{case}-{sfx}.csv"
if q.exists():
sym, p = case, q
break
if sym:
break
if p is None:
continue
try:
df = _read_csv_clean(p)
except Exception:
continue
if colname not in df.columns:
continue
ser = _apply_corrections(sym, sfx, df[colname], colname)
updates[key][sym] = ser if sfx == "history" else ser.fillna(0.0)
authoritative.add(sym)
for fname in changed:
if fname.startswith("corrections/"):
_recompute_corrected(fname[12:])
continue
sfx, sym = _suffix(fname)
if sfx is None:
continue
if not fname.startswith("frozen/") and sym in frozen:
continue
try:
df = _read_csv_clean(root / fname)
df = _read_csv_clean(_path(fname))
except Exception:
continue # e.g. a file mid-download
if sfx == "history":
if "Adj Close" in df.columns:
updates["adj"][sym] = df["Adj Close"]
updates["adj"][sym] = _apply_corrections(
sym, "history", df["Adj Close"], "Adj Close")
if "Close" in df.columns:
updates["close"][sym] = df["Close"]
updates["close"][sym] = _apply_corrections(
sym, "history", df["Close"], "Close")
elif sfx == "dividend" and "Dividends" in df.columns:
updates["div"][sym] = df["Dividends"].fillna(0.0)
updates["div"][sym] = _apply_corrections(sym, sfx, df["Dividends"]) \
.fillna(0.0)
elif sfx == "capitalGain" and "Capital Gains" in df.columns:
updates["capg"][sym] = df["Capital Gains"].fillna(0.0)
updates["capg"][sym] = _apply_corrections(sym, sfx, df["Capital Gains"]) \
.fillna(0.0)
for fname in removed:
sfx, sym = _suffix(fname)
if fname.startswith("corrections/"):
_recompute_corrected(fname[12:])
continue
if fname.startswith("frozen/"):
continue # frozen files are not data-root symbols
if sym in frozen:
continue # data-root file of a frozen symbol vanished; the
# frozen copy remains authoritative
sfx, sym = _suffix(fname)
if sfx is not None:
drops.add(sym)
@@ -207,10 +525,15 @@ def _apply_changes(root: Path, cache: Path, old: dict, new: dict) -> None:
for sym, s in upd.items():
s = s.rename(sym)
if sym in old:
# new values win where present; keep old values for dates
# the new file doesn't cover (e.g. a partial re-download)
uidx = panel.index.union(s.index)
s = s.reindex(uidx).combine_first(old[sym].reindex(uidx))
if sym in authoritative:
# corrections-derived: a date missing from the new
# series was intentionally removed, not "not covered"
s = s.reindex(uidx).fillna(0.0)
else:
# new values win where present; keep old values for
# dates the new file doesn't cover (partial download)
s = s.reindex(uidx).combine_first(old[sym].reindex(uidx))
extras.append(s)
extra = pd.concat(extras, axis=1)
extra.columns = list(upd)
@@ -272,6 +595,8 @@ def refresh(root: Path = DEFAULT_ROOT, cache: Path = CACHE_DIR,
else:
names = _read_names(root)
names_path.write_text(json.dumps(names))
apply_invariants(panels["div"], panels["capg"],
panels["adj"], panels["close"])
bundle = Bundle(panels["adj"], panels["close"], panels["div"],
panels["capg"], names)
# keep only the newest bundle: there is no room for two
+250
View File
@@ -933,3 +933,253 @@ the overnight screen and had exited with it.
**App:** Fund Lab tab shows the CEF shortlist table (character
actual-vs-model flag, discount, 5y, vol, scenarios, tenders, score).
### CASH axis: money-market / cash-equivalent funds as a driver
**Problem:** money-market and ultra-short funds fell into the "no
dominant driver" cluster. There WAS a cash sleeve (shv; bil was dropped
from the regression for shv/bil collinearity), but cash funds still
didn't load on it: a fund's yield is a near-CONSTANT in return space,
so OLS puts it in the INTERCEPT (alpha_ann), not in any beta. shv/bil
betas only measure the response to rate CHANGES — tiny for cash-like
funds. Evidence: qcmmrx (Money Market Account) had shv 0.13, bil 0.12,
R² 0.08, but alpha_ann 1.91%/yr = the average cash level over its
history.
**Benchmark:** the canonical cash benchmark is the 13-week T-bill /
0-3m Treasury index (SIXM). Local stand-ins: shv/sgov/bil/gbil
total-return (Adj Close), trailing 1y ≈ 3.7% in the current regime.
**Fix (factors.py + cluster.py + app.py):**
- `factors.cash_yield()`: shv trailing-1y total return (fallback sgov,
bil) — the normalizer.
- `factors.AXES = DRIVERS + ["cash"]`: a VIRTUAL cash axis per fund =
alpha_ann / cash_yield (1.0 = "earns the cash rate"), from the full
window (rec5 fallback when the row falls back to rec5). It is a
clustering/display axis, NOT a regressor (the level is already in
the intercept; regressing on a constant is collinear by design).
- `cluster.loading_matrix()` appends the cash column (winsorized ±4
like the betas). SLEEVE_NAME["cash"] = "cash (yield)".
- `cluster.emphasized(V)`: the cash axis is a LEVEL, not a sensitivity
— in raw Euclidean space a pure cash fund (0,...,0,~0.5) sits inside
the low-exposure balanced/target-date cloud and k-means swallows it.
K-means (app + run_kmeans) runs on the cash-2x-emphasized matrix;
LABELS still use the raw values. The hclust tree stays raw.
- `cluster.label()`: cash-aware — the median cash in a mixed
low-exposure cluster is diluted, so cash counts as the driver at
>=0.25 (vs 0.30 for betas) and must be >=1.5x the runner-up.
**Result (k=30):** the grab-bag 331-fund "no dominant driver" cluster
splits into "cash (yield) +0.64" (n=187: qcmmrx + the ultra-short
government/bond funds), "cash (yield) +1.26" (n=59 pure), and the
genuinely balanced remainder. 637 funds now have CASH as their
dominant axis (>=0.30 and > every beta) — mostly the short-duration
complex, which is correct: their return IS mostly the coupon level.
**Note:** the machine rebooted during this work (12:50) — it silently
kills nohup'd processes (the CEF batch and the first watchdog both
died that way; the batch was resumable so no data was lost).
server_watchdog.sh had to be relaunched manually; consider a
boot-time starter (systemd/cron @reboot) if reboots repeat.
- 2026-08-30 15:09 === stage screen ===
- 2026-08-30 15:09 screen: 2384 funds, 2384 to do
- 2026-08-30 15:10 screen: 100/2384
- 2026-08-30 15:11 screen: 200/2384
- 2026-08-30 15:11 screen: 300/2384
- 2026-08-30 15:12 screen: 400/2384
- 2026-08-30 15:12 screen: 500/2384
- 2026-08-30 15:13 screen: 600/2384
- 2026-08-30 15:13 screen: 700/2384
- 2026-08-30 15:14 screen: 800/2384
- 2026-08-30 15:14 screen: 900/2384
- 2026-08-30 15:15 screen: 1000/2384
- 2026-08-30 15:15 screen: 1100/2384
- 2026-08-30 15:16 screen: 1200/2384
- 2026-08-30 15:17 screen: 1300/2384
- 2026-08-30 15:17 screen: 1400/2384
- 2026-08-30 15:18 screen: 1500/2384
- 2026-08-30 15:18 screen: 1600/2384
- 2026-08-30 15:19 screen: 1700/2384
- 2026-08-30 15:19 screen: 1800/2384
- 2026-08-30 15:20 screen: 1900/2384
- 2026-08-30 15:20 screen: 2000/2384
- 2026-08-30 15:21 screen: 2100/2384
- 2026-08-30 15:21 screen: 2200/2384
- 2026-08-30 15:22 screen: 2300/2384
- 2026-08-30 15:22 screen done: 2384 funds
- 2026-08-30 15:22 === stage finalize ===
- 2026-08-30 15:22 finalize: 2384 funds screened
- 2026-08-30 15:22 1339 sleeve mix
- 2026-08-30 15:22 1001 weak/unstable alpha
- 2026-08-30 15:22 17 no 5y window
- 2026-08-30 15:22 11 CANDIDATE
- 2026-08-30 15:22 10 alpha, but correlated with current portfolio
- 2026-08-30 15:22 6 alpha in 5y window, but not persistent
- 2026-08-30 15:22 candidates v1 name-filter would have missed: ['aguax', 'etsix', 'femdx', 'hicox', 'prfrx', 'puls', 'rctix', 'rpifx', 'scfzx']
- 2026-08-30 15:22 === overnight run finished in 0.2h ===
### Alphas recomputed in EXCESS of the 3-mo T-bill rate (risk-free netting)
**Question that triggered it:** "Are we using cash return as a risk-free
rate in the alpha calculations?" — No. Alpha was the OLS intercept of
RAW daily total returns. For a fund whose net sleeve exposure is not
~100% (under-invested or levered), the raw intercept absorbs the T-bill
yield on the uninvested/levered part, so "alpha" mixed skill with cash
drag. Magnitude (5y, R²>0.5 funds): 582 funds >2%/yr apart, 533 in
1-2%, 345 in 0.5-1%. Sum-of-betas was also polluted by level-matching
(median 1.15; a plain growth fund like bggsx showed 3.7 with a −10%/yr
"alpha" that was pure level-splitting).
**Changes:**
- decompose.py: `rf_series()` = BIL (SPDR 1-3mo T-Bill) daily total
return — the local stand-in for the 3-mo T-bill yield; `excess()`
nets the fund AND the sleeves against it before every regression.
Cash positions now contribute exactly zero (cash IS the rf).
- CASH_SLEEVES {shv, bil} dropped from the regressors: in excess space
they are ~0 columns (ill-conditioning); the cash position is captured
by the residual instead. Same for factors.py (shv added to
DROP_FROM_REGRESSION).
- **FULL_WINDOW moved 1990-01-01 → 2007-06-01** (BIL inception):
mixing raw pre-2007 with excess post-2007 returns breaks the
full-window fit (cosix: R²≈0, zero components selected).
- **CASH axis redefined** from alpha_ann/cash_yield (the old version
was measuring the yield level that no longer lives in the intercept)
to **net cash position = 1 − Σβ**: the betas are the net-invested
mix, the leftover is cash/T-bills. Pure MMF → 1.0; levered → < 0.
Labeled "cash (net posn)". `factors.cash_yield()` removed.
- Alphas in the app are now true excess-return alphas: intercept of
(fund − rf) on (sleeves − rf).
**Verification (probes):** qcmmrx (money market): alpha −0.17%/yr
(t=−1.3, noise), cash 1.00. vsbsx (short-T index): alpha 0.03%, cash
0.77 + short duration. bggsx: Σβ 1.25 (was 3.7), alpha −3.6%
(t=−0.6). IVV: alpha 0.00% (t=+36.7). cosix full-window fixed
(R² 0.60, vweax 0.45/agg 0.15/ief 0.15).
**Consequence — the CANDIDATE list shrank 250 → 11.** Most of the old
250 were under-invested funds (bond funds with Σβ<1) whose "alpha" was
the T-bill yield on their uninvested portion. The 11 that survive are
funds whose excess alpha is real. Verdict mix now: 1339 sleeve mix,
1001 weak/unstable alpha, 11 CANDIDATE, 10 correlated, 6 not
persistent, 17 no 5y window.
**Reference visibility (the "what is alpha computed vs" question):**
alpha is NOT vs one index — it is vs the fund's own fitted sleeve mix
(BIC forward selection). fundlab/refback.py recomputes the forward
selection per fund and stores `ref_5y`/`ref_full` strings in
search_all.json; the app's alpha-search table now has a "reference
(5y)" column.
**Backups of the raw-alpha era (NOT deleted):**
factor_results_rawalpha.json, decompose_results_rawalpha.json,
search_all_rawalpha.json, cluster_kmeans_rawalpha.json.
---
## Per-fund report: HTML + app + narrative engine (2026-08-30)
**Deliverable.** `fundlab/report.py` -> `reports/fund_report.html`
(self-contained, plotly inlined, 20 MB) and `fundlab/reportdata.py` ->
`reports/report_data.json` (3 MB, the app's static build). 24 funds: the
11 excess-return candidates + the 13 unique shortlist funds (pmfkx/lcrix/
egrsx are share classes of pmaix/lcorx/eagmx and are merged).
Per fund: max-history equity curve (fund vs fitted reference vs IVV);
period table (full/5y/1y, the 5 market episodes, 6 calendar years) with
the **fund-minus-reference** column (period alpha/timing); drivers
(reference-model R²/alpha/t + 34-sleeve signature + curated decomposition
verdict + N-PORT cross-check notes); the reference mix explained
sleeve-by-sleeve (SLEEVE_DESC: what each exposure actually is); tax
character + placement; and a peer table of the 4 best-alpha funds in the
same k=30 return-driver cluster with computed adv/dis.
**BUG FOUND AND FIXED — `mix_series()` never applied the betas.** The
"fitted reference" curve summed the RAW sleeve daily returns instead of
β·return. For high-fit funds the reference was garbage (JLPSX "reference"
+407% 5y vs the fund's +123%; CVSIX +465%; PMAIX +1160%). After the fix
the mix tracks the fund (JLPSX ref +127% vs fund +123%). Every reference
curve and table in the HTML report was wrong before this and has been
regenerated. Lesson: a regression on returns does not hand you a price
path — the β weighting is the whole point.
**Weak-fit funds anchor to CASH, not their fitted mix.** For idiosyncratic
funds (R² < 0.5) the BIC forward selection can pick a statistically-thin
OFFSETTING combination (SCFZX: +0.35 VIX futures, −0.23 20+y Treasuries,
+0.10 HY) whose cumulated path is meaningless (a "reference" that loses
79% in 2022 for a fund that lost 2.4%). Below the 0.5 fit gate the
performance table and curve use BIL as the reference; the loadings are
still shown with an explicit "weak fit — read with care" caveat.
**Narrative engine (`fundlab/narrative.py`).** Data-driven English prose,
5 paragraphs per fund: (1) what the fund is (objective, N-PORT buckets,
cluster); (2) the performance in plain terms (CAGR/vol/DD, 5y vs reference,
episode behaviour, calendar-year pattern); (3) what is driving it — tiered
by fit (≥0.7 "mostly the exposures", 0.5–0.7 "mix + residual", <0.5
"idiosyncratic: here is the estimate and its t-stat"); (4) **what we do
NOT know** — stated explicitly: the unexplained share, alpha steadiness
(share of 6m windows trailing), recent-vs-full significance, short sample,
holdings opacity (egrix: 100% in one managed fund, underlying undisclosed);
(5) bottom line (account placement, best cluster peer, portfolio
correlation). Rules learned while reviewing the prose: negative/weak 5y
alpha must not be called "outperformance" (the template assumed positive
alpha and lied about atesx, −1.6% t=−0.5); MIXED tax placement must not be
rendered as "IRA"; a fund with no price history must not be assigned a
cluster (zero loading vector parks everything in the cash cluster);
drift < 0.5 = "roughly stable" (0.44 is not "tactical"); sleeve prose
needs short names (dbb/gsg → "broad commodities") because SLEEVE_DESC
lead-ins reference sibling tickers.
**App integration.** The Fund Lab "Summary" page now renders
`reports/report_data.json`: at-a-glance table (24 funds: 5y, CAGR, maxDD,
R²5y, alpha5y, cluster) + one expander per fund (narrative first, then
chart, period table, drivers, reference mix, tax, peers) + an "expand
all" checkbox. Static build so the page stays fast; regenerate with
`python -m fundlab.reportdata` (~8 s) and `python -m fundlab.report`
(~11 s for the HTML).
**Report charts: re-basing-on-zoom widget (2nd pass).** The first report
build used static st.plotly_chart with pre-rebased series — zooming to a
window left the lines starting at different levels (no comparison
possible). Replaced with the SAME widget as the Equity curves tab
(`chart_widget.equity_chart_html` + st.iframe): on every relayout each
visible line is re-based to 1.0 at its left edge and y fits the visible
data, so fund/reference/index are comparable in any window. report_data
still stores the full-history series; the app divides by each series'
first point before handing it to the widget (per-series 1.0 start, as
the widget expects). Also removed the "expand all" checkbox (24 expanded
sections made the page unusable and hid the sections below) and added a
"rest of the Fund Lab continues below" marker.
**On-demand reports for any Symbol-box fund.** `reportdata.ensure_adhoc(syms)`
builds the same full report entry (narrative, chart, period table, drivers,
reference, tax, peers) for ARBITRARY symbols, cached in memory + on disk
(reports/report_data_adhoc.json, gitignored) so repeat loads are instant and
survive restarts; build time ~0.3-0.9 s per new fund after the one-time
~30-60 s driver-panel warmup. The app triggers it for symbols that stand
ALONE in the Symbol box (a parsed item with a single component) - portfolio
components (comma-joined) are explicitly excluded, per user request. Ad-hoc
entries render at the top of the Fund Lab Summary as group "A" (before the
pre-built 24), the per-fund rendering was extracted into render_fund_report()
shared by both, and a pointer at the top of the page tells the user where
the generated reports are. ETFs with no name on file render as "A01 · TLT"
(no duplicated name).
**Style-tilt battery in the report pipeline (2026-08-30, 3rd pass).**
`fundlab/styletilt.py`: 22 style/asset sleeves (EFA/VWO, growth/value,
IWM/RSP size+equal-weight, USMV/DFLVX low-vol, QUAL, MTUM, HDV/VYM
dividend, TLT, GLD, FXE/FXY/FXU, the five big sectors) regressed on the
fund's excess-of-T-bill returns, full history + 5y. Plain OLS gives every
factor's β + t (exploratory); BIC forward selection gives the IDENTIFIED
tilt stack (strict gate); residual alpha after the identified stack says
"skill left or pure factor exposure". Data-driven commentary: tilt
sentences with strength words (t≥10 strong / ≥5 clear / ≥2 modest),
sign-specific phrasing for the tricky ones (short-euro = USD carry,
anti-quality = flip side of high payout, anti-momentum = contrarian),
5y-only factors called out separately, and an explicit residual-verdict
paragraph. Wired as a "Style tilts" block (factor table + commentary)
into both report builders (app + HTML); ~0.1-0.8 s per fund after the
one-time battery-panel build. All 24 pre-built + 8 ad-hoc reports
rebuilt (23/24 have the block; lcorx has no history). Worked example
(lvhi): identified stack = intl-dev 0.78 + short EUR 0.42 + HDV +0.28
(t+20) + anti-QUAL 0.21 (t-12) + short FXY + short VWO; residual alpha
+2.3%/y t=+1.1 -> "factor exposure, not skill".
+38 -7
View File
@@ -30,7 +30,7 @@ HERE = Path(__file__).parent
RESULTS = HERE / "factor_results.json"
TREE = HERE / "cluster_tree.json"
KMEANS = HERE / "cluster_kmeans.json"
from fundlab.factors import DRIVERS # noqa: E402
from fundlab.factors import AXES, DRIVERS # noqa: E402
def log(msg: str) -> None:
@@ -50,6 +50,11 @@ def loading_matrix() -> tuple[list[str], np.ndarray]:
continue
row = np.array([f["betas"].get(s, 0.0) or 0.0 for s in DRIVERS],
dtype=float)
# virtual CASH axis = net cash position = 1 - sum of the betas.
# Alphas are in excess of the T-bill rate, so the betas are the
# NET INVESTED mix; whatever is left over sits in cash/T-bills.
# Pure money-market fund: all betas ~ 0 -> cash ~ 1.
row = np.append(row, 1.0 - row.sum())
# winsorize at +/-4: everything beyond that is an OLS noise fit
# (R2 ~ 0.01, |t| < 2 - e.g. fyhtx shv +63.8), never a real
# exposure (no open-end fund runs 400% of a sleeve)
@@ -120,7 +125,7 @@ def cluster_means(syms: list[str], V: np.ndarray,
idx = [i for i, s in assign.items() if s == c]
med = np.median(V[idx], axis=0)
top = np.argsort(-np.abs(med))[:4]
prof = {DRIVERS[t]: float(med[t]) for t in top
prof = {AXES[t]: float(med[t]) for t in top
if abs(med[t]) >= 0.05}
out.append({"n": len(idx), "top": prof,
"syms": [syms[i] for i in idx]})
@@ -140,15 +145,41 @@ SLEEVE_NAME = {
"xlv": "healthcare", "xlp": "staples", "xlu": "utilities",
"xly": "consumer disc", "xlb": "materials", "dbmf": "CTA/futures",
"dbb": "commodities",
"cash": "cash (net posn)",
}
# the CASH axis is a POSITION (net cash, 1.0 = fully in cash), not a
# return SENSITIVITY like the betas. In raw Euclidean space a
# pure cash fund (0,...,0,~0.5) sits inside the cloud of low-exposure
# balanced/target-date funds and k-means swallows it. Emphasize the axis
# for DISTANCE only (labels still use the raw values).
CASH_EMPHASIS = 2.0
def emphasized(V: np.ndarray, ci: int) -> np.ndarray:
W = V.copy()
W[:, ci] *= CASH_EMPHASIS
return W
def label(prof: dict) -> str:
# a real driver shows up as >=0.3 on a median loading; below that the
# cluster is balanced mixes with no single dominant driver
if not prof or max(abs(v) for v in prof.values()) < 0.30:
# cluster is balanced mixes with no single dominant driver. The CASH
# axis is a level, not a beta: in a mixed low-exposure cluster the
# median cash is diluted, so it gets a slightly lower threshold and
# must clearly beat the runner-up to count as THE driver.
if not prof:
return "no dominant driver (balanced/idio)"
names = sorted(prof, key=lambda s: -abs(prof[s]))
top_s, top_v = names[0], prof[names[0]]
runner = abs(prof[names[1]]) if len(names) > 1 else 0.0
if top_s == "cash":
if top_v >= 0.25 and top_v >= 1.5 * runner:
return " + ".join(f"{SLEEVE_NAME.get(s, s)} {prof[s]:+.2f}"
for s in names[:3])
return "no dominant driver (balanced/idio)"
if abs(top_v) < 0.30:
return "no dominant driver (balanced/idio)"
return " + ".join(f"{SLEEVE_NAME.get(s, s)} {prof[s]:+.2f}"
for s in names[:3])
@@ -182,7 +213,7 @@ def kmeans(V: np.ndarray, k: int, seed: int = 0,
def run_kmeans(k: int = 30) -> dict:
syms, V = loading_matrix()
lab = kmeans(V, k)
lab = kmeans(emphasized(V, AXES.index("cash")), k)
out: dict[int, dict] = {}
for c in range(k):
idx = [i for i, l in enumerate(lab) if l == c]
@@ -190,7 +221,7 @@ def run_kmeans(k: int = 30) -> dict:
continue
med = np.median(V[idx], axis=0)
top = np.argsort(-np.abs(med))[:4]
prof = {DRIVERS[t]: float(med[t]) for t in top
prof = {AXES[t]: float(med[t]) for t in top
if abs(med[t]) >= 0.08}
out[c] = {"n": len(idx), "top": prof, "label": label(prof),
"syms": [syms[i] for i in idx]}
@@ -203,7 +234,7 @@ def run() -> None:
log(f"cluster: {len(syms)} funds x {V.shape[1]} drivers")
merges = hclust(V)
TREE.write_text(json.dumps({"syms": syms, "merges": merges,
"n": len(syms), "sleeves": DRIVERS}))
"n": len(syms), "sleeves": AXES}))
log(f"hierarchical tree written in {time.time() - t0:.0f}s -> {TREE.name}")
# NOTE: fixed-k cuts of the tree peel small pure-sleeve clusters off a
# giant blend blob (most funds are multi-sleeve mixes) - the useful
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+36 -3
View File
@@ -22,6 +22,7 @@ intercept; alphas are annualized (x252); t-stats use the OLS covariance.
from __future__ import annotations
import json
from functools import lru_cache
from pathlib import Path
import numpy as np
@@ -49,6 +50,29 @@ def adj_close(sym: str, root: Path = DATA) -> pd.Series | None:
return s
@lru_cache(maxsize=1)
def rf_series() -> pd.Series | None:
"""Daily risk-free rate: BIL (SPDR 1-3 Month T-Bill) total return —
the local stand-in for the 3-month T-bill yield. Alphas are computed
in EXCESS of this rate (both the fund and the sleeves are netted
against it), so the intercept is a true excess-return alpha and a
cash position contributes zero (cash IS the risk-free rate). 0 where
BIL has no history (pre-2007)."""
a = adj_close("bil")
if a is None:
return None
return a.pct_change().fillna(0.0)
def excess(panel: pd.DataFrame) -> pd.DataFrame:
"""Net every column against the daily risk-free rate."""
rf = rf_series()
if rf is None:
return panel
rf = rf.reindex(panel.index).fillna(0.0)
return panel.sub(rf, axis=0)
def returns_panel(symbols: list[str], start: str | None = None) -> pd.DataFrame:
"""Daily simple returns, outer-joined on dates (NaN where a series
has no data). Callers must handle missing values per regressor —
@@ -207,9 +231,17 @@ CANDIDATES: dict[str, list[str]] = {
}
# share classes: same underlying fund
ALIAS = {"pmfkx": "pmaix", "lcrix": "lcorx", "egrsx": "eagmx"}
FULL_WINDOW = "1990-01-01" # effectively all history
FULL_WINDOW = "2007-06-01" # from BIL inception: alphas are in excess of
# the T-bill rate, which needs the rf series (raw pre-2007 returns
# mixed with excess post-2007 returns breaks the full-window fit)
RECENT_WINDOW = "2021-01-01" # last ~5 years
# sleeves that ARE the risk-free rate. Alphas are now computed in excess of
# the T-bill rate, so these columns are ~0 in excess space and would make
# the regression ill-conditioned. Cash exposure is captured by the residual
# (1 - sum of betas) instead, so they are dropped from the regressors.
CASH_SLEEVES = {"shv", "bil"}
def _drift(rb: pd.DataFrame, full_beta: np.ndarray) -> dict[str, float]:
"""Mean |rolling beta - full-sample beta| per component, as a fraction
@@ -225,13 +257,14 @@ def _drift(rb: pd.DataFrame, full_beta: np.ndarray) -> dict[str, float]:
def decompose(fund: str, start: str = FULL_WINDOW,
candidates: dict[str, list[str]] | None = None) -> dict:
cand_syms = (candidates or CANDIDATES).get(fund, [])
r = returns_panel([fund] + cand_syms, start=start)
r = excess(returns_panel([fund] + cand_syms, start=start))
if fund not in r.columns:
return {"fund": fund, "error": "no return history in the data set",
"verdict": "no return history", "start": start}
y = r[fund].to_numpy()
dates = r.index
cand = {s: r[s].to_numpy() for s in r.columns if s != fund}
cand = {s: r[s].to_numpy() for s in r.columns
if s != fund and s not in CASH_SLEEVES}
y_ok = ~np.isnan(y)
if y_ok.sum() < 252:
return {"fund": fund, "error": "insufficient return history",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+18 -2
View File
@@ -69,9 +69,19 @@ SLEEVES_V2 = list(dict.fromkeys(BROAD_SLEEVES + EXTRA_SLEEVES))
# short-rate exposure as huge offsetting shv/bil coefficients (shv +64 /
# bil -54) - shv (1-3m) alone carries the cash/ultra-short axis, shy
# keeps the 1-3y axis.
DROP_FROM_REGRESSION = {"vea", "vug", "finux", "bil"}
DROP_FROM_REGRESSION = {"vea", "vug", "finux", "bil", "shv"}
# (bil/shv are the risk-free sleeves - alphas are now computed in
# excess of the T-bill rate, where they are ~0 columns; the cash
# position shows up in the residual / the virtual CASH axis instead)
DRIVERS = [s for s in SLEEVES_V2 if s not in DROP_FROM_REGRESSION]
# clustering/display basis = the regression sleeves + a virtual CASH axis.
# Alphas are computed in EXCESS of the T-bill rate (decompose.excess), so
# the beta vector is the fund's NET INVESTED mix and the leftover
# (1 - sum of betas) is its cash/T-bill position: a pure money-market
# fund has all betas ~ 0 -> CASH ~ 1, a levered fund -> CASH < 0.
AXES = DRIVERS + ["cash"]
def _resid(y: pd.Series, X: pd.DataFrame) -> pd.Series:
m = y.notna() & X.notna().all(axis=1)
@@ -93,6 +103,7 @@ def _panel() -> pd.DataFrame:
log(f"building driver panel ({len(DRIVERS)} axes)")
p = decompose.returns_panel(SLEEVES_V2).sort_index()
p = p[~p.index.duplicated(keep="last")][DRIVERS]
p = decompose.excess(p) # alphas are in excess of the T-bill rate
# pure vol axis: vblix residualized on the core equity/duration axes
core = [c for c in ("ivv", "tlt") if c in p.columns]
if "vblix" in p.columns and core:
@@ -142,11 +153,16 @@ def _beta_window(y: pd.Series, X: pd.DataFrame, start: str) -> dict | None:
}
def factor_screen(sym: str, start: str = "1990-01-01") -> dict | None:
def factor_screen(sym: str, start: str = None) -> dict | None:
if start is None:
start = decompose.FULL_WINDOW
fund = decompose.adj_close(sym)
if fund is None or len(fund) < 250:
return None
y = fund.pct_change().dropna()
rf = decompose.rf_series()
if rf is not None:
y = y.sub(rf.reindex(y.index).fillna(0.0))
X = _panel().reindex(y.index)
# sleeves must have history for most of the fund's window
avail = [c for c in X.columns if X[c].notna().mean() > 0.3]
+14
View File
@@ -0,0 +1,14 @@
15:03:47 factor screen: 2384 funds, 2384 to do
15:03:47 building driver panel (34 axes)
15:03:55 200/2384
15:04:02 400/2384
15:04:10 600/2384
15:04:18 800/2384
15:04:30 1000/2384
15:04:43 1200/2384
15:04:52 1400/2384
15:04:59 1600/2384
15:05:07 1800/2384
15:05:14 2000/2384
15:05:21 2200/2384
15:05:28 factor screen done: 2384 funds -> factor_results.json
+444
View File
@@ -0,0 +1,444 @@
"""Per-fund narrative: English prose explaining the performance and its
drivers, built from the analysis we have on file.
The prose is data-driven (every number comes from the computed results),
and it is required to be honest about limits: when the return drivers
are unknown or only weakly identified, the text says so explicitly.
Paragraphs:
1. what the fund is (name, stated strategy if on file, what its
N-PORT actually holds, which return-driver cluster it sits in)
2. the performance in plain terms (full history, 5y, recent year,
behaviour in the defined market episodes, calendar-year pattern)
3. what is driving it (fit quality -> whose exposures vs idiosyncratic
alpha; the economic meaning of the top loadings; weight stability)
4. what we do NOT know (unexplained share, alpha steadiness, sample
size, holdings opacity) - stated plainly
5. bottom line (account placement, best cluster peers, role)
Run: .venv/bin/python -m fundlab.narrative (prints all narratives)
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
from fundlab import report as _r
from fundlab.searchlist import BROAD_SLEEVES
from fundlab import decompose as _dc
HERE = Path(__file__).parent
_XC = json.loads((HERE / "xcheck_report.json").read_text()) \
if (HERE / "xcheck_report.json").exists() else {}
def _pct(x, nd=1) -> str:
if x is None or (isinstance(x, float) and np.isnan(x)):
return "no data"
return f"{100 * x:+.{nd}f}%"
def _num(x, nd=2) -> str:
if x is None or (isinstance(x, float) and np.isnan(x)):
return "n/a"
return f"{x:.{nd}f}"
# short prose names for sleeves whose SLEEVE_DESC lead-in references a
# sibling ticker ("same HY exposure as VWEAX via a different fund")
_PROSE_NAME = {
"vea": "international developed markets",
"efa": "international developed markets",
"hyg": "high-yield corporate bonds",
"vweax": "high-yield corporate bonds",
"dbb": "broad commodities",
"gsg": "broad commodities",
"vblix": "crash vol (VIX futures)",
"bil": "cash (T-bills)",
"shv": "cash (T-bills)",
}
def _sleeve_prose(sym: str, beta: float) -> str:
nm, desc = _r.sleeve_desc(sym)
short = _PROSE_NAME.get(sym)
head = short.split(";")[0].strip() if short else \
desc.split(";")[0].strip()
head = head[0].upper() + head[1:] if head else nm
if abs(beta) < 0.15:
return f"a small tilt to {head.lower()}"
if beta > 0:
return f"exposure to {head.lower()}"
return f"short-like exposure to {head.lower()} (it rises when that " \
f"asset falls)"
def _top_sleeves(fr: dict, window: str, n: int = 3) -> list[tuple[str, float]]:
f = fr.get(window) or {}
betas = f.get("betas") or {}
top = sorted(betas.items(), key=lambda kv: -abs(kv[1]))[:n]
return [(s, b) for s, b in top if abs(b) >= 0.08]
def _fit(fr: dict, srow: dict) -> tuple[float | None, float | None,
float | None]:
"""(r2, alpha_ann_5y, t5) preferring the reference-model numbers."""
r2 = srow.get("r2_5y")
a5 = srow.get("alpha_ann_5y")
t5 = srow.get("alpha_t_5y")
if not isinstance(r2, (int, float)):
r2 = (fr.get("rec5") or fr.get("full") or {}).get("r2")
if not isinstance(a5, (int, float)):
a5 = (fr.get("rec5") or fr.get("full") or {}).get("alpha_ann")
if not isinstance(t5, (int, float)):
t5 = (fr.get("rec5") or fr.get("full") or {}).get("alpha_t")
return (r2 if isinstance(r2, (int, float)) else None,
a5 if isinstance(a5, (int, float)) else None,
t5 if isinstance(t5, (int, float)) else None)
def narrate(sym: str) -> list[str]:
sym = sym.lower()
srow = _r.search_row(sym)
fr = _r.factor_row(sym)
dr = _r.decomp_row(sym)
tax = _r.tax_row(sym)
ddr = _r.dd_row(sym)
xcr = _XC.get(sym, {})
p = _r.price(sym)
name = (srow.get("name") or _r.FONDS.get(sym, {}).get("name")
or (fr or {}).get("name") or sym.upper())
out: list[str] = []
# ------------------------------------------------------------ 1. what
who = []
who.append(f"{sym.upper()} is the {name}.")
obj = (_r.FONDS.get(sym) or {}).get("objective")
if obj:
first = obj.split(". ")[0].strip().rstrip(".")
who.append(f"Stated strategy: {first}.")
if xcr and not xcr.get("error"):
b = [x["name"] for x in xcr.get("buckets", [])[:2]]
if b:
who.append(f"Per its latest N-PORT its actual holdings are "
f"mostly {b[0]}"
+ (f" and {b[1]}" if len(b) > 1 else "") + ".")
out.append(" ".join(who))
if p is None:
# no return history: do NOT claim a cluster - the loading vector
# is all zeros and would park the fund in the cash cluster
out.append("There is no local return history for this share "
"class yet (new class), so performance and drivers "
"cannot be measured from returns. The N-PORT shows "
"what it holds: " + ((dr or {}).get("note")
or "see holdings"))
return out
if sym in _r.MEMBER:
_cid, clabel, cn = _r.MEMBER[sym]
who = out[0]
out[0] = (who + f" In the return-driver analysis it sits in the "
f"'{clabel}' cluster with {cn - 1} other funds.")
else:
try:
load = _r.fund_loading_row(fr)
_cid, clabel = _r.cluster_of_row(load)
out[0] = (out[0] + f" Its return-driver signature is closest "
f"to the '{clabel}' cluster.")
except Exception:
pass
st = _r.perf_stats(p)
r2, a5, t5 = _fit(fr, srow)
tf = (fr.get("full") or {}).get("alpha_t")
a_f = (fr.get("full") or {}).get("alpha_ann")
refs = _r.ref_components(sym, fr)
r2f_ = (fr.get("rec5") or fr.get("full") or {}).get("r2")
fit = r2 if r2 is not None else r2f_
r25 = srow.get("r2_5y") if isinstance(srow.get("r2_5y"), (int, float)) \
else r2f_
refs_curve = refs if (fit is not None and fit >= 0.5) else []
mix = _r.mix_series(refs_curve) if refs_curve else _r.price("bil")
ivv = _r.price("ivv")
t5y = _r.window_ret(p, "2021-01-01", st["end"])
t1y = _r.window_ret(p, "2025-09-01", st["end"])
ref5y = _r.window_ret(mix, "2021-01-01", st["end"]) if mix is not None \
else None
iv5y = _r.window_ret(ivv, "2021-01-01", st["end"]) if ivv is not None \
else None
# --------------------------------------------------------- 2. performance
perf = []
tot = p.iloc[-1] / p.iloc[0] - 1
perf.append(
f"Since {st['start'][:4]} it has compounded at "
f"{_pct(st['cagr'])} per year (a {_pct(tot, 0)} total return) "
f"with {_pct(st['vol'], 0)} annualized volatility and a maximum "
f"drawdown of {100 * abs(st['mdd']):.0f}%.")
perf.append(
f"Over the last five years it returned {_pct(t5y)} versus "
f"{_pct(ref5y)} for its reference"
+ (f" and {_pct(iv5y)} for the S&P 500" if iv5y is not None else "")
+ f". The last twelve months have done {_pct(t1y)}.")
yrs = _r.annual_table(p, 7)
pos = sum(1 for _y, v in yrs if v > 0)
perf.append(f"It was positive in {pos} of the last {len(yrs)} "
f"calendar years (including the partial current year).")
# episodes
rets = ddr.get("rets", {})
if rets:
best = max(rets.items(), key=lambda kv: kv[1])
worst = min(rets.items(), key=lambda kv: kv[1])
perf.append(
f"Across the defined market episodes it did best in "
f"'{best[0]}' ({_pct(best[1])}) and worst in '{worst[0]}' "
f"({_pct(worst[1])}) - the peak-to-trough windows when "
f"equities fell hardest.")
_dv = ddr.get("verdict") or ""
if _dv and not _dv.startswith("CANDIDATE"):
perf.append(f"Its drawdown screen verdict: {_dv}.")
out.append(" ".join(perf))
# --------------------------------------------------------- 3. drivers
drv = []
tops = _top_sleeves(fr, "rec5", 3)
if fit is not None and fit >= 0.7:
tops_txt = ", ".join(_sleeve_prose(s, b) for s, b in tops)
drv.append(
f"The fit is strong: {100 * fit:.0f}% of its excess returns "
f"over the last five years are explained by its measured "
f"exposures"
+ (f" - {tops_txt}" if tops else "") + ".")
drv.append(
f"In other words, most of what this fund does is charge you "
f"for those exposures in the form of a fund; what is left - "
f"an alpha of {_pct(a5)} per year (t = {_num(t5, 1)}) - is "
+ ("statistically indistinguishable from zero, i.e. the "
"strategy is not clearly adding anything on top of the "
"mix it owns."
if (t5 or 0) < 1.75 else
"small relative to the beta, but it is what separates "
"this fund from the equivalent index mix.")
)
elif fit is not None and fit >= 0.5:
tops_txt = ", ".join(_sleeve_prose(s, b) for s, b in tops)
drv.append(
f"The measured exposures explain a good share but not all "
f"({100 * fit:.0f}% R²) of its excess returns."
+ (f" The main ones: {tops_txt}." if tops else ""))
drv.append(
f"The residual is {_pct(a5)} per year (t = {_num(t5, 1)}): "
+ ("a real edge on top of the mix, but a material part of "
"the performance IS the mix - judge the exposures and "
"the skill separately."
if (t5 or 0) >= 1.75 else
"not statistically distinct from noise at the five-year "
"horizon, so treat the outperformance as part beta, part "
"luck until it accumulates more history.")
)
else:
tops_txt = ", ".join(_sleeve_prose(s, b) for s, b in tops)
drv.append(
f"The broad sleeve framework explains little of its excess "
f"returns (R² = {_num(fit) if fit is not None else 'n/a'}). "
+ (f"The loadings that do show up - {tops_txt} - are minor "
"tilts, not the story."
if tops else
"No benchmark loading is even large."))
long_ctx = ""
if isinstance(a_f, (int, float)):
long_ctx = (f" Over the full history the same estimate is "
f"{_pct(a_f)} per year (t = {_num(tf, 1)}).")
if (t5 or 0) >= 2:
drv.append(
f"The bulk of the performance is therefore "
f"idiosyncratic: it comes from the fund's own holdings "
f"and decisions, which nothing in our 34-sleeve space "
f"replicates. The estimate of that idiosyncratic return "
f"is {_pct(a5)} per year over the last five years "
f"(t = {_num(t5, 1)}) - statistically significant, so "
f"the outperformance is real; what the returns alone "
f"cannot tell us is its source.{long_ctx}")
elif (a5 or 0) >= 0:
drv.append(
f"The bulk of the performance is therefore "
f"idiosyncratic: it comes from the fund's own holdings "
f"and decisions, which nothing in our 34-sleeve space "
f"replicates. The estimate of that idiosyncratic return "
f"is {_pct(a5)} per year over the last five years "
f"(t = {_num(t5, 1)}) - at that t-stat it is not yet "
f"clearly different from a lucky streak.{long_ctx}")
else:
drv.append(
f"Most of the performance is therefore idiosyncratic "
f"rather than benchmark-like. The honest five-year read "
f"of its excess return is {_pct(a5)} per year "
f"(t = {_num(t5, 1)}): over the recent window this fund "
f"is NOT measurably adding to its fitted reference.{long_ctx}")
if (a5 or 0) < 0 and isinstance(tf, (int, float)) and tf >= 1.25:
drv.append(
f"The longer record is better: over the full history the "
f"alpha is {_pct(a_f)} per year (t = {_num(tf, 1)}), "
f"which IS significant - so the five-year estimate "
f"looks like a flat patch in a longer positive trend, "
f"not evidence the edge has gone.")
if xcr and not xcr.get("error"):
b = [x["name"] for x in xcr.get("buckets", [])[:2]]
if b:
drv.append(
f"The N-PORT is consistent with that: the alpha is "
f"plausibly coming from {b[0]}"
+ (f" and {b[1]}" if len(b) > 1 else "")
+ " - asset classes our sleeve set either does not "
"model directly or models too coarsely. That is an "
"interpretation from the holdings, not something "
"the returns prove.")
if obj and (a5 or 0) > 0:
_o = obj.split(". ")[0].rstrip(".")
if len(_o) > 110:
_o = _o[:110].rsplit(" ", 1)[0] + "..."
drv.append(
f"The stated strategy ('{_o}') is a plausible mechanism "
f"as well, but that is a hypothesis - the returns only "
f"tell us the outperformance exists, not why.")
# stability (curated funds)
roll = (dr or {}).get("rolling") or {}
if "verdict" in (dr or {}) and roll.get("max_drift") is not None:
md = roll["max_drift"]
drv.append(
f"The curated decomposition's read: {dr['verdict']}. "
f"Weight stability: the one-year rolling betas move by at "
f"most {md:.2f} (relative to the full-sample weights) - "
+ ("so the weights are roughly stable over time."
if md < 0.5 else
"so treat this as a tactically active fund, not a "
"static mix."))
out.append(" ".join(drv))
# ------------------------------------------------- 4. what we do NOT know
unk = []
if fit is not None:
if (t5 or 0) >= 2:
unk.append(
f"To be explicit about the limits: "
f"{100 * (1 - fit):.0f}% of this fund's excess return "
f"is NOT attributed to any measured exposure by our "
f"analysis - we know the outperformance is real, we do "
f"not know from returns what produces it; the source "
f"has to be read from the filings before sizing up.")
else:
unk.append(
f"To be explicit about the limits: the excess return is "
f"not measurable against noise at the current sample "
f"size, so there is not even a reliable alpha to "
f"attribute; {100 * (1 - fit):.0f}% of the return is "
f"outside our sleeve model either way.")
pf = srow.get("alpha_pos_frac")
if isinstance(pf, (int, float)) and pf < 0.60:
unk.append(
f"The alpha is also not steady: in {100 * (1 - pf):.0f}% of "
f"rolling six-month windows the fund trailed its reference, "
f"so the five-year number is carrying periods of "
f"underperformance.")
if (t5 or 0) >= 2 and isinstance(tf, (int, float)) and tf < 1.25:
unk.append(
"The significance is recent - over the full history the "
"alpha is not significant, so this is a provisional read on "
"a ~5-year sample.")
if st["years"] < 3:
unk.append(
f"The whole sample is short ({st['years']:.1f} years), so "
f"every number above has a wide error bar.")
if xcr.get("note"):
unk.append(xcr["note"].rstrip(".") + ".")
note = (dr or {}).get("note")
if note and "N-PORT" in note:
# holdings cross-check sentence (shortlist)
for sentence in note.split(". "):
if "N-PORT" in sentence or "holdings" in sentence.lower():
unk.append(sentence.strip().rstrip(".") +
" - the holdings check is the ground truth "
"here, and the return model is only a "
"description of it.")
break
if not unk:
unk.append("No major caveats beyond the usual: the past fit may "
"not persist, and the sleeves are models of the "
"fund, not the fund itself.")
out.append(" ".join(unk))
# --------------------------------------------------------- 5. bottom line
bot = []
loc = tax.get("location")
if loc:
basis = "N-PORT holdings" if tax.get("basis") == "N-PORT" \
else "the sleeve model"
if "MIXED" in loc:
bot.append(
f"Account placement: not settled by the model - the "
f"sleeve model calls it MIXED, so the last 1099-DIV is "
f"the arbiter before choosing taxable vs IRA.")
else:
bot.append(
f"Account placement: "
f"{'taxable' if 'TAXABLE' in loc else 'IRA'} "
f"({basis} says {loc}).")
# peers
if sym in _r.MEMBER:
cid = _r.MEMBER[sym][0]
members = _r.KMEANS["clusters"][cid]["syms"]
peers = []
for s in members:
if s == sym:
continue
v = _r.search_row(s)
if isinstance(v.get("alpha_t_5y"), (int, float)) and \
v["alpha_t_5y"] > 0:
pp = _r.price(s)
if pp is None:
continue
peers.append((v["alpha_t_5y"], v.get("alpha_ann_5y"), s))
peers.sort(reverse=True)
if peers:
b_t, b_a, b_s = peers[0]
bp = _r.price(b_s)
bt5 = _r.window_ret(bp, "2021-01-01",
_r.perf_stats(bp)["end"])
bot.append(
f"Within its cluster the strongest alternative is "
f"{b_s.upper()} (5y {_pct(bt5)}, alpha t = {b_t:+.1f}); "
f"the choice between them should turn on the conviction "
f"in the strategy, the tax fit and the price paid, not "
f"on the statistics - they are the same kind of "
f"position.")
cp = srow.get("corr_portfolio")
if isinstance(cp, (int, float)):
bot.append(
f"Its correlation with your current portfolio is "
f"{cp:+.2f} - "
+ ("a genuine diversifier" if cp < 0.3
else "not very diversified vs what you already own".rstrip("."))
+ ".")
out.append(" ".join(bot))
return out
def main() -> None:
from fundlab.nport import FUND_TOKENS
from fundlab.decompose import ALIAS
cand = [v["sym"] for v in _r.SEARCH.values()
if isinstance(v, dict)
and str(v.get("verdict", "")).startswith("CANDIDATE")]
short = [s for s in FUND_TOKENS if s not in ALIAS]
for s in cand + short:
print(f"=== {s.upper()} ===")
for para in narrate(s):
print(para)
print()
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
5847
+36
View File
@@ -0,0 +1,36 @@
15:09:56 === stage screen ===
15:09:56 screen: 2384 funds, 2384 to do
15:10:29 screen: 100/2384
15:11:01 screen: 200/2384
15:11:33 screen: 300/2384
15:12:04 screen: 400/2384
15:12:36 screen: 500/2384
15:13:09 screen: 600/2384
15:13:42 screen: 700/2384
15:14:15 screen: 800/2384
15:14:45 screen: 900/2384
15:15:20 screen: 1000/2384
15:15:56 screen: 1100/2384
15:16:31 screen: 1200/2384
15:17:07 screen: 1300/2384
15:17:38 screen: 1400/2384
15:18:14 screen: 1500/2384
15:18:45 screen: 1600/2384
15:19:16 screen: 1700/2384
15:19:47 screen: 1800/2384
15:20:19 screen: 1900/2384
15:20:51 screen: 2000/2384
15:21:23 screen: 2100/2384
15:21:54 screen: 2200/2384
15:22:26 screen: 2300/2384
15:22:53 screen done: 2384 funds
15:22:53 === stage finalize ===
15:22:53 finalize: 2384 funds screened
15:22:53 1339 sleeve mix
15:22:53 1001 weak/unstable alpha
15:22:53 17 no 5y window
15:22:53 11 CANDIDATE
15:22:53 10 alpha, but correlated with current portfolio
15:22:53 6 alpha in 5y window, but not persistent
15:22:53 candidates v1 name-filter would have missed: ['aguax', 'etsix', 'femdx', 'hicox', 'prfrx', 'puls', 'rctix', 'rpifx', 'scfzx']
15:22:53 === overnight run finished in 0.2h ===
+98
View File
@@ -0,0 +1,98 @@
[2026-08-30 15:40:42] rows=2384 todo=2384
[2026-08-30 15:40:48] 25/2384 done (saved)
[2026-08-30 15:40:53] 50/2384 done (saved)
[2026-08-30 15:40:59] 75/2384 done (saved)
[2026-08-30 15:41:04] 100/2384 done (saved)
[2026-08-30 15:41:10] 125/2384 done (saved)
[2026-08-30 15:41:16] 150/2384 done (saved)
[2026-08-30 15:41:22] 175/2384 done (saved)
[2026-08-30 15:41:28] 200/2384 done (saved)
[2026-08-30 15:41:33] 225/2384 done (saved)
[2026-08-30 15:41:39] 250/2384 done (saved)
[2026-08-30 15:41:45] 275/2384 done (saved)
[2026-08-30 15:41:51] 300/2384 done (saved)
[2026-08-30 15:41:57] 325/2384 done (saved)
[2026-08-30 15:42:03] 350/2384 done (saved)
[2026-08-30 15:42:08] 375/2384 done (saved)
[2026-08-30 15:42:14] 400/2384 done (saved)
[2026-08-30 15:42:20] 425/2384 done (saved)
[2026-08-30 15:42:26] 450/2384 done (saved)
[2026-08-30 15:42:32] 475/2384 done (saved)
[2026-08-30 15:42:37] 500/2384 done (saved)
[2026-08-30 15:42:42] 525/2384 done (saved)
[2026-08-30 15:42:48] 550/2384 done (saved)
[2026-08-30 15:42:54] 575/2384 done (saved)
[2026-08-30 15:43:00] 600/2384 done (saved)
[2026-08-30 15:43:06] 625/2384 done (saved)
[2026-08-30 15:43:11] 650/2384 done (saved)
[2026-08-30 15:43:18] 675/2384 done (saved)
[2026-08-30 15:43:24] 700/2384 done (saved)
[2026-08-30 15:43:29] 725/2384 done (saved)
[2026-08-30 15:43:36] 750/2384 done (saved)
[2026-08-30 15:43:42] 775/2384 done (saved)
[2026-08-30 15:43:48] 800/2384 done (saved)
[2026-08-30 15:43:53] 825/2384 done (saved)
[2026-08-30 15:43:59] 850/2384 done (saved)
[2026-08-30 15:44:05] 875/2384 done (saved)
[2026-08-30 15:44:10] 900/2384 done (saved)
[2026-08-30 15:44:16] 925/2384 done (saved)
[2026-08-30 15:44:22] 950/2384 done (saved)
[2026-08-30 15:44:28] 975/2384 done (saved)
[2026-08-30 15:44:34] 1000/2384 done (saved)
[2026-08-30 15:44:39] 1025/2384 done (saved)
[2026-08-30 15:44:45] 1050/2384 done (saved)
[2026-08-30 15:44:51] 1075/2384 done (saved)
[2026-08-30 15:44:56] 1100/2384 done (saved)
[2026-08-30 15:45:02] 1125/2384 done (saved)
[2026-08-30 15:45:08] 1150/2384 done (saved)
[2026-08-30 15:45:14] 1175/2384 done (saved)
[2026-08-30 15:45:19] 1200/2384 done (saved)
[2026-08-30 15:45:25] 1225/2384 done (saved)
[2026-08-30 15:45:31] 1250/2384 done (saved)
[2026-08-30 15:45:36] 1275/2384 done (saved)
[2026-08-30 15:45:42] 1300/2384 done (saved)
[2026-08-30 15:45:47] 1325/2384 done (saved)
[2026-08-30 15:45:53] 1350/2384 done (saved)
[2026-08-30 15:45:59] 1375/2384 done (saved)
[2026-08-30 15:46:04] 1400/2384 done (saved)
[2026-08-30 15:46:10] 1425/2384 done (saved)
[2026-08-30 15:46:16] 1450/2384 done (saved)
[2026-08-30 15:46:22] 1475/2384 done (saved)
[2026-08-30 15:46:28] 1500/2384 done (saved)
[2026-08-30 15:46:33] 1525/2384 done (saved)
[2026-08-30 15:46:38] 1550/2384 done (saved)
[2026-08-30 15:46:44] 1575/2384 done (saved)
[2026-08-30 15:46:49] 1600/2384 done (saved)
[2026-08-30 15:46:55] 1625/2384 done (saved)
[2026-08-30 15:47:01] 1650/2384 done (saved)
[2026-08-30 15:47:06] 1675/2384 done (saved)
[2026-08-30 15:47:12] 1700/2384 done (saved)
[2026-08-30 15:47:18] 1725/2384 done (saved)
[2026-08-30 15:47:24] 1750/2384 done (saved)
[2026-08-30 15:47:30] 1775/2384 done (saved)
[2026-08-30 15:47:35] 1800/2384 done (saved)
[2026-08-30 15:47:41] 1825/2384 done (saved)
[2026-08-30 15:47:47] 1850/2384 done (saved)
[2026-08-30 15:47:53] 1875/2384 done (saved)
[2026-08-30 15:47:59] 1900/2384 done (saved)
[2026-08-30 15:48:05] 1925/2384 done (saved)
[2026-08-30 15:48:10] 1950/2384 done (saved)
[2026-08-30 15:48:16] 1975/2384 done (saved)
[2026-08-30 15:48:22] 2000/2384 done (saved)
[2026-08-30 15:48:28] 2025/2384 done (saved)
[2026-08-30 15:48:33] 2050/2384 done (saved)
[2026-08-30 15:48:39] 2075/2384 done (saved)
[2026-08-30 15:48:45] 2100/2384 done (saved)
[2026-08-30 15:48:51] 2125/2384 done (saved)
[2026-08-30 15:48:57] 2150/2384 done (saved)
[2026-08-30 15:49:03] 2175/2384 done (saved)
[2026-08-30 15:49:09] 2200/2384 done (saved)
[2026-08-30 15:49:15] 2225/2384 done (saved)
[2026-08-30 15:49:21] 2250/2384 done (saved)
[2026-08-30 15:49:27] 2275/2384 done (saved)
[2026-08-30 15:49:33] 2300/2384 done (saved)
[2026-08-30 15:49:38] 2325/2384 done (saved)
[2026-08-30 15:49:44] 2350/2384 done (saved)
[2026-08-30 15:49:50] 2375/2384 done (saved)
[2026-08-30 15:49:52] 2384/2384 done (saved)
[2026-08-30 15:49:52] done: 2384 rows carry a reference
+76
View File
@@ -0,0 +1,76 @@
"""Backfill the per-fund alpha REFERENCE into search_all.json.
The alpha search verdict (fundlab/search.py) computes alpha as the OLS
intercept of the fund's daily total returns against the sleeves BIC
forward-selection picked from the 21 broad sleeve axes (the same set for
every fund). The picked sleeves ARE the fund's reference - a fitted
sleeve mix, not a single index - but the screen never stored them, so
the app couldn't show them.
This script recomputes the forward selection (full + last-5y) for every
screened fund and stores a compact, human-readable reference string on
each row:
ref_5y "ivv +0.62, tlt +0.31" (sleeves picked for the 5y model)
ref_full "ivv +0.38, efa +0.15, ..."
"pure alpha (no sleeve selected)" when the model has no components
Resumable: rows that already carry ref_5y are skipped.
Run: .venv/bin/python -m fundlab.refback (logs to fundlab/refback.log)
"""
from __future__ import annotations
import json
import time
from fundlab import decompose
from fundlab.searchlist import BROAD_SLEEVES
HERE = __import__("pathlib").Path(__file__).parent
SRC = HERE / "search_all.json"
LOG = HERE / "refback.log"
def log(msg: str) -> None:
line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}"
print(line, flush=True)
with LOG.open("a") as f:
f.write(line + "\n")
def _fmt(m: dict) -> str:
comps = m.get("components") or []
if not comps:
return "pure alpha (no sleeve selected)"
return ", ".join(f"{c['sym']} {c['beta']:+.2f}" for c in comps)
def run() -> None:
d = json.loads(SRC.read_text())
todo = [k for k, v in d.items()
if isinstance(v, dict)
and isinstance(v.get("r2_5y"), (int, float))
and "ref_5y" not in v]
log(f"rows={len(d)} todo={len(todo)}")
for i, k in enumerate(todo, 1):
sym = d[k]["sym"]
try:
rec = decompose.decompose(sym, start=decompose.RECENT_WINDOW,
candidates={sym: BROAD_SLEEVES})
full = decompose.decompose(sym, candidates={sym: BROAD_SLEEVES})
d[k]["ref_5y"] = _fmt(rec)
d[k]["ref_full"] = _fmt(full)
except Exception as e: # noqa: BLE001 - batch must not die
d[k]["ref_5y"] = f"(backfill failed: {e})"
if i % 25 == 0 or i == len(todo):
SRC.write_text(json.dumps(d, indent=1))
log(f"{i}/{len(todo)} done (saved)")
SRC.write_text(json.dumps(d, indent=1))
n = sum(1 for v in d.values()
if isinstance(v, dict) and v.get("ref_5y"))
log(f"done: {n} rows carry a reference")
if __name__ == "__main__":
run()
+835
View File
@@ -0,0 +1,835 @@
"""Fund report: candidates + shortlist, self-contained HTML.
One section per fund:
- equity curve over the maximum available period (fund vs its fitted
reference mix vs IVV),
- performance: full history, calendar years, and the defined market
episodes (2022 bear, 2023 rate shock, 2024 vol spike, 2025 tariff
crash, 2026 Q1) - fund vs reference mix vs IVV, with the fund-vs-
reference gap (period alpha/timing),
- what drove it: the excess-of-T-bill sleeve loadings (full + 5y),
alpha + t, R^2, rolling drift, verdict,
- the reference mix explained: each picked sleeve with what it
actually exposes you to (not just the ticker),
- tax character + taxable/IRA placement,
- cluster peers: the 3-4 best funds of the same k=30 return-driver
cluster, compared, with this fund's advantages/disadvantages.
Run: .venv/bin/python -m fundlab.report -> reports/fund_report.html
"""
from __future__ import annotations
import html
import json
import time
from pathlib import Path
import numpy as np
import pandas as pd
from fundlab import cluster as _cl
from fundlab import decompose
from fundlab import factors
from fundlab.searchlist import BROAD_SLEEVES
HERE = Path(__file__).parent
REPORTS = HERE.parent / "reports"
REPORTS.mkdir(exist_ok=True)
OUT = REPORTS / "fund_report.html"
TAX = json.loads((HERE / "taxplan_results.json").read_text())
DD = json.loads((HERE / "drawdown_results.json").read_text())
FACTOR = json.loads((HERE / "factor_results.json").read_text())
SEARCH = json.loads((HERE / "search_all.json").read_text())
DECOMP = json.loads((HERE / "decompose_results.json").read_text())
FONDS = json.loads((HERE.parent / "funds.json").read_text())
KMEANS = json.loads((HERE / "cluster_kmeans.json").read_text())
# ------------------------------------------------------------------ sleeves
# what each sleeve actually EXPOSES you to (the report must explain the
# exposure, not just name the ticker)
SLEEVE_DESC = {
"qqq": ("US large growth (Nasdaq-100)",
"growth/tech-heavy US equities; high sensitivity to earnings "
"surprises and long-end rates (duration of growth cash flows)"),
"ivv": ("US large blend (S&P 500)",
"core US equity market; the default 'own the economy' exposure"),
"iwm": ("US small cap (Russell 2000)",
"small-cap cycle: domestic credit, margin pressure, IPO window"),
"vea": ("Intl developed ex-US (Vanguard)",
"developed-market equities outside the US (EU, Japan, UK); FX-"
"hedged-off, currency moves matter"),
"efa": ("Intl developed ex-US (MSCI EAFE)",
"developed-market equities outside the US; same exposure as VEA "
"via a different index provider"),
"vwo": ("Emerging-market equity",
"EM corporate profits + EM currency + China/FX flows; "
"high-vol, high-carry, dollar-sensitive"),
"vnq": ("US REITs",
"physical real estate: rents vs rates, leverage in the property "
"sector; equity-like income"),
"bil": ("1-3 month T-bills (cash)",
"the risk-free rate itself; ~zero volatility, pure carry"),
"shv": ("0-3 month T-bills (ultra-short cash)",
"the risk-free rate itself; netted out of the excess-return "
"regression, shown only as part of a fund's cash position"),
"shy": ("1-3 year Treasuries (short duration)",
"short duration: modest rate sensitivity, ~cash-plus-carry"),
"ief": ("7-10 year Treasuries (core duration)",
"the core rate bet: price moves when the Fed path changes"),
"tlt": ("20+ year Treasuries (long duration)",
"levered duration: big moves on rate expectations, steepener/"
"bull-steepener exposure"),
"vblix": ("VIX futures (pure vol axis)",
"crash insurance / short-vol funding; positive loading = "
"long-vol (rises in panic), negative = short-vol carry"),
"agg": ("Aggregate bonds (Treasuries + IG credit)",
"the core bond market: ~60% Treasuries, IG corporates, MBS; "
"moderate duration"),
"vweax": ("High-yield corporate bonds",
"credit spread cycle: HY junk yields, default risk in "
"recessions, strong carry in stable times"),
"hyg": ("High-yield corporate bonds (iShares)",
"same HY credit-spread exposure as VWEAX via a different fund"),
"vmbix": ("Agency RMBS (mortgage-backed)",
"mortgage credit + prepayment/extension risk; the refi cycle"),
"lqd": ("Investment-grade corporate bonds",
"IG credit spreads over Treasuries; milder default risk than HY"),
"finux": ("Intl bonds (Fidelity; TERMINATED 2017)",
"non-US credit/duration; data ends 2017 so recent windows "
"never use it"),
"pff": ("Preferred stocks",
"hybrid: fixed-rate equity-like instruments; rate + credit + "
"equity risk in one"),
"emb": ("Emerging-market debt",
"EM sovereign/corporate carry; EM currency + dollar cycle"),
"tip": ("TIPS (inflation-linked Treasuries)",
"breakeven inflation exposure: rises when inflation "
"expectations rise"),
"vtv": ("US value",
"cheap/asset-rich US names (financials, energy, cyclicals); "
"value-vs-growth style cycle"),
"dbmf": ("CTA / managed futures",
"trend-following across futures; long in crises, earns "
"un-correlated carry otherwise"),
"dbb": ("Broad commodities",
"commodity basket: inflation hedge + global growth proxy"),
"djp": ("Natural gas",
"a single volatile commodity: winter/hedging cycles"),
"gsg": ("Broad commodities (SPDR)",
"same commodity exposure as DBB via a different fund"),
"gld": ("Gold",
"crisis/inflation hedge; real-rate sensitive, no yield"),
"fxe": ("Long euros vs the dollar",
"EUR/USD: carries the euro interest-rate differential"),
"fxy": ("Long yen vs the dollar",
"USD/JPY: carries the Japan rate differential; carry-trade "
"crowding risk"),
"xlk": ("US tech sector", "the tech sector index"),
"xlf": ("US financials sector", "banks/insurance: rate + credit cycle"),
"xle": ("US energy sector", "oil prices + US drilling"),
"xlv": ("US healthcare sector", "defensive pharma/providers"),
"xlp": ("US staples sector", "defensive consumer"),
"xlu": ("US utilities sector", "bond-proxy utilities; rate sensitive"),
"xly": ("US consumer discretionary", "cyclicals: autos, retail, "
"leisure; earnings cycle"),
"xlb": ("US materials sector", "industrial materials: capex cycle"),
}
def sleeve_desc(sym: str) -> tuple[str, str]:
return SLEEVE_DESC.get(sym, (sym.upper(), "no description on file"))
# ------------------------------------------------------------------ data
def price(sym: str) -> pd.Series | None:
f = decompose.DATA / f"{sym.lower()}-history.csv"
if not f.exists():
return None
try:
s = (pd.read_csv(f, parse_dates=["Date"], index_col="Date")
["Adj Close"].dropna())
s = s[~s.index.duplicated(keep="last")].sort_index()
except Exception:
return None
return s if len(s) > 40 else None
EPISODES = [] # (label, start, end) from the drawdown engine
for _e in DD["episodes"]:
EPISODES.append((_e["label"], pd.Timestamp(_e["peak"]),
pd.Timestamp(_e["trough"])))
# k=30 cluster membership (sym -> cluster id/label)
MEMBER = {}
for _c, _v in KMEANS["clusters"].items():
for _s in _v["syms"]:
MEMBER[_s] = (_c, _v["label"], _v["n"])
def loading_matrix_cached():
return _cl.loading_matrix()
CENTROIDS = {} # sym -> (cluster, centroid) for NEW points
def _centroids(syms: list[str], V: np.ndarray) -> dict[int, np.ndarray]:
lab = _cl.kmeans(_cl.emphasized(V, _cl.AXES.index("cash")), 30)
out = {}
for c in range(30):
idx = [i for i, l in enumerate(lab) if l == c]
if idx:
out[c] = np.median(V[idx], 0)
return out
def cluster_of_row(row: np.ndarray) -> tuple[str, str]:
"""Assign a new loading row to the k=30 scheme (distance to cluster
medians in the emphasized space)."""
global CENTROIDS
if not CENTROIDS:
syms, V = loading_matrix_cached()
CENTROIDS = _centroids(syms, V)
r = row.copy()
r[_cl.AXES.index("cash")] *= _cl.CASH_EMPHASIS
best, bd = None, None
for c, cent in CENTROIDS.items():
d = float(np.sum((r - cent) ** 2))
if bd is None or d < bd:
best, bd = c, d
for c, v in KMEANS["clusters"].items():
if int(c) == best:
return (c, v["label"])
return (str(best), "?")
def factor_row(sym: str) -> dict:
"""Full + 5y excess-of-T-bill loadings for ANY fund (shortlist funds
are not in the 2,384 factor file)."""
if sym in FACTOR:
return FACTOR[sym]
r = factors.factor_screen(sym)
return r or {}
_FWD: dict = {}
def ref_components(sym: str, fr: dict, window: str = "rec5") -> list[dict]:
"""The fund's FORWARD-SELECTED reference (the mix its alpha is
measured against): BIC-gated selection from the 21 broad sleeves,
excess-of-T-bill. Recomputed (cached) because the screen stored only
the display strings. Falls back to the 34-sleeve OLS loadings when
the fund is not in the search universe."""
key = (sym, window)
if key in _FWD:
return _FWD[key]
out = None
try:
m = decompose.decompose(sym, start=decompose.RECENT_WINDOW
if window == "rec5" else None,
candidates={sym: BROAD_SLEEVES})
if m.get("components"):
out = [{"sym": c["sym"], "beta": c["beta"]}
for c in m["components"]]
except Exception:
out = None
if out is None:
comps = (fr.get(window) or fr.get("full") or {}).get("betas") or {}
out = [{"sym": s, "beta": b} for s, b in sorted(
comps.items(), key=lambda kv: -abs(kv[1])) if abs(b) >= 0.08]
_FWD[key] = out
return out
def search_row(sym: str) -> dict:
return SEARCH.get(sym, {})
def decomp_row(sym: str) -> dict:
return DECOMP.get(sym, {})
def tax_row(sym: str) -> dict:
up = sym.upper()
if up in TAX["shortlist"]:
return TAX["shortlist"][up]
for k in (sym, up, sym.lower()):
if k in TAX["candidates"]:
return TAX["candidates"][k]
return {}
def dd_row(sym: str) -> dict:
return DD["funds"].get(sym, {})
# ------------------------------------------------------------------ stats
def perf_stats(p: pd.Series, rf_annual: float = 0.037) -> dict:
r = p.pct_change().dropna()
years = (p.index[-1] - p.index[0]).days / 365.25
cagr = (p.iloc[-1] / p.iloc[0]) ** (1 / years) - 1 if years > 0.5 else np.nan
vol = r.std() * np.sqrt(252)
roll_max = p.cummax()
mdd = float(((p / roll_max) - 1).min())
sharpe = (cagr - rf_annual) / vol if vol > 0 else np.nan
return {"start": str(p.index[0].date()), "end": str(p.index[-1].date()),
"years": years, "cagr": cagr, "vol": vol, "mdd": mdd,
"sharpe": sharpe}
def window_ret(p: pd.Series, a, b) -> float | None:
s = p[(p.index >= a) & (p.index <= b)]
if len(s) < 2:
return None
return float(s.iloc[-1] / s.iloc[0] - 1)
def annual_table(p: pd.Series, n: int = 8) -> list[tuple[str, float]]:
yr = p.resample("YE").last().dropna()
out = []
for i in range(len(yr) - 1):
lab = str(yr.index[i].year)
if i == 0:
continue
out.append((lab, float(yr.iloc[i] / yr.iloc[i - 1] - 1)))
# partial current year from last full year-end
out.append(("YTD", float(p.iloc[-1] / yr.iloc[-1] - 1)))
return out[-(n + 1):]
def mix_series(refs: list[dict]) -> pd.Series | None:
"""Fitted reference mix: sum of beta * sleeve daily returns, cumulated
to a price path (rebased 100). Pure beta path - the fund minus this
is the alpha path."""
if not refs:
b = price("bil")
if b is None:
return None
return 100 * b / b.iloc[0]
idx = None
for c in refs:
p = price(c["sym"])
if p is None:
continue
r = c["beta"] * p.pct_change()
idx = r if idx is None else idx.combine(r, lambda x, y: x + y,
fill_value=0.0)
if idx is None:
return None
idx = idx.fillna(0.0)
path = (1 + idx).cumprod()
return 100 * path / path.iloc[0]
# ------------------------------------------------------------------ html
PLOTLY_JS = ""
def load_plotly():
global PLOTLY_JS
try:
import plotly
PLOTLY_JS = plotly.offline.get_plotlyjs()
except Exception:
PLOTLY_JS = None
def fig_html(fig, h: int = 420) -> str:
import plotly.io as pio
s = pio.to_html(fig, full_html=False, include_plotlyjs=False,
config={"displayModeBar": False}, div_id="")
return s.replace("<div>", f'<div style="height:{h}px">')
def equity_figure(sym: str, name: str, refs: list[dict]) -> str:
import plotly.graph_objects as go
p = price(sym)
if p is None:
return "<p>No local price history.</p>"
fig = go.Figure()
fig.add_trace(go.Scatter(x=p.index, y=100 * p / p.iloc[0],
name=sym.upper(), line=dict(width=2)))
m = mix_series(refs)
if m is not None:
fig.add_trace(go.Scatter(x=m.index, y=m, name="fitted reference",
line=dict(width=1.2, dash="dash")))
iv = price("ivv")
if iv is not None:
fig.add_trace(go.Scatter(
x=iv.index, y=100 * iv / iv.iloc[0], name="IVV (S&P 500)",
line=dict(width=1, dash="dot"), opacity=0.7))
fig.update_layout(height=430, margin=dict(l=10, r=10, t=30, b=10),
title=f"{html.escape(name)} - total return since "
f"{p.index[0].year} (rebased 100)",
legend=dict(orientation="h", y=1.08),
hovermode="x unified")
return fig_html(fig)
def fmt_pct(x, nd=1, sign=True):
if x is None or (isinstance(x, float) and np.isnan(x)):
return "—"
s = f"{100 * x:+.{nd}f}%" if sign else f"{100 * x:.{nd}f}%"
return s
def fmt_r2(x):
return "—" if x is None or (isinstance(x, float) and np.isnan(x)) \
else f"{x:.2f}"
def perf_table(p: pd.Series, refs: list[dict]) -> str:
m = mix_series(refs)
iv = price("ivv")
rows = []
def add(label, a, b, ann=False):
fr_ = window_ret(p, a, b)
mr = window_ret(m, a, b) if m is not None else None
ir = window_ret(iv, a, b) if iv is not None else None
gap = (fr_ - mr) if (fr_ is not None and mr is not None) else None
rows.append(f"<tr><td>{label}</td>"
f"<td>{fmt_pct(fr_)}</td><td>{fmt_pct(mr)}</td>"
f"<td>{fmt_pct(ir)}</td><td>{fmt_pct(gap)}</td></tr>")
st = perf_stats(p)
add("Full history", st["start"], st["end"])
add("Last 5y", "2021-01-01", st["end"])
add("Last 1y", "2025-09-01", st["end"])
for lab, a, b in EPISODES:
add(lab, a, b)
# calendar years (last 6)
yr = p.resample("YE").last().dropna()
years = [str(yr.index[i].year) for i in range(1, len(yr))][-6:]
for i, y in enumerate(years):
a = f"{y}-01-01"
b = f"{int(y) + 1}-01-01" if i < len(years) - 1 else st["end"]
add(y, a, b)
return ('<table><tr><th>period</th><th>fund</th><th>reference</th>'
'<th>IVV</th><th>fund − ref</th></tr>' + "".join(rows)
+ '</table><p class="small">fund − reference = period '
'alpha/timing (the part of that period the sleeve mix does '
'not explain). IVV shown for scale - for non-equity funds '
'the IVV column is only context.</p>')
def drivers_section(fr: dict, dr: dict, srow: dict) -> str:
out = []
if srow:
a5 = srow.get("alpha_ann_5y")
t5 = srow.get("alpha_t_5y")
r25 = srow.get("r2_5y")
if isinstance(r25, (int, float)) or isinstance(a5, (int, float)):
out.append(
f"<p><b>Reference model, last 5 years:</b> R² = "
f"{fmt_r2(r25 if isinstance(r25, (int, float)) else None)}, "
f"alpha = {fmt_pct(a5) if isinstance(a5, (int, float)) else '—'}"
f"{' (t = ' + format(t5, '+.1f') + ')' if isinstance(t5, (int, float)) else ''} "
f"vs the fitted reference mix (next section).")
rf = (fr.get("full") or {}).get("alpha_ann")
tf = (fr.get("full") or {}).get("alpha_t")
r2f = srow.get("r2_full")
if isinstance(r2f, (int, float)) or isinstance(rf, (int, float)):
out.append(
f"<p><b>Reference model, full history:</b> R² = "
f"{fmt_r2(r2f if isinstance(r2f, (int, float)) else None)}, "
f"alpha = {fmt_pct(rf) if isinstance(rf, (int, float)) else '—'}"
f"{' (t = ' + format(tf, '+.1f') + ')' if isinstance(tf, (int, float)) else ''}.</p>")
f = fr.get("rec5") or {}
betas = f.get("betas") or {}
top = sorted(betas.items(), key=lambda kv: -abs(kv[1]))[:6]
if top:
out.append(
"<p><b>Return-driver signature (34 sleeves, for clustering "
"context):</b> " + ", ".join(
f"{s} {b:+.2f}" for s, b in top) + " - net cash "
f"{1 - sum(betas.values()):+.2f}.</p>")
# drift + verdict from the curated decomposition, when available
if dr and "verdict" in dr:
out.append(f"<p><b>Decomposition verdict:</b> "
f"{html.escape(dr['verdict'])}</p>")
roll = dr.get("rolling") or {}
if roll.get("max_drift") is not None:
out.append(
f"<p>Weight stability: max 1y β-drift = "
f"{roll['max_drift']:.2f} (relative to full-sample β; "
f"0 = perfectly stable, &gt;1 = the weight is unstable).</p>")
note = dr.get("note")
if note:
out.append(f"<p class='small'>{html.escape(note)}</p>")
if srow:
v = str(srow.get("verdict", ""))
if v:
out.append(f"<p><b>Screen verdict:</b> {html.escape(v)}</p>")
return "".join(out)
def reference_section(refs: list[dict], refs_curve: list[dict],
sym: str) -> str:
weak = bool(refs) and not refs_curve
caveat = ""
if weak:
caveat = ("<p class='small'><b>Weak fit - read with care.</b> "
"These loadings are each individually significant but "
"collectively explain little of the excess return; the "
"economically meaningful picture is a mostly-cash "
"vehicle with idiosyncratic alpha (the performance "
"table anchors to cash, not to this mix).</p>")
if not refs:
srow = search_row(sym)
a = srow.get("alpha_ann_5y")
return caveat + ("<p><b>Reference: cash (the T-bill rate itself)."
"</b> No "
"sleeve passed the forward-selection gates, so the fund's "
"excess returns are not explained by any benchmark mix - "
f"its entire excess performance is idiosyncratic (5y alpha "
f"{fmt_pct(a) if isinstance(a, (int, float)) else '—'}). "
"There is no meaningful 'beta' to this fund; it is a "
"standalone position.</p>")
sb = sum(c["beta"] for c in refs)
cash = 1 - sb
rows = []
for c in refs:
nm, desc = sleeve_desc(c["sym"])
rows.append(f"<tr><td><b>{c['sym'].upper()}</b> {c['beta']:+.2f}"
f"</td><td>{html.escape(nm)}</td>"
f"<td>{html.escape(desc)}</td></tr>")
cash_line = ""
if weak:
cash_line = caveat + cash_line
if cash > 0.05:
cash_line = (f"<p>The loadings sum to {sb:.2f}, i.e. the fund is "
f"~{cash:.0%} NET CASH (earns the T-bill rate; adds "
f"zero excess alpha).</p>")
elif cash < -0.05:
cash_line = (f"The loadings sum to {sb:.2f}, i.e. the fund is ~"
f"{-cash:.0%} NET LEVERED (borrows at ~the T-bill "
f"rate; that financing shows up as negative cash).</p>")
return ('<table><tr><th>loading</th><th>what it is</th>'
'<th>what it exposes you to</th></tr>' + "".join(rows)
+ "</table>" + cash_line
+ '<p class="small">The reference is NOT one index - it is '
'this fitted mix, rebuilt from the fund\'s own returns. '
'"Alpha" everywhere in this report means outperformance vs '
'this mix, in excess of the T-bill rate.</p>')
def tax_section(sym: str) -> str:
t = tax_row(sym)
if not t:
return "<p>No tax classification on file.</p>"
loc = t.get("location", "?")
basis = t.get("basis", "?")
conf = {"N-PORT": "from actual N-PORT holdings (high confidence)",
"sleeves": "from the return-sleeve mix (model, medium "
"confidence)"}.get(basis, basis)
notes = html.escape(t.get("notes") or "")
rec = {"TAXABLE": "Keep in the <b>taxable</b> account.",
"TAXABLE (munis)": "Keep in the <b>taxable</b> account - "
"tax-exempt interest is wasted in an IRA.",
"TAXABLE (defers to LTCG)": "Keep in the <b>taxable</b> "
"account - the income mostly "
"defers to the LTCG/ROC rate."}.get(
loc, f"Recommended account: <b>{html.escape(loc)}</b>.")
return (f"<p>Character score {t.get('score', '?')} "
f"({conf}). <b>Placement: {rec}</b></p>"
+ (f"<p class='small'>{notes}</p>" if notes else ""))
def cluster_section(sym: str, fr: dict, row: np.ndarray | None) -> str:
srow = search_row(sym)
if sym in MEMBER:
cid, clabel, cn = MEMBER[sym]
members = KMEANS["clusters"][cid]["syms"]
else:
if row is None:
return "<p>Not in the cluster scheme (no loading vector).</p>"
cid, clabel = cluster_of_row(row)
cn = KMEANS["clusters"].get(cid, {}).get("n", 0)
members = KMEANS["clusters"].get(cid, {}).get("syms", [])
peers = []
for s in members:
if s == sym:
continue
v = search_row(s)
if not isinstance(v.get("alpha_t_5y"), (int, float)):
continue
peers.append((v["alpha_t_5y"], v.get("r2_5y") or 0, s, v))
# best peers = highest POSITIVE alpha t (a fund with t = -5 is the
# cluster's worst, not a peer worth copying); top-4, positives first
peers.sort(key=lambda p: (p[0] > 0, p[0]), reverse=True)
pos = [p for p in peers if p[0] > 0]
peers = (pos + [p for p in peers if p[0] <= 0])[:4]
peers = [p[2] for p in peers]
if not peers:
return (f"<p>In cluster <b>{html.escape(clabel)}</b> (n={cn}) but "
"no peer with 5y alpha statistics.</p>")
rows = []
def statline(s: str) -> str:
p = price(s)
if p is None:
return ("—", "—", "—", "—", "—", "n/a")
st = perf_stats(p)
v = search_row(s)
t5 = window_ret(p, "2021-01-01", st["end"])
r2 = v.get("r2_5y")
a5 = v.get("alpha_ann_5y")
tt = v.get("alpha_t_5y")
tax = (tax_row(s) or {}).get("location") or "n/a"
return (fmt_pct(t5), fmt_pct(st["cagr"]), fmt_pct(st["mdd"]),
fmt_r2(r2),
(f"{fmt_pct(a5)} (t={tt:+.1f})"
if isinstance(a5, (int, float)) else "—"), tax)
p = price(sym)
st = perf_stats(p) if p is not None else {}
my = statline(sym)
rows.append(f"<tr class='me'><td><b>{sym.upper()} (this fund)</b></td>"
+ "".join(f"<td>{x}</td>" for x in my) + "</tr>")
for s in peers:
rows.append(f"<tr><td>{s.upper()} — "
f"{html.escape((search_row(s) or {}).get('name', '')[:40])}"
f"</td>" + "".join(f"<td>{x}</td>" for x in statline(s))
+ "</tr>")
tbl = ('<table><tr><th>fund</th><th>5y</th><th>CAGR</th>'
'<th>maxDD</th><th>R² 5y</th><th>alpha 5y</th><th>tax</th></tr>'
+ "".join(rows) + "</table>")
# advantages / disadvantages: computed deltas vs the peer set
adv, dis = [], []
if p is not None:
t5 = window_ret(p, "2021-01-01", st["end"])
vals = {}
for s in peers:
pp = price(s)
if pp is None:
continue
ss = perf_stats(pp)
vals[s] = (window_ret(pp, "2021-01-01", ss["end"]), ss["mdd"],
ss["vol"])
if vals:
best_t5 = max(v[0] for v in vals.values() if v[0] is not None)
best_dd = max(v[1] for v in vals.values())
low_vol = min(v[2] for v in vals.values())
if t5 is not None and t5 >= best_t5 - 0.02:
adv.append("5y return at the top of the cluster")
elif t5 is not None and t5 < best_t5 - 0.10:
dis.append(f"5y return trails the best peer by "
f"{100 * (best_t5 - t5):.0f}pp")
if st["mdd"] > best_dd + 0.05:
dis.append(f"deeper drawdown than the calmest peer "
f"({fmt_pct(st['mdd'])} vs {fmt_pct(best_dd)})")
elif st["mdd"] < best_dd - 0.05:
adv.append("sharpest drawdown in the cluster")
if st["vol"] < low_vol - 0.02:
adv.append("lowest volatility in the cluster")
elif st["vol"] > low_vol + 0.05:
dis.append("meaningfully more volatile than the "
"calmest peer")
txt = ""
if adv:
txt += "<p><b>Advantages vs peers:</b> " + "; ".join(adv) + ".</p>"
if dis:
txt += "<p><b>Disadvantages vs peers:</b> " + "; ".join(dis) + ".</p>"
if not txt:
txt = ("<p>The fund sits in the middle of its cluster - no "
"decisive edge on return, drawdown or volatility vs the "
"peers; the choice among them should come down to alpha "
"quality (t-stat), tax fit and the conviction in the "
"strategy.</p>")
return (f"<p>Cluster: <b>{html.escape(clabel)}</b> "
f"(n={cn}, k=30 grouping by return-driver signature).</p>"
+ tbl + txt)
def fund_loading_row(fr: dict) -> np.ndarray:
f = fr.get("full") or fr.get("rec5") or {}
betas = f.get("betas") or {}
row = np.array([betas.get(s, 0.0) or 0.0 for s in factors.DRIVERS],
dtype=float)
return np.append(row, 1.0 - row.sum())
def strategy_block(sym: str) -> str:
f = FONDS.get(sym)
if not f:
return ""
out = ""
if f.get("strategy"):
out += f"<details><summary>Strategy (excerpt from the filing)</summary>"
f"<p class='small'>{html.escape(f['strategy'])}</p></details>"
return out
def style_block(sym: str) -> str:
from fundlab import styletilt
prof = styletilt.style_profile(sym)
if not prof or not prof.get("full"):
return ""
f5 = {x["sym"]: x for x in (prof.get("rec5") or {}).get("factors", [])}
rows = []
for x in prof["full"]["factors"]:
y5 = f5.get(x["sym"], {})
if abs(x["t"]) < 2 and abs(y5.get("t", 0) or 0) < 2:
continue
rows.append(
f"<tr><td>{html.escape(x['name'])}</td>"
f"<td>{x['beta']:+.2f}</td><td>{x['t']:+.1f}</td>"
f"<td>{y5['beta']:+.2f}</td><td>{y5['t']:+.1f}</td>"
f"<td>{'&#10003;' if x['sym'] in prof.get('identified', []) else ''}</td></tr>")
tbl = ('<table><tr><th>factor</th><th>β full</th><th>t full</th>'
'<th>β 5y</th><th>t 5y</th><th>identified</th></tr>'
+ "".join(rows) + "</table>")
para = "".join(f"<p>{html.escape(p)}</p>" for p in prof.get("commentary", []))
return ('<h4>Style tilts</h4>'
'<p class="small">22 style/asset sleeves regressed on the '
'excess returns of the fund (US funds proxy the global '
'factors); "identified" = survived the BIC forward-selection '
'gate on the full history.</p>' + tbl + para)
def narrative_block(sym: str) -> str:
from fundlab.narrative import narrate
return "".join(f"<p>{html.escape(par)}</p>" for par in narrate(sym))
# ------------------------------------------------------------------ build
def fund_section(sym: str, title: str, subtitle: str) -> str:
fr = factor_row(sym)
dr = decomp_row(sym)
srow = search_row(sym)
name = (srow.get("name") or (FONDS.get(sym) or {}).get("name")
or (fr or {}).get("name") or sym.upper())
refs = ref_components(sym, fr)
load = fund_loading_row(fr) if fr else None
# weak-fit (idiosyncratic) funds: the forward-selected mix is a
# statistically-thin spec combination (offsetting VIX/duration legs);
# anchoring the table to it misleads (a "reference" that loses 79% in
# 2022 for a fund that lost 2.4%). Below the fit gate the honest
# reference is CASH - the fund IS ~net-cash + idiosyncratic alpha.
r25 = srow.get("r2_5y") if isinstance(srow.get("r2_5y"),
(int, float)) else None
r2f = (fr.get("rec5") or fr.get("full") or {}).get("r2")
fit = r25 if r25 is not None else r2f
refs_curve = refs if (fit is not None and fit >= 0.5) else []
return f"""
<h3 id="{sym}">{html.escape(title)}
<span class="sub">{html.escape(subtitle)}</span></h3>
<div class="fund">{strategy_block(sym)}
<h4>Discussion</h4>
{narrative_block(sym)}
{equity_figure(sym, name, refs_curve)}
<h4>Performance</h4>
{perf_table(price(sym), refs_curve) if price(sym) is not None else '<p>no price data</p>'}
<h4>What drove the returns</h4>
{drivers_section(fr, dr, srow)}
{style_block(sym)}
<h4>The reference mix - and what it exposes you to</h4>
{reference_section(refs, refs_curve, sym)}
<h4>Tax character &amp; placement</h4>
{tax_section(sym)}
<h4>Peer comparison (same return-driver cluster)</h4>
{cluster_section(sym, fr, load)}
</div>"""
def main() -> None:
t0 = time.time()
load_plotly()
print("building report ...", flush=True)
cand = [v for v in SEARCH.values()
if isinstance(v, dict)
and str(v.get("verdict", "")).startswith("CANDIDATE")]
cand.sort(key=lambda v: -(v.get("alpha_t_5y")
if isinstance(v.get("alpha_t_5y"),
(int, float)) else -9))
# shortlist: the 16 actively-managed funds (3 are share classes of
# the same fund: pmfkx=pmaix, lcrix=lcorx, egrsx=eagmx)
from fundlab.decompose import ALIAS
from fundlab.nport import FUND_TOKENS
short = [s for s in FUND_TOKENS if s not in ALIAS]
toc = []
body = []
for i, v in enumerate(cand, 1):
s = v["sym"]
toc.append(f'<li><a href="#{s}">{s.upper()}</a> — '
f'{html.escape((v.get("name") or "")[:48])}</li>')
body.append(fund_section(
s, f"C{i:02d} · {s.upper()}",
f"{v.get('name', '')} — {str(v.get('verdict', ''))[:60]}"))
for i, s in enumerate(short, 1):
nm = (FONDS.get(s) or {}).get("name", s.upper())
toc.append(f'<li><a href="#{s}">S{i:02d} · {s.upper()}</a> — '
f'{html.escape(nm[:48])}</li>')
body.append(fund_section(s, f"S{i:02d} · {s.upper()}", nm))
doc = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8">
<title>Fund report - candidates &amp; shortlist</title>
<style>
body {{ font-family: -apple-system, 'Segoe UI', Helvetica, Arial, sans-serif;
margin: 0; color: #1a1a2e; background: #fafafa; }}
.wrap {{ display: flex; }}
nav {{ width: 270px; min-width: 270px; position: sticky; top: 0;
height: 100vh; overflow-y: auto; background: #fff;
border-right: 1px solid #ddd; padding: 16px; box-sizing: border-box; }}
main {{ flex: 1; padding: 24px 36px; max-width: 1150px; }}
h1 {{ font-size: 26px; }} h3 {{ border-top: 3px solid #1a1a2e;
padding-top: 18px; margin-top: 40px; }}
h3 .sub {{ font-weight: normal; font-size: 14px; color: #555;
display: block; margin-top: 4px; }}
h4 {{ margin: 18px 0 6px; font-size: 15px; }}
table {{ border-collapse: collapse; margin: 8px 0 14px; font-size: 13px; }}
th, td {{ border: 1px solid #ccc; padding: 4px 9px; text-align: left; }}
th {{ background: #eee; }}
tr.me td {{ background: #fff8e1; }}
.small {{ color: #555; font-size: 12.5px; }}
nav a {{ text-decoration: none; color: #1a1a2e; font-size: 13px;
display: block; padding: 3px 0; }}
nav a:hover {{ color: #b00020; }}
nav h2 {{ font-size: 14px; margin: 14px 0 6px; }}
details {{ margin: 6px 0; }} summary {{ cursor: pointer;
font-size: 13px; color: #333; }}
</style>
{"<script>" + PLOTLY_JS + "</script>" if PLOTLY_JS else
'<script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>'}
</head><body><div class="wrap">
<nav>
<b>Return-driver report</b><br><span class="small">generated
{time.strftime('%Y-%m-%d %H:%M')}</span>
<h2>Candidates (alpha screen, excess of T-bill)</h2>
<ol>{''.join(toc[:len(cand)])}</ol>
<h2>Shortlist (your funds)</h2>
<ol start="{len(cand) + 1}">{''.join(toc[len(cand):])}</ol>
</nav>
<main>
<h1>Fund report - {len(cand)} alpha candidates &amp; {len(short)}
shortlist funds</h1>
<p class="small"><b>Method.</b> Every alpha in this report is computed
<b>in excess of the 3-month T-bill rate</b> (BIL total return as the
local risk-free series): the fund's daily total returns are regressed on
sleeve benchmarks that are netted against the same rate, so a cash
position contributes exactly zero. "Reference" is never one index - it
is each fund's <b>own fitted sleeve mix</b> (BIC forward selection on the
broad axes, or the full 34-sleeve OLS for the loadings). R² measures how
much of the excess return the mix explains; alpha is what is left.
"Net cash" = 1 − (sum of loadings). Equity curves are total-return
(Adj Close) over the maximum local history, rebased to 100.</p>
{''.join(body)}
<p class="small" style="margin-top:40px">Generated by fundlab.report -
data as of {time.strftime('%Y-%m-%d')}. Local price histories may lag a
day or two. Cluster = k=30 k-means on the excess-return loading vectors
(34 sleeves + net-cash axis).</p>
</main></div></body></html>"""
OUT.write_text(doc)
print(f"wrote {OUT} in {time.time() - t0:.0f}s "
f"({len(doc) / 1e6:.1f} MB)")
if __name__ == "__main__":
main()
+400
View File
@@ -0,0 +1,400 @@
"""Build reports/report_data.json: everything the web app (and the HTML
report) need for the per-fund report pages, in one structured file.
One entry per fund (11 alpha candidates + 13 shortlist funds):
meta name, verdict, group, order
narrative list of prose paragraphs (fundlab.narrative)
chart {dates, fund, ref, ivv} (downsampled price paths, rebased)
perf rows [period, fund, reference, ivv, fund-ref] (strings)
drivers markdown lines (reference model, signature, verdicts)
reference {rows [[loading, name, exposure]], weak, netcash, text}
tax plain text
peers {cluster, rows, proscons}
Run: .venv/bin/python -m fundlab.reportdata
"""
from __future__ import annotations
import json
import time
from pathlib import Path
import numpy as np
import pandas as pd
from fundlab import report as _r
from fundlab import decompose
from fundlab import styletilt
from fundlab.narrative import narrate
HERE = Path(__file__).parent
OUT = HERE.parent / "reports" / "report_data.json"
MAX_PTS = 1500
def _down(s: pd.Series) -> tuple[list, list]:
if s is None:
return [], []
if len(s) > MAX_PTS:
s = s.iloc[:: (len(s) // MAX_PTS + 1)]
return [str(d.date()) for d in s.index], [float(v) for v in s]
def _chart(sym: str, refs_curve: list[dict]) -> dict:
p = _r.price(sym)
fd, fv = _down(100 * p / p.iloc[0] if p is not None else None)
if refs_curve:
mix = _r.mix_series(refs_curve)
else:
b = _r.price("bil")
mix = 100 * b / b.iloc[0] if b is not None else None
md, mv = _down(mix)
iv = _r.price("ivv")
id_, ivv = _down(100 * iv / iv.iloc[0] if iv is not None else None)
return {"dates": fd, "fund": fv, "ref_dates": md, "ref": mv,
"ivv_dates": id_, "ivv": ivv}
def _perf_rows(sym: str, refs_curve: list[dict]) -> list[list[str]]:
p = _r.price(sym)
if p is None:
return []
mix = (_r.mix_series(refs_curve) if refs_curve
else _r.price("bil"))
iv = _r.price("ivv")
st = _r.perf_stats(p)
rows = []
def add(label, a, b):
fr_ = _r.window_ret(p, a, b)
mr = _r.window_ret(mix, a, b)
ir = _r.window_ret(iv, a, b)
gap = (fr_ - mr) if (fr_ is not None and mr is not None) else None
rows.append([label, _r.fmt_pct(fr_), _r.fmt_pct(mr),
_r.fmt_pct(ir), _r.fmt_pct(gap)])
add("Full history", st["start"], st["end"])
add("Last 5y", "2021-01-01", st["end"])
add("Last 1y", "2025-09-01", st["end"])
for lab, a, b in _r.EPISODES:
add(lab, a, b)
yr = p.resample("YE").last().dropna()
years = [str(yr.index[i].year) for i in range(1, len(yr))][-6:]
for i, y in enumerate(years):
a = f"{y}-01-01"
b = f"{int(y) + 1}-01-01" if i < len(years) - 1 else st["end"]
add(y, a, b)
return rows
def _drivers(sym: str, fr: dict, srow: dict, dr: dict) -> list[str]:
out = []
a5 = srow.get("alpha_ann_5y")
t5 = srow.get("alpha_t_5y")
r25 = srow.get("r2_5y")
if isinstance(r25, (int, float)) or isinstance(a5, (int, float)):
out.append(
f"**Reference model, last 5 years:** R² = "
f"{_r.fmt_r2(r25 if isinstance(r25, (int, float)) else None)}, "
f"alpha = "
f"{_r.fmt_pct(a5) if isinstance(a5, (int, float)) else '—'}"
f"{' (t = ' + format(t5, '+.1f') + ')' if isinstance(t5, (int, float)) else ''}")
a_f = (fr.get("full") or {}).get("alpha_ann")
t_f = (fr.get("full") or {}).get("alpha_t")
r2f = srow.get("r2_full")
if isinstance(r2f, (int, float)) or isinstance(a_f, (int, float)):
out.append(
f"**Reference model, full history:** R² = "
f"{_r.fmt_r2(r2f if isinstance(r2f, (int, float)) else None)}, "
f"alpha = "
f"{_r.fmt_pct(a_f) if isinstance(a_f, (int, float)) else '—'}"
f"{' (t = ' + format(t_f, '+.1f') + ')' if isinstance(t_f, (int, float)) else ''}.")
f = fr.get("rec5") or {}
betas = f.get("betas") or {}
top = sorted(betas.items(), key=lambda kv: -abs(kv[1]))[:6]
if top:
out.append("**Return-driver signature (34 sleeves):** "
+ ", ".join(f"`{s}` {b:+.2f}" for s, b in top)
+ f" - net cash {1 - sum(betas.values()):+.2f}.")
if dr and "verdict" in dr:
out.append(f"**Decomposition verdict:** {dr['verdict']}")
roll = dr.get("rolling") or {}
if roll.get("max_drift") is not None:
out.append(f"Weight stability: max 1y β-drift = "
f"{roll['max_drift']:.2f} (0 = perfectly stable, "
f">1 = unstable).")
if dr.get("note"):
out.append(f"*{dr['note']}*")
if srow.get("verdict"):
out.append(f"**Screen verdict:** {srow['verdict']}")
return out
def _reference(sym: str, fr: dict, refs: list[dict],
refs_curve: list[dict]) -> dict:
rows = []
for c in refs:
nm, desc = _r.sleeve_desc(c["sym"])
rows.append([f"{c['sym'].upper()} {c['beta']:+.2f}", nm, desc])
sb = sum(c["beta"] for c in refs)
cash = 1 - sb
if cash > 0.05:
net = f"loadings sum to {sb:.2f} → ~{cash:.0%} net cash"
elif cash < -0.05:
net = f"loadings sum to {sb:.2f} → ~{-cash:.0%} net levered"
else:
net = f"loadings sum to {sb:.2f} → fully invested"
weak = bool(refs) and not refs_curve
text = ("**Weak fit - read with care.** These loadings are each "
"individually significant but collectively explain little; "
"the performance table anchors to cash, not this mix."
if weak else
"The reference is the fund's own fitted sleeve mix; "
"'alpha' everywhere means outperformance vs this mix, in "
"excess of the T-bill rate.")
return {"rows": rows, "weak": weak, "netcash": net, "text": text}
def _tax(sym: str) -> str:
t = _r.tax_row(sym)
if not t:
return "No tax classification on file."
loc = t.get("location", "?")
basis = t.get("basis", "?")
conf = "from actual N-PORT holdings (high confidence)" \
if basis == "N-PORT" else "from the return-sleeve mix (model)"
s = (f"Character score {t.get('score', '?')} ({conf}). ")
if "MIXED" in loc:
s += "Model says MIXED - the last 1099-DIV is the arbiter."
elif "TAXABLE" in loc:
if "munis" in loc:
s += ("Keep in the **taxable** account "
"(munis - tax-exempt interest is wasted in an IRA).")
elif "defers" in loc:
s += ("Keep in the **taxable** account "
"(income mostly defers to the LTCG/ROC rate).")
else:
s += "Keep in the **taxable** account."
else:
s += f"Recommended account: **{loc}**."
if t.get("notes"):
s += f" _{t['notes']}_"
return s
def _peers(sym: str, fr: dict) -> dict:
# no return history: a zero loading vector would park the fund in the
# cash cluster - no peer table for a fund with no measured returns
if _r.price(sym) is None:
return {}
if sym in _r.MEMBER:
cid, clabel, cn = _r.MEMBER[sym]
members = _r.KMEANS["clusters"][cid]["syms"]
else:
try:
cid, clabel = _r.cluster_of_row(_r.fund_loading_row(fr))
except Exception:
return {}
cn = _r.KMEANS["clusters"].get(cid, {}).get("n", 0)
members = _r.KMEANS["clusters"].get(cid, {}).get("syms", [])
peers = []
for s in members:
if s == sym:
continue
v = _r.search_row(s)
if isinstance(v.get("alpha_t_5y"), (int, float)):
peers.append((v["alpha_t_5y"], s))
peers.sort(key=lambda x: (x[0] > 0, x[0]), reverse=True)
pos = [p for p in peers if p[0] > 0]
peers = [s for _t, s in (pos + [p for p in peers if p[0] <= 0])[:4]]
def statline(s: str) -> list[str]:
p = _r.price(s)
if p is None:
return ["—", "—", "—", "—", "—", "n/a"]
st = _r.perf_stats(p)
v = _r.search_row(s)
t5 = _r.window_ret(p, "2021-01-01", st["end"])
a5 = v.get("alpha_ann_5y")
tt = v.get("alpha_t_5y")
tax = (_r.tax_row(s) or {}).get("location") or "n/a"
return [_r.fmt_pct(t5), _r.fmt_pct(st["cagr"]),
_r.fmt_pct(st["mdd"]),
_r.fmt_r2(v.get("r2_5y")),
(f"{_r.fmt_pct(a5)} (t={tt:+.1f})"
if isinstance(a5, (int, float)) else "—"), tax]
rows = [[f"{sym.upper()} (this fund)", *statline(sym)]]
for s in peers:
rows.append([s.upper(), *statline(s)])
# pros / cons
adv, dis = [], []
p = _r.price(sym)
if p is not None and peers:
st = _r.perf_stats(p)
t5 = _r.window_ret(p, "2021-01-01", st["end"])
vals = {}
for s in peers:
pp = _r.price(s)
if pp is None:
continue
ss = _r.perf_stats(pp)
vals[s] = (_r.window_ret(pp, "2021-01-01", ss["end"]),
ss["mdd"], ss["vol"])
if vals:
best_t5 = max(v[0] for v in vals.values() if v[0] is not None)
best_dd = max(v[1] for v in vals.values())
low_vol = min(v[2] for v in vals.values())
if t5 is not None and t5 >= best_t5 - 0.02:
adv.append("5y return at the top of the cluster")
elif t5 is not None and t5 < best_t5 - 0.10:
dis.append(f"5y return trails the best peer by "
f"{100 * (best_t5 - t5):.0f}pp")
if st["mdd"] < best_dd - 0.05:
adv.append("sharpest drawdown in the cluster")
elif st["mdd"] > best_dd + 0.05:
dis.append(f"deeper drawdown than the calmest peer "
f"({_r.fmt_pct(st['mdd'])} vs "
f"{_r.fmt_pct(best_dd)})")
if st["vol"] < low_vol - 0.02:
adv.append("lowest volatility in the cluster")
elif st["vol"] > low_vol + 0.05:
dis.append("meaningfully more volatile than the "
"calmest peer")
if adv:
pc = "**Advantages vs peers:** " + "; ".join(adv) + "."
elif dis:
pc = "**Disadvantages vs peers:** " + "; ".join(dis) + "."
else:
pc = ("Middle of the cluster - no decisive edge on return, "
"drawdown or volatility; the choice comes down to alpha "
"quality (t), tax fit and conviction in the strategy.")
if dis and adv:
pc += " **Disadvantages:** " + "; ".join(dis) + "."
return {"cluster": clabel, "n": cn,
"rows": rows, "proscons": pc}
ADHOC_FILE = HERE.parent / "reports" / "report_data_adhoc.json"
_ADHOC_MEM: dict = None # lazy-loaded disk cache
def _adhoc_store() -> dict:
global _ADHOC_MEM
if _ADHOC_MEM is None:
try:
_ADHOC_MEM = json.loads(ADHOC_FILE.read_text())
except Exception:
_ADHOC_MEM = {"funds": {}}
return _ADHOC_MEM
def ensure_adhoc(syms: list[str]) -> dict[str, dict]:
"""Build report entries for ARBITRARY funds (any symbol the user puts
in the portfolio box), cached in memory + on disk so repeat loads are
instant and survive server restarts. The one-time ~30-60 s driver-panel
build happens on the first call in a fresh process."""
store = _adhoc_store()
funds = store["funds"]
missing = [s for s in syms
if s not in funds
and _r.price(s) is not None]
if missing:
for s in missing:
funds[s] = build_fund(s, "adhoc",
order=len(funds) + 1)
ADHOC_FILE.parent.mkdir(exist_ok=True)
ADHOC_FILE.write_text(json.dumps(store))
return {s: funds[s] for s in syms if s in funds}
def build_fund(sym: str, group: str, order: int) -> dict:
t0 = time.time()
fr = _r.factor_row(sym)
dr = _r.decomp_row(sym)
srow = _r.search_row(sym)
name = (srow.get("name") or _r.FONDS.get(sym, {}).get("name")
or (fr or {}).get("name") or sym.upper())
refs = _r.ref_components(sym, fr)
r2f_ = (fr.get("rec5") or fr.get("full") or {}).get("r2")
r25 = srow.get("r2_5y") if isinstance(srow.get("r2_5y"), (int, float)) \
else None
fit = r25 if r25 is not None else r2f_
refs_curve = refs if (fit is not None and fit >= 0.5) else []
p = _r.price(sym)
st_ = _r.perf_stats(p) if p is not None else {}
stats = {"t5y": _r.fmt_pct(_r.window_ret(p, "2021-01-01",
st_["end"])) if p is not None
else "—",
"cagr": _r.fmt_pct(st_.get("cagr")),
"mdd": _r.fmt_pct(st_.get("mdd")),
"r2_5y": _r.fmt_r2(srow.get("r2_5y")),
"alpha_5y": (f"{_r.fmt_pct(srow['alpha_ann_5y'])} "
f"(t={srow['alpha_t_5y']:+.1f})"
if isinstance(srow.get("alpha_ann_5y"),
(int, float)) else "—")}
d = {
"meta": {"sym": sym, "name": name, "group": group, "order": order,
"verdict": srow.get("verdict", ""),
"objective": (_r.FONDS.get(sym) or {}).get("objective",
"")},
"stats": stats,
"narrative": narrate(sym),
"chart": _chart(sym, refs_curve),
"perf": _perf_rows(sym, refs_curve),
"drivers": _drivers(sym, fr, srow, dr),
"reference": _reference(sym, fr, refs, refs_curve),
"tax": _tax(sym),
"peers": _peers(sym, fr),
}
try:
d["style"] = styletilt.style_profile(sym)
except Exception:
d["style"] = None
print(f" {sym:8s} {time.time() - t0:5.1f}s", flush=True)
return d
def main() -> None:
from fundlab.decompose import ALIAS
from fundlab.nport import FUND_TOKENS
t0 = time.time()
cand = [v["sym"] for v in _r.SEARCH.values()
if isinstance(v, dict)
and str(v.get("verdict", "")).startswith("CANDIDATE")]
cand.sort(key=lambda s: -(_r.SEARCH[s]["alpha_t_5y"]
if isinstance(_r.SEARCH[s].get("alpha_t_5y"),
(int, float)) else -9))
short = [s for s in FUND_TOKENS if s not in ALIAS]
data = {"generated": time.strftime("%Y-%m-%d %H:%M"),
"funds": {}}
i = 0
for s in cand:
i += 1
data["funds"][s] = build_fund(s, "candidate", i)
for s in short:
i += 1
data["funds"][s] = build_fund(s, "shortlist", i)
OUT.parent.mkdir(exist_ok=True)
OUT.write_text(json.dumps(data))
# rebuild any on-demand (Symbol-box) reports so they gain the new
# sections too; keep their "adhoc" group
if ADHOC_FILE.exists():
try:
_old = json.loads(ADHOC_FILE.read_text())["funds"]
except Exception:
_old = {}
for j, s in enumerate(_old, 1):
if s in cand or s in short:
continue
_old[s] = build_fund(s, "adhoc", order=-j)
ADHOC_FILE.write_text(json.dumps({"funds": _old}))
print(f"rebuilt {len(_old)} ad-hoc reports")
print(f"wrote {OUT} in {time.time() - t0:.0f}s "
f"({OUT.stat().st_size / 1e6:.1f} MB, {len(data['funds'])} funds)")
if __name__ == "__main__":
main()
+47682 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2
View File
@@ -1,2 +1,4 @@
2026-08-28 14:52:00
server_watchdog: no answer on :8599 - relaunching
2026-08-30 13:26:18
server_watchdog: no answer on :8599 - relaunching
+257
View File
@@ -0,0 +1,257 @@
"""Style-tilt battery: mathematical factor identification for one fund.
Regresses the fund's daily excess-of-T-bill returns on a battery of 22
style/asset sleeves (US funds proxying the global style factors; a fund
expresses them in its own universe, so betas are the right sign and
magnitude but approximate), over the full history and the last 5 years:
* plain OLS -> every factor's beta + t-stat (exploratory view)
* BIC forward selection -> the IDENTIFIED tilt stack (the strict gate:
a factor is only in if it measurably improves the model)
* residual alpha after the identified stack -> "is there skill left?"
Plus data-driven English commentary (fundlab.styletilt.commentary).
Caveats stated in the commentary, not hidden: US sleeves proxy global
factors; style sleeves are mutually collinear, so single-OLS t-stats are
indicative and the BIC set is the identification.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from fundlab import decompose
# factor label -> sleeve ticker (US proxies for the global factors)
BATTERY: dict[str, str] = {
"int-dev (EFA)": "efa", "EM (VWO)": "vwo", "growth (VUG)": "vug",
"value (VTV)": "vtv", "small (IWM)": "iwm", "equalwt (RSP)": "rsp",
"lowvol (USMV)": "usmv", "lowvol (DFLVX)": "dflvx",
"quality (QUAL)": "qual", "momentum (MTUM)": "mtum",
"dividend (HDV)": "hdv", "div-apprec (VYM)": "vym",
"longdur (TLT)": "tlt", "gold (GLD)": "gld",
"EUR (FXE)": "fxe", "JPY (FXY)": "fxy", "AUD (FXU)": "fxu",
"utilities (XLU)": "xlu", "staples (XLP)": "xlp",
"health (XLV)": "xlv", "banks (XLF)": "xlf", "energy (XLE)": "xle",
}
SYMS = list(dict.fromkeys(BATTERY.values()))
INV = {v: k for k, v in BATTERY.items()}
_PANEL: pd.DataFrame | None = None
def _panel() -> pd.DataFrame:
"""Battery sleeves' daily EXCESS-of-T-bill returns, cached per process."""
global _PANEL
if _PANEL is None:
_PANEL = decompose.excess(
decompose.returns_panel(SYMS, start=decompose.FULL_WINDOW))
return _PANEL
def _fund_excess(sym: str) -> pd.Series:
p = decompose.adj_close(sym)
if p is None:
return pd.Series(dtype=float)
y = p.pct_change()
rf = decompose.rf_series()
if rf is not None:
y = y.sub(rf.reindex(y.index).fillna(0.0))
return y
def _fit(y: pd.Series, a: str | None, b: str | None) -> dict:
x = _panel()
idx = x.index
msk = idx >= (a or idx[0])
if b is not None:
msk &= idx <= b
x = x[msk]
y = y.reindex(x.index)
ok = y.notna() & x.notna().all(axis=1)
if ok.sum() < 252:
return {}
X = np.column_stack([np.ones(int(ok.sum()))] +
[x[s][ok].to_numpy() for s in SYMS])
yn = y[ok].to_numpy()
beta, *_ = np.linalg.lstsq(X, yn, rcond=None)
res = yn - X @ beta
dof = max(int(ok.sum()) - len(SYMS) - 1, 1)
sigma2 = float(res @ res) / dof
se = np.sqrt(np.diag(np.linalg.inv(X.T @ X)) * sigma2)
t = np.where(se > 0, beta / se, 0.0)
r2 = 1 - float(res @ res) / float((yn - yn.mean()) @ (yn - yn.mean()))
return {
"n": int(ok.sum()),
"start": str(x.index[ok][0].date()),
"end": str(x.index[ok][-1].date()),
"r2": float(r2),
"alpha_ann": float(beta[0] * 252),
"alpha_t": float(t[0]),
"factors": [
{"name": INV[s], "sym": s, "beta": float(beta[k + 1]),
"t": float(t[k + 1])}
for k, s in enumerate(SYMS)],
}
def _forward(y: pd.Series, a: str | None, b: str | None) -> list[str]:
"""BIC-gated forward selection over the battery -> identified sleeves."""
x = _panel()
idx = x.index
msk = idx >= (a or idx[0])
if b is not None:
msk &= idx <= b
x = x[msk]
y = y.reindex(x.index)
ok = y.notna()
if ok.sum() < 252:
return []
cand = {s: x[s].to_numpy() for s in SYMS}
chosen, _m, _okk = decompose.forward_select(y.to_numpy(), cand, y_ok=ok)
return list(chosen)
# ------------------------------------------------------------- commentary
# human meaning of each sleeve (used for the prose)
MEANING: dict[str, str] = {
"efa": "international developed markets", "vwo": "emerging markets",
"vug": "US growth equities", "vtv": "US value equities",
"iwm": "US small caps", "rsp": "equal-weight (small-tilted) US",
"usmv": "low volatility", "dflvx": "low volatility",
"qual": "quality (high-ROE, low-debt, stable earnings)",
"mtum": "momentum (recent winners)", "hdv": "high dividend",
"vym": "high dividend (appreciation-tilted)",
"tlt": "long-duration Treasuries", "gld": "gold",
"fxe": "the euro", "fxy": "the yen", "fxu": "the Australian dollar",
"xlu": "utilities (defensive bond-proxy)",
"xlp": "consumer staples (defensive)",
"xlv": "healthcare (defensive)", "xlf": "banks/financials",
"xle": "energy",
}
# sign-specific phrasing where the generic 'tilt toward/away from' is wrong
SPECIAL: dict[tuple[str, bool], str] = {
("fxe", False): ("short-euro position that carries the USD/EUR "
"interest-rate differential"),
("fxy", False): ("short-yen position that carries the USD/JPY "
"rate differential"),
("fxu", False): "short-AUD position (USD carry)",
("fxu", True): "long-AUD position (AUD carry)",
("fxe", True): "long-euro position (exposed to EUR moves)",
("fxy", True): "long-yen position (safe-haven/carry)",
("qual", False): ("anti-quality tilt - systematically underweight "
"high-ROE, low-debt names; the mechanical flip side "
"of a high-payout dividend mandate"),
("qual", True): "quality tilt (high-ROE, low-debt, stable earnings)",
("mtum", False): ("anti-momentum character - it does not chase "
"recent winners (low-turnover/contrarian)"),
("mtum", True): "momentum tilt (preference for recent winners)",
("hdv", True): ("high-dividend tilt - a systematic preference for "
"income-paying names"),
("hdv", False): "underweight to high-dividend names",
("vym", True): "dividend-appreciation tilt (growing payers)",
("rsp", False): "cap-weight concentration (tilt away from "
"equal-weight/small)",
("rsp", True): "equal-weight (small-tilted) exposure",
("vwo", False): "developed-only tilt (away from emerging markets)",
("vwo", True): "an emerging-market tilt",
("usmv", True): "low-volatility (defensive beta) tilt",
("dflvx", True): "low-volatility (defensive beta) tilt",
("dflvx", False): "underweight to low-volatility names",
("usmv", False): "underweight to low-volatility names",
}
def _strength(t: float) -> str:
a = abs(t)
return "strong" if a >= 10 else "clear" if a >= 5 else "modest"
def _tilt_sentence(f: dict) -> str:
s = f["sym"]
key = (s, f["beta"] > 0)
if key in SPECIAL:
body = SPECIAL[key]
else:
m = MEANING.get(s, f["name"])
body = (f"tilt toward {m}" if f["beta"] > 0
else f"tilt away from {m}")
return (f"{_strength(f['t'])} {body} "
f"(β {f['beta']:+.2f}, t {f['t']:+.0f})")
def commentary(sym: str, prof: dict) -> list[str]:
"""English prose for the style-tilt block (data-driven)."""
if not prof or not prof.get("full"):
return []
full, rec5 = prof["full"], prof.get("rec5") or {}
sig_full = {f["sym"]: f for f in full["factors"] if abs(f["t"]) >= 2}
sig_5 = {f["sym"]: f for f in rec5.get("factors", [])
if abs(f["t"]) >= 2}
out = []
# paragraph 1: the identified stack
parts = []
core = sig_full.get("efa")
if core:
parts.append(
f"the core exposure is {abs(core['beta']):.0%} of "
f"international developed equities (t {core['t']:+.0f})")
for f in sorted(sig_full.values(), key=lambda x: -abs(x["t"])):
if f["sym"] == "efa":
continue
parts.append(_tilt_sentence(f))
if parts:
out.append(
f"Style-tilt analysis (22 style/asset sleeves regressed on "
f"the fund's excess returns; US funds proxying the global "
f"factors): over {full['start'][:4]}-to-{full['end'][:4]} the "
f"fit explains {full['r2']:.0%} of the excess return (R² "
f"{full['r2']:.2f}). The statistically identified tilt stack: "
+ "; ".join(parts) + ".")
# factors that only appear in the 5y window
recent_only = [s for s in sig_5
if s not in sig_full and s != "efa"]
if recent_only:
out.append(
"Visible only in the recent 5-year window: "
+ "; ".join(_tilt_sentence(sig_5[s]) for s in recent_only)
+ " - newer behavior, or a factor the longer sample dilutes.")
# paragraph 2: the residual - is there skill left?
a, t = full["alpha_ann"], full["alpha_t"]
if abs(t) < 1.75:
out.append(
f"After stripping the identified tilts, the residual excess "
f"return is {a * 100:+.1f}%/year (t {t:+.1f}) - NOT "
f"statistically significant: the fund's outperformance is "
f"factor exposure, not skill alpha.")
else:
out.append(
f"After stripping the identified tilts, a significant "
f"residual of {a * 100:+.1f}%/year (t {t:+.1f}) remains - "
f"genuine alpha on top of the factor stack.")
out.append(
"Caveat: the sleeves are US funds proxying global factors; the "
"fund expresses them in its own holdings, so the betas are the "
"right sign and magnitude but approximate. An index-matched "
"benchmark (the fund's own published index, when one exists) "
"would absorb part of the residual as well.")
return out
def style_profile(sym: str) -> dict | None:
"""Full + 5y battery fits, the BIC-identified stack, and commentary.
Returns None when the fund has no usable local history."""
y = _fund_excess(sym)
if len(y.dropna()) < 252:
return None
full = _fit(y, None, None)
if not full:
return None
rec5 = _fit(y, "2021-01-01", None)
prof = {"full": full,
"rec5": rec5 or {},
"identified": _forward(y, None, None)}
prof["commentary"] = commentary(sym, prof)
return prof
+22 -9
View File
@@ -18,6 +18,17 @@ def daily_returns(price: pd.Series | pd.DataFrame) -> pd.Series | pd.DataFrame:
return price.pct_change().fillna(0.0)
def excess(returns: pd.Series, rf: float | pd.Series | None) -> pd.Series:
"""Net returns against the risk-free rate.
rf may be a scalar ANNUAL rate (subtracted as rf/252 per day), a
DAILY rate series aligned by index (e.g. BIL total returns, filled 0
where absent), or None/0 for no adjustment."""
if rf is None or isinstance(rf, (int, float)):
return returns - rf / ANN
return returns - rf.reindex(returns.index).fillna(0.0)
def total_return(price: pd.Series | pd.DataFrame) -> float:
return float(price.iloc[-1] / price.iloc[0] - 1.0)
@@ -31,14 +42,14 @@ def annualized_vol(returns: pd.Series | pd.DataFrame) -> float:
return float(returns.std() * np.sqrt(ANN))
def sharpe(returns: pd.Series, rf: float = 0.0) -> float:
r = returns - rf / ANN
def sharpe(returns: pd.Series, rf: float | pd.Series | None = 0.0) -> float:
r = excess(returns, rf)
sd = r.std()
return float(r.mean() / sd * np.sqrt(ANN)) if sd > 0 else 0.0
def sortino(returns: pd.Series, rf: float = 0.0) -> float:
r = returns - rf / ANN
def sortino(returns: pd.Series, rf: float | pd.Series | None = 0.0) -> float:
r = excess(returns, rf)
dd = float(np.sqrt(np.mean(np.minimum(r, 0.0) ** 2)))
return float(r.mean() / dd * np.sqrt(ANN)) if dd > 0 else 0.0
@@ -53,18 +64,20 @@ def calmar(price: pd.Series | pd.DataFrame) -> float:
return float(annualized_return(price) / -mdd) if mdd < 0 else 0.0
def beta_alpha(returns: pd.Series, bench: pd.Series, rf: float = 0.0):
def beta_alpha(returns: pd.Series, bench: pd.Series,
rf: float | pd.Series | None = 0.0):
"""CAPM regression. Returns (beta, annualized_alpha)."""
r = (returns - rf / ANN).dropna()
b = (bench - rf / ANN).dropna()
r = excess(returns, rf).dropna()
b = excess(bench, rf).dropna()
r, b = r.align(b, join="inner")
beta = np.cov(r, b)[0, 1] / np.var(b)
alpha_daily = r.mean() - (rf / ANN + beta * (b.mean() - rf / ANN))
# r and b are already rf-adjusted
alpha_daily = r.mean() - beta * b.mean()
return float(beta), float(alpha_daily * ANN)
def summary(price: pd.Series, bench: pd.Series | None = None,
rf: float = 0.0) -> dict[str, float]:
rf: float | pd.Series | None = 0.0) -> dict[str, float]:
r = daily_returns(price)
out = {
"total_return": total_return(price),
View File
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "aaaux",
"dedup": [
[
"2014-03-18",
0.003
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+34
View File
@@ -0,0 +1,34 @@
{
"symbol": "aacdx",
"dedup": [
[
"2013-12-17",
0.369
],
[
"2014-12-16",
0.343
],
[
"2015-03-17",
0.001
],
[
"2015-12-22",
0.317
],
[
"2016-12-20",
0.089
],
[
"2017-12-19",
0.284
],
[
"2018-12-18",
0.29
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+22
View File
@@ -0,0 +1,22 @@
{
"symbol": "aadbx",
"dedup": [
[
"2012-12-20",
0.308
],
[
"2014-12-22",
0.78
],
[
"2018-12-20",
1.125
],
[
"2019-12-20",
1.167
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+50
View File
@@ -0,0 +1,50 @@
{
"symbol": "abcix",
"dedup": [
[
"2012-12-20",
0.008
],
[
"2013-12-20",
0.089
],
[
"2014-12-22",
0.122
],
[
"2016-12-22",
0.098
],
[
"2018-12-20",
0.274
],
[
"2019-12-20",
1.175
],
[
"2020-12-11",
0.21
],
[
"2021-12-22",
0.137
],
[
"2022-12-22",
0.541
],
[
"2023-12-21",
0.131
],
[
"2024-12-20",
2.388
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+34
View File
@@ -0,0 +1,34 @@
{
"symbol": "abrvx",
"dedup": [
[
"2015-12-15",
0.053
],
[
"2016-12-15",
0.125
],
[
"2017-12-15",
0.333
],
[
"2018-12-14",
0.375
],
[
"2019-12-13",
0.083
],
[
"2020-12-11",
3.014
],
[
"2021-12-14",
1.096
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+54
View File
@@ -0,0 +1,54 @@
{
"symbol": "acazx",
"dedup": [
[
"2013-12-18",
1.535
],
[
"2014-12-18",
3.23
],
[
"2015-12-16",
1.669
],
[
"2016-12-14",
0.168
],
[
"2017-12-15",
1.668
],
[
"2018-12-18",
2.539
],
[
"2019-12-18",
2.201
],
[
"2020-12-16",
5.152
],
[
"2021-12-15",
7.408
],
[
"2022-12-15",
0.838
],
[
"2023-12-14",
1.817
],
[
"2024-12-12",
4.346
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "acfnx",
"dedup": [
[
"2020-12-08",
0.332
],
[
"2021-12-07",
1.39
],
[
"2025-12-04",
5.869
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+22
View File
@@ -0,0 +1,22 @@
{
"symbol": "addvx",
"dedup": [
[
"2013-12-06",
0.086
],
[
"2016-12-13",
0.013
],
[
"2020-12-08",
0.311
],
[
"2021-12-07",
0.107
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+26
View File
@@ -0,0 +1,26 @@
{
"symbol": "adgzx",
"dedup": [
[
"2014-12-18",
2.845
],
[
"2015-12-17",
1.283
],
[
"2017-06-12",
0.017
],
[
"2017-12-14",
2.221
],
[
"2021-12-09",
3.709
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+46
View File
@@ -0,0 +1,46 @@
{
"symbol": "adozx",
"dedup": [
[
"2011-12-20",
0.154
],
[
"2013-12-18",
0.801
],
[
"2014-12-18",
0.736
],
[
"2015-12-16",
0.339
],
[
"2016-12-14",
0.039
],
[
"2017-12-15",
0.885
],
[
"2018-12-18",
0.243
],
[
"2019-12-18",
0.515
],
[
"2020-12-16",
0.952
],
[
"2021-12-15",
1.077
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "aectx",
"dedup": [
[
"2018-12-18",
0.414
],
[
"2020-12-22",
0.608
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+38
View File
@@ -0,0 +1,38 @@
{
"symbol": "aemgx",
"dedup": [
[
"2004-12-16",
0.462
],
[
"2005-12-15",
2.267
],
[
"2006-12-14",
5.53
],
[
"2007-12-13",
8.648
],
[
"2008-12-18",
2.986
],
[
"2021-12-22",
0.039
],
[
"2022-12-22",
0.194
],
[
"2024-12-20",
0.127
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+30
View File
@@ -0,0 +1,30 @@
{
"symbol": "aeudx",
"dedup": [
[
"2013-12-06",
0.549
],
[
"2014-12-09",
0.662
],
[
"2015-12-08",
0.632
],
[
"2016-12-13",
0.522
],
[
"2017-12-12",
0.898
],
[
"2018-12-11",
0.471
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "afcmx",
"dedup": [
[
"2019-12-17",
0.326
],
[
"2020-03-10",
0.137
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+38
View File
@@ -0,0 +1,38 @@
{
"symbol": "afgfx",
"dedup": [
[
"2016-12-15",
1.009
],
[
"2018-12-20",
5.899
],
[
"2019-12-19",
7.046
],
[
"2020-12-17",
6.115
],
[
"2021-12-16",
13.675
],
[
"2022-12-21",
2.828
],
[
"2023-12-20",
1.61
],
[
"2024-12-18",
3.895
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "afgzx",
"dedup": [
[
"2021-12-15",
3.19
],
[
"2024-12-12",
4.569
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "agbdx",
"dedup": [
[
"2013-12-10",
0.037
],
[
"2016-12-20",
0.029
],
[
"2017-12-19",
0.026
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+30
View File
@@ -0,0 +1,30 @@
{
"symbol": "agctx",
"dedup": [
[
"2017-12-19",
0.721
],
[
"2018-03-20",
0.044
],
[
"2018-12-18",
0.233
],
[
"2019-12-17",
0.78
],
[
"2020-12-22",
1.06
],
[
"2021-03-23",
0.301
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+34
View File
@@ -0,0 +1,34 @@
{
"symbol": "aggdx",
"dedup": [
[
"2013-12-17",
0.278
],
[
"2014-12-16",
0.875
],
[
"2015-03-17",
0.176
],
[
"2016-12-20",
0.063
],
[
"2017-12-19",
1.471
],
[
"2020-03-10",
0.066
],
[
"2020-12-22",
1.444
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+26
View File
@@ -0,0 +1,26 @@
{
"symbol": "agrdx",
"dedup": [
[
"2020-12-08",
1.563
],
[
"2021-12-07",
5.308
],
[
"2022-03-22",
1.01
],
[
"2023-12-19",
2.335
],
[
"2024-12-17",
3.458
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "ahidx",
"dedup": [
[
"2021-12-07",
0.096
],
[
"2022-05-24",
0.017
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "ahlix",
"dedup": [
[
"2017-12-21",
0.423
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+26
View File
@@ -0,0 +1,26 @@
{
"symbol": "ahszx",
"dedup": [
[
"2015-12-16",
3.39
],
[
"2017-12-15",
0.752
],
[
"2018-12-18",
1.882
],
[
"2020-12-16",
3.753
],
[
"2021-12-15",
7.001
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "ahydx",
"dedup": [
[
"2013-12-06",
0.057
],
[
"2014-12-09",
0.052
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "aifrx",
"dedup": [
[
"2013-12-06",
0.348
],
[
"2014-12-05",
0.19
],
[
"2024-12-20",
1.215
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+30
View File
@@ -0,0 +1,30 @@
{
"symbol": "aigyx",
"dedup": [
[
"2015-12-04",
0.27
],
[
"2016-12-16",
0.471
],
[
"2018-12-20",
6.483
],
[
"2022-12-21",
0.67
],
[
"2023-12-21",
0.162
],
[
"2024-12-20",
1.096
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "alczx",
"dedup": [
[
"2021-12-15",
1.969
],
[
"2024-12-12",
0.993
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "alfvx",
"dedup": [
[
"2016-12-21",
2.929
],
[
"2017-12-20",
3.182
],
[
"2019-12-20",
3.287
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+38
View File
@@ -0,0 +1,38 @@
{
"symbol": "algzx",
"dedup": [
[
"2017-12-15",
1.542
],
[
"2018-12-18",
0.643
],
[
"2019-12-18",
0.857
],
[
"2020-12-16",
1.04
],
[
"2021-12-15",
1.384
],
[
"2022-12-15",
0.092
],
[
"2023-12-14",
0.438
],
[
"2024-12-12",
0.804
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "allfx",
"dedup": [
[
"2013-12-13",
0.914
],
[
"2017-12-13",
0.697
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "alvdx",
"dedup": [
[
"2017-12-12",
0.38
],
[
"2018-12-11",
0.398
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "alzfx",
"dedup": [
[
"2015-12-16",
0.269
],
[
"2017-12-15",
1.226
],
[
"2021-12-15",
7.964
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+22
View File
@@ -0,0 +1,22 @@
{
"symbol": "amczx",
"dedup": [
[
"2017-12-15",
0.114
],
[
"2018-12-18",
0.71
],
[
"2019-12-18",
1.197
],
[
"2020-12-16",
2.15
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+30
View File
@@ -0,0 +1,30 @@
{
"symbol": "amdvx",
"dedup": [
[
"2013-12-06",
0.961
],
[
"2014-12-09",
1.646
],
[
"2015-12-08",
1.441
],
[
"2016-12-13",
0.475
],
[
"2017-12-12",
1.387
],
[
"2018-12-11",
1.71
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "amfax",
"dedup": [
[
"2014-04-08",
0.095
],
[
"2018-04-10",
0.118
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "anazx",
"dedup": [
[
"2016-12-07",
0.065
],
[
"2020-12-04",
0.06
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "andvx",
"dedup": [
[
"2016-12-15",
0.586
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "anfvx",
"dedup": [
[
"2014-12-11",
7.121
],
[
"2015-12-10",
3.231
],
[
"2016-12-15",
0.563
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+34
View File
@@ -0,0 +1,34 @@
{
"symbol": "anodx",
"dedup": [
[
"2017-10-10",
0.03
],
[
"2017-10-17",
0.576
],
[
"2017-12-19",
0.099
],
[
"2018-12-18",
2.328
],
[
"2019-12-17",
1.0
],
[
"2020-12-08",
2.721
],
[
"2021-12-07",
4.612
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "anprx",
"dedup": [
[
"2019-04-11",
0.128
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+38
View File
@@ -0,0 +1,38 @@
{
"symbol": "apgzx",
"dedup": [
[
"2015-12-16",
3.492
],
[
"2017-12-13",
1.954
],
[
"2018-12-11",
4.431
],
[
"2020-12-08",
2.146
],
[
"2021-10-11",
4.709
],
[
"2021-12-07",
2.391
],
[
"2022-12-06",
0.605
],
[
"2025-12-09",
11.022
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+54
View File
@@ -0,0 +1,54 @@
{
"symbol": "aphmx",
"dedup": [
[
"2012-12-19",
1.823
],
[
"2013-11-21",
3.798
],
[
"2014-11-19",
4.884
],
[
"2015-11-19",
6.556
],
[
"2016-11-17",
3.343
],
[
"2017-11-21",
5.704
],
[
"2018-11-20",
7.967
],
[
"2019-11-21",
4.526
],
[
"2020-11-24",
7.178
],
[
"2021-11-23",
8.589
],
[
"2024-12-10",
5.232
],
[
"2025-12-10",
6.328
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+38
View File
@@ -0,0 +1,38 @@
{
"symbol": "aphrx",
"dedup": [
[
"2011-12-15",
0.112
],
[
"2016-11-17",
0.034
],
[
"2017-11-21",
1.069
],
[
"2020-11-24",
2.401
],
[
"2021-11-23",
3.985
],
[
"2023-12-07",
0.712
],
[
"2024-12-10",
3.917
],
[
"2025-12-10",
1.193
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+42
View File
@@ -0,0 +1,42 @@
{
"symbol": "aphsx",
"dedup": [
[
"2015-11-19",
2.713
],
[
"2016-11-17",
0.329
],
[
"2017-11-21",
4.966
],
[
"2018-11-20",
5.428
],
[
"2019-11-21",
2.646
],
[
"2020-11-24",
2.705
],
[
"2021-11-23",
5.072
],
[
"2024-12-10",
1.832
],
[
"2025-12-10",
2.912
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "aphyx",
"dedup": [
[
"2020-11-24",
1.109
],
[
"2021-11-23",
2.062
],
[
"2021-12-30",
0.003
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "apodx",
"dedup": [
[
"2013-12-06",
0.023
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "aqmix",
"dedup": [
[
"2013-12-20",
0.107
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+62
View File
@@ -0,0 +1,62 @@
{
"symbol": "arbfx",
"dedup": [
[
"2004-12-31",
0.522
],
[
"2006-12-28",
0.517
],
[
"2007-12-10",
0.866
],
[
"2008-12-10",
0.523
],
[
"2010-12-16",
0.273
],
[
"2011-12-16",
0.295
],
[
"2013-12-18",
0.057
],
[
"2014-12-09",
0.031
],
[
"2015-12-16",
0.296
],
[
"2016-12-15",
0.123
],
[
"2019-12-19",
0.275
],
[
"2020-12-17",
0.885
],
[
"2021-12-14",
0.068
],
[
"2023-12-14",
0.244
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "aredx",
"dedup": [
[
"2016-12-20",
2.612
],
[
"2017-12-19",
1.249
],
[
"2018-12-18",
1.131
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "artix",
"dedup": [
[
"1996-12-03",
0.115
],
[
"2000-11-15",
3.55
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "arydx",
"dedup": [
[
"2022-04-19",
0.792
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "ascfx",
"dedup": [
[
"2018-12-20",
1.627
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+10
View File
@@ -0,0 +1,10 @@
{
"symbol": "asddx",
"dedup": [
[
"2021-12-07",
0.039
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+30
View File
@@ -0,0 +1,30 @@
{
"symbol": "asdex",
"dedup": [
[
"2019-12-17",
4.35
],
[
"2020-12-08",
6.321
],
[
"2021-12-07",
9.628
],
[
"2022-12-21",
7.799
],
[
"2023-12-19",
5.215
],
[
"2024-12-17",
4.473
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "asipx",
"dedup": [
[
"2020-12-08",
0.083
],
[
"2021-12-07",
0.215
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+34
View File
@@ -0,0 +1,34 @@
{
"symbol": "asmdx",
"dedup": [
[
"2013-12-17",
0.601
],
[
"2014-03-18",
0.004
],
[
"2014-12-16",
0.6
],
[
"2015-12-22",
0.449
],
[
"2016-12-20",
0.079
],
[
"2017-12-19",
0.651
],
[
"2018-12-18",
0.567
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+26
View File
@@ -0,0 +1,26 @@
{
"symbol": "atesx",
"dedup": [
[
"2016-12-23",
0.09
],
[
"2017-12-22",
0.668
],
[
"2018-12-27",
0.822
],
[
"2019-12-20",
1.354
],
[
"2022-12-09",
0.949
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+18
View File
@@ -0,0 +1,18 @@
{
"symbol": "atezx",
"dedup": [
[
"2021-12-07",
17.691
],
[
"2024-12-10",
11.705
],
[
"2025-12-09",
18.145
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "atgdx",
"dedup": [
[
"2015-03-17",
0.024
],
[
"2020-03-10",
0.005
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+54
View File
@@ -0,0 +1,54 @@
{
"symbol": "athdx",
"dedup": [
[
"2013-12-04",
3.602
],
[
"2014-12-16",
3.851
],
[
"2015-12-22",
2.729
],
[
"2016-12-20",
1.758
],
[
"2017-12-19",
2.109
],
[
"2018-12-18",
4.318
],
[
"2019-12-17",
2.346
],
[
"2020-12-08",
3.547
],
[
"2021-12-07",
3.078
],
[
"2022-03-22",
0.18
],
[
"2023-12-19",
0.171
],
[
"2024-12-17",
3.704
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+34
View File
@@ -0,0 +1,34 @@
{
"symbol": "auldx",
"dedup": [
[
"2018-12-18",
3.333
],
[
"2019-12-17",
2.229
],
[
"2020-12-08",
2.125
],
[
"2021-12-07",
5.941
],
[
"2022-12-21",
4.095
],
[
"2023-12-19",
4.536
],
[
"2024-12-17",
3.344
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+26
View File
@@ -0,0 +1,26 @@
{
"symbol": "avudx",
"dedup": [
[
"2014-12-09",
0.532
],
[
"2015-12-08",
0.524
],
[
"2016-12-13",
0.149
],
[
"2017-12-12",
0.512
],
[
"2018-12-11",
0.71
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+34
View File
@@ -0,0 +1,34 @@
{
"symbol": "baffx",
"dedup": [
[
"2018-12-17",
0.743
],
[
"2019-12-16",
1.021
],
[
"2020-12-15",
0.843
],
[
"2021-12-14",
1.272
],
[
"2022-12-13",
0.924
],
[
"2023-12-13",
0.851
],
[
"2024-12-13",
1.87
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+30
View File
@@ -0,0 +1,30 @@
{
"symbol": "bafhx",
"dedup": [
[
"2018-12-17",
0.975
],
[
"2019-12-16",
0.504
],
[
"2020-12-15",
0.728
],
[
"2021-12-14",
1.098
],
[
"2022-12-13",
0.08
],
[
"2024-12-13",
0.415
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+66
View File
@@ -0,0 +1,66 @@
{
"symbol": "bafsx",
"dedup": [
[
"2007-12-12",
1.024
],
[
"2008-12-10",
0.363
],
[
"2011-12-08",
0.269
],
[
"2012-12-12",
2.687
],
[
"2013-12-13",
1.684
],
[
"2014-12-23",
4.215
],
[
"2015-12-21",
5.093
],
[
"2016-12-19",
1.126
],
[
"2017-12-19",
0.508
],
[
"2018-12-17",
1.594
],
[
"2019-12-16",
0.885
],
[
"2020-12-15",
0.45
],
[
"2021-12-14",
7.23
],
[
"2022-12-13",
3.323
],
[
"2024-12-13",
2.603
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+46
View File
@@ -0,0 +1,46 @@
{
"symbol": "bafwx",
"dedup": [
[
"2012-12-12",
0.006
],
[
"2013-12-13",
0.144
],
[
"2014-12-23",
0.305
],
[
"2015-12-21",
0.746
],
[
"2016-12-19",
0.118
],
[
"2017-12-19",
0.354
],
[
"2018-12-17",
0.781
],
[
"2019-12-16",
0.209
],
[
"2021-12-14",
0.911
],
[
"2024-12-13",
2.88
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+14
View File
@@ -0,0 +1,14 @@
{
"symbol": "bafzx",
"dedup": [
[
"2015-12-21",
0.038
],
[
"2016-12-19",
0.07
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+42
View File
@@ -0,0 +1,42 @@
{
"symbol": "barux",
"dedup": [
[
"2016-06-28",
0.02
],
[
"2016-11-29",
2.804
],
[
"2018-11-29",
4.732
],
[
"2019-07-25",
0.029
],
[
"2019-11-26",
1.504
],
[
"2020-11-24",
3.394
],
[
"2021-11-23",
8.982
],
[
"2023-12-07",
3.415
],
[
"2024-12-17",
17.552
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+46
View File
@@ -0,0 +1,46 @@
{
"symbol": "bauux",
"dedup": [
[
"2013-12-13",
0.942
],
[
"2015-12-21",
0.452
],
[
"2016-12-19",
0.032
],
[
"2017-12-19",
1.014
],
[
"2018-12-17",
2.934
],
[
"2019-12-16",
1.144
],
[
"2021-12-14",
0.097
],
[
"2022-12-13",
1.568
],
[
"2023-12-13",
1.583
],
[
"2024-12-13",
4.28
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}
+38
View File
@@ -0,0 +1,38 @@
{
"symbol": "bbgpx",
"dedup": [
[
"2009-12-22",
0.192
],
[
"2010-12-22",
0.365
],
[
"2011-12-21",
0.125
],
[
"2012-12-21",
0.201
],
[
"2017-12-22",
0.004
],
[
"2018-12-21",
0.017
],
[
"2019-12-23",
0.004
],
[
"2022-12-19",
0.002
]
],
"note": "Bulk correction from the double-listing scan (scripts/scan_double_listing.py): Yahoo listed this distribution in both the dividend and capitalGains event files (same date, same amount); one copy is spurious. The 'dedup' invariant keeps at most one copy, layout-agnostically. Mechanism verified against official filings for JLPSX/GDEUX/GSOUX/FAEVX/CVSIX/FZAGX; mechanism-inferred for this symbol (no per-fund official check). Revert the entry if a future official cross-check shows both rows were real."
}

Some files were not shown because too many files have changed in this diff Show More