feat: implement SOLUSDT carry-aware trend overlay 15m strategy (closes #216)

This commit is contained in:
Stanley Isaac
2026-05-21 18:40:10 +00:00
parent a9a8b24cba
commit 16f54e175e
4 changed files with 264 additions and 1 deletions
@@ -0,0 +1,51 @@
# SOLUSDT Carry-aware trend overlay 15m
This strategy implements a carry-aware trend overlay approach for SOLUSDT on 15-minute candles using XGBoost.
## Overview
- **Pair**: SOLUSDT
- **Timeframe**: 15m
- **Model**: XGBoost with feature engineering focused on carry-aware trend overlay
- **Goal**: Combine carry (cost of holding) signals with trend overlay for improved timing
## Features Engineered
1. **Basic returns**: 1, 3, 6, 12, 24 period returns
2. **Carry-aware features** (proxy for funding rates/cost of carry):
- Price momentum (24-period)
- Volume momentum (24-period)
- Carry proxy (price momentum × volume momentum)
3. **Trend overlay features**:
- Multiple timeframe EMAs (9, 21, 55 periods)
- Trend strength and direction between timeframes
- Price position relative to each EMA
4. **ATR for normalization**: Average True Range for volatility measurement
5. **ATR-normalized candle range and close location value** (from idea)
6. **Distance from EMAs** (from idea): 20, 50, and 200 period EMAs
7. **Prior swing high and swing low distance** (from idea)
8. **Volume features**: Z-score and ratio to moving average
9. **Rolling volatility percentile** (from idea): Fast/slow volatility ratio, volatility percentile
## Configuration
See `quant.config.json` for hyperparameters:
- `lookback`: 100 candles for prediction
- `horizon`: 4 candles forward for labeling (1 hour for 15m timeframe)
- `threshold`: 0.006 (60 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.
@@ -0,0 +1,30 @@
{
"pair": "SOLUSDT",
"timeframe": "15m",
"model_family": "XGBoost",
"runtime_target": "edge",
"artifact_format": "weights_bundle",
"parameters": {
"lookback": 100,
"horizon": 4,
"threshold": 0.006,
"min_confidence": 0.5
},
"training_requirements": [
"numpy",
"pandas",
"scikit-learn",
"xgboost",
"joblib"
],
"inference_requirements": [
"numpy",
"pandas",
"scikit-learn",
"xgboost",
"joblib"
],
"symbol": "SOLUSDT",
"description": "SOLUSDT carry-aware trend overlay strategy using XGBoost",
"disclaimer": "Educational template only. Not financial advice."
}
@@ -0,0 +1,182 @@
import numpy as np
import pandas as pd
from xgboost import XGBClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
SYMBOL = "SOLUSDT"
MODEL_NAME = "solusdt-carry-aware-trend-overlay-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(subset=["open", "high", "low", "close"]).reset_index(drop=True)
def _rsi(close, n=14):
delta = close.diff()
gain = delta.clip(lower=0).ewm(alpha=1 / n, adjust=False).mean()
loss = (-delta.clip(upper=0)).ewm(alpha=1 / n, adjust=False).mean()
return 100 - 100 / (1 + gain / (loss + 1e-9))
def _features(df):
c = df["close"]
h = df["high"]
l = df["low"]
o = df["open"]
v = df["volume"]
rng = (h - l).replace(0, np.nan)
f = pd.DataFrame(index=df.index)
# Basic returns
for n in [1, 3, 6, 12, 24]:
f[f"ret{n}"] = c.pct_change(n)
# Carry-aware features (proxy for funding rates/cost of carry)
# Approximate carry using price momentum and volume
f["price_momentum"] = c.pct_change(24) # 24-period momentum (6 hours for 15m)
f["volume_momentum"] = v.pct_change(24)
f["carry_proxy"] = f["price_momentum"] * f["volume_momentum"] # Simple carry proxy
# Trend overlay features
# Multiple timeframe EMAs for trend detection
f["ema_fast"] = c.ewm(span=9, adjust=False).mean()
f["ema_medium"] = c.ewm(span=21, adjust=False).mean()
f["ema_slow"] = c.ewm(span=55, adjust=False).mean()
# Trend strength and direction
f["trend_fast_medium"] = (f["ema_fast"] - f["ema_medium"]) / c
f["trend_medium_slow"] = (f["ema_medium"] - f["ema_slow"]) / c
f["trend_fast_slow"] = (f["ema_fast"] - f["ema_slow"]) / c
# Price position relative to EMAs
f["price_vs_ema_fast"] = (c - f["ema_fast"]) / c
f["price_vs_ema_medium"] = (c - f["ema_medium"]) / c
f["price_vs_ema_slow"] = (c - f["ema_slow"]) / c
# 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 - o) / rng
f["close_pos"] = (c - l) / rng
# 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(24).mean()) / (v.rolling(24).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", 4)) # 4 candles = 1 hour for 15m timeframe
threshold = float(params.get("threshold", 0.006))
df = _normalise(data)
feat = _features(df)
y = _labels(df["close"], feat.index, horizon, threshold)
# Create pipeline with StandardScaler and XGBoost
scaler = StandardScaler()
x_scaled = scaler.fit_transform(feat.values.astype(np.float32))
clf = XGBClassifier(
n_estimators=200,
max_depth=5,
learning_rate=0.05,
subsample=0.8,
colsample_bytree=0.8,
objective="multi:softprob",
num_class=3,
random_state=42,
n_jobs=-1
)
clf.fit(x_scaled, y.values)
# Create a pipeline-like object for consistency
model = {"scaler": scaler, "clf": clf}
preds = clf.predict(x_scaled)
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}}
# Apply same preprocessing as in training
scaler = model["model"]["scaler"]
clf = model["model"]["clf"]
feat_scaled = scaler.transform(feat.values.astype(np.float32))
prob = clf.predict_proba(feat_scaled)[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
}}