Trading Dev AcademyFree quant education

Free lesson · Statistical arbitrage

Two-leg backtesting, borrow, capacity and ML extensions

Open interactive lessonPractice calculationsExplore labs

Start with the idea

The unit of evidence is a fully accounted portfolio path. A residual chart omits the costs and risks of holding real instruments. ML can improve a component—selection, convergence forecasting or cost estimation—without replacing that accounting.

Symbols, units & horizon
  • q_i: fixed signed share holdings in leg i over the example
  • ΔP_i: exit minus entry price
  • Δq_j: executed quantity at transaction j
  • c_j: per-share commission and slippage cost
  • b_i: annualised simple borrow fraction
  • d: calendar holding days
  • 365: example accrual convention, replace with actual contract convention
  • Π_net: currency P&L before other financing or dividends

When and why to use this

Use this ledger to decide whether a statistical forecast remains valuable after turning it into a financed, executable position.

Backtest cash and each instrument position, using executable bid/ask or conservative slippage, commissions, borrow and funding. Charge costs on all entry, exit and rebalance trades. Calendar spreads need contract rolls and multipliers; cross-venue positions need transfer, collateral and basis risks.

Simulate the possibility that only one leg fills. A hedge order can reduce unwanted directional exposure but incurs another price and cost. Pair portfolios must net instrument orders consistently; report gross versus net turnover and whether netting was actually feasible at the same decision time.

Useful ML targets include residual return over a fixed horizon, probability of convergence before a time stop, conditional loss size and borrow/cost forecasts. Train these on out-of-fold signals, preserving the complete candidate universe. Compare each learned component against the same fixed-rule baseline and capital budget.

Πnet=∑iqiΔPi−∑j|Δqj|cj−∑i:qi<0|qi|Pibid365
Model assumptions, derivation and arithmetic

Two-leg backtesting, borrow, capacity and ML extensions

  1. Sum signed share holdings times each price change for gross marked P&L.
  2. For every transaction multiply absolute executed quantity by its per-share cost, so both sides of the round trip are charged.
  3. Compute simple borrow from the short notional times annual rate times year fraction. For changing prices or rates, accrue daily instead of using this constant-notional approximation.
Work it by hand

Long 100 A and short 200 B earn $100 gross. Four entry/exit fills total 600 shares at $.02/share cost $12. Short notional $2,000 at 5% for 10 days costs $2.7397. Net≈$85.2603 before other financing.

Apply it in a strategy

  • Reconcile one trade manually, then aggregate trades and daily marked P&L without double counting.
  • Stress borrow recalls, asynchronous fills, widened spreads, slower convergence and capacity.
  • Only then test whether a learned selector or forecast adds out-of-sample net value over the established baseline.

Research deliverable

Present net performance by year and regime, a complete cost decomposition, gross exposures and a failure-case ledger for unhedged fills.

Research checkpoint · reviewed 11 September 2026

These sources inform the questions to test. A result is conditional on its data, simulator and evaluation design. The examples in this module are teaching calculations, not reproductions of the reported experiments.

Recent relative-value research. The publisher abstract for Pairs trading with time-series deep learning models describes learned residual forecasts on S&P 500 and cryptocurrency universes and reports improvements over a relative-value baseline. Access here was limited to the publisher abstract; the exact full sample endpoints and execution robustness were not verified. Metadata shows a 2026 DOI/copyright but a volume labelled December 2025. This makes it a replication candidate, not an established best implementation.

Further reading: Pairs trading with time-series deep learning models · journal article ↗

Costs across related legs. This preprint models cross-contract and transient impact and describes a crude-oil calendar-spread application around index rolls. Abstract and metadata reviewed; sample dates and code were not assessed. Its relevance here is the possibility that joint execution costs differ from adding independent leg costs. Our teaching inference is to test the joint cost model, not assume the paper’s results transfer to another universe.

Further reading: Yinjun-Wang & Udell · Convex Modeling of Price Cross-Impact over Time · 4 September 2026 ↗

Research sources, review dates and limitations

Extend the research question

List every leg, hedge quantity, financing charge and failure state. A stationary fitted residual is not a contractual claim to convergence.

Continue with the connected research module →

Python implementation

Self-contained teaching example. Python 3.10+; dependencies and input conventions are shown in the code and notation. Run in your own Python environment.

def two_leg_net(holdings,changes,traded_shares,cost_per_share,short_notional,borrow,days):
    if len(holdings)!=len(changes) or min(traded_shares,cost_per_share,short_notional,borrow,days)<0: raise ValueError("Invalid ledger")
    gross=sum(q*dp for q,dp in zip(holdings,changes))
    return gross-traded_shares*cost_per_share-short_notional*borrow*days/365

print(two_leg_net([100,-200],[-1,-1],600,.02,2000,.05,10))

Continue learning

Statistical Arbitrage: Relative Value to Tradable Portfolios — all lessons
  1. What statistical arbitrage is—and where it applies
  2. Construct the spread: price ratios, log ratios and executable units
  3. Cointegration, reversion speed and structural breaks
  4. Causal z-scores and a complete entry–exit state machine
  5. From pairs to residual baskets and factor neutrality
  6. Two-leg backtesting, borrow, capacity and ML extensions

Quantitative finance and development glossary · Python resources and libraries · Research sources and limitations