"""Lesson 2: draw the charts and run the 'which strategy fits which market' experiment."""
import os, json, numpy as np, pandas as pd, matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from markets import make_market
from strategies import *
OUT = os.path.dirname(os.path.abspath(__file__))
plt.rcParams.update({"figure.facecolor": "white", "axes.spines.top": False, "axes.spines.right": False, "font.size": 11})
sharpe = lambda x: x.mean() / x.std() * np.sqrt(252) if x.std() > 0 else 0.0

# ---------- Figure 1: Turtle on a trending market ----------
df = make_market("trend", 3, strength=1.5)
sig = turtle_signal(df)
hi, lo = df.High.rolling(20).max().shift(1), df.Low.rolling(10).min().shift(1)
a, b = 560, 960
d = df.iloc[a:b]
fig, ax = plt.subplots(figsize=(11, 4.8))
ax.plot(d.Close, color="#1f2937", lw=1.2, label="Close")
ax.plot(hi.iloc[a:b], color="#10b981", lw=1.2, label="Entry line: highest high of last 20 days")
ax.plot(lo.iloc[a:b], color="#dc2626", lw=1.2, label="Exit line: lowest low of last 10 days")
ch = sig.diff().fillna(0).iloc[a:b]
ax.scatter(d.index[ch > 0], d.Close[ch > 0], marker="^", s=90, color="#059669", zorder=5, label="Buy")
ax.scatter(d.index[ch < 0], d.Close[ch < 0], marker="v", s=90, color="#b91c1c", zorder=5, label="Sell")
ax.set_title("Turtle breakout: buy a new 20-day high, sell a new 10-day low"); ax.legend(frameon=False, loc="upper left", fontsize=9)
fig.tight_layout(); fig.savefig(f"{OUT}/1_turtle.png", dpi=140); plt.close()

# ---------- Figure 2: Bollinger on a mean-reverting market ----------
df2 = make_market("revert", 5)
s2, mid, up, lw_ = bollinger_signal(df2)
a, b = 300, 560; d = df2.iloc[a:b]
fig, ax = plt.subplots(figsize=(11, 4.8))
ax.fill_between(d.index, lw_.iloc[a:b], up.iloc[a:b], color="#93c5fd", alpha=.3, label="Band: average ± 2 standard deviations")
ax.plot(mid.iloc[a:b], color="#2563eb", lw=1, ls="--", label="20-day average (the target)")
ax.plot(d.Close, color="#1f2937", lw=1.2)
ch = s2.diff().fillna(0).iloc[a:b]; prev = s2.shift(1).fillna(0).iloc[a:b]
ent_l = (ch > 0) & (prev <= 0) & (s2.iloc[a:b] == 1); ent_s = (ch < 0) & (prev >= 0) & (s2.iloc[a:b] == -1)
ax.scatter(d.index[ent_l], d.Close[ent_l], marker="^", s=90, color="#059669", zorder=5, label="Buy (bounce off lower band)")
ax.scatter(d.index[ent_s], d.Close[ent_s], marker="v", s=90, color="#b91c1c", zorder=5, label="Short (roll over from upper band)")
ax.set_title("Bollinger Bands: bet that a stretched price snaps back to its average"); ax.legend(frameon=False, loc="upper left", fontsize=9, ncol=2)
fig.tight_layout(); fig.savefig(f"{OUT}/2_bollinger.png", dpi=140); plt.close()

# ---------- Figure 3: Dual Thrust, one illustrative day ----------
rng = np.random.default_rng(4)
open_, R, k1 = 100.0, 3.0, 0.5
buy, sell = open_ + k1 * R, open_ - k1 * R
steps = rng.normal(0, 0.18, 120)
steps[8:40] += 0.075                                   # a gentle push up, enough to reach the trigger
path = open_ + np.concatenate([[0], np.cumsum(steps)])
fig, ax = plt.subplots(figsize=(11, 4.6))
ax.plot(path, color="#1f2937", lw=1.4, label="Today's price")
ax.axhline(open_, color="#6b7280", ls=":", label="Today's open = 100")
ax.axhline(buy, color="#059669", ls="--", label=f"Buy trigger = open + 0.5 x range = {buy:.1f}")
ax.axhline(sell, color="#dc2626", ls="--", label=f"Sell trigger = open - 0.5 x range = {sell:.1f}")
cross = int(np.argmax(path >= buy))
ax.scatter([cross], [buy], s=120, color="#059669", zorder=5)
ax.annotate("price touches the trigger:\ngo long at about 101.5", (cross, buy), (cross + 8, buy - 2.2), arrowprops=dict(arrowstyle="->"), fontsize=10)
ax.set_ylim(sell - 1.5, max(path.max(), buy) + 1.5)
ax.set_xlabel("time during the day"); ax.set_title("Dual Thrust (illustration, with a range of 3.0): the day's own open sets the triggers")
ax.legend(frameon=False, loc="upper left", fontsize=9, bbox_to_anchor=(1.0, 1.0))
fig.tight_layout(); fig.savefig(f"{OUT}/3_dual_thrust.png", dpi=140, bbox_inches="tight"); plt.close()

# ---------- Experiment: average Sharpe by market type ----------
def run(kind, strength, M, base=1000):
    r = {"Turtle": [], "Bollinger": [], "Dual Thrust": [], "Buy & hold": []}
    for s in range(M):
        df = make_market(kind, base + s, strength=strength)
        r["Turtle"].append(sharpe(to_returns(turtle_signal(df), df.Close)))
        r["Bollinger"].append(sharpe(to_returns(bollinger_signal(df)[0], df.Close)))
        r["Dual Thrust"].append(sharpe(dual_thrust_returns(df)))
        r["Buy & hold"].append(sharpe(df.Close.pct_change().dropna()))
    return {k: (float(np.mean(v)), float(np.std(v) / np.sqrt(M)), float(np.mean(np.array(v) > 0))) for k, v in r.items()}

M = 120
main = {k: run(k, 1.0, M) for k in ["random", "trend", "revert"]}
json.dump(main, open(f"{OUT}/main.json", "w"), indent=1)
for k, v in main.items(): print(k, {n: round(x[0], 2) for n, x in v.items()})

names = ["Turtle", "Bollinger", "Dual Thrust", "Buy & hold"]; cols = ["#2563eb", "#d97706", "#7c3aed", "#9ca3af"]
fig, ax = plt.subplots(figsize=(11, 4.8)); w = 0.2
for i, n in enumerate(names):
    vals = [main[k][n][0] for k in ["trend", "random", "revert"]]; errs = [1.96 * main[k][n][1] for k in ["trend", "random", "revert"]]
    ax.bar(np.arange(3) + (i - 1.5) * w, vals, w, yerr=errs, color=cols[i], label=n, capsize=3)
ax.axhline(0, color="k", lw=.8); ax.set_xticks(range(3)); ax.set_xticklabels(["Trending market", "Random market (no edge)", "Mean-reverting market"])
ax.set_ylabel(f"Average Sharpe over {M} markets"); ax.set_title("No strategy wins everywhere: each needs its own kind of market"); ax.set_ylim(-1.25, 1.45); ax.legend(frameon=False, ncol=4, loc="upper left")
fig.tight_layout(); fig.savefig(f"{OUT}/4_regimes.png", dpi=140); plt.close()

# ---------- Sweep for the interactive slider: -2 (strongly reverting) .. 0 (random) .. +2 (strongly trending) ----------
sweep = {}
for s in [-2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2]:
    sweep[str(s)] = run("revert" if s < 0 else ("trend" if s > 0 else "random"), abs(s), 60, base=5000)
    print("sweep", s, {n: round(x[0], 2) for n, x in sweep[str(s)].items()}, flush=True)
json.dump(sweep, open(f"{OUT}/sweep.json", "w"))
