"""BRK07 — N-day-high momentum (long-flat) IDEA: Long-flat: position 1 while close is within X% of its rolling 100-bar max, else 0. Trend-persistence proxy. Optionally vol-targeted. Grid: threshold X% in {2%, 5%} x vol_target in {False, True} -> 4 configs, 2 TFs = 8 total backtests. """ import sys sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt") import altlib as al import numpy as np LOOKBACK = 100 # fixed as per hypothesis def make_target(df, threshold_pct: float = 5.0, use_vol_target: bool = True) -> np.ndarray: """Long (1) when close is within threshold_pct% of its rolling 100-bar max, else 0.""" c = df["close"].values.astype(float) n = len(c) # Rolling max of close over last LOOKBACK bars (causal: includes close[i]) roll_max = ( __import__("pandas").Series(c) .rolling(LOOKBACK, min_periods=LOOKBACK) .max() .values ) # Position: 1 if close >= roll_max * (1 - threshold_pct/100), else 0 threshold = threshold_pct / 100.0 direction = np.where( (roll_max > 0) & np.isfinite(roll_max) & (c >= roll_max * (1.0 - threshold)), 1.0, 0.0 ) # Before we have enough bars, stay flat direction[:LOOKBACK - 1] = 0.0 if use_vol_target: return al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0) else: return direction configs = [ {"threshold_pct": 2.0, "use_vol_target": False, "label": "thr2pct_flat"}, {"threshold_pct": 5.0, "use_vol_target": False, "label": "thr5pct_flat"}, {"threshold_pct": 2.0, "use_vol_target": True, "label": "thr2pct_vt"}, {"threshold_pct": 5.0, "use_vol_target": True, "label": "thr5pct_vt"}, ] best_rep = None best_score = -9999.0 for cfg in configs: label = cfg["label"] threshold_pct = cfg["threshold_pct"] use_vol_target = cfg["use_vol_target"] print(f"\n=== BRK07 config: {label} (threshold={threshold_pct}%, vol_target={use_vol_target}) ===") fn = lambda df, t=threshold_pct, v=use_vol_target: make_target(df, t, v) rep = al.study_weights( f"BRK07-{label}", fn, tfs=("1d", "12h"), ) print(al.fmt(rep)) print("JSON:", al.as_json(rep)) # Score = min holdout sharpe across both assets in best TF score = rep["verdict"].get("best_holdout_sharpe", -9999.0) or -9999.0 if score > best_score: best_score = score best_rep = rep best_cfg = cfg print("\n\n========== BEST CONFIG ==========") print(f"Config: {best_cfg['label']}") print(al.fmt(best_rep)) print("JSON:", al.as_json(best_rep))