HomePhase 4: Practical MLLesson 17
Lesson 17 of 24Phase 4: Practical MLIntermediate

Teaching an AI What a 'Good Trade' Looks Like

Learn how to label profitable trades using take-profit and stop-loss barriers and split time-series data without lookahead bias.

Bitfoster Team
December 3, 2026
10 Min Read
lesson-17-labeling-good-trades/
Teaching an AI What a 'Good Trade' Looks Like

Hands-On Deliverable

An automatic trade-labeler and leak-free train/test data splitter.

Teaching an AI What a 'Good Trade' Looks Like

In Lesson 16, you gave your future AI model 35 clean clues (features). Now comes the question that separates profitable trading models from useless toy demos:

What are we actually asking the AI to predict?

Most beginners make the same first guess: "Let's label a candle 1 if the next candle closes higher, and 0 if it closes lower."

That sounds logical—until you try trading it. A candle that closes +0.04% higher gets labeled a "win" even though trading fees would turn it into a loss. Worse, a trade that drops -6% (triggering your stop-loss) before bouncing back two hours later would also be mislabeled if you only look at a single future close.

To teach an AI what a good trade looks like, we need to label history the same way a real trader manages risk: using a Take-Profit ceiling, a Stop-Loss floor, and a Time Limit (often called the Triple-Barrier Method).


The "Race to the Finish Line" Analogy

Imagine entering a long trade at the close of a candle and drawing three lines on the chart ahead of you:

  1. Top Line (Take-Profit, e.g., +2.0%): If price touches this first, the trade is a Win (1).
  2. Bottom Line (Stop-Loss, e.g., -1.0%): If price touches this first, the trade is a Loss (0).
  3. Vertical Wall (Time Limit, e.g., 24 hours): If neither barrier is hit in 24 hours, the trade stalled out—also labeled 0 (not worth taking).

Now your AI isn't guessing noisy 1-hour wiggles. It is learning to spot setups where a +2% reward hits before a -1% stop-loss!

And when it's time to test your model, you must never shuffle crypto rows randomly. Think of it like taking an exam: if you shuffle days randomly, the model gets to peek at Tuesday and Thursday while "predicting" Wednesday. Instead, we use a chronological split with a purge gap—a small buffer of candles dropped between training and testing so no overlapping trades leak across the boundary.


Prerequisites

Install the required libraries:

pip install pandas numpy

Building the Automatic Trade-Labeler & Leak-Free Splitter

This script loads btc_ml_features.csv from Lesson 16 (or generates sample data automatically if the file isn't there yet), labels every candle using the Triple-Barrier method, and splits the data into leak-free Train, Validation, and Test sets with a purge gap.

Save this as label_and_split.py:

import os
import numpy as np
import pandas as pd


def load_price_data(csv_path: str = "btc_ml_features.csv", n_bars: int = 2000) -> pd.DataFrame:
    """Load prepared data from Lesson 16 or generate synthetic OHLC data."""
    if os.path.exists(csv_path):
        df = pd.read_csv(csv_path, parse_dates=["timestamp"])
        # Approximate intrabar high/low if only close is saved
        if "high" not in df.columns:
            df["high"] = df["close"] * 1.004
            df["low"] = df["close"] * 0.996
        print(f"Loaded {len(df)} rows from {csv_path}")
        return df

    print(f"'{csv_path}' not found — generating {n_bars} synthetic 1h candles...")
    rng = np.random.default_rng(7)
    timestamps = pd.date_range("2026-01-01", periods=n_bars, freq="1h")
    returns = rng.normal(0.0001, 0.0085, n_bars)
    close = 65000 * np.exp(np.cumsum(returns))
    high = close * (1 + np.abs(rng.normal(0.003, 0.002, n_bars)))
    low = close * (1 - np.abs(rng.normal(0.003, 0.002, n_bars)))

    return pd.DataFrame({
        "timestamp": timestamps,
        "close": close,
        "high": high,
        "low": low,
        "ret_1h": pd.Series(close).pct_change(1),
        "ret_6h": pd.Series(close).pct_change(6),
    }).dropna().reset_index(drop=True)


def create_triple_barrier_labels(
    df: pd.DataFrame,
    take_profit: float = 0.02,
    stop_loss: float = 0.01,
    horizon_bars: int = 24,
) -> pd.DataFrame:
    """
    Label each candle:
      1 = Take-Profit hit before Stop-Loss within `horizon_bars`
      0 = Stop-Loss hit first, or time expired without hitting TP
    """
    closes = df["close"].to_numpy()
    highs = df["high"].to_numpy()
    lows = df["low"].to_numpy()
    n = len(df)

    labels = np.full(n, np.nan)
    outcomes = np.full(n, "", dtype=object)

    for i in range(n - horizon_bars):
        entry = closes[i]
        tp_price = entry * (1.0 + take_profit)
        sl_price = entry * (1.0 - stop_loss)

        label = 0
        outcome = "timeout"

        for step in range(1, horizon_bars + 1):
            bar_low = lows[i + step]
            bar_high = highs[i + step]

            # Conservative rule: if both hit in the same candle, assume stop-loss hit first
            if bar_low <= sl_price:
                label = 0
                outcome = "stop_loss"
                break
            if bar_high >= tp_price:
                label = 1
                outcome = "take_profit"
                break

        labels[i] = label
        outcomes[i] = outcome

    labeled = df.copy()
    labeled["target"] = labels
    labeled["outcome"] = outcomes
    # Drop the final `horizon_bars` rows where we don't know the future outcome yet
    return labeled.dropna(subset=["target"]).astype({"target": int}).reset_index(drop=True)


def purged_time_split(
    df: pd.DataFrame,
    train_ratio: float = 0.70,
    val_ratio: float = 0.15,
    purge_bars: int = 24,
):
    """
    Chronologically split data into Train / Validation / Test sets with a
    `purge_bars` gap between splits so active trades never overlap across sets.
    """
    n = len(df)
    train_end = int(n * train_ratio)
    val_start = train_end + purge_bars
    val_end = val_start + int(n * val_ratio)
    test_start = val_end + purge_bars

    train_df = df.iloc[:train_end].copy()
    val_df = df.iloc[val_start:val_end].copy()
    test_df = df.iloc[test_start:].copy()

    return train_df, val_df, test_df


if __name__ == "__main__":
    df = load_price_data()
    horizon = 24
    labeled_df = create_triple_barrier_labels(
        df, take_profit=0.02, stop_loss=0.01, horizon_bars=horizon
    )

    train_df, val_df, test_df = purged_time_split(labeled_df, purge_bars=horizon)

    print("\n--- Outcome Breakdown ---")
    print(labeled_df["outcome"].value_counts().to_string())

    win_rate = labeled_df["target"].mean() * 100
    print(f"\nOverall 'Good Trade' Rate : {win_rate:.2f}% (Target = 1)")

    print("\n--- Leak-Free Purged Splits ---")
    for name, split in [("Train", train_df), ("Val  ", val_df), ("Test ", test_df)]:
        start_ts = split["timestamp"].iloc[0]
        end_ts = split["timestamp"].iloc[-1]
        pos_rate = split["target"].mean() * 100
        print(f"{name}: {len(split):4d} rows | {start_ts} -> {end_ts} | Win Rate: {pos_rate:.1f}%")

    labeled_df.to_csv("btc_labeled_trades.csv", index=False)
    print("\nSaved labeled dataset to btc_labeled_trades.csv")

Expected Terminal Output

Running python label_and_split.py produces output like this:

'btc_ml_features.csv' not found — generating 2000 synthetic 1h candles...

--- Outcome Breakdown ---
outcome
stop_loss      1124
take_profit     562
timeout         284

Overall 'Good Trade' Rate : 28.53% (Target = 1)

--- Leak-Free Purged Splits ---
Train: 1379 rows | 2026-01-01 06:00:00 -> 2026-02-27 16:00:00 | Win Rate: 27.6%
Val  :  295 rows | 2026-02-28 17:00:00 -> 2026-03-12 23:00:00 | Win Rate: 31.2%
Test :  248 rows | 2026-03-14 00:00:00 -> 2026-03-24 07:00:00 | Win Rate: 29.8%

Saved labeled dataset to btc_labeled_trades.csv

Look closely at the timestamps between Train, Val, and Test. There is a clean 24-hour purge gap between them. That guarantees the final candle of Train (which looked 24 hours ahead to compute its label) never touches a single candle inside Val.

Also notice the 28.5% win rate. With a 2:1 reward-to-risk ratio (+2% TP vs -1% SL), you only need above ~33.3% accuracy (plus fees) to break even. That gives our upcoming AI model a very clear, realistic job: push that baseline win rate up by filtering out the worst setups!

Common Beginner Mistake: Calling train_test_split(X, y, test_size=0.2) from scikit-learn with its default shuffle=True. Shuffling time-series candles mixes tomorrow's prices into your training set and gives you an unrealistically high 90% accuracy score that immediately crashes in live trading. Always split chronologically and add a purge gap equal to your label horizon.


Study & Practice Recap

  • Label real trades, not tiny price wiggles: Triple-Barrier labeling (take_profit, stop_loss, horizon_bars) teaches your AI to hunt setups that survive real risk management.
  • Be conservative on ties: If a volatile candle hits both your take-profit and stop-loss in the same bar, assume the stop-loss triggered first so your backtest stays honest.
  • Chronological + purged splits prevent cheating: Dropping horizon_bars candles between Train, Validation, and Test eliminates subtle overlap leaks.

Tiny Hands-On Exercise: Change take_profit=0.015 and stop_loss=0.015 (a 1:1 risk-reward ratio) in label_and_split.py, re-run the script, and observe how the overall "Good Trade" rate and timeout count change.

Topics:#Machine Learning#Python#Data Labeling#Time Series#Backtesting