"""Recompute Migna US Quality's score yourself, from public data (Migna, R-930, 30 Nov 2026).

Migna publishes no prices and no returns. It publishes the companies, their dates and these rules; you bring the prices.

THE RULES (the factsheet's "How the record is kept", applied exactly):
  1. Base: the close of 20 October 2026. The first counted session is 21 October 2026.
  2. A company counts from the OPEN of its `entry_session`, as the companies file gives it (the record's own date). On that session
     its move is open -> close, with no dividend adjustment (the open already trades ex-dividend). On later sessions it is close ->
     close. It counts through the close of `last_counted` (to `as_of` while held). A company whose entry_session is on or before the
     base was already held: it counts close -> close from the 20 October close.
  3. Total return: dividends are reinvested on the ex-dividend day: that day's move is (close + dividend) / previous close. Back-
     adjusted prices (each earlier price scaled by 1 - dividend / previous close) give the same result.
  4. Equal shares, re-set at every close: each session the portfolio's move is the simple average of the moves of the companies held
     that session. Withdrawn companies count like any other, up to their last counted close.
  5. The portfolio compounds its daily moves from the base. The score counts only from the first session with at least 10 holdings.
  6. Benchmark: SPY, total return (dividend-adjusted closes), over exactly the same sessions.
  The sessions are the file's `sessions` list (New York trading days from 21 October 2026 to `as_of`). Every price must be present:
  the script stops if one is missing, rather than leave a company out of a day.
  7. Before costs. Points ahead = portfolio % minus SPY %.

CHECK YOU APPLIED THE RULES RIGHT: the membership fingerprint is the SHA-256 (UTF-8, lowercase hex) of one line per session, in
date order, joined by a newline with none at the end: `YYYY-MM-DD:` then the companies held that session as `TICKER@entry_session`,
sorted by ticker then entry_session, joined by commas. It uses names and dates only. If yours matches the file's `membership_sha256`,
you held the right companies on the right sessions; any remaining difference from someone else's figure comes from prices.

Usage:
    python migna_recompute.py companies.json                 # fetches prices with yfinance (pip install yfinance), for your own use
    python migna_recompute.py companies.json prices.csv      # or your own prices: csv with ticker,date,open,close (dividend-adjusted)
"""
import csv
import hashlib
import json
import sys

BASE = "2026-10-20"
MIN_HELD = 10


def load_prices_csv(path):
    px = {}
    with open(path, newline="", encoding="utf-8") as f:
        for r in csv.DictReader(f):
            px.setdefault(r["ticker"].upper(), {})[r["date"][:10]] = (float(r["open"]), float(r["close"]))
    return px


def fetch_prices(tickers, start, end):
    import yfinance as yf          # your own use, under Yahoo's terms
    px = {}
    for tk in tickers:
        h = yf.Ticker(tk.replace(".", "-")).history(start=start, end=end, auto_adjust=True, actions=False)
        px[tk] = {d.strftime("%Y-%m-%d"): (float(o), float(c)) for d, o, c in zip(h.index, h["Open"], h["Close"])}
    return px


def membership(companies, sessions):
    """{session: [companies held]} under rule 2. A company that left and was later found again is two entries."""
    return {d: sorted((c for c in companies if c["entry_session"] <= d and (not c.get("last_counted") or d <= c["last_counted"])),
                      key=lambda c: (c["ticker"], c["entry_session"])) for d in sessions}


def membership_sha256(held):
    text = "\n".join("%s:%s" % (d, ",".join("%s@%s" % (c["ticker"], c["entry_session"]) for c in held[d])) for d in sorted(held))
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def main():
    data = json.load(open(sys.argv[1], encoding="utf-8"))
    companies, as_of = data["companies"], data["as_of"]
    tickers = sorted({c["ticker"].upper() for c in companies} | {"SPY"})
    px = load_prices_csv(sys.argv[2]) if len(sys.argv) > 2 else fetch_prices(tickers, "2026-10-01", "2026-12-31")
    sessions = data.get("sessions") or sorted(d for d in px["SPY"] if BASE < d <= as_of)
    held = membership(companies, sessions)
    print("membership_sha256:", membership_sha256(held))

    def close(tk, d):
        return (px.get(tk) or {}).get(d, (None, None))[1]

    pot = spy = 1.0
    started, prev, missing = False, BASE, []
    for d in sessions:
        moves = []
        for c in held[d]:
            tk = c["ticker"]
            o_, c_ = (px.get(tk) or {}).get(d, (None, None))
            base = o_ if d == c["entry_session"] else close(tk, prev)
            if base and c_:
                moves.append(c_ / base - 1)
            else:
                missing.append("%s %s" % (tk, d))
        if missing:
            sys.exit("missing prices, no score: %s. Fetch them (tickers are plain exchange symbols, e.g. BRK.B) and run again." % ", ".join(missing[:8]))
        if close("SPY", d) is None or close("SPY", prev) is None:
            sys.exit("missing SPY close on %s or %s" % (prev, d))
        if not started and len(held[d]) >= MIN_HELD:
            started = True
        if started and moves:
            pot *= 1 + sum(moves) / len(moves)
            spy *= close("SPY", d) / close("SPY", prev)
        prev = d
    p, s = 100 * (pot - 1), 100 * (spy - 1)
    print("sessions: %s to %s (%d)" % (sessions[0], sessions[-1], len(sessions)))
    print("Migna US Quality: %+.2f%%   SPY: %+.2f%%   points ahead: %+.2f" % (p, s, p - s))



if __name__ == "__main__":
    main()
