"""TRD11 — SMA50 slope momentum
HYPOTHESIS: Position = sign of slope of SMA(50) over last k bars (long-flat variant).
The slope of SMA(50) captures the direction of the medium-term trend.
Long-flat: go long when slope > 0, flat otherwise.
Grid: slope_window (k) in {3, 5, 10} bars.
Vol-targeted position (target_vol=20%, leverage_cap=2x).
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np


def make_target(sma_period: int = 50, slope_win: int = 5, long_flat: bool = True):
    """Return a target function for study_weights.

    sma_period: period of the SMA
    slope_win: number of bars to measure the slope over (slope = sma[i] - sma[i-slope_win])
    long_flat: if True, only go long (flat when slope <= 0); if False, long/short
    """
    def target(df):
        c = df["close"].values.astype(float)
        s = al.sma(c, sma_period)

        # Slope = change in SMA over slope_win bars (causal: uses s[i] vs s[i-slope_win])
        slope = np.full(len(s), np.nan)
        for i in range(slope_win, len(s)):
            if np.isfinite(s[i]) and np.isfinite(s[i - slope_win]):
                slope[i] = s[i] - s[i - slope_win]

        # Direction signal
        if long_flat:
            direction = np.where(slope > 0, 1.0, 0.0)
        else:
            direction = np.where(slope > 0, 1.0, np.where(slope < 0, -1.0, 0.0))

        # Mask NaN slope with flat
        direction = np.where(np.isfinite(slope), direction, 0.0)

        # Vol-target
        tgt = al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)
        return tgt

    target.__name__ = f"sma{sma_period}_slope{slope_win}_{'lf' if long_flat else 'ls'}"
    return target


# Small internal grid: slope windows [3, 5, 10] all long-flat, plus one L/S variant
configs = [
    {"sma_period": 50, "slope_win": 3,  "long_flat": True},
    {"sma_period": 50, "slope_win": 5,  "long_flat": True},
    {"sma_period": 50, "slope_win": 10, "long_flat": True},
    {"sma_period": 50, "slope_win": 5,  "long_flat": False},  # L/S variant
]

best_rep = None
best_score = -999.0

for cfg in configs:
    name = f"TRD11-sma{cfg['sma_period']}-k{cfg['slope_win']}-{'LF' if cfg['long_flat'] else 'LS'}"
    fn = make_target(**cfg)
    rep = al.study_weights(name, fn, tfs=("1d", "12h"))

    # Score = min of BTC/ETH full Sharpe (most conservative)
    cells = rep.get("cells", [])
    best_cell_score = -999.0
    for cell in cells:
        pa = cell.get("per_asset", {})
        btc_sh = pa.get("BTC", {}).get("full", {}).get("sharpe", -999)
        eth_sh = pa.get("ETH", {}).get("full", {}).get("sharpe", -999)
        min_sh = min(btc_sh, eth_sh)
        # Also require positive holdout on both
        btc_ho = pa.get("BTC", {}).get("holdout", {}).get("sharpe", -999)
        eth_ho = pa.get("ETH", {}).get("holdout", {}).get("sharpe", -999)
        if btc_ho > 0 and eth_ho > 0:
            min_sh += 0.5  # bonus for positive holdout
        if min_sh > best_cell_score:
            best_cell_score = min_sh

    if best_cell_score > best_score:
        best_score = best_cell_score
        best_rep = rep
        print(f"\n*** NEW BEST: {name} score={best_cell_score:.3f} ***")

    print(al.fmt(rep))

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