mirror of
https://github.com/PyP-Quant/quant-trading-strategy-templates.git
synced 2026-08-21 14:48:08 +00:00
feat: implement BTCUSDT opening range continuation 15m strategy (closes #214)
This commit is contained in:
@@ -41,4 +41,4 @@ BTCUSDT may show repeatable behavior when opening range continuation conditions
|
||||
|
||||
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 #21
|
||||
Closes #214
|
||||
@@ -0,0 +1,46 @@
|
||||
# BTCUSDT Opening range continuation 15m
|
||||
|
||||
This strategy implements an opening range continuation approach for BTCUSDT on 15-minute candles using LightGBM.
|
||||
|
||||
## Overview
|
||||
|
||||
- **Pair**: BTCUSDT
|
||||
- **Timeframe**: 15m
|
||||
- **Model**: LightGBM with feature engineering focused on opening range continuation
|
||||
- **Goal**: Trade continuations of price movements that break out of the opening range
|
||||
|
||||
## Features Engineered
|
||||
|
||||
1. **Returns**: 1, 3, 6, 12 period returns
|
||||
2. **Opening range features**:
|
||||
- Position within opening range (previous period's high/low)
|
||||
- Breakout signals above/below opening range
|
||||
- Continuation signals (price moving further in breakout direction)
|
||||
3. **ATR-normalized candle range and close location value** (from idea)
|
||||
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`: 3 candles forward for labeling (45 minutes for 15m timeframe)
|
||||
- `threshold`: 0.008 (80 pips) for ATR-normalized breakout
|
||||
- `min_confidence`: 0.48 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.
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"pair": "BTCUSDT",
|
||||
"timeframe": "15m",
|
||||
"model_family": "LightGBM",
|
||||
"runtime_target": "edge",
|
||||
"artifact_format": "weights_bundle",
|
||||
"parameters": {
|
||||
"lookback": 100,
|
||||
"horizon": 3,
|
||||
"threshold": 0.008,
|
||||
"min_confidence": 0.48
|
||||
},
|
||||
"training_requirements": [
|
||||
"numpy",
|
||||
"pandas",
|
||||
"scikit-learn",
|
||||
"lightgbm",
|
||||
"joblib"
|
||||
],
|
||||
"inference_requirements": [
|
||||
"numpy",
|
||||
"pandas",
|
||||
"scikit-learn",
|
||||
"lightgbm",
|
||||
"joblib"
|
||||
],
|
||||
"symbol": "BTCUSDT",
|
||||
"description": "BTCUSDT opening range continuation strategy using LightGBM",
|
||||
"disclaimer": "Educational template only. Not financial advice."
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from lightgbm import LGBMClassifier
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
|
||||
SYMBOL = "BTCUSDT"
|
||||
MODEL_NAME = "btcusdt-opening-range-continuation-15m"
|
||||
|
||||
|
||||
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().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)
|
||||
|
||||
# Opening range features (first 4 candles of the session)
|
||||
# Assuming 15m data, we'll look at first 4 bars (1 hour) as opening range
|
||||
# In practice, this would need session detection logic
|
||||
window_4 = 4
|
||||
if len(df) >= window_4:
|
||||
opening_high = h.rolling(window_4).max().shift(1) # Previous period's opening range high
|
||||
opening_low = l.rolling(window_4).min().shift(1) # Previous period's opening range low
|
||||
opening_range = opening_high - opening_low
|
||||
|
||||
# Position within opening range
|
||||
out["position_in_opening_range"] = (c - opening_low) / opening_range.replace(0, np.nan)
|
||||
|
||||
# Breakout from opening range
|
||||
out["breakout_above_opening"] = (c > opening_high).astype(int)
|
||||
out["breakout_below_opening"] = (c < opening_low).astype(int)
|
||||
|
||||
# Continuation signals (price moving further in breakout direction)
|
||||
out["continuation_up"] = out["breakout_above_opening"] * np.maximum(0, c - opening_high) / c
|
||||
out["continuation_down"] = out["breakout_below_opening"] * np.maximum(0, opening_low - c) / c
|
||||
else:
|
||||
# Not enough data for opening range calculation
|
||||
out["position_in_opening_range"] = 0.5
|
||||
out["breakout_above_opening"] = 0
|
||||
out["breakout_below_opening"] = 0
|
||||
out["continuation_up"] = 0
|
||||
out["continuation_down"] = 0
|
||||
|
||||
# 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)
|
||||
|
||||
# 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(24).mean()) / (v.rolling(24).std() + 1e-9)
|
||||
out["volume_ratio"] = v / v.rolling(20).mean()
|
||||
|
||||
# Rolling volatility percentile (from idea)
|
||||
returns = c.pct_change()
|
||||
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", 3)) # 3 candles = 45 minutes for 15m timeframe
|
||||
threshold = float(params.get("threshold", 0.008)) # 80 pips for BTC
|
||||
df = _normalise(data)
|
||||
feat = _features(df)
|
||||
y = _labels(df["close"], feat.index, horizon, threshold)
|
||||
|
||||
model = Pipeline([
|
||||
("scaler", StandardScaler()),
|
||||
("clf", LGBMClassifier(n_estimators=300, learning_rate=0.04, max_depth=5, random_state=42, verbose=-1))
|
||||
])
|
||||
model.fit(feat.values, y.values)
|
||||
|
||||
metrics = {
|
||||
"training_bars": int(len(feat)),
|
||||
"feature_count": int(feat.shape[1]),
|
||||
"buy_signals": int((model.predict(feat.values) == 2).sum()),
|
||||
"sell_signals": int((model.predict(feat.values) == 0).sum()),
|
||||
"hold_signals": int((model.predict(feat.values) == 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.48))
|
||||
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}}
|
||||
|
||||
prob = model["model"].predict_proba(feat.values)[0]
|
||||
klass = int(np.argmax(prob))
|
||||
conf = float(np.max(prob))
|
||||
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
|
||||
}}
|
||||
Reference in New Issue
Block a user