"""python3 -I fun.py DATA_DIR SYMBOL : $10,000 curves, drawdowns, the luckiest monkey, crash windows and the yearly race."""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
D, SYM = sys.argv[1], sys.argv[2]; sys.argv = ["monkey.py", D, "0.001"]
import numpy as np, pandas as pd, monkey as M
R = M.run(SYM); o, idx, i0, F = R["_o"], R["_idx"], R["_i0"], M.FEE
def curve(a, b):   # marked at each bar's open, $10,000 at the window's start
    e = np.full(len(o), np.nan); cash = 10000.0; last = i0
    for x, y in zip(a, b):
        e[last:x + 1] = cash; u = cash * (1 - F) / o[x]; e[x:y] = u * o[x:y]; cash = u * o[y] * (1 - F); last = y
    e[last:] = cash; return e[i0:]
mdd = lambda e: float(np.min(e / np.maximum.accumulate(e) - 1))
ix = idx[i0:]; C = {}
print(f"== {SYM} $10,000 from {ix[0].date()} (fees 0.1%/side)")
for n, r in R["res"].items():
    e = curve(*r["_tr"]); C[n] = e; mk = r["_mk"]
    print(f"{n:30s} -> ${e[-1]:>10,.0f}  maxDD {mdd(e):+.0%}  monkeys beating it {int((mk > e[-1] / 1e4).sum()):4d}/1000  luckiest x{mk.max():6.1f} (${mk.max() * 1e4:>11,.0f})  unluckiest x{mk.min():.2f}")
bh = 10000 * o[i0:] / o[i0] * (1 - F) ** 2; C["Buy & hold"] = bh; print(f"{'Buy & hold':30s} -> ${bh[-1]:>10,.0f}  maxDD {mdd(10000 * o[i0:] / o[i0]):+.0%}")
r = C["RSI under 30 / over 70"]; below = np.where(r < 10000)[0]
print("RSI first below $10k:", ix[below[0]], "| ever back to $10k after that:", bool((r[below[0]:] >= 10000).any()), "| low $%.0f on %s | best after first dip $%.0f on %s" % (r.min(), ix[r.argmin()], r[below[0]:].max(), ix[below[0] + r[below[0]:].argmax()]))
for w, (a, b) in {"COVID": ("2020-03-08", "2020-03-14"), "LUNA": ("2022-05-05", "2022-05-13"), "FTX": ("2022-11-06", "2022-11-10"), "Aug 2024": ("2024-08-01", "2024-08-06")}.items():
    m = (ix >= a) & (ix < b); s = f"{w:9s} BTC {o[i0:][m].min() / o[i0:][m][0] - 1:+.0%} | "
    for n, e in C.items():
        if n == "Buy & hold": continue
        s += f"{n.split()[0]} {e[m].min() / e[m][0] - 1:+.0%}  "
    print(s)
yrs = [f"{y}-01-01" for y in range(2019, 2027)]
print("race (on 1 Jan, $k):", "  ".join(y[:4] for y in yrs), " end")
for n, e in C.items(): print(f"  {n:30s}", "  ".join(f"{e[ix.searchsorted(pd.Timestamp(y))] / 1000:6.1f}" for y in yrs), f"{e[-1] / 1000:7.1f}")
