Financial Markets and Data¶
Financial markets are among the most unforgiving playgrounds in all of machine learning, because every pattern you discover is buried in noise and actively hunted by rival algorithms. This file explores why financial data breaks standard ML assumptions, how limit order books turn buy and sell intentions into prices, and how purged cross-validation protects backtests from seductive illusions.
Why Financial Data Breaks Standard Machine Learning¶
-
Suppose you train an image classifier (chapter 08) to tell golden retrievers from tabby cats. The pixels of a cat face shout the right label clearly, cats will still look like cats next decade, and publishing your model weights on GitHub will never convince cats to grow floppy ears just to trick you. Financial markets fail every single one of those cosy assumptions simultaneously.
-
Four structural properties make financial data uniquely hostile to off-the-shelf supervised learning.
-
Extremely low signal-to-noise ratio. In computer vision or speech recognition, the deterministic signal explains nearly 100% of the label. In daily equity returns, unpredictable news shocks, liquidity squeezes, and random order flow routinely account for over 95% to 99% of day-to-day variance. A model achieving an out-of-sample \(R^2\) of just \(0.005\) (half of one percent!) on daily stock returns can power a multibillion-pound quantitative fund, yet standard deep neural networks trained with naive mean squared error will gleefully memorise the 99.5% noise instead of the 0.5% signal.
-
Non-stationarity and regime shifts. Standard statistical learning (chapter 06) assumes training and test points are drawn independently from the same fixed distribution \(P(X, Y)\). Markets obey no such truce. An inflation shock, a sudden central bank rate hike, a sovereign debt crisis, or a new electronic exchange rule abruptly shifts volatility, correlations, and investor behaviour. A relationship that held faithfully during a calm ten-year bull market can invert overnight during a liquidity panic.
-
Adversarial reflexivity. Financial markets are not passive physical systems like weather or planetary orbits. They are multiplayer games populated by intelligent, profit-seeking agents. As investor George Soros emphasised with the concept of reflexivity, beliefs and actions reshape the market itself. If you uncover a reliable statistical edge and publish it, or simply trade it with massive capital, competing desks crowd into the exact same trade. That crowding pushes prices away before you can enter and destroys the very pattern your model learned.
-
Fat-tailed returns and volatility clustering. Textbook finance often approximates asset returns with a tidy Gaussian bell curve (chapter 05). Real markets are far wilder. Large moves arrive in bursts (volatility clustering, first documented by Benoit Mandelbrot in 1963), where turbulent days breed more turbulent days and quiet months breed quiet months. Moreover, empirical return distributions exhibit heavy fat tails (high excess kurtosis), closely resembling a Student-\(t\) distribution with low degrees of freedom (\(\nu \approx 3\) to \(5\)).
-
-
To see how dangerous the Gaussian assumption is, imagine measuring human height. Nobody walks down the street who is twenty feet tall, because height obeys a thin-tailed bell curve. Asset returns behave nothing like height. Under a Gaussian model with daily volatility \(\sigma = 1\%\), a \(6\sigma\) crash should occur roughly once every 1.4 billion trading days, far longer than human civilisation. In real equity markets, \(5\sigma\) to \(8\sigma\) drops happen every few years (such as October 1987, the 2008 global financial crisis, and March 2020). Models calibrated to Gaussian tails underestimate crash risk by orders of magnitude.
-
Mathematically, the excess kurtosis of a return series \(r_1, \dots, r_T\) with mean \(\mu\) and standard deviation \(\sigma\) measures how heavily probability mass sits in the extreme tails relative to a Normal distribution.
- A Gaussian distribution has excess kurtosis equal to \(0\). Daily stock and cryptocurrency returns routinely display excess kurtosis between \(5\) and \(50\), warning us immediately that extreme shocks are normal citizens of financial data rather than rare measurement bugs to be clipped away.
Market Microstructure and the Limit Order Book¶
-
Most beginners picture "the price of a stock" as a single smooth curve printed in a newspaper. Zoom down to the millisecond level on a modern electronic exchange, however, and there is no single price. Instead, there is a living, breathing auction ledger called the Limit Order Book (LOB).
-
Picture a busy farmers' market where two queues of stalls face each other across a narrow aisle. On one side stand buyers holding up signs saying "I will buy 500 apples at £99.98 each" or "I will buy 900 apples at £99.96 each". On the opposite side stand sellers holding up signs saying "I will sell 420 apples at £100.02 each" or "I will sell 680 apples at £100.04 each". Those patient offers resting in the queues are limit orders. They supply liquidity to the market.
-
Now suppose an impatient shopper dashes down the aisle shouting "Sell me 1,500 apples right now at whatever price is available!" That urgent instruction is a market order. It demands immediacy and consumes the resting limit orders from the front of the queue outward.
-
Five core quantities describe the state of a limit order book at any instant \(t\).
- Best bid (\(p_t^{\text{bid}}\)) and best ask (\(p_t^{\text{ask}}\)) are the highest price any resting buyer is willing to pay and the lowest price any resting seller is willing to accept.
- The mid-price sits halfway between those two best quotes, serving as the standard reference point for fair short-term value.
- **The bid-ask spread** $s_t = p_t^{\text{ask}} - p_t^{\text{bid}}$ is the immediate cost of impatience. If you buy with a market order at the best ask and immediately sell with a market order at the best bid, you lose one full spread even if the mid-price never budges.
- **Order-book imbalance (OBI)** compares resting volume at the best bid ($V_t^{\text{bid}}$) against resting volume at the best ask ($V_t^{\text{ask}}$).
- When $\text{OBI}_t$ approaches $+1$, a thick wall of buyers stands ready while only a thin queue of sellers remains, signalling strong short-term upward price pressure. High-frequency traders routinely combine multi-level order-book imbalance with recent trade direction to forecast price ticks a fraction of a second ahead.
- **Price impact and walking the book.** If your market buy order is larger than the shares available at $p_t^{\text{ask}}$, it wipes out the first price level and climbs up to the next more expensive ask levels. Paying an average fill price worse than the starting mid-price is called **slippage** or **price impact**. Empirically across global equities, the temporary and permanent price impact $\Delta P$ of executing a large order of size $Q$ relative to daily volume $V$ follows an approximate **square-root law**, $\Delta P \propto \sigma \sqrt{Q / V}$, meaning impact grows sublinearly yet painfully fast as order size scales up.
Sampling in Information Time with Tick, Volume, and Dollar Bars¶
-
How should we turn a firehose of raw exchange ticks into tidy tabular rows for a machine learning model? Almost everyone starts with clock-time bars (recording open, high, low, close, and volume every 1 minute or every 1 hour). Yet markets do not tick at a steady metronome. The first fifteen minutes after the opening bell can see twenty times more news and trading volume than a sleepy Tuesday lunchtime.
-
Clock-time bars therefore oversample quiet periods (filling your dataset with stagnant, autocorrelated noise) and undersample frantic periods (compressing huge price moves into a single bar). Marcos López de Prado popularised three activity-driven alternatives that sample the market in information time instead of human wall-clock time.
- Tick bars emit a new bar after every fixed number of trades (say, every 1,000 transactions), regardless of whether those trades took three seconds or forty minutes.
- Volume bars emit a new bar after every fixed number of shares or contracts change hands (say, every 50,000 shares), preventing a single large order split into tiny child fills from distorting tick counts.
- Dollar bars (or pound bars) emit a new bar after a fixed monetary value is exchanged (say, every 5 million dollars of turnover). Dollar bars remain consistent even when a stock's share price doubles or splits over several years, and empirical tests show their resulting returns are noticeably closer to Gaussian and homoscedastic than raw clock-time bars.
Fatal Backtesting Traps¶
-
A backtest simulates how a trading strategy would have performed on historical market data. In theory, it acts like a flight simulator before risking real capital. In practice, naive backtesting is the single fastest way to fool yourself into deploying a money-losing algorithm. Four classic traps account for the vast majority of blown-up quantitative models.
-
Look-ahead bias occurs whenever information from the future secretly leaks into a decision made at time \(t\). Imagine trying to predict Friday's lottery numbers using Saturday's newspaper. In financial pipelines, look-ahead bias hides in subtle places, such as normalising a feature using the mean and standard deviation of the entire ten-year dataset before splitting train and test, using a company's quarterly earnings on the fiscal period end date rather than the later public announcement date, or computing a feature with today's closing price while assuming you executed at today's open.
-
Survivorship bias happens when you build a historical stock universe using only companies that still exist today. Think of judging how safe a mountain trail is by interviewing only hikers who made it back to the car park. If you backtest a value-investing strategy on today's S&P 500 constituents going back twenty years, you silently omit Enron, Lehman Brothers, and hundreds of distressed firms that went bankrupt and were delisted. Your backtest looks spectacular because every cheap stock in your database magically survived to prosper.
-
Ignoring transaction costs and slippage turns imaginary paper profits into real-world losses. Suppose a short-term reversal model predicts an average gross return of 6 basis points (\(0.06\%\)) per trade. If crossing the bid-ask spread, paying exchange fees, and suffering market impact cost 9 basis points round-trip, that "winning" strategy bleeds 3 basis points on every single fill. High-turnover ML models are especially vulnerable because frequent trading magnifies even tiny per-trade frictions.
-
Multiple-testing overfitting (p-hacking). Imagine handing 1,000 chimpanzees coins and asking them to call twenty flips in a row. Purely by luck, one chimpanzee will look like a prophetic genius. Quantitative researchers accidentally do the exact same thing when they try 500 feature sets, hyperparameter grids, and neural architectures on the same historical dataset and report only the highest Sharpe ratio (annualised excess return divided by annualised volatility, \(S = \frac{\mathbb{E}[r - r_f]}{\sigma} \sqrt{252}\)). As de Prado showed with the Deflated Sharpe Ratio, the expected maximum Sharpe ratio among \(N\) purely random noise strategies grows roughly like \(\sqrt{2 \ln N}\). Without tracking how many trials you ran, your "best" backtest is usually just the luckiest noise curve.
Purged and Embargoed Cross-Validation¶
-
In standard machine learning (chapter 06), researchers estimate generalisation performance with \(K\)-fold cross-validation, randomly shuffling rows into \(K\) folds. Never randomly shuffle financial time series! If Tuesday's return sits in the test fold while Monday's and Wednesday's returns sit in the training fold, your model can interpolate directly across the missing day using overlapping technical indicators and shared macro regimes.
-
Even chronological walk-forward validation or blocked \(K\)-fold has a sneaky leakage flaw whenever labels span multiple time steps. Suppose at day \(t\) your model predicts the 10-day forward return from \(t\) to \(t + 10\). If day \(t_{\text{train}}\) lies three days before the test fold begins at \(t_{\text{test}}\), its label overlaps seven full days inside the test period! Worse still, because market volatility and macroeconomic shocks decay slowly, training samples immediately after the test fold remain strongly autocorrelated with the test outcomes.
-
Marcos López de Prado solved both leaks with Purged and Embargoed Cross-Validation.
- Purging deletes every training observation whose label evaluation window \([t_i,\, t_i + h]\) overlaps with any timestamp inside the validation fold. That guarantees zero shared price moves between training targets and validation targets.
- Embargoing removes an additional buffer of training observations immediately following the end of the validation fold (typically \(1\%\) to \(5\%\) of the dataset length, or several times the autocorrelation decay length). That prevents slow-moving volatility regimes or serial correlation from leaking backward from the test period into adjacent post-test training folds.
-
Combined with strict out-of-sample holdout periods kept locked in a vault until the very end of research, purged and embargoed validation turns backtesting from a flattering vanity mirror into an honest scientific stress test.
Take-Home¶
- Financial data breaks i.i.d. machine learning because signal-to-noise ratios are tiny, regimes shift abruptly, fat-tailed crashes recur far more often than Gaussian curves predict, and adversarial reflexivity erodes crowded edges.
- Limit order books reveal real market mechanics where resting bids and asks form the bid-ask spread, order-book imbalance captures immediate supply-demand pressure, and urgent market orders pay price impact as they walk up the book.
- Volume and dollar bars beat clock-time bars by sampling markets in information time, producing return distributions that are more uniform and closer to statistical stationarity.
- Most shiny backtests fail live due to subtle look-ahead bias, survivorship bias in stock universes, unmodelled transaction costs and slippage, and multiple-testing overfitting across hundreds of trials.
- Purged and embargoed cross-validation eliminates hidden temporal leakage by stripping overlapping multi-horizon training labels and inserting a post-test embargo buffer.
Coding Tasks (use CoLab or notebook)¶
-
Simulate daily returns from both a Gaussian model and a heavy-tailed Student-\(t\) model (using pure JAX normal and chi-squared scaling with \(\nu = 4\) degrees of freedom, matched to the same variance), compare empirical excess kurtosis and the frequency of extreme \(>4\sigma\) crashes, and plot both distributions on a log-density scale.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(42) k1, k2, k3 = jax.random.split(key, 3) N = 20000 sigma_daily = 0.01 # 1% daily volatility df = 4 # heavy-tailed degrees of freedom # 1. Gaussian returns r_gauss = jax.random.normal(k1, (N,)) * sigma_daily # 2. Student-t returns built from Z / sqrt(chi2 / df), rescaled to match variance z = jax.random.normal(k2, (N,)) chi2 = jnp.sum(jax.random.normal(k3, (N, df)) ** 2, axis=1) t_raw = z / jnp.sqrt(chi2 / df) # Analytical variance of t(df) is df / (df - 2) t_std = jnp.sqrt(df / (df - 2.0)) r_student = (t_raw / t_std) * sigma_daily def summary_stats(r, name): mu = jnp.mean(r) sd = jnp.std(r) kurt = jnp.mean(((r - mu) / sd) ** 4) - 3.0 crashes_4s = int(jnp.sum(jnp.abs(r - mu) > 4.0 * sd)) crashes_6s = int(jnp.sum(jnp.abs(r - mu) > 6.0 * sd)) print(f"{name:10s} | std={float(sd):.4f} | excess kurtosis={float(kurt):6.2f} | >4sigma={crashes_4s:3d} | >6sigma={crashes_6s:2d}") summary_stats(r_gauss, "Gaussian") summary_stats(r_student, "Student-t") fig, axes = plt.subplots(1, 2, figsize=(12, 4)) bins = jnp.linspace(-0.09, 0.09, 90) axes[0].hist(r_gauss * 100, bins=bins * 100, density=True, alpha=0.45, color="#3498db", label="Gaussian") axes[0].hist(r_student * 100, bins=bins * 100, density=True, alpha=0.45, color="#e74c3c", label="Student-t (df=4)") axes[0].set_yscale("log") axes[0].set_xlabel("Daily Return (%)") axes[0].set_ylabel("Log Probability Density") axes[0].set_title("Log-Scale Tail Comparison (Fat Crash Tails)") axes[0].legend() # Show 400-day sample path for visual contrast axes[1].plot(r_gauss[:400] * 100, color="#3498db", lw=1.0, alpha=0.75, label="Gaussian") axes[1].plot(r_student[:400] * 100, color="#e74c3c", lw=1.1, alpha=0.85, label="Student-t") axes[1].set_xlabel("Trading Day") axes[1].set_ylabel("Daily Return (%)") axes[1].set_title("400-Day Return Paths (Same Volatility, Wildly Different Shocks)") axes[1].legend() plt.tight_layout() plt.show() -
Build a multi-level Limit Order Book simulator in JAX, compute its mid-price, spread, and order-book imbalance, then execute market buy orders of growing size to measure how walking the book creates nonlinear slippage and price impact.
import jax.numpy as jnp import matplotlib.pyplot as plt # Limit order book levels (prices in pounds, quantities in shares) ask_prices = jnp.array([100.02, 100.04, 100.06, 100.09, 100.13, 100.18, 100.25]) ask_sizes = jnp.array([420.0, 680.0, 950.0, 1100.0, 1250.0, 1400.0, 1800.0]) bid_prices = jnp.array([99.98, 99.96, 99.94, 99.91, 99.87, 99.82, 99.75]) bid_sizes = jnp.array([780.0, 920.0, 1060.0, 1150.0, 1300.0, 1450.0, 1700.0]) mid_price = 0.5 * (ask_prices[0] + bid_prices[0]) spread = ask_prices[0] - bid_prices[0] obi = (bid_sizes[0] - ask_sizes[0]) / (bid_sizes[0] + ask_sizes[0]) print(f"Mid-price={float(mid_price):.2f} | Spread={float(spread):.2f} | Top-level OBI={float(obi):+.3f}") def walk_ask_book(order_qty, prices, sizes): """Compute average fill price and slippage (in bps) for a market buy order.""" cum_before = jnp.concatenate([jnp.array([0.0]), jnp.cumsum(sizes)[:-1]]) filled_at_level = jnp.clip(order_qty - cum_before, 0.0, sizes) total_filled = jnp.sum(filled_at_level) vwap_fill = jnp.sum(filled_at_level * prices) / (total_filled + 1e-8) slippage_bps = ((vwap_fill - mid_price) / mid_price) * 10000.0 return vwap_fill, slippage_bps order_sizes = jnp.linspace(100.0, 6500.0, 35) slippages = [] avg_fills = [] for q in order_sizes: fill_p, slip = walk_ask_book(q, ask_prices, ask_sizes) avg_fills.append(float(fill_p)) slippages.append(float(slip)) slippages = jnp.array(slippages) print(f"500-share buy slippage = {float(walk_ask_book(500.0, ask_prices, ask_sizes)[1]):.2f} bps") print(f"4000-share buy slippage = {float(walk_ask_book(4000.0, ask_prices, ask_sizes)[1]):.2f} bps") fig, axes = plt.subplots(1, 2, figsize=(12, 4)) axes[0].barh(ask_prices, ask_sizes, height=0.014, color="#e74c3c", alpha=0.65, label="Asks (Sellers)") axes[0].barh(bid_prices, bid_sizes, height=0.014, color="#27ae60", alpha=0.65, label="Bids (Buyers)") axes[0].axhline(float(mid_price), color="#3498db", ls="--", lw=1.4, label="Mid-Price") axes[0].set_xlabel("Queued Shares") axes[0].set_ylabel("Price Level") axes[0].set_title("Limit Order Book Depth Profile") axes[0].legend() axes[1].plot(order_sizes, slippages, "o-", color="#9b59b6", lw=2, markersize=4) axes[1].set_xlabel("Market Buy Order Size (Shares)") axes[1].set_ylabel("Execution Slippage vs Mid (bps)") axes[1].set_title("Walking the Book Generates Rising Price Impact") plt.tight_layout() plt.show() -
Demonstrate multiple-testing overfitting on pure random noise (testing 400 candidate signals in-sample and watching the "winning" strategy collapse out-of-sample), then implement a Purged and Embargoed \(K\)-fold splitter for overlapping multi-day return labels and visualise the train, purged, test, and embargo windows.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Part A: Multiple-testing overfitting on zero-alpha white noise key = jax.random.PRNGKey(123) k1, k2 = jax.random.split(key) T_in, T_out = 504, 504 # 2 years in-sample, 2 years out-of-sample N_trials = 400 # 400 random candidate strategies # Pure zero-mean Gaussian noise returns (no true edge exists!) strat_in = jax.random.normal(k1, (T_in, N_trials)) * 0.01 strat_out = jax.random.normal(k2, (T_out, N_trials)) * 0.01 sharpe_in = jnp.sqrt(252.0) * jnp.mean(strat_in, axis=0) / jnp.std(strat_in, axis=0) sharpe_out = jnp.sqrt(252.0) * jnp.mean(strat_out, axis=0) / jnp.std(strat_out, axis=0) best_idx = int(jnp.argmax(sharpe_in)) print(f"Best of {N_trials} random strategies in-sample Sharpe = {float(sharpe_in[best_idx]):+.2f}") print(f"That same winner's out-of-sample Sharpe = {float(sharpe_out[best_idx]):+.2f}") # Part B: Purged and Embargoed K-Fold Splitter for overlapping h-day labels def purged_embargo_folds(n_samples, n_splits=5, label_horizon=15, embargo_len=12): """Return integer masks per fold (0=train, 1=test, 2=purged, 3=embargo).""" fold_size = n_samples // n_splits idx = jnp.arange(n_samples) masks = [] for k in range(n_splits): t_start = k * fold_size t_end = (k + 1) * fold_size if k < n_splits - 1 else n_samples is_test = (idx >= t_start) & (idx < t_end) # Purge training samples whose [t, t + label_horizon] overlaps [t_start, t_end) is_purged = (idx < t_start) & ((idx + label_horizon) > t_start) # Embargo training samples immediately after t_end is_embargo = (idx >= t_end) & (idx < t_end + embargo_len) mask = jnp.where(is_test, 1, jnp.where(is_purged, 2, jnp.where(is_embargo, 3, 0))) masks.append(mask) return jnp.stack(masks, axis=0) masks = purged_embargo_folds(n_samples=300, n_splits=5, label_horizon=15, embargo_len=12) fig, axes = plt.subplots(1, 2, figsize=(12, 4)) axes[0].scatter(sharpe_in, sharpe_out, alpha=0.45, s=18, color="#3498db", label="400 noise strategies") axes[0].scatter([sharpe_in[best_idx]], [sharpe_out[best_idx]], color="#e74c3c", s=70, zorder=5, label="In-sample winner") axes[0].axhline(0.0, color="#666666", ls="--", lw=1) axes[0].axvline(0.0, color="#666666", ls="--", lw=1) axes[0].set_xlabel("In-Sample Sharpe Ratio") axes[0].set_ylabel("Out-of-Sample Sharpe Ratio") axes[0].set_title("Multiple-Testing Illusion on Pure Noise") axes[0].legend() axes[1].imshow(masks, aspect="auto", interpolation="nearest", cmap="viridis") axes[1].set_yticks(range(5)) axes[1].set_yticklabels([f"Fold {i+1}" for i in range(5)]) axes[1].set_xlabel("Time Index") axes[1].set_title("Purged & Embargoed CV (0=Train, 1=Test, 2=Purged, 3=Embargo)") plt.tight_layout() plt.show()