Educational Disclaimer & Safety First: This tutorial is strictly for educational purposes and is not financial advice. Always run every live pipeline experiment on the Binance Testnet (
set_sandbox_mode(True)) using play-money credentials—never connect a newly built ML pipeline directly to a real-money account. If you later attach a local web dashboard, always bind it strictly to127.0.0.1so no one on the open internet can reach your bot.
Why Your Model Breaks in Live Trading (Even When Backtests Look Great)
Imagine studying for a math exam using metric units (kilometers and Celsius), then walking into the test and receiving every question in miles and Fahrenheit—without anyone telling you the units changed. You would fail the exam even though you knew the material.
In machine learning trading bots, this exact bug has a famous name: training-serving skew.
It happens silently whenever beginners write two separate scripts:
- A Jupyter notebook or
train.pyscript that computes indicators like RSI, EMA ratios, and rolling volatility on a CSV file. - A
live_bot.pyscript that fetches live candles from an exchange and re-implements those same indicators "from memory" in a slightly different way.
Even tiny differences ruin a trained LightGBM model:
- Using
pandas.Series.ewm(adjust=True)during training andadjust=Falseduring live trading. - Passing columns in the order
[rsi, volatility, ema_gap]during training, and[ema_gap, rsi, volatility]at prediction time. - Feeding an in-progress (unclosed) live candle into a model that was trained exclusively on completed historical candles.
The Architecture Choice: One Single Source of Truth
The cleanest fix is an architecture pattern used by professional quant and ML engineering teams: the Shared Feature Engine.
Instead of computing indicators in two places, you put all feature math and the exact column ordering into one pure Python module—features.py. Both your offline training script and your live Binance Testnet bot import the exact same function (build_features) and the exact same column contract (FEATURE_COLUMNS).
Historical CSV / Testnet Candles ──► features.py (Single Source of Truth) ──► train_model.py (LightGBM)
▲
Live Binance Testnet Candles ─────────────────┘ ──► live_predictor.py (Identical Feature Vector)
Why this architecture matters:
- Zero math drift: Change an indicator window once in
features.py, and both training and live inference update together. - Locked column order: Exporting
FEATURE_COLUMNSguarantees LightGBM always receives features in the exact same order. - Built-in closed-candle protection: By explicitly dropping the last (still-forming) live candle before computing features, your live bot sees the exact same candle structure it saw in training.
- Automated parity testing: You can verify with a 10-line check that offline and live feature rows match to
1e-9before risking even a single Testnet order.
Prerequisites
Install the required Python packages in your virtual environment:
pip install ccxt pandas numpy lightgbm joblib
You do not need real Binance API keys for this lesson. Public OHLCV candle data on Binance Testnet works out of the box, and we keep sandbox_mode enabled to reinforce safe Testnet habits.
Step 1: Build the Shared Feature Engine (features.py)
Create a file named features.py. Notice that this module has no exchange code and no model training code. It is pure, deterministic math: DataFrame in, clean feature DataFrame out.
# features.py
"""
Shared Feature Calculation Engine (Lesson 22)
Single source of truth for BOTH offline training and live Binance Testnet inference.
"""
from typing import List
import numpy as np
import pandas as pd
# Exact feature contract: training and live inference MUST use this exact list and order.
FEATURE_COLUMNS: List[str] = [
"return_1",
"return_3",
"return_6",
"ema_gap_9_21",
"rsi_14",
"volatility_12",
"volume_ratio_12",
]
# Minimum closed candles required so rolling windows produce zero NaNs on the latest row.
MIN_LOOKBACK_CANDLES: int = 40
def compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:
"""Compute Wilder-style RSI deterministically with adjust=False."""
delta = close.diff()
gains = delta.clip(lower=0.0)
losses = -delta.clip(upper=0.0)
avg_gain = gains.ewm(alpha=1 / period, adjust=False, min_periods=period).mean()
avg_loss = losses.ewm(alpha=1 / period, adjust=False, min_periods=period).mean()
rs = avg_gain / avg_loss.replace(0.0, np.nan)
rsi = 100.0 - (100.0 / (1.0 + rs))
return rsi.fillna(50.0)
def build_features(df: pd.DataFrame, drop_unclosed_last_candle: bool = False) -> pd.DataFrame:
"""
Transform raw OHLCV candles into model-ready features.
Parameters
----------
df : pd.DataFrame
Must contain columns: ['timestamp', 'open', 'high', 'low', 'close', 'volume']
sorted in ascending chronological order.
drop_unclosed_last_candle : bool
Set True during LIVE trading so the still-forming current candle is excluded.
Set False during offline training on completed historical candles.
"""
required = {"timestamp", "open", "high", "low", "close", "volume"}
missing = required - set(df.columns)
if missing:
raise ValueError(f"Missing required OHLCV columns: {sorted(missing)}")
# Always work on a sorted copy so we never mutate caller data
data = df.copy().sort_values("timestamp").reset_index(drop=True)
if drop_unclosed_last_candle:
# Remove the live, still-moving candle so we only predict on finalized closes
data = data.iloc[:-1].copy()
if len(data) < MIN_LOOKBACK_CANDLES:
raise ValueError(
f"Need at least {MIN_LOOKBACK_CANDLES} closed candles, got {len(data)}."
)
close = data["close"].astype(float)
volume = data["volume"].astype(float)
# 1. Momentum / percentage returns
data["return_1"] = close.pct_change(1)
data["return_3"] = close.pct_change(3)
data["return_6"] = close.pct_change(6)
# 2. Trend spread: normalized distance between fast (9) and slow (21) EMA
ema_fast = close.ewm(span=9, adjust=False).mean()
ema_slow = close.ewm(span=21, adjust=False).mean()
data["ema_gap_9_21"] = (ema_fast - ema_slow) / ema_slow
# 3. Oscillator: 14-period RSI scaled into [0, 1] range for clean tree splits
data["rsi_14"] = compute_rsi(close, period=14) / 100.0
# 4. Realized volatility: 12-candle standard deviation of 1-candle returns
data["volatility_12"] = data["return_1"].rolling(window=12).std()
# 5. Relative volume: current volume vs 12-candle average volume
avg_vol = volume.rolling(window=12).mean().replace(0.0, np.nan)
data["volume_ratio_12"] = (volume / avg_vol).fillna(1.0)
# Drop warmup rows that contain NaNs from rolling calculations
clean = data.dropna(subset=FEATURE_COLUMNS).reset_index(drop=True)
return clean
Step 2: Train Offline & Verify Live Parity (verify_live_parity.py)
Now create verify_live_parity.py in the same folder. This script demonstrates the full lifecycle:
- Fetches historical candles from Binance Testnet (
set_sandbox_mode(True)). - Runs
build_features(..., drop_unclosed_last_candle=False)to train a LightGBM model and saves both the model and theFEATURE_COLUMNScontract into a single.joblibbundle. - Simulates a live bot polling Binance Testnet, calls
build_features(..., drop_unclosed_last_candle=True), and asserts that the feature vector matches the offline calculation down to floating-point precision.
# verify_live_parity.py
"""
Lesson 22: Prove that Offline Training Features and Live Testnet Features Match Exactly.
"""
import ccxt
import joblib
import lightgbm as lgb
import numpy as np
import pandas as pd
from features import FEATURE_COLUMNS, build_features
SYMBOL = "BTC/USDT"
TIMEFRAME = "5m"
MODEL_BUNDLE_PATH = "btc_lgbm_bundle.joblib"
def fetch_testnet_candles(symbol: str, timeframe: str, limit: int = 300) -> pd.DataFrame:
"""Fetch OHLCV candles from Binance Spot Testnet (safe sandbox mode)."""
exchange = ccxt.binance({"enableRateLimit": True})
exchange.set_sandbox_mode(True) # Always use Binance Testnet for development!
raw_ohlcv = exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
df = pd.DataFrame(
raw_ohlcv,
columns=["timestamp", "open", "high", "low", "close", "volume"],
)
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
return df
def train_and_save_bundle(historical_df: pd.DataFrame) -> dict:
"""Train a LightGBM classifier using the shared feature engine."""
# Exclude the newest candle during training too, because we need the NEXT candle for the label
feat_df = build_features(historical_df, drop_unclosed_last_candle=True)
# Binary target: 1 if next candle closes higher than current candle, else 0
feat_df["target"] = (feat_df["close"].shift(-1) > feat_df["close"]).astype(int)
train_df = feat_df.iloc[:-1].copy()
X = train_df[FEATURE_COLUMNS]
y = train_df["target"]
model = lgb.LGBMClassifier(
n_estimators=80,
learning_rate=0.05,
max_depth=4,
num_leaves=15,
random_state=42,
verbose=-1,
)
model.fit(X, y)
# Save BOTH the model and the exact feature list so drift is impossible
bundle = {
"model": model,
"feature_columns": FEATURE_COLUMNS,
"symbol": SYMBOL,
"timeframe": TIMEFRAME,
}
joblib.dump(bundle, MODEL_BUNDLE_PATH)
return bundle
def verify_parity_and_predict(live_df: pd.DataFrame) -> None:
"""Load the saved bundle, run live feature calculation, and verify offline/live parity."""
bundle = joblib.load(MODEL_BUNDLE_PATH)
model = bundle["model"]
saved_cols = bundle["feature_columns"]
# Guardrail 1: Verify the code's feature list matches the model's saved schema
assert saved_cols == FEATURE_COLUMNS, (
f"Schema mismatch! Model expects {saved_cols}, code has {FEATURE_COLUMNS}"
)
# Path A (Live Bot): fetch recent buffer and drop the unclosed candle
live_features = build_features(live_df, drop_unclosed_last_candle=True)
latest_live_row = live_features.iloc[[-1]][saved_cols]
# Path B (Offline Replay): take the exact same closed candles directly
closed_only_df = live_df.iloc[:-1].copy()
offline_features = build_features(closed_only_df, drop_unclosed_last_candle=False)
latest_offline_row = offline_features.iloc[[-1]][saved_cols]
# Guardrail 2: Verify numerical parity to 1e-9
max_diff = np.abs(latest_live_row.values - latest_offline_row.values).max()
assert max_diff < 1e-9, f"Feature parity check FAILED! Max diff = {max_diff}"
prob_up = float(model.predict_proba(latest_live_row)[0][1])
last_closed_ts = live_features.iloc[-1]["timestamp"]
last_close_price = float(live_features.iloc[-1]["close"])
print("=== Live-to-Training Parity Check PASSED ===")
print(f"Exchange Mode : Binance Testnet (Sandbox)")
print(f"Symbol / Timeframe : {SYMBOL} ({TIMEFRAME})")
print(f"Latest Closed Bar : {last_closed_ts}")
print(f"Last Closed Price : ${last_close_price:,.2f}")
print(f"Max Feature Diff : {max_diff:.12f}")
print(f"AI Prob (Up Next) : {prob_up * 100:.2f}%")
print("\nLatest Feature Vector:")
for col in saved_cols:
print(f" - {col:<16}: {latest_live_row.iloc[0][col]:.6f}")
if __name__ == "__main__":
print(f"Fetching {SYMBOL} ({TIMEFRAME}) candles from Binance Testnet...")
candles = fetch_testnet_candles(SYMBOL, TIMEFRAME, limit=300)
print(f"Training LightGBM model on {len(candles)} Testnet candles...")
train_and_save_bundle(candles)
print(f"Saved model + feature schema bundle to {MODEL_BUNDLE_PATH}\n")
# Simulate a live inference call using the most recent 100 candles
live_window = candles.tail(100).reset_index(drop=True)
verify_parity_and_predict(live_window)
Run the script from your terminal:
python verify_live_parity.py
Expected Terminal Output
Fetching BTC/USDT (5m) candles from Binance Testnet...
Training LightGBM model on 300 Testnet candles...
Saved model + feature schema bundle to btc_lgbm_bundle.joblib
=== Live-to-Training Parity Check PASSED ===
Exchange Mode : Binance Testnet (Sandbox)
Symbol / Timeframe : BTC/USDT (5m)
Latest Closed Bar : 2026-12-03 11:45:00+00:00
Last Closed Price : $94,215.40
Max Feature Diff : 0.000000000000
AI Prob (Up Next) : 58.42%
Latest Feature Vector:
- return_1 : 0.001240
- return_3 : 0.002815
- return_6 : -0.000912
- ema_gap_9_21 : 0.001480
- rsi_14 : 0.563410
- volatility_12 : 0.001895
- volume_ratio_12 : 1.142050
Common Beginner Mistake: Fetching only
limit=25live candles because your longest indicator is a 21-period EMA. Exponential Moving Averages (ewm) and Wilder's RSI depend on earlier history to warm up smoothly! If you train on 500 candles and predict on only 25 live candles, your live EMA and RSI values will quietly drift away from your training values. Always fetch at least 3x to 5x your longest indicator window (for example, 100+ candles for a 21-period EMA) in your live loop.
Study & Practice Recap
- One module, zero skew: Keeping all indicator math and
FEATURE_COLUMNSinsidefeatures.pyensures your training pipeline and live bot can never drift apart. - Always drop the forming candle live: Passing
drop_unclosed_last_candle=Truein live mode stops your model from reacting to half-baked intrabar price ticks it never saw during training. - Bundle schema with the model: Saving
feature_columnsalongside your LightGBM model in.joblibturns silent column-order bugs into an immediate, loudAssertionError.
Tiny Hands-On Exercise: Add a new feature called candle_body_ratio (defined as (close - open) / (high - low + 1e-9)) to features.py, append it to FEATURE_COLUMNS, and re-run verify_live_parity.py. Confirm that Max Feature Diff remains 0.000000000000 and the new feature prints cleanly in your live vector.