From ed83cb18cb729f0731b124b98524203693e55a28 Mon Sep 17 00:00:00 2001 From: Stanley Isaac Date: Thu, 21 May 2026 16:14:28 +0000 Subject: [PATCH] feat: implement GBPJPY news-window risk gate 5m strategy (closes #211) --- ...dea-008-gbpjpy-news-window-risk-gate-5m.md | 2 +- .../gbpjpy-news-window-risk-gate-5m/README.md | 47 +++++ .../quant.config.json | 28 +++ .../strategy.py | 169 ++++++++++++++++++ 4 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 templates/gbpjpy-news-window-risk-gate-5m/README.md create mode 100644 templates/gbpjpy-news-window-risk-gate-5m/quant.config.json create mode 100644 templates/gbpjpy-news-window-risk-gate-5m/strategy.py diff --git a/ideas/idea-008-gbpjpy-news-window-risk-gate-5m.md b/ideas/idea-008-gbpjpy-news-window-risk-gate-5m.md index b4b9336..421ac61 100644 --- a/ideas/idea-008-gbpjpy-news-window-risk-gate-5m.md +++ b/ideas/idea-008-gbpjpy-news-window-risk-gate-5m.md @@ -41,4 +41,4 @@ GBPJPY may show repeatable behavior when news-window risk gate conditions align This idea is intentionally Markdown-only. A future template can add `strategy.py`, `quant.config.json`, and a focused README once PPE results justify turning the idea into executable code. -Closes #15 +Closes #211 \ No newline at end of file diff --git a/templates/gbpjpy-news-window-risk-gate-5m/README.md b/templates/gbpjpy-news-window-risk-gate-5m/README.md new file mode 100644 index 0000000..c43b4b4 --- /dev/null +++ b/templates/gbpjpy-news-window-risk-gate-5m/README.md @@ -0,0 +1,47 @@ +# GBPJPY News-window risk gate 5m + +This strategy implements a news-window risk gate approach for GBPJPY on 5-minute candles using HistGradientBoostingClassifier. + +## Overview + +- **Pair**: GBPJPY +- **Timeframe**: 5m +- **Model**: HistGradientBoostingClassifier with feature engineering focused on news-window risk management +- **Goal**: Reduce trading during high-impact news events while capturing post-news reversals + +## Features Engineered + +1. **Returns**: 1, 3, 6, 12 period returns +2. **ATR-normalized candle range and close location value** (from idea) +3. **News-window risk gate**: + - Volatility spikes (proxy for news events) + - Volume spikes (accompanying news) + - Combined news likelihood signal + - Post-news reaction features (fade the initial move) +4. **Distance from EMAs** (from idea): 20, 50, and 200 period EMAs +5. **Prior swing high and swing low distance** (from idea) +6. **Volume features**: Z-score and ratio to moving average +7. **Rolling volatility percentile** (from idea): Fast/slow volatility ratio, volatility percentile + +## Configuration + +See `quant.config.json` for hyperparameters: +- `lookback`: 100 candles for prediction +- `horizon`: 5 candles forward for labeling (5m timeframe) +- `threshold`: 0.0012 (12 pips) for ATR-normalized breakout +- `min_confidence`: 0.52 minimum probability for signal generation + +## Usage + +This template follows the PyP Quant Mode contract: +```python +def train(data, config): + return model, metrics + +def predict(model, market_data, config): + return {"signal": "UP|DOWN|HOLD", "confidence": 0.0, "metadata": {}} +``` + +## Disclaimer + +Educational template only. Not financial advice. Past performance does not guarantee future results. \ No newline at end of file diff --git a/templates/gbpjpy-news-window-risk-gate-5m/quant.config.json b/templates/gbpjpy-news-window-risk-gate-5m/quant.config.json new file mode 100644 index 0000000..603778c --- /dev/null +++ b/templates/gbpjpy-news-window-risk-gate-5m/quant.config.json @@ -0,0 +1,28 @@ +{ + "pair": "GBPJPY", + "timeframe": "5m", + "model_family": "sklearn HistGradientBoostingClassifier", + "runtime_target": "edge", + "artifact_format": "weights_bundle", + "parameters": { + "lookback": 100, + "horizon": 5, + "threshold": 0.0012, + "min_confidence": 0.52 + }, + "training_requirements": [ + "numpy", + "pandas", + "scikit-learn", + "joblib" + ], + "inference_requirements": [ + "numpy", + "pandas", + "scikit-learn", + "joblib" + ], + "symbol": "GBPJPY", + "description": "GBPJPY news-window risk gate strategy using HistGradientBoostingClassifier", + "disclaimer": "Educational template only. Not financial advice." +} \ No newline at end of file diff --git a/templates/gbpjpy-news-window-risk-gate-5m/strategy.py b/templates/gbpjpy-news-window-risk-gate-5m/strategy.py new file mode 100644 index 0000000..4e741fb --- /dev/null +++ b/templates/gbpjpy-news-window-risk-gate-5m/strategy.py @@ -0,0 +1,169 @@ +import numpy as np +import pandas as pd +from sklearn.experimental import enable_hist_gradient_boosting # noqa +from sklearn.ensemble import HistGradientBoostingClassifier +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import StandardScaler + + +SYMBOL = "GBPJPY" +MODEL_NAME = "gbpjpy-news-window-risk-gate-5m" + + +def _normalise(data): + df = data.copy() + df.columns = [str(c).lower() for c in df.columns] + if "volume" not in df.columns: + df["volume"] = 1.0 + for col in ["open", "high", "low", "close", "volume"]: + df[col] = pd.to_numeric(df[col], errors="coerce") + return df.dropna(subset=["open", "high", "low", "close"]).reset_index(drop=True) + + +def _features(df): + c = df["close"] + h = df["high"] + l = df["low"] + v = df["volume"] + + # Basic returns + out = pd.DataFrame(index=df.index) + out["ret1"] = c.pct_change() + out["ret3"] = c.pct_change(3) + out["ret6"] = c.pct_change(6) + out["ret12"] = c.pct_change(12) + + # ATR for normalization + tr = np.maximum(h - l, np.maximum(abs(h - c.shift(1)), abs(l - c.shift(1)))) + atr = pd.Series(tr).rolling(14).mean() + out["atr"] = atr + + # ATR-normalized candle range and close location value + out["range_pct"] = (h - l) / c + out["body_pct"] = (c - df["open"]) / (h - l).replace(0, np.nan) + out["close_pos"] = (c - l) / (h - l).replace(0, np.nan) + + # News-window risk gate features + # Approximate news windows (major economic releases) + # In practice, this would use actual economic calendar data + # For now, we'll use time-of-day proxies and volatility spikes + + # Time-based features (assuming UTC times - would need actual timestamps) + # Major news often occurs at specific times: 8:30am EST (13:30 UTC), 2:00pm EST (19:00 UTC), etc. + # Since we don't have timestamps, we'll use volatility spikes as proxy for news + + # Volatility spikes (potential news events) + returns = c.pct_change() + vol_spike = returns.rolling(5).std() / returns.rolling(60).std() + out["volatility_spike"] = vol_spike + out["is_high_vol"] = (vol_spike > vol_spike.rolling(100).quantile(0.8)).astype(int) + + # Volume spikes (accompanying news) + vol_ma = v.rolling(20).mean() + vol_ratio = v / vol_ma + out["volume_spike"] = vol_ratio + out["is_high_volume"] = (vol_ratio > vol_ratio.rolling(100).quantile(0.8)).astype(int) + + # Combined news likelihood signal + out["news_likelihood"] = (out["is_high_vol"] * 0.6 + out["is_high_volume"] * 0.4) + + # Post-news reaction features (fade the initial move) + # Look for reversals after high volatility/volume periods + out["price_change_during_news"] = returns * out["news_likelihood"] + out["reversal_potential"] = -out["price_change_during_news"].rolling(3).sum() + + # Distance from EMAs (from idea) + out["ema20_dist"] = (c - c.ewm(span=20, adjust=False).mean()) / c + out["ema50_dist"] = (c - c.ewm(span=50, adjust=False).mean()) / c + out["ema200_dist"] = (c - c.ewm(span=200, adjust=False).mean()) / c + + # Prior swing high and swing low distance (from idea) + swing_high = h.rolling(20, center=False).max().shift(1) + swing_low = l.rolling(20, center=False).min().shift(1) + out["dist_to_swing_high"] = (swing_high - c) / c + out["dist_to_swing_low"] = (c - swing_low) / c + + # Volume features + out["volume_z"] = (v - v.rolling(48).mean()) / (v.rolling(48).std() + 1e-9) + out["volume_ratio"] = v / v.rolling(20).mean() + + # Rolling volatility percentile (from idea) + out["volatility_fast"] = returns.rolling(16).std() + out["volatility_slow"] = returns.rolling(64).std() + out["volatility_ratio"] = out["volatility_fast"] / (out["volatility_slow"] + 1e-9) + out["volatility_percentile"] = out["volatility_fast"].rolling(200).apply( + lambda x: pd.Series(x).rank(pct=True).iloc[-1] if len(x) > 0 else 0.5, raw=False) + + return out.replace([np.inf, -np.inf], np.nan).dropna() + + +def _labels(close, index, horizon, threshold): + fwd = close.pct_change(horizon).shift(-horizon) + y = pd.Series(1, index=close.index) + y[fwd > threshold] = 2 + y[fwd < -threshold] = 0 + return y.reindex(index).fillna(1).astype(int) + + +def train(data, config): + params = config.get("parameters", {}) + horizon = int(params.get("horizon", 5)) # 5m horizon for 5m timeframe + threshold = float(params.get("threshold", 0.0012)) + df = _normalise(data) + feat = _features(df) + y = _labels(df["close"], feat.index, horizon, threshold) + + model = Pipeline([ + ("scaler", StandardScaler()), + ("clf", HistGradientBoostingClassifier( + learning_rate=0.08, + max_iter=150, + max_depth=7, + min_samples_leaf=15, + l2_regularization=0.1, + random_state=42 + )), + ]) + model.fit(feat.values.astype(np.float32), y.values) + preds = model.predict(feat.values.astype(np.float32)) + + metrics = { + "training_bars": int(len(feat)), + "feature_count": int(feat.shape[1]), + "buy_signals": int((preds == 2).sum()), + "sell_signals": int((preds == 0).sum()), + "hold_signals": int((preds == 1).sum()), + } + return {"model": model, "features": list(feat.columns), "symbol": SYMBOL}, metrics + + +def predict(model, market_data, config): + params = config.get("parameters", {}) + lookback = int(params.get("lookback", 100)) + min_conf = float(params.get("min_confidence", 0.52)) + candles = market_data.get("candles", []) + + if len(candles) < lookback: + return {"signal": "HOLD", "confidence": 0.0, "metadata": {"reason": "not_enough_candles", "model": MODEL_NAME}} + + df = _normalise(pd.DataFrame(candles, columns=["open", "high", "low", "close", "volume"])) + feat = _features(df).tail(1) + + if feat.empty: + return {"signal": "HOLD", "confidence": 0.0, "metadata": {"reason": "no_features", "model": MODEL_NAME}} + + proba = model["model"].predict_proba(feat.values.astype(np.float32))[0] + klass = int(np.argmax(proba)) + conf = float(proba[klass]) + signal = {0: "DOWN", 1: "HOLD", 2: "UP"}[klass] + + if conf < min_conf: + signal = "HOLD" + + return {"signal": signal, "confidence": round(conf, 4), "metadata": { + "p_sell": round(float(proba[0]), 4), + "p_hold": round(float(proba[1]), 4), + "p_buy": round(float(proba[2]), 4), + "model": MODEL_NAME, + "symbol": SYMBOL + }} \ No newline at end of file