"""up3_path.py -- [2026-10-27] the user: is the problem the ENTRY or the EXIT? Price path after each up3 buy (exit ignored) vs a random
baseline (every 10th minute 9:33-11:00 on the same listed stock-days), and how much of the rise C3 kept."""
import json, sys
import numpy as np
from up3_test import load, run, path, DAYS, hm
S = load(); half = DAYS[6]; N = int(sys.argv[1]) if len(sys.argv) > 1 else 3
print(f'== {N} higher closes in a row ==')
base = []
for day, s, D, bk in S:
    b, M = D.b, D.m
    for i in range(8, len(b) - 1):
        if 3 <= M[i] <= 90 and M[i] % 10 == 0 and M[i] in bk:
            base.append(dict(day=day, **path(b, i + 1, b[i + 1]["o"])))
def row(lab, T):
    def f(Z):
        if not Z: return "-"
        a = lambda k: np.mean([z[k] for z in Z])
        cap = f" | C3 kept {a('pl') + 0.2:+.2f}% of best-60 {a('mfe60'):+.2f}% => C3 after cost {a('pl'):+.3f}%" if "pl" in Z[0] else ""
        return (f"n {len(Z):4} | +1% first {np.mean([z['first'] == 1 for z in Z]):3.0%} -1% first {np.mean([z['first'] == -1 for z in Z]):3.0%} | "
                f"after 5m {a('r5'):+.2f} 15m {a('r15'):+.2f} 30m {a('r30'):+.2f} 60m {a('r60'):+.2f} | best/worst 15m {a('mfe15'):+.2f}/{a('mae15'):+.2f} "
                f"30m {a('mfe30'):+.2f}/{a('mae30'):+.2f}{cap}")
    print(f"{lab}\n   days 1-6  {f([x for x in T if x['day'] < half])}\n   days 7-11 {f([x for x in T if x['day'] >= half])}\n   all       {f(T)}")
row("B + volume + buyers, NO queue", run(S, True, "+BUYERS", n=N)) if False else None
print("price moves in % from the buy price (gross, no cost)\n")
row("RANDOM minute, same stocks (baseline)", base)
row(f"A signal ({N} higher closes)", run(S, False, "SIGNAL", n=N))
row("B signal (+ above yesterday's close)", run(S, True, "SIGNAL", n=N))
row("B + volume + buyers", run(S, True, "+BUYERS", n=N))
row("B + volume", run(S, True, "+VOL", n=N))
row("B full rule (+ queue)", F := run(S, True, "+QUEUE", n=N))
w = [x for x in F if x["mfe30"] >= 1.5]
print(f"\nfull rule: {len(w)} of {len(F)} trades rose >= +1.5% within 30 min; C3 result on those: {np.mean([x['pl'] for x in w]):+.2f}% after cost, "
      f"exits: { {k: sum(x['why'] == k for x in w) for k in set(x['why'] for x in w)} }")
l = [x for x in F if x["mfe30"] < 0.5]
print(f"full rule: {len(l)} of {len(F)} trades never rose +0.5% in 30 min (entry problem); C3 result on those {np.mean([x['pl'] for x in l]):+.2f}%")
