PnL ProfitEncyclopedia
🌐 English

Machine Learning in Trading

7 min read · Updated Nov 23, 2026
More in Algorithmic & Quant Trading

Machine learning (ML) in trading is a branch of algorithmic trading that uses algorithms that learn patterns from data, rather than following hand-written rules, to forecast prices, classify market conditions or process text such as news. It is widely used by quantitative funds, but financial data is noisy and constantly changing, which makes ML models unusually prone to finding patterns that are not there. Used carefully, ML is a useful tool; used carelessly, it is one of the fastest ways to build a convincing backtest that fails live.

Key takeaways

  • Most trading ML is supervised learning: predicting a future return or direction from features known today.
  • How you define labels and validate models matters more than which algorithm you pick.
  • Markets are non-stationary and the signal-to-noise ratio is very low, so small accuracy gains can be meaningful and large ones are suspicious.
  • Standard cross-validation leaks future information in time series; use walk-forward or purged validation.
  • Large language models are useful for reading and classifying text, but backtests that use them can be contaminated by knowledge of events after the test date.
On this page
  1. What ML can and cannot do
  2. Supervised learning for signals
  3. Features
  4. Labeling
  5. Non-stationarity and noise
  6. Validation without leakage
  7. LLMs for news and sentiment
  8. Worked example: accuracy is not profit
  9. Common mistakes

What ML can and cannot do

ML is good at combining many weak signals, capturing nonlinear relationships and processing data humans cannot read at scale, such as thousands of news articles or filings. It cannot create predictability that is not in the data. Asset prices are largely unpredictable over most horizons, and much of what predictability exists is competed away. In a well-known 2020 study, Gu, Kelly and Xiu found that flexible methods such as tree ensembles and neural networks forecast monthly US stock returns better than traditional linear models, but the predictable share of returns was small.

Supervised learning for signals

Problem types

  • Regression: predict the size of the next return, such as the 5-day return.
  • Classification: predict a category, such as up or down, or "hits profit target before stop".
  • Ranking: order assets by expected return and buy the top, short the bottom, a common approach in cross-sectional stock selection.

Common models

Model family Strengths Weaknesses
Linear and regularized regression (ridge, lasso) Simple, stable, interpretable Misses nonlinear effects
Tree ensembles (random forests, gradient boosting) Handle nonlinearity and mixed features well; strong on tabular data Can overfit noise; less smooth predictions
Neural networks Flexible; handle sequences, text and images Need lots of data; hard to interpret; easiest to overfit

On typical tabular trading data, regularized linear models and gradient-boosted trees are common starting points. More complex models need more data to justify them.

Features

Features are the inputs a model uses. They must be known at the moment of the prediction.

  • Price-based: past returns over several horizons, volatility, distance from moving averages, technical indicators such as RSI.
  • Volume and order flow: relative volume, order book imbalance, trade direction.
  • Cross-sectional: an asset's return relative to its sector or the market.
  • Fundamental: valuation ratios, earnings surprises, using data only from its publication date.
  • Alternative data: text sentiment, web traffic, satellite or transaction data.
  • Market context: volatility indices, interest rates, sentiment indicators such as funding rates.

Normalize features using only past data, for example a rolling z-score, so that the model never sees statistics computed from the future. Data sourcing and timestamps are covered in market data.

Labeling

The label is what the model learns to predict, and choosing it well is half the problem.

  • Fixed-horizon labels: the sign or size of the return over the next N bars. Simple, but it ignores the path and how a real trade would be managed.
  • Triple-barrier labels: described by Marcos López de Prado in his 2018 book Advances in Financial Machine Learning. Each sample is labeled by which comes first: an upper barrier (profit target), a lower barrier (stop) or a time limit. This matches how trades actually exit.
  • Meta-labeling: a primary model or rule decides direction, and a secondary ML model predicts whether each primary signal will succeed, which can be used to filter trades or set position size.

Overlapping labels, such as 5-day returns computed every day, share information. That has to be handled in validation.

Non-stationarity and noise

Financial relationships change. A pattern that held during low interest rates may vanish when rates rise; a feature that worked before many traders used it may stop working afterward. Signal-to-noise is very low: a model that predicts daily direction correctly 52% to 53% of the time can be useful, while 70% accuracy on daily direction almost always indicates a bug or leakage.

This is the same regime problem that troubles rule-based mean reversion and trend systems. Practical responses include retraining on rolling windows, preferring simpler models, combining many weak signals, and monitoring live performance for decay.

Validation without leakage

Standard k-fold cross-validation shuffles data randomly, so the model trains on the future and tests on the past. For trading, use:

  • Walk-forward validation: train on past data, test on the next period, roll forward.
  • Gaps and purging: remove training samples whose labels overlap the test period, and leave an embargo gap after it.
  • A final holdout: a recent period never touched during development.
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import TimeSeriesSplit

def walk_forward_accuracy(X, y, horizon=5, n_splits=5):
    """X: features known at time t; y: label for t -> t+horizon. Rows in time order."""
    splitter = TimeSeriesSplit(n_splits=n_splits, gap=horizon)  # gap avoids label overlap
    scores = []
    for train_idx, test_idx in splitter.split(X):
        model = GradientBoostingClassifier(max_depth=3, n_estimators=200)
        model.fit(X[train_idx], y[train_idx])
        scores.append((model.predict(X[test_idx]) == y[test_idx]).mean())
    return np.mean(scores), np.std(scores)

Every model you train and evaluate is another trial, so the multiple-testing problems in overfitting and data snooping apply with extra force.

LLMs for news and sentiment

Large language models can read news, earnings call transcripts, filings and social media posts, and turn them into structured signals: positive or negative tone, event type, companies mentioned, or summaries for a human trader. Practical uses include filtering a news flow, tagging events, and screening large volumes of text faster than a person could.

Important caveats:

  • Look-ahead contamination. A model trained on internet text up to a recent date may "know" how a company or market actually fared after the date of a historical article. A backtest of LLM-based sentiment on past news can therefore look far better than live trading. Use models whose training cutoff precedes the test period where possible, or test only on data after the cutoff.
  • Errors and hallucinations. LLMs can misread numbers, confuse companies or invent details. Validate outputs, especially extracted figures.
  • Latency and cost. By the time a model processes a headline, fast traders may already have acted. LLM signals tend to suit slower horizons.
  • Crowding. Widely available models applied to widely available news are unlikely to provide a durable edge on their own.

Reinforcement learning, where an agent learns a trading policy by trial and error in a simulator, is an active research area, but it is especially sensitive to simulator realism and overfitting.

Worked example: accuracy is not profit

A classifier predicts next-day direction for a stock index fund with 53% accuracy on walk-forward tests. Assume average up and down days are both about 1.0%.

  • Expected gross return per trade = 0.53 × 1.0% − 0.47 × 1.0% = 0.06%.
  • With round-trip costs of 0.05%, the net edge is 0.01% per trade, or roughly 252 × 0.01% ≈ 2.5% per year if it trades every day (ignoring compounding).
  • With costs of 0.10% per round trip, the net edge is −0.04% per trade, roughly −10% per year.

The same model also has to keep its 53% accuracy in the future, which non-stationarity makes uncertain. ML signals often work best combined with low-turnover strategies, where costs eat less of a small edge.

Common mistakes

  • Random train/test splits on time series. This leaks the future into training.
  • Features computed with future data, such as full-sample normalization or revised economic figures.
  • Chasing high accuracy. Very high accuracy on returns is usually a sign of leakage.
  • Complex models on small data. A deep network trained on a few years of daily bars has far more parameters than useful observations.
  • Ignoring costs and turnover. Small edges vanish if the model trades too often.
  • Trusting LLM backtests on old news without addressing training-data contamination.

FAQ

Can machine learning predict stock prices?

Machine learning can find weak, statistically useful patterns in returns, but it cannot predict prices reliably. Research suggests the predictable part of returns is small, and patterns change over time.

What is the best machine learning model for trading?

There is no single best model. Regularized linear models and gradient-boosted trees are common starting points for tabular data, and the choice of labels, features and validation method usually matters more than the algorithm.

Can I use ChatGPT or other LLMs to trade?

LLMs can help summarize news, classify sentiment and write or review code, but they do not have reliable insight into future prices. Treat their outputs as one input to test, and be careful of backtests that may be contaminated by the model's training data.

Why do machine learning trading strategies fail?

Common reasons are overfitting to noise, data leakage in validation, changing market conditions and trading costs that exceed a small predicted edge.

Educational content only. Nothing here is financial, investment, legal or tax advice. Trading carries a high risk of loss, and leveraged products can lose more than you deposit. Rules, fees and platform details change: check current terms with your broker, exchange or regulator before you trade.