"""RSK05 — Chandelier-Exit Trend Strategy.

Idea: Go long when price crosses above an EMA (or breaks out). Exit via a chandelier
ATR stop (trailing stop set as highest-high minus N*ATR). When stopped out, go flat
(no shorting). Optionally apply vol-targeting for position sizing.

The chandelier stop is updated each bar using the rolling highest-high minus atr_mult * ATR.
Entry: EMA(fast) crosses above EMA(slow) (or close > EMA).
Exit (flat): close drops below chandelier stop.

Grid (<=4 param sets, total backtests = 4 configs x 2 TFs x 2 assets = 16, but we pick
best config from 2 TFs x 2 assets = manageable):
  Config A: fast=20, slow=50, atr_win=22, atr_mult=3.0 (classic chandelier)
  Config B: fast=10, slow=30, atr_win=14, atr_mult=2.5
  Config C: fast=50, slow=200, atr_win=22, atr_mult=3.0 (long-trend)
  Config D: fast=20, slow=50, atr_win=14, atr_mult=2.0 (tighter stop)
"""

import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np


def chandelier_trend(df, fast=20, slow=50, atr_win=22, atr_mult=3.0, vol_tgt=True):
    """
    Continuous-position chandelier trend following strategy.

    - Long signal: EMA(fast) > EMA(slow) (trend is up)
    - Chandelier stop: rolling(high, atr_win).max() - atr_mult * ATR(atr_win)
    - Position: +1 if in trend AND close > chandelier_stop, else 0
    - Vol-target: scale position to target 20% annualized vol, cap 2x

    All causal: everything uses data up to and including close[i].
    """
    c = df["close"].values.astype(float)
    h = df["high"].values.astype(float)
    n = len(c)

    # EMA crossover
    ema_fast = al.ema(c, fast)
    ema_slow = al.ema(c, slow)
    trend_up = (ema_fast > ema_slow).astype(float)  # 1 = bullish regime

    # ATR (causal EWM)
    atr_vals = al.atr(df, win=atr_win)

    # Chandelier stop: highest HIGH over atr_win bars (causal rolling, no shift needed
    # because we compare close[i] which was not used to compute max(high[i-atr_win:i]))
    # Actually high[i] is part of bar i. We need max of highs up to bar i (inclusive).
    # The close[i] is what we use for decision; chandelier is based on high (not close).
    # Using max including bar i's high is causal since close[i] comes after open/high/low
    # of bar i (and the bar has already completed when we decide at close[i]).
    highest_high = (
        df["high"]
        .rolling(atr_win, min_periods=max(2, atr_win // 2))
        .max()
        .values
    )
    chandelier_stop = highest_high - atr_mult * atr_vals

    # Position: long only if in trend AND close above chandelier stop
    raw_pos = np.where((trend_up > 0) & (c > chandelier_stop), 1.0, 0.0)

    # Fill NaN periods (warm-up) with 0
    raw_pos = np.nan_to_num(raw_pos, nan=0.0)

    if vol_tgt:
        return al.vol_target(raw_pos, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)
    else:
        return raw_pos


# Grid: 4 configs
CONFIGS = [
    dict(fast=20, slow=50,  atr_win=22, atr_mult=3.0, label="A:f20s50a22m3.0"),
    dict(fast=10, slow=30,  atr_win=14, atr_mult=2.5, label="B:f10s30a14m2.5"),
    dict(fast=50, slow=200, atr_win=22, atr_mult=3.0, label="C:f50s200a22m3.0"),
    dict(fast=20, slow=50,  atr_win=14, atr_mult=2.0, label="D:f20s50a14m2.0"),
]

# Run each config on 1d and 12h (2 TFs), pick best by min_asset_holdout_sharpe
best_rep = None
best_hold = -999.0
best_label = ""

for cfg in CONFIGS:
    label = cfg["label"]
    fast = cfg["fast"]
    slow = cfg["slow"]
    atr_win = cfg["atr_win"]
    atr_mult = cfg["atr_mult"]

    def make_target(fast=fast, slow=slow, atr_win=atr_win, atr_mult=atr_mult):
        def target_fn(df):
            return chandelier_trend(df, fast=fast, slow=slow,
                                    atr_win=atr_win, atr_mult=atr_mult, vol_tgt=True)
        return target_fn

    rep = al.study_weights(
        f"RSK05-{label}",
        make_target(),
        tfs=("1d", "12h"),
    )

    v = rep["verdict"]
    hold_sh = v.get("best_holdout_sharpe", -999.0)
    print(f"Config {label}: grade={v['grade']} best_tf={v['best_tf']} "
          f"full={v.get('best_full_sharpe')} hold={hold_sh}")

    if hold_sh > best_hold:
        best_hold = hold_sh
        best_rep = rep
        best_label = label

print(f"\nBest config: {best_label} (hold={best_hold:.3f})")
print()
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
