"""up3rise.py fmc DAY SYM | 12d | 2y -- [2026-10-27] the user: judge the ENTRY by HOW FAR THE PRICE RISES after the signal (the exit is a
separate job). Rule (no 'above yesterday's close'): dip >= 0.5% then 3 GREEN 1-min bars each closing higher + volume (3 bars >= 0.9x
the 5 before) + 3-min buy share ABOVE the 15-min (no cross needed) + BOTH INCREASING (UP1: vs 1 minute ago / UP3: vs 3 minutes ago);
with / without buy share >= 55%. Each signal measured alone from the buy price (next open), 15-min cooldown per stock, signals 9:35-15:15:
max rise within 30 / 60 min and to the close, % reaching +1/+2/+3% within 60 min, max drop within 30 min, +1% before -1%.
Baseline: a random minute (every 10th) on the same stock-days."""
import gzip, json, sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent; TR = Path("/var/www/screener/trade")
for p in (str(HERE), str(TR / "reports/playbook"), str(TR)): sys.path.insert(0, p)
def share(fb, fs, t, n):
    t = max(t, 0); B = sum(fb[max(0, t - n + 1):t + 1]); S_ = sum(fs[max(0, t - n + 1):t + 1]); return B / (B + S_) if B + S_ else 0.5
V = {"signal only: dip + 3 green + volume": ["VOL"], "OLD rule (prev close + volume + buyers)": ["PC", "VOL", "BUY"],
     "ABOVE: 3m > 15m + both up (1 min)": ["VOL", "ABOVE", "UP1"], "ABOVE + both up (1 min) + buyers >= 55%": ["VOL", "BUY", "ABOVE", "UP1"],
     "ABOVE: 3m > 15m + both up (3 min)": ["VOL", "ABOVE", "UP3"], "ABOVE + both up (3 min) + buyers >= 55%": ["VOL", "BUY", "ABOVE", "UP3"]}
def rise(b, bi, P):
    w30, w60 = b[bi:bi + 30], b[bi:bi + 60]; first = 0
    for x in b[bi:bi + 120]:
        if x["l"] <= P * 0.99: first = -1; break
        if x["h"] >= P * 1.01: first = 1; break
    r60 = (max(x["h"] for x in w60) / P - 1) * 100
    return dict(r30=(max(x["h"] for x in w30) / P - 1) * 100, r60=r60, reod=(max(x["h"] for x in b[bi:]) / P - 1) * 100,
                d30=(min(x["l"] for x in w30) / P - 1) * 100, first=first, P=P)
def scan(b, M, pc, fb, fs, need, bk=None):
    out = []; last = -99
    for i in range(9, len(b) - 1):
        t = M[i]
        if t < 5 or t > 345 or t - last < 15 or M[i] - M[i - 4] != 4 or (bk is not None and t not in bk): continue
        if not (b[i - 3]["c"] < b[i - 4]["c"] and all(b[k]["c"] > b[k - 1]["c"] and b[k]["c"] > b[k]["o"] for k in (i - 2, i - 1, i))): continue
        hi = max(x["c"] for x in b[max(0, i - 18):i - 2])
        if (1 - b[i - 3]["c"] / hi) * 100 < 0.5: continue
        s3, s15 = share(fb, fs, t, 3), share(fb, fs, t, 15)
        chk = {"PC": b[i]["c"] >= pc, "VOL": np.mean([x["v"] for x in b[i - 2:i + 1]]) >= 0.9 * np.mean([x["v"] for x in b[i - 7:i - 2]]),
               "BUY": s3 >= 0.55, "ABOVE": s3 > s15,
               "UP1": s3 > share(fb, fs, t - 1, 3) and s15 > share(fb, fs, t - 1, 15), "UP3": s3 > share(fb, fs, t - 3, 3) and s15 > share(fb, fs, t - 3, 15)}
        if bk is not None:
            q = [bk[k]["imbalance"] for k in (t - 2, t - 1, t) if k in bk]; chk["Q"] = bool(q) and np.mean(q) > 0
        if all(chk[k] for k in need):
            out.append(dict(t=t, **rise(b, i + 1, b[i + 1]["o"]))); last = t
    return out
def base(b, M):
    return [dict(t=M[i], **rise(b, i + 1, b[i + 1]["o"])) for i in range(len(b) - 1) if 5 <= M[i] <= 345 and M[i] % 10 == 0]
def f(Z):
    if not Z: return "n     0"
    a = lambda k: np.mean([z[k] for z in Z])
    return (f"n {len(Z):6} | max rise 30m {a('r30'):+.2f}% 60m {a('r60'):+.2f}% to close {a('reod'):+.2f}% | reached +1% {np.mean([z['r60'] >= 1 for z in Z]):3.0%} "
            f"+2% {np.mean([z['r60'] >= 2 for z in Z]):3.0%} +3% {np.mean([z['r60'] >= 3 for z in Z]):3.0%} (60m) | max drop 30m {a('d30'):+.2f}% | +1% before -1% {np.mean([z['first'] == 1 for z in Z]):3.0%} / {np.mean([z['first'] == -1 for z in Z]):3.0%}")
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
mode = sys.argv[1]
if mode == "fmc":
    import ev3
    from datetime import datetime
    from zoneinfo import ZoneInfo
    from config_loader import get_env
    from alpaca.data.requests import StockBarsRequest
    from alpaca.data.timeframe import TimeFrame
    from alpaca.data.historical import StockHistoricalDataClient
    ET = ZoneInfo("America/New_York"); env = get_env(); hc = StockHistoricalDataClient(env.api_key, env.secret_key)
    day, sym = sys.argv[2], sys.argv[3]; d0 = datetime.fromisoformat(day)
    raw = hc.get_stock_bars(StockBarsRequest(symbol_or_symbols=sym, timeframe=TimeFrame.Minute, start=d0.replace(hour=9, minute=30, tzinfo=ET), end=d0.replace(hour=16, tzinfo=ET))).data[sym]
    b = [{"t": x.timestamp, "o": x.open, "h": x.high, "l": x.low, "c": x.close, "v": x.volume} for x in raw if 0 <= ev3.minute_of(x.timestamp) < 390]
    ref = json.load(open(TR / f"data/reference/{day}/{sym}.json")); fl = json.loads((TR / f"reports/open_window/flow/{day}/{sym}.json").read_text())
    M = [ev3.minute_of(x["t"]) for x in b]
    for lab, need in V.items():
        T = scan(b, M, ref["prev_close"], fl["buy"], fl["sell"], need)
        print(f"{lab:42} -> " + (", ".join(f"buy {hm(x['t'] + 1)} {x['P']:.2f}: rose {x['r60']:+.1f}% in 60m (drop {x['d30']:+.1f}%)" for x in T) or "no signal"))
elif mode == "12d":
    import io, contextlib
    with contextlib.redirect_stdout(io.StringIO()):
        from up3_test import load, DAYS
    S = load(); half = DAYS[6]
    V12 = dict(V); V12.update({"ABOVE (1 min) + QUEUE": ["VOL", "ABOVE", "UP1", "Q"], "ABOVE (1 min) + buyers + QUEUE": ["VOL", "BUY", "ABOVE", "UP1", "Q"]})
    print(f"{len(S)} stock-days, {len(DAYS)} recorded days (live watch list) | rise after the signal, from the buy price (next open)")
    B = [dict(day=d, **x) for d, s, D, bk in S for x in base(D.b, D.m) if x["t"] in bk]
    print(f"RANDOM minute (baseline)\n   days 1-6  {f([x for x in B if x['day'] < half])}\n   days 7-{len(DAYS)} {f([x for x in B if x['day'] >= half])}")
    for lab, need in V12.items():
        T = [dict(day=d, **x) for d, s, D, bk in S for x in scan(D.b, D.m, D.ref["prev_close"], D.fl["buy"], D.fl["sell"], need, bk=bk)]
        print(f"{lab}\n   days 1-6  {f([x for x in T if x['day'] < half])}\n   days 7-{len(DAYS)} {f([x for x in T if x['day'] >= half])}")
else:
    import v2_bar_replay as R
    OUT = {k: [] for k in ["RANDOM minute (baseline)"] + list(V)}; n = 0
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not ("2024-10-01" <= day <= "2026-10-02"): continue
        d = json.load(gzip.open(p, "rt"))
        for s in d["top30_current"]:
            fp = R.OW / "flow" / day / f"{s}.json"; ref = R.REF.load(day, s)
            if s not in d["symbols"] or not fp.exists() or not ref or not ref.get("prev_close"): continue
            b = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(b) < 200: continue
            M = [R.minute(x["t"]) for x in b]; fl = json.loads(fp.read_text())
            OUT["RANDOM minute (baseline)"] += [dict(day=day, **x) for x in base(b, M)]
            for k, need in V.items():
                OUT[k] += [dict(day=day, **x) for x in scan(b, M, ref["prev_close"], fl["buy"], fl["sell"], need)]
        del d; R.REF._CACHE.clear(); n += 1
        if n % 50 == 0: print(day, n, flush=True)
    print(f"\n{n} days | rise after the signal, from the buy price (next open); year 1 = 2024-10..2025-09, year 2 = 2025-10..2026-10")
    for k, T in OUT.items():
        print(f"{k}\n   year 1 {f([x for x in T if x['day'] < '2025-10-01'])}\n   year 2 {f([x for x in T if x['day'] >= '2025-10-01'])}")
    print("UP3RISE_DONE")
