"""BRK01 — Donchian 10/20/55 channel breakout, long-short and long-flat variants.

Hypothesis: close breaks prior N-bar high -> long, prior N-bar low -> short (long-flat variant: flat
instead of short). Grid N in {10, 20, 55}. Best config picked by min-asset hold-out Sharpe.
With vol-targeting to 20% annualized volatility (TP01-style).

CAUSAL: al.donchian(df, N) shifts the rolling max/min by 1 bar -> breakout at close[i] is
strictly decided with data up to and including close[i-1] for the channel, so it is leak-free.
"""

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

# ---- Strategy implementation -----------------------------------------------

def make_brk_ls(N: int):
    """Long-short Donchian breakout: +1 if close breaks N-bar prior high, -1 if breaks prior low,
    hold otherwise. Vol-targeted to 20%."""
    def target(df):
        hi, lo = al.donchian(df, N)
        c = df["close"].values.astype(float)
        # signal: +1 long, -1 short, nan=hold previous
        sig = np.full(len(c), np.nan)
        sig[c > hi] = 1.0
        sig[c < lo] = -1.0
        # forward-fill (hold position until next signal)
        direction = pd.Series(sig).ffill().fillna(0.0).values
        return al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)
    return target


def make_brk_lf(N: int):
    """Long-flat Donchian breakout: +1 if close breaks N-bar prior high, 0 if breaks prior low.
    Vol-targeted to 20%."""
    def target(df):
        hi, lo = al.donchian(df, N)
        c = df["close"].values.astype(float)
        sig = np.full(len(c), np.nan)
        sig[c > hi] = 1.0
        sig[c < lo] = 0.0
        direction = pd.Series(sig).ffill().fillna(0.0).values
        return al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)
    return target


# ---- Run grid: N in {10, 20, 55} x variant {LS, LF}, TF=1d only (keep <=6 backtests) ----
# Total: 3 N values x 2 variants x 1 TF x 2 assets = 12 asset-runs but only 3 study_weights calls
# Each study_weights call does 2 assets = 6 total calls -> 6 cells, fine.
# We also add 12h for the best N to compare frequency.

configs = [
    ("BRK01-N10-LS",  make_brk_ls(10),  ("1d",)),
    ("BRK01-N20-LS",  make_brk_ls(20),  ("1d",)),
    ("BRK01-N55-LS",  make_brk_ls(55),  ("1d",)),
    ("BRK01-N20-LF",  make_brk_lf(20),  ("1d",)),
]

# Run all configs and collect results
results = []
for name, fn, tfs in configs:
    print(f"\n>>> Running {name}...")
    rep = al.study_weights(name, fn, tfs=tfs)
    print(al.fmt(rep))
    print("JSON:", al.as_json(rep))
    results.append(rep)

# Pick best by min_asset_holdout_sharpe
best_rep = max(results, key=lambda r: r["verdict"].get("best_holdout_sharpe", -99))
print("\n\n=== BEST CONFIG ===")
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
