"""trend_time.py collect A..B OUT | analyze OUT.. -- [2026-10-29] user: "how long do we need to identify the stock trend?" For every library
stock-day (old-score top 30), at checkpoints T (minutes after 9:30) read the trend so far: UP = above the open AND above VWAP AND EMA9 > EMA20,
DOWN = below the open AND below VWAP AND EMA9 < EMA20, else MIXED; strength = move from the open in daily ATRs. Outcome from the next bar's open:
rest-of-day (to 15:55) direction, +2% vs -2% first, max rise / max drop to the close."""
import gzip, json, sys
from pathlib import Path
import numpy as np
TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR / "reports/playbook")); sys.path.insert(0, str(TR))
CK = [5, 10, 15, 30, 45, 60, 90, 120, 150]
if sys.argv[1] == "collect":
    import v2_bar_replay as R
    a, b_ = sys.argv[2].split(".."); out = open(sys.argv[3], "w")
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not (a <= day <= b_): continue
        d = json.load(gzip.open(p, "rt"))
        for s in d["top30_current"]:
            ref = R.REF.load(day, s)
            if s not in d["symbols"] or not ref or not ref.get("atr14"): continue
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(bars) < 300 or R.minute(bars[0]["t"]) != 0: continue
            M = [R.minute(x["t"]) for x in bars]; o = bars[0]["o"]
            e9 = e20 = bars[0]["c"]; cv = pv = 0; k = 0; end = max(j for j in range(len(bars)) if M[j] <= 385)
            for i, x in enumerate(bars):
                e9 += (x["c"] - e9) * 0.2; e20 += (x["c"] - e20) * 2 / 21; cv += x["v"]; pv += (x["h"] + x["l"] + x["c"]) / 3 * x["v"]
                while k < len(CK) and M[i] >= CK[k] - 1:
                    if M[i] == CK[k] - 1 or (i + 1 < len(bars) and M[i + 1] > CK[k] - 1):
                        c = x["c"]; vw = pv / cv
                        up = c > o and c > vw and e9 > e20; dn = c < o and c < vw and e9 < e20
                        P = bars[i + 1]["o"]; rest = bars[i + 1:end + 1]
                        f2 = 0
                        for z in rest:
                            if z["l"] <= P * 0.98: f2 = -1; break
                            if z["h"] >= P * 1.02: f2 = 1; break
                        out.write(json.dumps(dict(day=day, sym=s, T=CK[k], st="UP" if up else "DOWN" if dn else "MIXED", str=round((c - o) / ref["atr14"], 3),
                            rest=round((bars[end]["c"] / P - 1) * 100, 3), f2=f2, rise=round((max(z["h"] for z in rest) / P - 1) * 100, 3),
                            drop=round((min(z["l"] for z in rest) / P - 1) * 100, 3))) + "\n")
                    k += 1
        del d; R.REF._CACHE.clear(); out.flush()
    out.close(); print("TT_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    Y = lambda Z, h: [z for z in Z if (z["day"] < "2025-10-01") == (h == 1)]
    hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
    print("Trend so far at T -> rest of the day (from the next open to 15:55). year 1 < 2025-10-01 <= year 2.")
    print("CONT = the rest of the day goes the SAME way as the trend so far (UP: closes higher than the buy price; DOWN: closes lower).")
    print("EDGE = +2% first - -2% first (points) from that minute.\n")
    for T in CK:
        Z = [x for x in X if x["T"] == T]
        line = []
        for st in ("UP", "DOWN"):
            for h in (1, 2):
                g = [z for z in Y(Z, h) if z["st"] == st]
                cont = np.mean([(z["rest"] > 0) if st == "UP" else (z["rest"] < 0) for z in g]) * 100
                e = (np.mean([z["f2"] == 1 for z in g]) - np.mean([z["f2"] == -1 for z in g])) * 100
                line.append(f"{st} y{h} n{len(g):5} cont {cont:3.0f}% edge {e:+3.0f}")
        g_all = Y(Z, 1) + Y(Z, 2)
        base = (np.mean([z["f2"] == 1 for z in g_all]) - np.mean([z["f2"] == -1 for z in g_all])) * 100
        print(f"{hm(T)}  (all stocks edge {base:+3.0f}, up-to-close {np.mean([z['rest'] > 0 for z in g_all]) * 100:3.0f}%)\n   " + "\n   ".join(line))
    print("\nSTRONG trends only (UP and >= +1 daily ATR from the open | DOWN and <= -1 ATR):")
    for T in CK:
        Z = [x for x in X if x["T"] == T]; line = []
        for st, cond in (("UP", lambda z: z["st"] == "UP" and z["str"] >= 1), ("DOWN", lambda z: z["st"] == "DOWN" and z["str"] <= -1)):
            for h in (1, 2):
                g = [z for z in Y(Z, h) if cond(z)]
                if not g: line.append(f"{st} y{h} n0"); continue
                cont = np.mean([(z["rest"] > 0) if st == "UP" else (z["rest"] < 0) for z in g]) * 100
                e = (np.mean([z["f2"] == 1 for z in g]) - np.mean([z["f2"] == -1 for z in g])) * 100
                line.append(f"{st} y{h} n{len(g):4} cont {cont:3.0f}% edge {e:+3.0f}")
        print(f"{hm(T)}  " + " | ".join(line))
    print("TT_ANALYSIS_DONE")
