"""
vwap_flow_entry_test.py -- [2026-10-13] EV3 = "entry version 3" (the user named it 10/16): the user's VWAP + buy-flow entry (test only):
  watch from 9:30; the close must be >= +1% over VWAP (no upper cap), but over +3% a BREAK-UP must be confirmed
  (the last 2 closes above the highest high of the 30 bars before them). Then either:
    PATH A  gradual rise + buying increasing: C[m] > C[m-3] > C[m-6], no spike bar (no bar in the last 3 with a range
            > 2x the average range of the 15 before), buy volume of the last 3 minutes > the 3 before, buy share of
            the last 3 minutes >= 50%
    PATH B  absorption then buyers: over bars m-3..m-1 sell volume > buy volume while the price did not fall vs the 3
            bars before (close m-1 >= close m-4 and no lower low), then bar m: buy > sell and buy volume above the
            absorption bars' average buy volume
  Buy at bar m's close. EXIT = the user's 1/4 GIVE-BACK: once the gain from the buy (peak high - buy) reaches the
  activation level (15 cents | 1%), sell when the price falls to peak - 1/4 of that gain. Before that, a volatility
  stop: 1/4 of the daily ATR below the buy, at least 1% (variant: a close under VWAP). 15:55 at the latest.
One position per stock at a time (re-entry after an exit allowed, 5-min pause). Real 0.2% round-trip cost.
Data: 2 years, daily top-30 lists with per-minute trade-by-trade buy/sell flow (reports/open_window/bars + flow).
    python3 vwap_flow_entry_test.py         -> vwap_flow_entry_test.log
"""
import gzip
import json
import sys
from collections import defaultdict
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
OW = HERE.parent / "open_window"
sys.path.insert(0, str(OW)); sys.path.insert(0, "/var/www/screener/trade")
from up2_styles_build import arrays  # noqa: E402
import reference as REF  # noqa: E402

COST, SPLIT = 0.2, "2025-10-01"
VARIANTS = {   # name: (start minute, give-back activation ("c", cents) | ("p", %), stop mode)
    "start 9:35 | act 15c | ATR stop": (5, ("c", 0.15), "atr"),
    "start 9:35 | act 1%  | ATR stop": (5, ("p", 1.0), "atr"),
    "start 9:45 | act 15c | ATR stop": (15, ("c", 0.15), "atr"),
    "start 9:45 | act 1%  | ATR stop": (15, ("p", 1.0), "atr"),
    "start 9:35 | act 15c | VWAP stop": (5, ("c", 0.15), "vwap"),
    "start 9:45 | act 1%  | VWAP stop": (15, ("p", 1.0), "vwap"),
}


def signals(O, H, L, C, V, bu, se, vw, start):
    """{minute: path} -- causal (bar m closed)."""
    out = {}
    rng = H - L
    for m in range(max(start, 9), 346):
        d = (C[m] / vw[m] - 1) * 100
        if d < 1.0:
            continue
        if d > 3.0:
            if m < 32:
                continue
            lvl = H[m - 31:m - 1].max()
            if not (C[m] > lvl and C[m - 1] > lvl):
                continue
        b3, b3p = bu[m - 2:m + 1].sum(), bu[m - 5:m - 2].sum()
        s3 = se[m - 2:m + 1].sum()
        avg_r = rng[max(0, m - 17):m - 2].mean() if m >= 4 else 0
        spike = avg_r > 0 and rng[m - 2:m + 1].max() > 2 * avg_r
        if (C[m] > C[m - 3] > C[m - 6] and not spike and b3 > b3p and b3 + s3 > 0 and b3 / (b3 + s3) >= 0.5):
            out[m] = "A"; continue
        ab_b, ab_s = bu[m - 3:m].sum(), se[m - 3:m].sum()
        if (ab_s > ab_b and C[m - 1] >= C[m - 4] and L[m - 3:m].min() >= L[m - 6:m - 3].min()
                and bu[m] > se[m] and bu[m] > bu[m - 3:m].mean()):
            out[m] = "B"
    return out


def trade(O, H, L, C, vw, m, act, stop_mode, atrp):
    e = C[m]
    stop = e * (1 - max(1.0, 0.25 * (atrp or 4.0)) / 100)
    peak = e
    for j in range(m + 1, 386):
        if stop_mode == "atr" and L[j] <= stop and peak - e < (act[1] if act[0] == "c" else e * act[1] / 100):
            return j, (min(stop, O[j]) / e - 1) * 100, "stop"
        if stop_mode == "vwap" and C[j] < vw[j] and peak - e < (act[1] if act[0] == "c" else e * act[1] / 100):
            return j, (C[j] / e - 1) * 100, "vwap"
        gain = peak - e
        need = act[1] if act[0] == "c" else e * act[1] / 100
        if gain >= need:
            floor = peak - 0.25 * gain
            if L[j] <= floor:
                return j, (min(floor, O[j]) / e - 1) * 100, "giveback"
        peak = max(peak, H[j])
    return 385, (C[385] / e - 1) * 100, "15:55"


def main():
    R = defaultdict(list)
    for p in sorted(OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        d = json.load(gzip.open(p, "rt"))
        for s in d["top30_current"]:
            fp = OW / "flow" / day / f"{s}.json"
            if s not in d["symbols"] or not fp.exists():
                continue
            a = arrays(d["symbols"][s]["bars"])
            if a is None:
                continue
            O, H, L, C, V = a
            fl = json.loads(fp.read_text()); bu, se = np.array(fl["buy"], float), np.array(fl["sell"], float)
            cv = np.cumsum(V); vw = np.cumsum((H + L + C) / 3 * V) / np.where(cv > 0, cv, np.nan)
            vw = np.where(np.isnan(vw), C, vw)
            ref = REF.load(day, s) or {}
            atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") and ref.get("prev_close") else None
            sig_cache = {}
            for name, (start, act, stop_mode) in VARIANTS.items():
                if start not in sig_cache:
                    sig_cache[start] = signals(O, H, L, C, V, bu, se, vw, start)
                sig = sig_cache[start]
                free = 0
                for m in sorted(sig):
                    if m < free:
                        continue
                    j, pl, why = trade(O, H, L, C, vw, m, act, stop_mode, atrp)
                    R[name].append((day, s, m, sig[m], pl - COST, why, (H[m + 1:386].max() / C[m] - 1) * 100 if m < 385 else 0,
                                    (atrp or 0) >= 8))
                    free = j + 5
        REF._CACHE.clear(); del d
        print(day, {k: len(v) for k, v in list(R.items())[:2]}, flush=True)
    json.dump({k: v for k, v in R.items()}, open(HERE / "vwap_flow_entry_trades.json", "w"))
    days = len({r[0] for v in R.values() for r in v})
    print(f"\n{days} days, daily top-30 lists, per trade after {COST}% cost (live v2 entries on the same data: -0.133%/trade)")
    for name, X in R.items():
        print(f"\n{name}")
        for lab, sel in (("ALL", lambda r: True), ("path A (rise + buying)", lambda r: r[3] == "A"),
                         ("path B (absorption)", lambda r: r[3] == "B"), ("ATR >= 8% stocks", lambda r: r[7])):
            Z = [r for r in X if sel(r)]
            if not Z:
                continue
            p = np.array([r[4] for r in Z]); y1 = np.array([r[0] < SPLIT for r in Z])
            why = defaultdict(int)
            for r in Z:
                why[r[5]] += 1
            print(f"  {lab:24} {len(Z):6} trades ({len(Z) / days:4.1f}/day) {p.mean():+.3f}%/trade win {np.mean(p > 0):.0%} | "
                  f"year 1 {p[y1].mean() if y1.any() else 0:+.3f}% year 2 {p[~y1].mean() if (~y1).any() else 0:+.3f}% | "
                  f"median best gain after {np.median([r[6] for r in Z]):.2f}% | exits " + ", ".join(f"{k} {v}" for k, v in sorted(why.items())))
    print("VWAP_FLOW_DONE")


if __name__ == "__main__":
    main()
