"""STA05 — EWMA-cross ensemble vote.

IDEA: Vote across many EMA crossovers (fast/slow pairs drawn from {5..200}).
      position = net_vote / n_pairs (continuous, in [-1,+1]).
      Apply vol-targeting on top. Diversified trend signal.

Grids tested (<=4 configs, <=6 total backtests):
  Config A: wide pairs (5 fast × 4 slow), log-spaced fast {5,10,20,40},
            slow {40,80,120,200} — only fast < slow. Position = sum(sign) / n.
            Vol-target 20% cap 2x. TFs: 1d, 12h  (2 cells × 2 assets = 4 runs, total 4)
  Config B: same pairs but LONG-ONLY (clip to [0,1]) — long-flat like TP01.
            TFs: 1d only (2 more runs = 6 total)

Both configs evaluated in the same pass by running study_weights twice on 1d/12h
for A (4 runs) and once on 1d for B (2 runs). Total = 6.
"""

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


# ---------------------------------------------------------------------------
# EMA PAIR POOL
# ---------------------------------------------------------------------------
FAST_SPANS = [5, 10, 20, 40]
SLOW_SPANS = [40, 80, 120, 200]

# all valid (fast, slow) pairs where fast < slow
PAIRS = [(f, s) for f in FAST_SPANS for s in SLOW_SPANS if f < s]
# e.g. (5,40),(5,80),...,(40,80),(40,120),(40,200) = 13 pairs


def _ewma_vote(df, long_only: bool = False) -> np.ndarray:
    """Ensemble vote across EMA crossover pairs.
    For each pair (fast, slow): signal = sign(ema_fast - ema_slow).
    Position = mean(signals) across pairs, clipped to [-1,1] (or [0,1] if long_only).
    Apply vol-targeting.
    """
    c = df["close"].values.astype(float)
    n = len(c)
    votes = np.zeros(n)

    for fast_span, slow_span in PAIRS:
        ema_fast = al.ema(c, fast_span)
        ema_slow = al.ema(c, slow_span)
        # sign: +1 if fast > slow (uptrend), -1 if below
        sig = np.sign(ema_fast - ema_slow)
        votes += sig

    # net vote normalized to [-1, 1]
    direction = votes / len(PAIRS)

    if long_only:
        direction = np.clip(direction, 0.0, 1.0)

    # vol-target: scale to 20% annualized vol, cap 2x
    pos = al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)
    return pos


# Config A: long-short ensemble
def target_ls(df):
    return _ewma_vote(df, long_only=False)

# Config B: long-only ensemble (long-flat)
def target_lo(df):
    return _ewma_vote(df, long_only=True)


# ---------------------------------------------------------------------------
# RUN — 4 runs for Config A (1d+12h), 2 for Config B (1d) = 6 total
# ---------------------------------------------------------------------------
print(f"EMA pairs: {PAIRS} ({len(PAIRS)} total)")
print("Running Config A (long-short) on 1d + 12h ...")
rep_a = al.study_weights("STA05-A-LS", target_ls, tfs=("1d", "12h"))
print(al.fmt(rep_a))
print("JSON:", al.as_json(rep_a))

print("\nRunning Config B (long-only) on 1d ...")
rep_b = al.study_weights("STA05-B-LO", target_lo, tfs=("1d",))
print(al.fmt(rep_b))
print("JSON:", al.as_json(rep_b))

# ---------------------------------------------------------------------------
# PICK BEST CONFIG
# ---------------------------------------------------------------------------
best_a = rep_a["verdict"].get("best_holdout_sharpe", -9)
best_b = rep_b["verdict"].get("best_holdout_sharpe", -9)

if best_a >= best_b:
    rep_best = rep_a
    print("\n>>> BEST: Config A (long-short)")
else:
    rep_best = rep_b
    print("\n>>> BEST: Config B (long-only)")

print("\n=== FINAL BEST ===")
print(al.fmt(rep_best))
print("JSON:", al.as_json(rep_best))
