import pandas as pd, numpy as np, urllib.request, io
R = "/tmp/claude-0/-home-claude/5101628c-bcc2-5fb2-9e13-0e431183bef0/scratchpad/"
L = pd.read_csv(R + "data/launches_15sep_4oct.csv.gz", usecols=["tok", "fee", "sym", "w"]).set_index("tok")
rng = np.random.default_rng(11)
def load(d):
    F = pd.read_csv(R + f"f2_d{d}.csv.gz")
    F = F[(F.cp == "trig") & (F.alive == 1) & (F.cap > 1000)].replace([np.inf, -np.inf], np.nan).copy()
    F["fee"] = F.tok.map(L.fee).fillna(0) / 1e6; F["sym"] = F.tok.map(L.sym); F["w"] = F.tok.map(L.w)
    F["half"] = np.where(F.day <= "2026-09-27", "A", "B")
    F["rule"] = (F.close_high <= 0.7841) & (F.alumni_share >= 0.0531)
    return F
def pnl(F, ticket):
    x = ticket / F.ethusd; Ev = F.Ev.fillna(F.Ev.median())
    fb = (1 + x / Ev) * (1 + F.fee)
    mult = np.where(F.Y5 == 1, 5.0, F.end_x)
    V = ticket / fb * mult / F.ethusd; Evx = Ev * np.sqrt(np.maximum(mult, 1e-9))
    p = ticket / fb * mult / (1 + V / Evx) * (1 - F.fee) - ticket
    return np.where(mult == 0, -ticket, p)
def pd_(s): return s.sum() / 7
print("weights in T1 coins:", load(0).w.value_counts().to_dict())
for d in (0, 5, 30, 35, 90):
    F = load(d)
    for tk in (100, 500, 1000):
        F["p"] = pnl(F, tk)
        line = []
        for h in "AB":
            a = F[F.half == h]; r = a[a.rule]
            sims = np.array([rng.choice(a.p.values, len(r), replace=False).sum() / 7 for _ in range(2000)])
            line.append(f"{h} n={len(r)} 5x={int(r.Y5.sum())} $/d={pd_(r.p):6.0f} beat={(sims < pd_(r.p)).mean():.2f}")
        print(f"delay {d:2d}s ticket ${tk:4d} | " + " | ".join(line))
# deeper checks on 30 s, $500
F = load(30); F["p"] = pnl(F, 500)
print("\nC13 drop top winners (30 s, $500):")
for h in "AB":
    r = F[(F.half == h) & F.rule].sort_values("p", ascending=False)
    print(h, "all", round(pd_(r.p)), "| -top1", round(pd_(r.p.iloc[1:])), "| -top3", round(pd_(r.p.iloc[3:])))
print("\nC15 clones: one trade per day per ticker, per creator, per crew (30 s, $500):")
for key in ("sym", "cr", "crew"):
    out = []
    for h in "AB":
        r = F[(F.half == h) & F.rule].sort_values("tc").drop_duplicates(["day", key])
        out.append(f"{h} n={len(r)} $/d={pd_(r.p):.0f}")
    print(key, " | ".join(out))
print("\nC18 positives (rule, 30 s):", F[F.rule].groupby("half").Y5.sum().to_dict(), " all T1:", F.groupby("half").Y5.sum().to_dict())
# C19: best of k random rules of the same size
for h in "AB":
    a = F[F.half == h]; n = int(a.rule.sum()); val = pd_(a[a.rule].p)
    for k in (50, 170):
        best = np.array([max(rng.choice(a.p.values, n, replace=False).sum() / 7 for _ in range(k)) for _ in range(300)])
        print(f"C19 {h}: rule {val:.0f} beats best-of-{k} random in {(best < val).mean():.2f}")
# C20 overlap with Second Window books
toks = set()
for f in ("sw-a2-24-book.csv", "sw-a2-21-trades.csv", "sw-a2-16-wide-trades.csv", "sw-a2-13-trades.csv"):
    try:
        req = urllib.request.Request("http://159.223.88.168/hx-c9ois/sw/" + f, headers={"User-Agent": "Mozilla/5.0"})
        d = pd.read_csv(io.BytesIO(urllib.request.urlopen(req, timeout=30).read()))
        for c in d.columns:
            if d[c].astype(str).str.match(r"^0x[0-9a-fA-F]{40}$").mean() > 0.5: toks |= set(d[c].str.lower())
    except Exception as e: print("sw read fail", f, e)
r = F[F.rule]; ov = r.tok.isin(toks)
print(f"\nC20 overlap: {ov.sum()} of {len(r)} rule trades are coins in SW books/trades; $/d split: overlap {r[ov].p.sum()/14:.0f}, new {r[~ov].p.sum()/14:.0f} (both halves, per day)")
print("C7 censoring: rule trades launched 30 Sep or later:", int((r.day >= "2026-09-30").sum()), "; $/d without them, B:", round(r[(r.half == "B") & (r.day < "2026-09-30")].p.sum() / 2))
