"""RSK09 — Target-vol + floor/cap + trend gate.

HYPOTHESIS: Long-flat TSMOM multi-horizon (like TP01), but with a hard exposure
floor=0.2 and cap=1.5 (instead of raw [0, leverage_cap]) when trend is UP,
and flat when trend is DOWN (same as TP01). The idea: smoother, more persistent
exposure when in-trend avoids whipsaw from momentary vol spikes reducing position
to near-zero, potentially improving risk-adjusted returns vs raw vol-target.

Grid:
  - vol_win_days: 20 or 30
  - floor when long: 0.2 (fixed — the core of the hypothesis)
  - cap when long: 1.5 (fixed — slightly higher than TP01's 2.0 but with floor)
  TFs tested: 1d, 12h (total 4 backtests, within 6-cell limit)
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np


def tsmom_direction(df, horizons_days=(21, 63, 126)):
    """Multi-horizon TSMOM direction: sign of blend of returns over multiple horizons.
    Returns +1 (trend up) or 0 (trend down/flat). Causal: uses close[i] vs close[i-k]."""
    c = df["close"].values.astype(float)
    bpd = al.bars_per_day(df)
    scores = []
    for h_days in horizons_days:
        win = max(2, int(h_days * bpd))
        ret = np.zeros(len(c))
        ret[win:] = c[win:] / c[:-win] - 1.0
        scores.append(np.sign(ret))
    blend = np.mean(scores, axis=0)
    # Long when majority of horizons agree (blend > 0), else flat
    direction = np.where(blend > 0, 1.0, 0.0)
    return direction


def rsk09_target(df, vol_win_days=30, exposure_floor=0.2, exposure_cap=1.5,
                 target_vol=0.20):
    """RSK09: vol-targeted TSMOM with floor/cap clamp on long exposure.

    When trend is UP:
      - compute raw vol-target scalar (target_vol / realized_vol)
      - clamp to [floor, cap] instead of [0, leverage_cap]
      -> ensures we're never near-zero even in high-vol regimes,
         but also never overleveraged
    When trend is DOWN (or mixed): flat (0.0)
    """
    direction = tsmom_direction(df)  # 0 or 1

    c = df["close"].values.astype(float)
    bpd = al.bars_per_day(df)
    bpy = bpd * 365.25
    r = al.simple_returns(c)
    vol = al.realized_vol(r, max(2, int(vol_win_days * bpd)), bpy)

    # Raw vol-scalar (avoid div-by-zero)
    scal = np.where((vol > 0) & np.isfinite(vol), target_vol / vol, 0.0)

    # When in trend: clamp to [floor, cap]
    # floor ensures we hold minimum exposure even in high-vol periods
    # cap ensures we don't over-lever in low-vol periods
    raw_exposure = np.clip(scal, exposure_floor, exposure_cap)

    # Apply trend gate: long-flat
    target = direction * raw_exposure
    target = np.nan_to_num(target, nan=0.0)
    return target


# Small grid: vol_win_days x TF (2 params x 2 TFs = 4 total backtests)
configs = [
    {"vol_win_days": 20, "label": "vw20"},
    {"vol_win_days": 30, "label": "vw30"},
]

best_rep = None
best_score = -9999.0

for cfg in configs:
    name = f"RSK09-floor02-cap15-{cfg['label']}"
    rep = al.study_weights(
        name,
        lambda df, c=cfg: rsk09_target(df, vol_win_days=c["vol_win_days"]),
        tfs=("1d", "12h"),
    )
    # Score by min hold-out Sharpe across cells
    cells = rep.get("cells", [])
    if cells:
        score = max((c.get("min_asset_holdout_sharpe", -9) for c in cells), default=-9)
    else:
        score = -9

    print(f"\n=== Config: {cfg['label']} | score={score:.3f} ===")
    print(al.fmt(rep))

    if score > best_score:
        best_score = score
        best_rep = rep

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