import json, statistics as S, collections
from eng2 import *
from eng import donch
# risk off sub states, every basket-day that is risk off (30/15 donchian off)
rows = collections.defaultdict(lambda: collections.defaultdict(list))
for k in KEYS:
    ds, L = SERIES[k]; on = donch(L, 30, 15)
    for i in range(40, len(L) - 14):
        if on[i]: continue
        lo20 = min(L[i - 19:i + 1]); newlow5 = min(L[i - 4:i + 1]) <= lo20 * 1.0001
        up_at = max(L[i - 29:i + 1]) / L[i] - 1
        st = 'almost bullish (<=5% to turn)' if up_at <= 0.05 else ('falling (new 20d low in last 5d)' if newlow5 else 'basing (no new low 5d+)')
        f = L[i + 14] / L[i] - 1; turned = any(on[i + 1:i + 15])
        per = 'A' if ds[i] < SPLIT else 'B'
        rows[st][per].append((f, turned)); rows[st]['all'].append((f, turned))
print("89-91 risk off states: next 14 days median, % up, % that turned bullish within 14 days")
for st, v in rows.items():
    print(f"  {st:34s}", " | ".join(f"{p}: n{len(x)} med{S.median([a for a,_ in x])*100:+5.1f}% up{sum(1 for a,_ in x if a>0)/len(x)*100:3.0f}% turned{sum(1 for _,b in x if b)/len(x)*100:3.0f}%" for p, x in v.items()))
# entry feature ranking on v4 trades
ts = []
for k in KEYS: ts += run(k)
print("\n92-99 which BUY signals did best (v4 trades, split at median of each feature)")
for f in ('f_r30', 'f_r7', 'f_vol', 'f_btc7', 'f_up90', 'f_dd90', 'f_rsi', 'f_meme'):
    xs = [t for t in ts if t.get(f) is not None]
    m = S.median([t[f] for t in xs])
    for per, lo, hi in (('A', '', SPLIT), ('B', SPLIT, '9')):
        g = [t for t in xs if lo <= t['entry'] < hi]
        hiG = [t['ret'] for t in g if t[f] > m]; loG = [t['ret'] for t in g if t[f] <= m]
        def pf(z):
            p = sum(x for x in z if x > 0); n = -sum(x for x in z if x <= 0); return p / n if n else 9.9
        print(f"  {f:7s} {per} median {m:+.2f}: high n{len(hiG)} avg{S.mean(hiG)*100:+5.1f} pf{pf(hiG):4.2f} | low n{len(loG)} avg{S.mean(loG)*100:+5.1f} pf{pf(loG):4.2f}")
json.dump({st: {p: [len(x), S.median([a for a, _ in x]), sum(1 for a, _ in x if a > 0) / len(x), sum(1 for _, b in x if b) / len(x)] for p, x in v.items()} for st, v in rows.items()}, open('res_h.json', 'w'))
