"""
double_bottom_study.py -- [2026-10-06] The user's W entry (RGNX 10/5): "the first V is the support, the
second V is the proof" -- buy as price turns up from a second low that holds the first low.
On every 9:30 top-30 stock-day of the 2-year library (1-minute bars):
  V1      a swing low (lowest low so far of the move) followed by a bounce >= BOUNCE % (close basis)
  V2      a later pullback whose low is within [V1 - UNDER %, V1 + OVER %] -- support held
  TRIGGER the first close above the previous bar's high after V2 (the turn) -> buy at the next minute's open
  STOP    V1 low - 0.1% (structure stop); measured: +2% before the stop / +1R / +2R before the stop
          within 60 min, and the result held to 15:55; 0.1% cost
  BASE    random buys at the same minute on other stocks of the same day (the luck level)
Variants: bounce 1 / 2 %, V2 tolerance (higher low only / equal +-0.3% / up to 1.5% above), V2 by 10:30 or
any time before 15:00, V2 volume lower than V1's (classic) or not.
    python3 double_bottom_study.py
"""
import gzip
import glob
import json
import random
import sys

import numpy as np

sys.path.insert(0, "/var/www/screener/trade/reports/playbook")
import lib_v2 as L2

COST = 0.1
random.seed(1)


def load():
    days = []
    for p in sorted(glob.glob("/var/www/screener/trade/reports/open_window/bars/bars_20*.json.gz")):
        d = json.load(gzip.open(p, "rt"))
        stocks = {}
        for s in d["top30_current"]:
            if s not in d["symbols"]:
                continue
            by = L2._minutes(d["symbols"][s]["bars"])
            if len(by) < 300:
                continue
            O, H, L, C, V = (np.zeros(390) for _ in range(5))
            last = by[min(by)][4]
            for m in range(390):
                b = by.get(m)
                if b:
                    O[m], H[m], L[m], C[m], V[m] = b[1], b[2], b[3], b[4], b[5]; last = b[4]
                else:
                    O[m] = H[m] = L[m] = C[m] = last
            stocks[s] = (O, H, L, C, V)
        days.append((d["date"], stocks))
    return days


def outcome(a, m, stop):
    O, H, L, C, V = a
    e = O[m]
    if stop >= e:
        return None
    R = e - stop
    hit = {"p2": None, "r1": None, "r2": None}
    pl = {}
    for tgt_r in (1, 2):
        res = None
        for k in range(m, min(m + 60, 386)):
            if L[k] <= stop:
                res = (min(stop, O[k]) / e - 1) * 100; break
            if H[k] >= e + tgt_r * R:
                res = (max(e + tgt_r * R, O[k]) / e - 1) * 100; break
        if res is None:
            res = (C[min(m + 59, 385)] / e - 1) * 100
        pl[f"pl{tgt_r}R"] = res - COST
    for k in range(m, min(m + 60, 386)):
        if L[k] <= stop:
            break
        for key, tgt in (("p2", e * 1.02), ("r1", e + R), ("r2", e + 2 * R)):
            if hit[key] is None and H[k] >= tgt:
                hit[key] = k
    return {"p2": hit["p2"] is not None, "r1": hit["r1"] is not None, "r2": hit["r2"] is not None,
            "close": (C[385] / e - 1) * 100 - COST, "risk": R / e * 100, **pl}


def signals(a, bounce, under, over, last_v2, vol_rule):
    O, H, L, C, V = a
    out, m = [], 1
    while m < last_v2:
        # V1: the lowest low so far from where we search, confirmed by a bounce of >= bounce %
        lo_m = m
        k = m
        v1 = None
        while k < last_v2:
            if L[k] < L[lo_m]:
                lo_m = k
            if C[k] >= L[lo_m] * (1 + bounce / 100):
                v1 = lo_m
                break
            k += 1
        if v1 is None:
            break
        # V2: after the bounce, price comes back down near V1 and holds
        j, v2 = k + 1, None
        peak = max(H[v1:k + 1])
        while j < last_v2:
            if L[j] < L[v1] * (1 - under / 100):
                break                                        # support broken: start over from here
            if L[j] <= L[v1] * (1 + over / 100) and L[j] < peak * (1 - bounce / 200):
                v2 = j
                # extend V2 to the lowest bar of this pullback (until the first turn-up)
                while j + 1 < last_v2 and L[j + 1] <= L[v2] and L[j + 1] >= L[v1] * (1 - under / 100):
                    j += 1; v2 = j
                break
            peak = max(peak, H[j]); j += 1
        if v2 is None:
            m = j + 1
            continue
        if vol_rule and V[max(v2 - 1, 0):v2 + 2].sum() >= V[max(v1 - 1, 0):v1 + 2].sum():
            m = v2 + 1
            continue
        # TRIGGER: first close above the previous bar's high after V2 (low not broken meanwhile)
        t = None
        for q in range(v2 + 1, min(v2 + 15, 384)):
            if L[q] < L[v1] * (1 - under / 100):
                break
            if C[q] > H[q - 1]:
                t = q
                break
        if t is not None:
            out.append((v1, v2, t + 1, L[v1] * 0.999))
            m = t + 30                                        # one signal per half hour
        else:
            m = v2 + 1
    return out


def main():
    days = load()
    print(f"{sum(len(s) for _, s in days)} stock-days, {len(days)} days", flush=True)
    variants = [(b, u, o, 60, False) for b in (1.0, 2.0, 3.0) for (u, o) in ((0.3, 0.3), (0.3, 1.5))]
    if "--all" in sys.argv:
        variants = [(b, u, o, lv, vr) for b in (1.0, 2.0) for (u, o) in ((0.0, 1.5), (0.3, 0.3), (0.3, 1.5))
                    for lv in (60, 330) for vr in (False, True)]
    half = "2025-10-01"
    for b, u, o, lv, vr in variants:
        S, B = [], []
        for day, stocks in days:
            syms = list(stocks)
            for s, a in stocks.items():
                for v1, v2, mb, stop in signals(a, b, u, o, lv, vr):
                    if mb > 345:
                        continue
                    r = outcome(a, mb, stop)
                    if r is None:
                        continue
                    r["y1"] = day < half
                    S.append(r)
                    # luck level: a random other stock at the same minute, same % risk
                    other = stocks[random.choice([x for x in syms if x != s] or [s])]
                    rb = outcome(other, mb, other[0][mb] * (1 - r["risk"] / 100))
                    if rb:
                        rb["y1"] = r["y1"]; B.append(rb)
        if not S:
            continue
        f = lambda X, k: np.mean([x[k] for x in X])
        y1 = [x for x in S if x["y1"]]; y2 = [x for x in S if not x["y1"]]
        print(f"bounce {b}% | V2 {-u:+.1f}..{o:+.1f}% of V1 | V2 by {'10:30' if lv == 60 else '15:00'} | "
              f"{'quieter V2' if vr else 'any volume'}: n {len(S):5} | +2% first {f(S, 'p2'):.0%} (random {f(B, 'p2'):.0%}) | "
              f"+1R {f(S, 'r1'):.0%} ({f(B, 'r1'):.0%}) | +2R {f(S, 'r2'):.0%} ({f(B, 'r2'):.0%}) | to close {f(S, 'close'):+.2f}% "
              f"(random {f(B, 'close'):+.2f}%) | y1/y2 +2% {f(y1, 'p2') if y1 else 0:.0%}/{f(y2, 'p2') if y2 else 0:.0%} | "
              f"risk {np.median([x['risk'] for x in S]):.2f}%", flush=True)
        print(f"      TRADE P/L (stop at V1, 60-min limit, 0.1% cost): target 1R {f(S, 'pl1R'):+.3f}%/trade (random {f(B, 'pl1R'):+.3f}%), "
              f"y1 {f(y1, 'pl1R'):+.3f} y2 {f(y2, 'pl1R'):+.3f} | target 2R {f(S, 'pl2R'):+.3f}% (random {f(B, 'pl2R'):+.3f}%), "
              f"y1 {f(y1, 'pl2R'):+.3f} y2 {f(y2, 'pl2R'):+.3f}", flush=True)


if __name__ == "__main__":
    main()
