Predicting Better Entries with XGBoost & LightGBM
If you ask experienced quant developers what machine learning models actually win on spreadsheet-style financial data, they rarely start with massive deep neural networks. Almost all of them reach for Gradient Boosted Decision Trees—specifically XGBoost and LightGBM.
Why? Imagine a team of 200 junior traders voting on a trade setup.
- Trader #1 looks at RSI and volume and makes a rough guess.
- Trader #2 studies only the mistakes Trader #1 made and tries to correct them.
- Trader #3 focuses on the mistakes Traders #1 and #2 still got wrong.
By the time all 200 small decision trees have worked together, the combined team is remarkably good at spotting subtle combinations of clues—like "momentum is turning up, volatility is cooling down, AND volume is quietly rising."
In this lesson, you will train both XGBoost and LightGBM as an AI signal filter: instead of trying to predict every candle of the day, the model scores each potential entry from 0.0 to 1.0 so your bot only takes the highest-confidence trades. You will also generate a visual bar chart of the exact clues the model relies on most.
Why Precision Matters More Than Accuracy
Suppose your baseline strategy wins 35% of the time. If a lazy model simply predicts "Don't Trade" (0) on every single candle, it gets 65% accuracy—while making $0 profit!
That is why trading models care deeply about Precision at High Confidence:
- Precision asks: "When the AI says YES (e.g., probability ≥
0.60), how often did the trade actually win?" - Trade Count asks: "Did the AI still take enough trades to be useful, or did it only take 2 trades all year?"
Prerequisites
Install the required packages:
pip install pandas numpy scikit-learn xgboost lightgbm matplotlib
Training XGBoost & LightGBM + Plotting Top Clues
This standalone script builds a realistic feature + label dataset (or reads your CSV if you pass one), trains both XGBoost and LightGBM on chronological splits, compares their filtered win rates against taking every trade blindly, and saves a visual chart (top_clues.png) of the model's favorite features.
Save this as train_signal_filter.py:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import precision_score, roc_auc_score
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
def make_demo_trading_dataset(n_bars: int = 3000) -> tuple[pd.DataFrame, list[str]]:
"""Generate a realistic crypto dataset with mild, learnable momentum/volatility edges."""
rng = np.random.default_rng(101)
returns = rng.normal(0.0001, 0.008, n_bars)
# Inject subtle regime momentum so features carry real signal (plus realistic noise)
for i in range(20, n_bars):
recent_trend = returns[i - 6 : i].mean()
returns[i] += 0.18 * recent_trend
close = 60000 * np.exp(np.cumsum(returns))
volume = rng.lognormal(6.2, 0.5, n_bars) * (1 + np.abs(returns) * 45)
df = pd.DataFrame({"close": close, "volume": volume})
# Engineer core clues
df["ret_1h"] = df["close"].pct_change(1)
df["ret_3h"] = df["close"].pct_change(3)
df["ret_6h"] = df["close"].pct_change(6)
df["ret_12h"] = df["close"].pct_change(12)
df["ret_24h"] = df["close"].pct_change(24)
df["vol_6h"] = df["ret_1h"].rolling(6).std()
df["vol_24h"] = df["ret_1h"].rolling(24).std()
df["vol_ratio"] = df["volume"] / df["volume"].rolling(24).mean()
sma_20 = df["close"].rolling(20).mean()
df["dist_sma_20"] = (df["close"] - sma_20) / sma_20
delta = df["close"].diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
df["rsi_14"] = 100 - (100 / (1 + gain / (loss + 1e-9)))
# Label: 1 if price rises >= +1.5% within next 12h before dropping -1.0%
horizon = 12
targets = np.full(len(df), np.nan)
c = df["close"].to_numpy()
for i in range(len(df) - horizon):
future = c[i + 1 : i + 1 + horizon] / c[i] - 1.0
hit_tp = np.where(future >= 0.015)[0]
hit_sl = np.where(future <= -0.010)[0]
if len(hit_tp) > 0 and (len(hit_sl) == 0 or hit_tp[0] < hit_sl[0]):
targets[i] = 1
else:
targets[i] = 0
df["target"] = targets
df = df.dropna().reset_index(drop=True)
df["target"] = df["target"].astype(int)
feature_cols = [c for c in df.columns if c not in ("close", "volume", "target")]
return df, feature_cols
def evaluate_filter(name: str, y_true: pd.Series, probs: np.ndarray, threshold: float = 0.55):
"""Compare the AI-filtered win rate against taking every trade."""
preds = (probs >= threshold).astype(int)
trades_taken = int(preds.sum())
auc = roc_auc_score(y_true, probs)
precision = precision_score(y_true, preds, zero_division=0)
print(
f"{name:10s} | ROC-AUC: {auc:.3f} | Trades Taken: {trades_taken:3d}/{len(y_true)} "
f"| Filtered Win Rate: {precision * 100:5.1f}%"
)
def plot_feature_importance(model, feature_cols: list[str], output_path: str = "top_clues.png"):
"""Save a horizontal bar chart showing which clues the model trusts most."""
importances = pd.Series(model.feature_importances_, index=feature_cols).sort_values()
plt.figure(figsize=(8, 5))
importances.plot(kind="barh", color="#2563eb")
plt.title("LightGBM Signal Filter — Top Decision Clues")
plt.xlabel("Importance Score (Splits Used)")
plt.tight_layout()
plt.savefig(output_path, dpi=150)
plt.close()
print(f"\nSaved visual clue chart to {output_path}")
if __name__ == "__main__":
df, feature_cols = make_demo_trading_dataset()
# Chronological 80/20 split with a 12-bar purge gap
split_idx = int(len(df) * 0.80)
purge = 12
train_df = df.iloc[:split_idx]
test_df = df.iloc[split_idx + purge :]
X_train, y_train = train_df[feature_cols], train_df["target"]
X_test, y_test = test_df[feature_cols], test_df["target"]
# Model 1: XGBoost (kept shallow with max_depth=3 to prevent memorizing noise)
xgb = XGBClassifier(
n_estimators=150,
max_depth=3,
learning_rate=0.05,
subsample=0.8,
colsample_bytree=0.8,
eval_metric="logloss",
random_state=42,
)
xgb.fit(X_train, y_train)
xgb_probs = xgb.predict_proba(X_test)[:, 1]
# Model 2: LightGBM (fast, leaf-wise boosting)
lgbm = LGBMClassifier(
n_estimators=150,
max_depth=3,
num_leaves=7,
learning_rate=0.05,
subsample=0.8,
colsample_bytree=0.8,
random_state=42,
verbose=-1,
)
lgbm.fit(X_train, y_train)
lgbm_probs = lgbm.predict_proba(X_test)[:, 1]
baseline_win_rate = y_test.mean() * 100
print(f"Baseline (No AI Filter) | Trades Taken: {len(y_test)}/{len(y_test)} | Win Rate: {baseline_win_rate:5.1f}%\n")
evaluate_filter("XGBoost", y_test, xgb_probs, threshold=0.55)
evaluate_filter("LightGBM", y_test, lgbm_probs, threshold=0.55)
plot_feature_importance(lgbm, feature_cols, "top_clues.png")
Expected Terminal Output
When you run python train_signal_filter.py, you should see output similar to this:
Baseline (No AI Filter) | Trades Taken: 580/580 | Win Rate: 39.1%
XGBoost | ROC-AUC: 0.614 | Trades Taken: 112/580 | Filtered Win Rate: 53.6%
LightGBM | ROC-AUC: 0.621 | Trades Taken: 104/580 | Filtered Win Rate: 55.8%
Saved visual clue chart to top_clues.png
Open top_clues.png after running the script: you'll see a clean horizontal bar chart ranking your clues from most influential to least influential. Notice how keeping max_depth=3 forces the trees to learn broad, repeatable rules instead of memorizing weird one-off market days.
Common Beginner Mistake: Cranking up
max_depth=12andn_estimators=2000until your training accuracy hits99.9%. In crypto markets, a99.9%training score almost always means your model memorized random noise (overfitting). Keep trees shallow (max_depthbetween3and5), use a lowlearning_rate, and always judge your model on unseen future test candles.
Study & Practice Recap
- Gradient boosting shines on tabular candle data: XGBoost and LightGBM build small trees sequentially, each correcting the mistakes of the previous ones.
- Filter instead of trading everything: Raising the confidence threshold (e.g.,
probs >= 0.55) lets your bot skip low-quality setups and improve win rate. - Inspect your model's brain: Plotting
feature_importances_reveals which clues actually help—and which noisy features you can safely delete.
Tiny Hands-On Exercise: Raise the probability threshold from 0.55 to 0.65 in evaluate_filter(), re-run python train_signal_filter.py, and observe the classic trading tradeoff: what happens to Trades Taken versus Filtered Win Rate?