"""MRV11 — Bollinger %b Reversion
HYPOTHESIS: Bollinger %b = position of close within Bollinger Bands.
  %b = (close - lower) / (upper - lower)
  Entry logic: go long when %b < threshold_low (deeply oversold), exit at 0.5 (middle band),
  with SMA200 trend filter (only long when close < SMA200, i.e., in downtrend/mean-reversion regime).

Style: continuous weights (al.study_weights).
Small grid: 2 BB params x 2 thresholds = 4 configs, tested on 2 TFs = max 6 (pick best by hold-out).
"""
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 make_target(bb_win: int, bb_k: float, entry_pctb: float, trend_win: int = 200):
    """
    Bollinger %b reversion target function.

    - Compute %b = (close - lower) / (upper - lower)
    - Long signal when %b < entry_pctb (close near/below lower band) AND close < SMA(trend_win)
    - Position scales linearly from max at %b=0 to 0 at %b=0.5 (exit threshold)
    - Vol-targeted to 20% annualized, leverage capped at 2x
    - All decisions use data <= close[i] (causal)

    Args:
        bb_win: Bollinger Band window (20 or 30)
        bb_k: Bollinger Band width in std devs (2.0)
        entry_pctb: %b threshold to enter long (0.05 or 0.10)
        trend_win: SMA window for trend filter (200 bars)
    """
    def _target(df: pd.DataFrame) -> np.ndarray:
        c = df["close"].values.astype(float)
        n = len(c)

        # Bollinger Bands (causal: uses data up to i)
        upper, mid, lower = al.bbands(c, win=bb_win, k=bb_k)

        # %b = (close - lower) / (upper - lower)
        band_width = upper - lower
        # Avoid division by zero when bands collapse
        pctb = np.where(band_width > 1e-10, (c - lower) / band_width, 0.5)

        # Trend filter: SMA200 (only enter when we're in a range/downtrend context)
        trend_sma = al.sma(c, trend_win)
        # below_trend: close < SMA200 (mean-reversion opportunity more likely)
        below_trend = c < trend_sma  # boolean array, causal

        # Continuous position signal:
        # - When %b < entry_pctb AND below SMA200: long with weight proportional to how
        #   deep we are (1 - %b/0.5 mapped to [0,1])
        # - When %b >= 0.5: flat (exit)
        # - Linearly scale between entry_pctb and 0.5

        # Compute raw direction:
        # Full strength at pctb=0, zero at pctb=0.5
        # Clamp: below entry_pctb -> scale from 0 to 1 relative to entry zone
        raw_long = np.where(
            (pctb < 0.5) & below_trend,
            np.clip((0.5 - pctb) / 0.5, 0.0, 1.0),  # linear fade: 1 at pctb=0, 0 at pctb=0.5
            0.0
        )

        # Apply NaN mask for warmup period
        warmup = max(bb_win, trend_win)
        raw_long[:warmup] = 0.0

        # Vol-target to 20% annualized, cap 2x leverage
        return al.vol_target(raw_long, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)

    return _target


# ── Grid: 4 configs (bb_win x entry_pctb) ─────────────────────────────────────
CONFIGS = [
    dict(bb_win=20, bb_k=2.0, entry_pctb=0.05, label="BB20k2-p05"),
    dict(bb_win=20, bb_k=2.0, entry_pctb=0.10, label="BB20k2-p10"),
    dict(bb_win=30, bb_k=2.0, entry_pctb=0.05, label="BB30k2-p05"),
    dict(bb_win=30, bb_k=2.0, entry_pctb=0.10, label="BB30k2-p10"),
]

# Run all configs at 1d (the hypothesis is cleaner at daily; 4 configs x 1 TF = 4 backtests)
# Also run best config at 12h (total = 4+2 = 6 max)
print("=== MRV11: Bollinger %b Reversion - Grid Search ===\n")

results = []
for cfg in CONFIGS:
    fn = make_target(cfg["bb_win"], cfg["bb_k"], cfg["entry_pctb"])
    rep = al.study_weights(
        f"MRV11-{cfg['label']}",
        fn,
        tfs=("1d",)
    )
    results.append((cfg, rep))
    v = rep["verdict"]
    cell_1d = rep["cells"][0]
    print(f"{cfg['label']:20s}: minFull={cell_1d['min_asset_full_sharpe']:+.3f}  "
          f"minHold={cell_1d['min_asset_holdout_sharpe']:+.3f}  "
          f"feeOK={cell_1d['fee_survives']}  grade={v['grade']}")

print()

# Pick best config by hold-out Sharpe at 1d
best_cfg, best_rep = max(results, key=lambda x: x[1]["cells"][0]["min_asset_holdout_sharpe"])
print(f"Best config: {best_cfg['label']}")
print()

# Run best config also on 12h
best_fn = make_target(best_cfg["bb_win"], best_cfg["bb_k"], best_cfg["entry_pctb"])
final_rep = al.study_weights(
    f"MRV11-{best_cfg['label']}",
    best_fn,
    tfs=("1d", "12h")
)

print(al.fmt(final_rep))
print()
print("JSON:", al.as_json(final_rep))
