From 76b525c7209887b28862cf70cee6730885b58894 Mon Sep 17 00:00:00 2001 From: Stanley Isaac Date: Thu, 21 May 2026 19:07:28 +0000 Subject: [PATCH] feat: implement ADAUSDT RSI failure swing filter 30m strategy (closes #219) --- ...16-adausdt-rsi-failure-swing-filter-30m.md | 2 +- .../README.md | 49 +++++ .../quant.config.json | 28 +++ .../strategy.py | 175 ++++++++++++++++++ 4 files changed, 253 insertions(+), 1 deletion(-) create mode 100644 templates/adausdt-rsi-failure-swing-filter-30m/README.md create mode 100644 templates/adausdt-rsi-failure-swing-filter-30m/quant.config.json create mode 100644 templates/adausdt-rsi-failure-swing-filter-30m/strategy.py diff --git a/ideas/idea-016-adausdt-rsi-failure-swing-filter-30m.md b/ideas/idea-016-adausdt-rsi-failure-swing-filter-30m.md index f2ed1c5..44a01da 100644 --- a/ideas/idea-016-adausdt-rsi-failure-swing-filter-30m.md +++ b/ideas/idea-016-adausdt-rsi-failure-swing-filter-30m.md @@ -41,4 +41,4 @@ ADAUSDT may show repeatable behavior when RSI failure swing filter conditions al 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 #31 +Closes #219 \ No newline at end of file diff --git a/templates/adausdt-rsi-failure-swing-filter-30m/README.md b/templates/adausdt-rsi-failure-swing-filter-30m/README.md new file mode 100644 index 0000000..880c756 --- /dev/null +++ b/templates/adausdt-rsi-failure-swing-filter-30m/README.md @@ -0,0 +1,49 @@ +# ADAUSDT RSI failure swing filter 30m + +This strategy implements an RSI failure swing filter approach for ADAUSDT on 30-minute candles using ExtraTreesClassifier. + +## Overview + +- **Pair**: ADAUSDT +- **Timeframe**: 30m +- **Model**: ExtraTreesClassifier with feature engineering focused on RSI failure swing patterns +- **Goal**: Trade RSI failure swings which are strong reversal signals + +## Features Engineered + +1. **Basic returns**: 1, 3, 6, 12 period returns +2. **RSI calculation**: Standard 14-period RSI +3. **RSI failure swing features**: + - RSI peak and trough identification + - Tracking previous RSI peaks and troughs + - Bearish failure swing detection (lower high then break below recent low) + - Bullish failure swing detection (higher low then break above recent high) + - Combined failure swing signal (bullish - bearish) +4. **ATR-normalized candle range and close location value** (from idea) +5. **Distance from EMAs** (from idea): 20, 50, and 200 period EMAs +6. **Prior swing high and swing low distance** (from idea) +7. **Volume features**: Z-score and ratio to moving average +8. **Rolling volatility percentile** (from idea): Fast/slow volatility ratio, volatility percentile + +## Configuration + +See `quant.config.json` for hyperparameters: +- `lookback`: 100 candles for prediction +- `horizon`: 6 candles forward for labeling (3 hours for 30m timeframe) +- `threshold`: 0.003 (30 pips) for ATR-normalized breakout +- `min_confidence`: 0.50 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/adausdt-rsi-failure-swing-filter-30m/quant.config.json b/templates/adausdt-rsi-failure-swing-filter-30m/quant.config.json new file mode 100644 index 0000000..6e6cd5b --- /dev/null +++ b/templates/adausdt-rsi-failure-swing-filter-30m/quant.config.json @@ -0,0 +1,28 @@ +{ + "pair": "ADAUSDT", + "timeframe": "30m", + "model_family": "ExtraTreesClassifier", + "runtime_target": "edge", + "artifact_format": "weights_bundle", + "parameters": { + "lookback": 100, + "horizon": 6, + "threshold": 0.003, + "min_confidence": 0.5 + }, + "training_requirements": [ + "numpy", + "pandas", + "scikit-learn", + "joblib" + ], + "inference_requirements": [ + "numpy", + "pandas", + "scikit-learn", + "joblib" + ], + "symbol": "ADAUSDT", + "description": "ADAUSDT RSI failure swing filter strategy using ExtraTreesClassifier", + "disclaimer": "Educational template only. Not financial advice." +} \ No newline at end of file diff --git a/templates/adausdt-rsi-failure-swing-filter-30m/strategy.py b/templates/adausdt-rsi-failure-swing-filter-30m/strategy.py new file mode 100644 index 0000000..36b2870 --- /dev/null +++ b/templates/adausdt-rsi-failure-swing-filter-30m/strategy.py @@ -0,0 +1,175 @@ +import numpy as np +import pandas as pd +from sklearn.ensemble import ExtraTreesClassifier +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import StandardScaler + + +SYMBOL = "ADAUSDT" +MODEL_NAME = "adausdt-rsi-failure-swing-filter-30m" + + +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"] + f = pd.DataFrame(index=df.index) + + # Basic returns + for n in [1, 3, 6, 12]: + f[f"ret{n}"] = c.pct_change(n) + + # RSI calculation + delta = c.diff() + gain = (delta.where(delta > 0, 0)).rolling(window=14).mean() + loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean() + rs = gain / (loss + 1e-9) + rsi = 100 - (100 / (1 + rs)) + f["rsi"] = rsi + + # RSI failure swing features + # Identify RSI peaks and troughs + f["rsi_peak"] = (f["rsi"] > f["rsi"].shift(1)) & (f["rsi"] > f["rsi"].shift(-1)) + f["rsi_trough"] = (f["rsi"] < f["rsi"].shift(1)) & (f["rsi"] < f["rsi"].shift(-1)) + + # Failure swing detection: + # Bearish failure swing: RSI makes lower high then breaks below recent low + # Bullish failure swing: RSI makes higher low then breaks above recent high + f["rsi_prev_peak"] = f["rsi"].where(f["rsi_peak"]).ffill() + f["rsi_prev_trough"] = f["rsi"].where(f["rsi_trough"]).ffill() + + # Bearish failure swing signal + f["bearish_failure_swing"] = ( + (f["rsi"] < f["rsi_prev_peak"]) & + (f["rsi"].shift(1) > f["rsi_prev_peak"]) & + (f["rsi"] < f["rsi"].rolling(10).min()) + ).astype(int) + + # Bullish failure swing signal + f["bullish_failure_swing"] = ( + (f["rsi"] > f["rsi_prev_trough"]) & + (f["rsi"].shift(1) < f["rsi_prev_trough"]) & + (f["rsi"] > f["rsi"].rolling(10).max()) + ).astype(int) + + # Combined failure swing signal + f["failure_swing_signal"] = f["bullish_failure_swing"] - f["bearish_failure_swing"] + + # 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() + f["atr"] = atr + + # ATR-normalized candle range and close location value + f["range_pct"] = (h - l) / c + f["body_pct"] = (c - df["open"]) / (h - l).replace(0, np.nan) + f["close_pos"] = (c - l) / (h - l).replace(0, np.nan) + + # Distance from EMAs (from idea) + f["ema20_dist"] = (c - c.ewm(span=20, adjust=False).mean()) / c + f["ema50_dist"] = (c - c.ewm(span=50, adjust=False).mean()) / c + f["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) + f["dist_to_swing_high"] = (swing_high - c) / c + f["dist_to_swing_low"] = (c - swing_low) / c + + # Volume features + f["volume_z"] = (v - v.rolling(48).mean()) / (v.rolling(48).std() + 1e-9) + f["volume_ratio"] = v / v.rolling(20).mean() + + # Rolling volatility percentile (from idea) + returns = c.pct_change() + f["volatility_fast"] = returns.rolling(16).std() + f["volatility_slow"] = returns.rolling(64).std() + f["volatility_ratio"] = f["volatility_fast"] / (f["volatility_slow"] + 1e-9) + f["volatility_percentile"] = f["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 f.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", 6)) # 6 candles = 3 hours for 30m timeframe + threshold = float(params.get("threshold", 0.003)) + df = _normalise(data) + feat = _features(df) + y = _labels(df["close"], feat.index, horizon, threshold) + + model = Pipeline([ + ("scaler", StandardScaler()), + ("clf", ExtraTreesClassifier( + n_estimators=200, + max_depth=10, + min_samples_split=5, + min_samples_leaf=2, + max_features='sqrt', + random_state=42, + n_jobs=-1 + )), + ]) + 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.5)) + 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(prob)) + 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(prob[0]), 4), + "p_hold": round(float(prob[1]), 4), + "p_buy": round(float(prob[2]), 4), + "model": MODEL_NAME, + "symbol": SYMBOL + }} \ No newline at end of file