import pandas as pd, numpy as np
d = pd.read_csv("an42_float.csv"); d["pnl"] = (d.x - 1) * 1000
PDAY = {("sw_live","A"):2503, ("sw_live","B"):10400, ("fw_mc5","A"):4473, ("fw_mc5","B"):13130}  # lab md $ a day, full book
rng = np.random.default_rng(7); out = []
for (b, h), s in d.groupby(["book", "half"]):
    days = s.pnl.sum() / PDAY[(b, h)]
    for name, m in (("opf>=0.33 (primary)", s.opf_share >= 0.33), ("opf>0 (sens.)", s.opf_share > 0), ("opb>=0.33 (OP-B)", s.opb_share >= 0.33)):
        k = s[~m]; n_skip = int(m.sum())
        full_tr = s.pnl.mean(); kept_tr = k.pnl.mean() if len(k) else np.nan
        full_day = s.pnl.sum() / days; kept_day = k.pnl.sum() / days
        r = [s.pnl.drop(rng.choice(s.index, n_skip, replace=False)).sum() for _ in range(1000)] if 0 < n_skip < len(s) else [s.pnl.sum()]
        beat = np.mean(np.array(r) < k.pnl.sum()) * 100
        top2 = lambda x: (x.sum() - x.nlargest(2).sum()) / days
        skipped_w = int((s[m].x >= 3).sum())
        out.append(dict(book=b, half=h, rule=name, trades=len(s), skipped=n_skip, skipped_3x=skipped_w, full_tr=round(full_tr), kept_tr=round(kept_tr) if kept_tr == kept_tr else None,
                        full_day=round(full_day), kept_day=round(kept_day), beat_rand=round(beat, 1), full_no2=round(top2(s.pnl)), kept_no2=round(top2(k.pnl)) if len(k) > 2 else None))
R = pd.DataFrame(out); pd.set_option("display.width", 250); print(R.to_string(index=False))
R.to_csv("an42_score.csv", index=False)
for b in ("sw_live", "fw_mc5"):
    p = R[(R.book == b) & (R.rule.str.startswith("opf>=0.33"))]
    ok = all((p.kept_tr > p.full_tr) & (p.kept_day >= p.full_day) & (p.beat_rand >= 95) & (p.kept_no2 >= p.full_no2))
    print(b, "PRIMARY", "PASS" if ok else "KILL")
