"""MRV09 — CCI Reversion
HYPOTHESIS: CCI(20) < -100 signals oversold -> go LONG. Exit when CCI > 0 (mean reversion).
Trend gate: only buy when price is above 200-day SMA (long-term uptrend confirmation).

CCI (Commodity Channel Index) = (TypicalPrice - SMA(TP, n)) / (0.015 * MeanAbsDev(TP, n))
Extreme readings (<-100) indicate oversold conditions; reversal expected.

CAUSAL: CCI at bar i uses data up to and including close[i].
Entry at close[i] when CCI[i] < -100 (AND trend gate: close[i] > SMA200[i]).
Exit at close[i] when CCI[i] > 0.
SL: ATR-based (entry - 2*ATR) to limit downside.
max_bars: cap position holding time.

Small grid: (cci_period, max_bars) -> 4 configs, 1d only.
"""

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


def cci(df: pd.DataFrame, period: int = 20) -> np.ndarray:
    """Commodity Channel Index (causal).
    CCI = (TP - SMA(TP, n)) / (0.015 * MeanAbsDev(TP, n))
    where TP = (high + low + close) / 3
    """
    h = df["high"].values.astype(float)
    l = df["low"].values.astype(float)
    c = df["close"].values.astype(float)
    tp = (h + l + c) / 3.0
    n = len(tp)
    cci_vals = np.full(n, np.nan)
    for i in range(period - 1, n):
        window = tp[i - period + 1:i + 1]
        m = np.mean(window)
        mad = np.mean(np.abs(window - m))
        if mad > 0:
            cci_vals[i] = (tp[i] - m) / (0.015 * mad)
        else:
            cci_vals[i] = 0.0
    return cci_vals


def make_entries(df, cci_period=20, sma_period=200, sl_atr_mult=2.0, max_bars=10, use_trend_gate=True):
    """
    Entry: CCI[i] < -100 (oversold), optionally gated by close > SMA200 (uptrend).
    Exit: CCI[i] > 0 (mean reversion complete), or SL or max_bars.
    All causal: uses data up to and including close[i].
    """
    c = df["close"].values.astype(float)
    n = len(df)

    # CCI (causal, computed above)
    cci_vals = cci(df, cci_period)

    # SMA200 for trend gate
    sma200 = al.sma(c, sma_period)

    # ATR for SL
    atr_vals = al.atr(df, win=14)

    entries = [None] * n

    for i in range(sma_period, n):
        ci = cci_vals[i]
        if np.isnan(ci):
            continue

        # Trend gate: only long when price is above long-term SMA
        if use_trend_gate and (np.isnan(sma200[i]) or c[i] <= sma200[i]):
            continue

        # Oversold condition
        if ci >= -100.0:
            continue

        # Entry at close[i], long
        entry_px = c[i]
        sl_px = entry_px - sl_atr_mult * atr_vals[i]

        # Sanity check: SL must be below entry
        if sl_px >= entry_px:
            continue

        entries[i] = {"dir": +1, "tp": None, "sl": sl_px, "max_bars": max_bars}

    return entries


# -----------------------------------------------------------------------
# Grid: small (4 configs total, 1d only -> 4 * 2 assets = 8 backtests)
# -----------------------------------------------------------------------
CONFIGS = [
    # (cci_period, sma_period, sl_atr_mult, max_bars, use_trend_gate, label)
    (20, 200, 2.0, 10, True,  "cci20_sma200_sl2atr_10d"),
    (20, 200, 2.0, 20, True,  "cci20_sma200_sl2atr_20d"),
    (14, 200, 1.5, 10, True,  "cci14_sma200_sl1.5atr_10d"),
    (20, 200, 2.0, 10, False, "cci20_nosma_sl2atr_10d"),   # no trend gate control
]

best_rep = None
best_min_hold = -999.0

for cci_period, sma_period, sl_atr_mult, max_bars, use_trend_gate, label in CONFIGS:
    name = f"MRV09-{label}"

    def make_fn(cp=cci_period, sp=sma_period, sa=sl_atr_mult, mb=max_bars, utg=use_trend_gate):
        return lambda df: make_entries(df, cci_period=cp, sma_period=sp,
                                       sl_atr_mult=sa, max_bars=mb, use_trend_gate=utg)

    rep = al.study_signals(name, make_fn(), tfs=("1d",))

    v = rep["verdict"]
    min_hold = v.get("best_holdout_sharpe", -999)
    print(f"\n--- Config: {label} ---")
    print(al.fmt(rep))
    print("JSON:", al.as_json(rep))

    if min_hold > best_min_hold:
        best_min_hold = min_hold
        best_rep = rep

print("\n\n=== BEST CONFIG ===")
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
