"""
s7_study.py -- [2026-10-22] S7 (stretched above VWAP) deep study, the user: "go deeper on S7". v2 already buys only at
0..+2% over VWAP; the question: inside that band, WHEN is the distance to VWAP a stretch (noise moment, buying the top)?
2 years, real v2 bar replay (every signal, BASE rules). At every buy, VWAP described in several ways:
  vwap %           plain % over VWAP (v2's own number)
  in daily ATRs    vwap % / daily ATR %                  (TAL 10/12: +2% = 0.7 ATR for a calm stock)
  in 1-min ranges  (price - VWAP) / mean 1-min range of the last 15 bars (the stock's own noise right now)
  VWAP slope       VWAP change over the last 15 / 30 min (%): rising VWAP = the trend carries it
  time above VWAP  minutes since the price was last at/under VWAP (fresh reclaim vs long ride)
  run from VWAP    the move since the last VWAP touch (%)
  ATR % and time of day for splits
OUTCOME: the trade P/L (0.2% cost), back to VWAP within 30 min (low <= VWAP at the buy), best/worst 60 min.
    nice -n 19 python3 s7_study.py   -> s7_study.jsonl + s7_study.log
"""
import gzip
import json
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R  # noqa: E402

OUT = HERE / "s7_study.jsonl"; SPLIT = "2025-10-01"
CTX = {}
_orig = R.entry_v2.evaluate


def feat(view, ref, metrics):
    done = view[:-1]
    if len(done) < 31:
        return None
    pv = cv = 0.0; vw = []
    for b in done:
        pv += (b["h"] + b["l"] + b["c"]) / 3 * b["v"]; cv += b["v"]; vw.append(pv / cv if cv else b["c"])
    P = done[-1]["c"]; V = vw[-1]
    r1 = sum(b["h"] - b["l"] for b in done[-15:]) / 15
    atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else None
    k = next((i for i in range(len(done) - 1, -1, -1) if done[i]["l"] <= vw[i]), None)
    vp = metrics.get("vwap_pct", (P / V - 1) * 100)
    return {"vwap": vp, "atr": atrp, "vwap_atr": vp / atrp if atrp else None, "vwap_r1": (P - V) / r1 if r1 > 0 else None,
            "slope15": (V / vw[-16] - 1) * 100, "slope30": (V / vw[-31] - 1) * 100,
            "above_min": (len(done) - 1 - k) if k is not None else len(done), "run": (P / done[k]["l"] - 1) * 100 if k is not None else None,
            "m": len(done) - 1, "vwap_px": V}


def wrapped(sym, view, ref, f15, pers, as_of=None, cfg=None, quote=None):
    d = _orig(sym, view, ref, f15, pers, as_of=as_of, cfg=cfg, quote=quote)
    if d.should_enter:
        try:
            CTX["sig"][R.minute(as_of) - 1] = feat(view, ref, d.metrics)
        except Exception:
            pass
    return d


R.entry_v2.evaluate = wrapped


def run():
    cfg = R.get_config(); ecfg = {**(cfg.get("entry_v2") or {}), "confirm_checks": 1}; xcfg = {**(cfg.get("exit_v2") or {}), "enabled": True}
    with open(OUT, "w") as out:
        for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
            day = p.name[5:15]
            if day > "2026-10-02":
                continue
            d = json.load(gzip.open(p, "rt")); bench = R.bench_pct(day); k = 0
            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:
                    continue
                flow = json.loads(fp.read_text()); CTX["sig"] = {}
                bars = [b for b in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(b["t"]) < 390]
                by = {R.minute(b["t"]): b for b in bars}
                for t in R.run_stock(day, s, d["symbols"][s]["bars"], flow, ref, bench, ecfg, xcfg):
                    f = CTX["sig"].get(t["buy_m"] - 1)
                    if not f:
                        continue
                    bm, bp = t["buy_m"], t["buy"]
                    a30 = [by[j] for j in range(bm, bm + 30) if j in by]; a60 = [by[j] for j in range(bm, bm + 60) if j in by]
                    out.write(json.dumps({"day": day, "sym": s, "buy_m": bm, "pl": t["pl"] + R.COST - 0.2, "why": t["why"], **f,
                                          "back30": bool(a30) and min(b["l"] for b in a30) <= f["vwap_px"],
                                          "max60": (max(b["h"] for b in a60) / bp - 1) * 100 if a60 else None,
                                          "min60": (min(b["l"] for b in a60) / bp - 1) * 100 if a60 else None}) + "\n"); k += 1
            R.REF._CACHE.clear(); del d
            print(day, k, flush=True)
    report()


def report():
    T = [json.loads(l) for l in open(OUT)]
    def line(lab, X):
        if len(X) < 15:
            print(f"   {lab:40} {len(X):5}"); return
        p = np.array([t["pl"] for t in X]); y = np.array([t["day"] < SPLIT for t in X])
        print(f"   {lab:40} {len(p):5} {p.mean():+7.3f}% win {np.mean(p > 0):4.0%} | y1 {p[y].mean() if y.any() else 0:+7.3f} y2 {p[~y].mean() if (~y).any() else 0:+7.3f} "
              f"| back to VWAP in 30m {np.mean([t['back30'] for t in X]):4.0%} | stop {np.mean([t['why'] == 'stop' for t in X]):4.0%}")
    print(f"\n2 years, v2 bar replay, every signal, P/L after 0.2% cost | buys, per trade, win, year 1, year 2, came back to VWAP within 30 min, stopped out")
    line("ALL base buys", T)
    def split(lab, key, cuts, X=None):
        X = [t for t in (X if X is not None else T) if t.get(key) is not None]
        print(f"  {lab}:")
        for lo, hi in zip(cuts, cuts[1:]):
            line(f"   {lo:g}..{hi:g}", [t for t in X if lo <= t[key] < hi])
    split("over VWAP %", "vwap", [0, 0.5, 1, 1.5, 2.01])
    split("over VWAP in daily ATRs", "vwap_atr", [0, 0.05, 0.1, 0.15, 0.2, 0.3, 9])
    split("over VWAP in 1-min ranges (the stock's own noise)", "vwap_r1", [0, 1, 2, 3, 4, 6, 99])
    split("VWAP slope 15 min %", "slope15", [-9, 0, 0.1, 0.25, 0.5, 9])
    split("VWAP slope 30 min %", "slope30", [-9, 0, 0.2, 0.5, 1, 9])
    split("minutes above VWAP (since the last touch)", "above_min", [0, 5, 15, 30, 60, 120, 999])
    split("run since the last VWAP touch %", "run", [0, 1, 2, 3, 5, 99])
    for a, b in ((0, 6), (6, 9), (9, 999)):
        split(f"ATR {a}-{b}%: over VWAP in 1-min ranges", "vwap_r1", [0, 2, 4, 99], [t for t in T if t["atr"] and a <= t["atr"] < b])
    print("S7STUDY_DONE")


if __name__ == "__main__":
    if "--report" in sys.argv:
        report()
    else:
        run()
