Skip to content

Algorithmic Trading and Execution

Forecasting an asset's return is only half the battle, because turning a statistical signal into live profit requires building diversified portfolios, executing giant orders without moving the market against yourself, and managing inventory risk second by second. This file bridges alpha generation, Almgren-Chriss optimal execution, Avellaneda-Stoikov market making, and reinforcement learning for trading.

Alpha Generation and Factor Investing

  • Suppose you invest in a technology stock and it climbs \(20\%\) during a year when the broader stock market climbs \(22\%\). Did you exhibit investment skill, or did a rising tide simply float your boat? Quantitative finance separates every portfolio's return into beta (exposure to broad systematic risk factors anyone can buy cheaply in an index fund) and alpha (genuine excess return left over after accounting for those exposures).

  • Decades of empirical finance research (pioneered by Eugene Fama and Kenneth French) showed that a handful of transparent risk factors explain much of the cross-sectional variation in stock returns.

    • Market (MKT) captures the excess return of equities over risk-free government bills.
    • Size (SMB, Small Minus Big) reflects the historical tendency of smaller companies to outperform giant corporations over long horizons.
    • Value (HML, High Minus Low) buys companies trading cheaply relative to accounting fundamentals (high book-to-market ratio) and shorts expensive glamour stocks.
    • Cross-sectional momentum ranks all stocks in a universe by their past 6-to-12-month returns (often skipping the most recent month), buying the recent winners and shorting the recent losers. Human under-reaction to gradual positive news and trend-following capital flows keep momentum alive across equities, currencies, and commodities.
    • Short-term mean reversion operates at the opposite horizon (minutes to a few days). When a large institution dumps a stock urgently for liquidity reasons rather than bad news, its price dips temporarily below fair value and snaps back once resting buyers step in.
  • Before an institutional desk celebrates a new ML alpha signal, it tests whether the signal delivers genuine incremental return after neutralising exposure to these well-known factors.

Information Coefficient and the Fundamental Law of Active Management

  • How much predictive accuracy do you actually need to run a world-class trading desk? Think of a casino versus a high-stakes gambler. A roulette house has only a tiny \(2.7\%\) edge per spin, yet because thousands of independent spins occur every night, the casino earns astonishingly steady profits.

  • Richard Grinold captured this exact principle in the Fundamental Law of Active Management. First, measure a signal's skill using its Information Coefficient (\(\text{IC}\)), defined as the cross-sectional correlation between your predicted scores \(\hat{\mathbf{r}}_t\) and the realised future returns \(\mathbf{r}_{t+1}\) across assets (often computed as Spearman rank correlation for robustness to outliers). Second, count your Breadth (\(\text{BR}\)), the number of independent bets your strategy makes per year. Grinold showed that your annualised Information Ratio (\(\text{IR}\)) (active return divided by active risk, the close cousin of the Sharpe ratio) scales approximately as follows.

\[\text{IR} \approx \text{IC}\,\sqrt{\text{BR}}\]
  • Look closely at what that square root reveals. A brilliant macro investor making 4 independent bets per year needs an astonishing \(\text{IC} \approx 0.50\) just to reach \(\text{IR} = 1.0\). By contrast, a statistical arbitrage desk with a seemingly modest \(\text{IC} = 0.04\) trading 2,500 independent stock-day opportunities per year achieves \(\text{IR} \approx 0.04 \times \sqrt{2500} = 2.0\)! Notice the crucial word independent. Betting on 500 tightly correlated bank stocks counts as roughly one bet, not 500, which is why orthogonalising signals across sectors matters as much as raw prediction accuracy.

Optimal Trade Execution

  • Imagine a pension fund decides to sell 2 million shares of a mid-sized company whose entire daily trading volume is 10 million shares. If the trader hits "Market Sell" right at the morning opening bell, the order smashes straight through every resting bid on the order book, crashing the stock price by several percent before the order even finishes filling. Worse still, sharp-eyed high-frequency desks spot the massive sell wave and step out of the way, turning temporary order-book exhaustion into permanent price impact.

  • To hide its footprint, an execution algorithm slices the large "parent" order of \(X_0\) shares into hundreds of tiny "child" orders over a trading horizon \(T\). Two classic benchmark schedules form the starting baseline on every Wall Street and City of London execution desk.

    • TWAP (Time-Weighted Average Price) divides the order into equal slices released at regular clock intervals (for instance, 10,000 shares every five minutes). It is simple and predictable, though rival algorithms can sometimes detect its rigid rhythm.
    • VWAP (Volume-Weighted Average Price) matches the market's natural intraday heartbeat. Real equity volume follows a pronounced U-shaped curve, roaring at the morning open, dozing through lunch, and surging again near the closing auction. VWAP trades bigger slices when the crowd is thick and smaller slices when the book is thin, keeping its footprint a steady tiny percentage of market volume.

The Almgren-Chriss Optimal Execution Framework

  • Still, slicing passively across the whole day creates an opposite danger. While you wait patiently to sell your remaining shares, bad news could strike and send the stock plunging before you finish! Implementation shortfall measures the total gap between the decision price \(P_0\) when you wanted to trade and the actual average price you realised.

  • In 2000, Robert Almgren and Neil Chriss formulated optimal execution as a crisp trade-off between expected market impact cost \(\mathbb{E}[C]\) (punishing haste) and price volatility variance \(\text{Var}(C)\) (punishing delay). Suppose your remaining inventory at time \(t\) is \(x(t)\) with liquidation rate \(v(t) = -\dot{x}(t)\), asset volatility is \(\sigma\), temporary impact coefficient is \(\eta\), and your risk aversion parameter is \(\lambda \ge 0\). Minimising the risk-adjusted objective \(\mathbb{E}[C] + \lambda\,\text{Var}(C)\) via calculus of variations (chapter 03) yields a closed-form optimal liquidation curve.

\[x(t) = X_0 \,\frac{\sinh\!\bigl(\kappa(T - t)\bigr)}{\sinh(\kappa T)}, \qquad \kappa = \sqrt{\frac{\lambda\,\sigma^2}{\eta}}\]
  • Check the two limiting extremes of this formula to feel its physical beauty.
    • When risk aversion \(\lambda \to 0\) (you do not care about price swings during the day), \(\kappa \to 0\) and \(\frac{\sinh(\kappa(T-t))}{\sinh(\kappa T)} \to 1 - \frac{t}{T}\), recovering straight-line TWAP!
    • When volatility \(\sigma\) or risk aversion \(\lambda\) is high, \(\kappa\) grows large and \(x(t)\) decays exponentially early in the session, front-loading most of the selling right away to cut exposure before prices can wander off.

Almgren-Chriss efficient frontier trading expected market impact cost against execution variance alongside remaining inventory trajectories for TWAP, VWAP, and risk-averse liquidation

Market Making and Inventory Control

  • If execution algorithms are impatient shoppers trying to buy or sell without moving prices, market makers are the shopkeepers who stand behind the counter all day quoting both a buy price (bid) and a sell price (ask). Every time an impatient seller dumps shares at the bid and an impatient buyer scoops them up at the ask, the market maker pockets the bid-ask spread.

  • That sounds like a licence to print money until you encounter the market maker's twin nightmares.

    • Adverse selection happens when an informed trader knows something you do not (for example, a leaked drug trial failure or a sudden jump on a correlated futures exchange). They rush in to hit your stale bid quote milliseconds before the whole market reprices downward. You buy right before a cliff, while your ask quote never fills.
    • Inventory risk happens when order flow tilts one-sidedly. Even without informed traders, a streak of nervous sellers can leave you holding a towering mountain of inventory (\(q \gg 0\)). Suddenly you are no longer a neutral spread-harvesting shopkeeper. You have become an accidental directional gambler praying the stock does not crash before you unload it.

The Avellaneda-Stoikov Quoting Model

  • Picture a fruit stall owner at four in the afternoon who still has twelve crates of ripe strawberries left before closing time at five o'clock. What do they do? They lower both the price they will pay wholesalers for new strawberries and the retail price on the chalk sign out front, nudging customers to clear out the excess crates before closing!

  • In 2008, Marco Avellaneda and Sasha Stoikov turned that street-market intuition into the foundational stochastic-control model of electronic market making. Given current mid-price \(s\), signed inventory \(q\) (positive when long, negative when short), risk aversion \(\gamma\), variance \(\sigma^2\), and remaining session time \(T - t\), the market maker first computes a personal reservation (indifference) price \(r\).

\[r(s, q, t) = s - q\,\gamma\,\sigma^2\,(T - t)\]
  • Around that shifted reservation price, the market maker places bid and ask quotes separated by an optimal total spread driven by risk and order-arrival elasticity \(k\).
\[\delta^a + \delta^b = \gamma\,\sigma^2\,(T - t) + \frac{2}{\gamma}\ln\!\left(1 + \frac{\gamma}{k}\right)\]
  • Watch how automatically this single equation protects the desk. When inventory is balanced (\(q = 0\)), your reservation price equals the market mid-price (\(r = s\)) and your quotes sit symmetrically to harvest the spread. The moment you accumulate positive inventory (\(q > 0\)), \(r\) drops below \(s\). Your ask quote moves closer to the market mid-price (making eager buyers much more likely to take shares off your hands), while your bid retreats further away (discouraging even more sellers from dumping onto you). Moreover, if volatility \(\sigma\) doubles, both your inventory skew and your total spread widen immediately to defend against violent price swings.

Avellaneda-Stoikov market making showing symmetric quoting when flat versus downward quote skewing when long inventory alongside spread capture and adverse selection risks

Reinforcement Learning for Execution and Hedging

  • Look back at optimal execution and market making and you will recognise a textbook Markov Decision Process (MDP) from chapter 06. At each step \(t\), the agent observes a rich state (remaining inventory \(q_t\), time left \(T - t\), bid-ask spread, order-book imbalance, recent volatility), chooses an action (child order size, or limit-order bid/ask offsets), and receives a reward combining realised trading profit, transaction costs, and a quadratic penalty \(-\lambda q_t^2 \sigma^2 \Delta t\) discouraging unhedged inventory.

  • Unlike rigid analytical formulas such as Almgren-Chriss or Avellaneda-Stoikov, which assume neat constant volatility and simple Poisson arrivals, Reinforcement Learning (RL) agents can learn nonlinear policies directly from multi-level order-book features and non-stationary volatility regimes.

  • A closely related success story is Deep Hedging (Buehler et al., 2019). Classical derivatives theory (Black-Scholes) assumes you can hedge an option continuously in a frictionless market with zero spreads and thin Gaussian tails. In reality, rebalancing every second incurs massive transaction costs, while rebalancing too rarely exposes the bank to jump risk. Deep hedging trains a neural policy via end-to-end policy gradients to minimise a risk-adjusted hedging objective (such as Conditional Value at Risk, CVaR) directly under realistic fees, discrete rebalancing intervals, and fat-tailed market dynamics.

  • Yet naive RL applied to financial trading has a notorious graveyard of failures, almost always caused by unrealistic market simulators. Three simulator illusions fool RL agents into learning disastrous policies.

    • Zero-impact historical replay. If you train an RL agent simply by stepping through recorded historical prices without modelling how the agent's own trades push prices away, the agent discovers fantastical "free-money" patterns that evaporate the instant real size hits the exchange.
    • Optimistic limit-order fills. Naive simulators assume that whenever the historical price touches your passive limit quote, you get filled completely. In real exchanges, you sit at the back of a crowded queue. You get filled almost every time the price punches straight through your quote (adverse selection!) and frequently get skipped when the price merely kisses your level and bounces away in your favour.
    • Overfitting a single historical path. Unlike chess or Atari, where an RL agent can play ten million fresh games against a fixed physics engine, markets give us only one realised historical timeline. Without realistic stochastic order-book simulators, domain randomisation over volatility and impact regimes, and conservative regularisation, an RL agent quickly memorises historical dates instead of learning durable control policies.

Take-Home

  • Factor models separate market beta from true alpha, and Grinold's Fundamental Law (\(\text{IR} \approx \text{IC}\sqrt{\text{BR}}\)) proves that a modest statistical edge applied across many independent bets beats occasional heroics.
  • Large orders pay severe market impact, so execution desks slice parent orders via TWAP, volume-matched VWAP, or Almgren-Chriss, which front-loads trading smoothly to balance impact cost against price-volatility risk.
  • Market makers earn the spread by managing inventory and adverse selection, and the Avellaneda-Stoikov reservation price \(r = s - q\gamma\sigma^2(T-t)\) automatically skews quotes against accumulated stock to pull inventory back toward zero.
  • Reinforcement learning and deep hedging generalise classical stochastic control to complex order-book states and realistic transaction costs, provided the training simulator faithfully models queue priority, adverse selection, and market impact.

Coding Tasks (use CoLab or notebook)

  1. Verify Grinold's Fundamental Law of Active Management (\(\text{IR} \approx \text{IC}\sqrt{\text{BR}}\)) by simulating cross-sectional stock universes with a fixed weak Information Coefficient (\(\text{IC} = 0.03\)) across varying breadth (number of independent stocks traded daily) and plotting realised annualised Information Ratio against the theoretical \(\text{IC}\sqrt{\text{BR}}\) curve.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(99)
    n_days = 1000
    ic_target = 0.03
    n_stocks_list = [5, 10, 25, 50, 100, 250, 500]
    
    emp_irs = []
    theo_irs = []
    
    for n_stocks in n_stocks_list:
        key, k1, k2 = jax.random.split(key, 3)
        # Generate unit-variance alpha score and realised return with correlation = ic_target
        score = jax.random.normal(k1, (n_days, n_stocks))
        noise = jax.random.normal(k2, (n_days, n_stocks))
        realised = (ic_target * score + jnp.sqrt(1.0 - ic_target ** 2) * noise) * 0.015
    
        # Dollar-neutral cross-sectional weights proportional to demeaned score
        w = score - jnp.mean(score, axis=1, keepdims=True)
        w = w / (jnp.sum(jnp.abs(w), axis=1, keepdims=True) + 1e-8)
    
        daily_pnl = jnp.sum(w * realised, axis=1)
        ir_emp = float(jnp.sqrt(252.0) * jnp.mean(daily_pnl) / (jnp.std(daily_pnl) + 1e-8))
        # Annual breadth is (n_stocks - 1) independent demeaned cross-sectional bets * 252 days
        breadth = (n_stocks - 1) * 252.0
        ir_theory = ic_target * float(jnp.sqrt(breadth))
        emp_irs.append(ir_emp)
        theo_irs.append(ir_theory)
        print(f"N={n_stocks:3d} stocks | BR={int(breadth):6d}/yr | Empirical IR={ir_emp:5.2f} | Theory IC*sqrt(BR)={ir_theory:5.2f}")
    
    plt.figure(figsize=(8.5, 4.2))
    plt.plot(n_stocks_list, theo_irs, "--", color="#e74c3c", lw=2.0, label="Theory  IR = IC * sqrt(BR)")
    plt.plot(n_stocks_list, emp_irs, "o-", color="#3498db", lw=2.2, label="Simulated Long-Short Portfolio")
    plt.xlabel("Independent Stocks Traded Daily (Breadth Scales Linearly)")
    plt.ylabel("Annualised Information Ratio (IR)")
    plt.title("Fundamental Law of Active Management (IC = 0.03)")
    plt.legend()
    plt.tight_layout()
    plt.show()
    

  2. Implement the Almgren-Chriss optimal liquidation schedule alongside TWAP and a U-shaped VWAP profile, then sweep risk aversion \(\lambda\) to trace the Expected Impact Cost versus Execution Variance efficient frontier.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    X0 = 100000.0   # 100,000 shares to liquidate
    T = 1.0         # 1 trading day
    N = 50          # 50 execution slices
    dt = T / N
    t_grid = jnp.linspace(0.0, T, N + 1)
    
    sigma = 0.02    # daily volatility (2%)
    eta = 2.5e-6    # temporary impact parameter
    
    def almgren_chriss_schedule(lam):
        """Compute remaining inventory x(t), expected temp impact cost, and variance."""
        if lam <= 1e-12:
            x = X0 * (1.0 - t_grid / T)
        else:
            kappa = jnp.sqrt(lam * (sigma ** 2) / eta)
            x = X0 * jnp.sinh(kappa * (T - t_grid)) / jnp.sinh(kappa * T)
        trades = x[:-1] - x[1:]                     # shares sold in each slice
        expected_cost = float(jnp.sum(eta * (trades ** 2) / dt))
        cost_var = float(jnp.sum((sigma ** 2) * (x[1:] ** 2) * dt))
        return x, expected_cost, cost_var
    
    # U-shaped VWAP intraday volume profile
    u_shape = 1.0 + 1.8 * ((t_grid[:-1] - 0.5) * 2.0) ** 2
    vwap_trades = X0 * (u_shape / jnp.sum(u_shape))
    x_vwap = jnp.concatenate([jnp.array([X0]), X0 - jnp.cumsum(vwap_trades)])
    
    x_twap, c_twap, v_twap = almgren_chriss_schedule(0.0)
    x_mid, c_mid, v_mid = almgren_chriss_schedule(2.0e-5)
    x_fast, c_fast, v_fast = almgren_chriss_schedule(2.5e-4)
    
    lambdas = jnp.logspace(-7, -3, 30)
    costs, stds = [], []
    for lam in lambdas:
        _, c, v = almgren_chriss_schedule(float(lam))
        costs.append(c)
        stds.append(v ** 0.5)
    
    print(f"TWAP            | Expected Impact={c_twap:7.1f} | Cost Std={v_twap**0.5:7.1f}")
    print(f"Balanced AC     | Expected Impact={c_mid:7.1f} | Cost Std={v_mid**0.5:7.1f}")
    print(f"Risk-Averse AC  | Expected Impact={c_fast:7.1f} | Cost Std={v_fast**0.5:7.1f}")
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 4))
    axes[0].plot(stds, costs, color="#3498db", lw=2.4, label="Almgren-Chriss Frontier")
    axes[0].scatter([v_twap**0.5, v_mid**0.5, v_fast**0.5], [c_twap, c_mid, c_fast],
                    color=["#f39c12", "#27ae60", "#e74c3c"], s=70, zorder=5)
    axes[0].set_xlabel("Execution Cost Std Dev (Timing Risk)")
    axes[0].set_ylabel("Expected Temporary Impact Cost")
    axes[0].set_title("Optimal Execution Efficient Frontier")
    axes[0].legend()
    
    axes[1].plot(t_grid, x_twap / 1000, "--", color="#666666", lw=1.8, label="TWAP (lambda = 0)")
    axes[1].plot(t_grid, x_vwap / 1000, color="#9b59b6", lw=2.0, label="VWAP (U-shaped volume)")
    axes[1].plot(t_grid, x_mid / 1000, color="#27ae60", lw=2.0, label="Balanced AC")
    axes[1].plot(t_grid, x_fast / 1000, color="#e74c3c", lw=2.2, label="Risk-Averse AC (front-loaded)")
    axes[1].set_xlabel("Trading Day Fraction (t / T)")
    axes[1].set_ylabel("Remaining Inventory (Thousands of Shares)")
    axes[1].set_title("Liquidation Trajectories Across Risk Aversion")
    axes[1].legend()
    plt.tight_layout()
    plt.show()
    

  3. Simulate an Avellaneda-Stoikov market maker facing random order arrivals over a full session, comparing an inventory-aware quoter (\(r = s - q\gamma\sigma^2(T-t)\)) against a naive symmetric quoter (\(r = s\)) on inventory drift and final PnL stability.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    def simulate_market_maker(key, use_skew=True, gamma=0.12, sigma=1.5, k_fill=1.5, A=140.0, n_steps=400):
        """Simulate market making over T=1.0 with Brownian mid-price and Poisson arrivals."""
        dt = 1.0 / n_steps
        k_price, k_bid, k_ask = jax.random.split(key, 3)
        dS = sigma * jnp.sqrt(dt) * jax.random.normal(k_price, (n_steps,))
        u_bid = jax.random.uniform(k_bid, (n_steps,))
        u_ask = jax.random.uniform(k_ask, (n_steps,))
    
        s = 100.0
        q = 0.0
        cash = 0.0
        inv_hist, pnl_hist = [], []
    
        for i in range(n_steps):
            t_left = max(1.0 - i * dt, 1e-4)
            s = s + float(dS[i])
            r = s - q * gamma * (sigma ** 2) * t_left if use_skew else s
            half_spread = 0.5 * (gamma * (sigma ** 2) * t_left + (2.0 / gamma) * float(jnp.log(1.0 + gamma / k_fill)))
    
            bid = r - half_spread
            ask = r + half_spread
            delta_b = max(s - bid, 0.0)
            delta_a = max(ask - s, 0.0)
    
            # Exponential arrival intensity lambda(delta) = A * exp(-k * delta)
            p_bid_fill = min(1.0, A * float(jnp.exp(-k_fill * delta_b)) * dt)
            p_ask_fill = min(1.0, A * float(jnp.exp(-k_fill * delta_a)) * dt)
    
            if float(u_bid[i]) < p_bid_fill:
                q += 1.0
                cash -= bid
            if float(u_ask[i]) < p_ask_fill:
                q -= 1.0
                cash += ask
    
            inv_hist.append(q)
            pnl_hist.append(cash + q * s)
    
        return jnp.array(inv_hist), jnp.array(pnl_hist)
    
    # Run 40 Monte Carlo episodes to compare inventory risk and PnL dispersion
    n_eps = 40
    key = jax.random.PRNGKey(55)
    pnl_as, pnl_sym, inv_as_end, inv_sym_end = [], [], [], []
    sample_inv_as, sample_inv_sym, sample_pnl_as, sample_pnl_sym = None, None, None, None
    
    for ep in range(n_eps):
        key, subk = jax.random.split(key)
        inv_a, p_a = simulate_market_maker(subk, use_skew=True)
        inv_s, p_s = simulate_market_maker(subk, use_skew=False)
        pnl_as.append(float(p_a[-1]))
        pnl_sym.append(float(p_s[-1]))
        inv_as_end.append(float(jnp.abs(inv_a[-1])))
        inv_sym_end.append(float(jnp.abs(inv_s[-1])))
        if ep == 0:
            sample_inv_as, sample_inv_sym = inv_a, inv_s
            sample_pnl_as, sample_pnl_sym = p_a, p_s
    
    pnl_as, pnl_sym = jnp.array(pnl_as), jnp.array(pnl_sym)
    print(f"Avellaneda-Stoikov | Mean PnL={float(jnp.mean(pnl_as)):6.2f} | Std PnL={float(jnp.std(pnl_as)):5.2f} | Avg |End q|={float(jnp.mean(jnp.array(inv_as_end))):.2f}")
    print(f"Naive Symmetric    | Mean PnL={float(jnp.mean(pnl_sym)):6.2f} | Std PnL={float(jnp.std(pnl_sym)):5.2f} | Avg |End q|={float(jnp.mean(jnp.array(inv_sym_end))):.2f}")
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 4))
    axes[0].plot(sample_inv_sym, color="#e74c3c", lw=1.6, alpha=0.8, label="Naive Symmetric Inventory")
    axes[0].plot(sample_inv_as, color="#27ae60", lw=2.0, label="Avellaneda-Stoikov Inventory")
    axes[0].axhline(0.0, color="#666666", ls="--", lw=1)
    axes[0].set_xlabel("Time Step")
    axes[0].set_ylabel("Signed Inventory q(t)")
    axes[0].set_title("Reservation Price Skew Pulls Inventory Back to Zero")
    axes[0].legend()
    
    axes[1].hist(pnl_sym, bins=14, alpha=0.5, color="#e74c3c", label="Naive Symmetric PnL")
    axes[1].hist(pnl_as, bins=14, alpha=0.6, color="#27ae60", label="Avellaneda-Stoikov PnL")
    axes[1].set_xlabel("Terminal Session PnL")
    axes[1].set_ylabel("Episode Count")
    axes[1].set_title("Terminal PnL Distribution (40 Sessions)")
    axes[1].legend()
    plt.tight_layout()
    plt.show()