"""MIC06 — Body-ratio momentum (long-flat, vol-targeted)
Hypothesis: Large positive candle body (body/range high) signals conviction upward move
-> hold long next bars. Body ratio = (close - open) / (high - low), smoothed over N bars.
When smoothed body-ratio > threshold -> long; else flat.
Grid: (lookback_smooth, threshold, hold_bars) x tfs (1d, 12h)
"""
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 body_ratio_signal(df: pd.DataFrame, smooth: int = 5, threshold: float = 0.15) -> np.ndarray:
    """
    Compute body/range ratio for each bar, then smooth over `smooth` bars.
    Go long when smoothed ratio > threshold (conviction upward), else flat.
    All causal: body_ratio[i] uses only close[i], open[i], high[i], low[i].
    The smoothed ratio uses bars up to i (causal rolling mean).
    """
    o = df["open"].values.astype(float)
    h = df["high"].values.astype(float)
    l = df["low"].values.astype(float)
    c = df["close"].values.astype(float)

    rng = h - l
    body = c - o
    # Body ratio: in [-1, 1]; positive = bullish bar, negative = bearish bar
    # Where range == 0 (doji), treat as 0
    ratio = np.where(rng > 0, body / rng, 0.0)

    # Smooth with a rolling mean (causal)
    smoothed = pd.Series(ratio).rolling(smooth, min_periods=max(1, smooth // 2)).mean().values

    # Direction: long if smoothed ratio > threshold, else flat
    direction = np.where(smoothed > threshold, 1.0, 0.0)

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


# Small internal grid: 4 param sets
CONFIGS = [
    dict(smooth=3,  threshold=0.10),
    dict(smooth=5,  threshold=0.15),
    dict(smooth=10, threshold=0.10),
    dict(smooth=10, threshold=0.20),
]

# Run 2 TFs x 4 configs = 8 backtests — but we pick best config first
# To stay within 6 total: we test all 4 configs on 1d only, pick best, then run 12h too
print("=== MIC06: Body-Ratio Momentum (long-flat, vol-targeted) ===\n")

# Phase 1: quick grid on 1d (4 backtests)
print("Phase 1: grid search on 1d...")
grid_results = []
for cfg in CONFIGS:
    rep = al.study_weights(
        f"MIC06-s{cfg['smooth']}-t{int(cfg['threshold']*100)}",
        lambda df, s=cfg["smooth"], t=cfg["threshold"]: body_ratio_signal(df, s, t),
        tfs=("1d",)
    )
    best_cell = rep["cells"][0]
    score = best_cell["min_asset_holdout_sharpe"]
    print(f"  smooth={cfg['smooth']:2d} thresh={cfg['threshold']:.2f}: "
          f"minFull={best_cell['min_asset_full_sharpe']:+.2f}  "
          f"minHold={best_cell['min_asset_holdout_sharpe']:+.2f}  "
          f"feeOK={best_cell['fee_survives']}")
    grid_results.append((score, cfg, rep))

# Pick best config by hold-out score
grid_results.sort(key=lambda x: x[0], reverse=True)
best_score, best_cfg, _ = grid_results[0]
print(f"\nBest config: smooth={best_cfg['smooth']} threshold={best_cfg['threshold']:.2f}")

# Phase 2: run best config on both TFs (2 backtests)
print("\nPhase 2: full eval on 1d + 12h with best config...")
final_rep = al.study_weights(
    "MIC06",
    lambda df, s=best_cfg["smooth"], t=best_cfg["threshold"]: body_ratio_signal(df, s, t),
    tfs=("1d", "12h")
)

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