Module contents
Lesson 25 of 30Core 120 min

Honest backtesting I: the engine, biases and costs

Build and evaluate backtests with vectorized and event-driven architectures, point-in-time data, leakage and survivorship checks, transaction costs, walk-forward validation, capacity and simulated book execution.

After this lesson you can

  • Implement an event-driven backtester separating available information from decisions.
  • Detect look-ahead and survivorship bias, revised data and unreachable prices with automated checks.
  • Model transaction costs and their dependence on size.
  • Apply anchored and rolling walk-forward validation and explain its limits.
  • Estimate capacity as the size at which net Sharpe reaches zero or halves.

Before you start

Simulating a decision that could have existed

A backtest asks what would have happened under specific rules, data and executions. The outcome is counterfactual: one’s own trade might have changed observed liquidity and prices. An attractive curve does not identify an edge by itself. Interpreting it requires reconstructing what was known, what could be traded, at what price and how many variants were tried.

An event-driven engine processes data, signals, orders, fills and accounting in an explicit order. A vectorized architecture can be faster and also correct if it respects the same clock; an event engine is not automatically immune to leakage. Comparing both in a simple case is a useful check, not complete certification.

Look-ahead and selection

Look-ahead bias occurs when a decision uses information not yet available. If a signal uses today’s official close, execution at that same close requires an auction rule allowing the order to be sent before knowing it; otherwise a later price is needed. A revision published months later does not replace the historically available value. The Kenneth French library archive illustrates that a dataset can have different vintages.

Survivorship bias occurs when reconstructing the past only with entities selected using later information, such as current index constituents. Excluding firms that disappeared often inflates measures in some designs, but the particular direction depends on selection rule, weights and delistings. Stable identifiers, inclusion dates and delisting returns are part of the universe; a ticker alone can change meaning.

A timing example helps detect leakage. A signal calculated from Monday’s close of 101 cannot retrospectively order a buy at 101 after learning that close. If the next open is 102, using 101 as the fill omits one unit of cost per share in that case. An order sent to the auction before the close can have a different rule and available information, but its timing and priority must be modeled.

InteractiveInject leakage

250 days and 80 assets with independent zero-mean Gaussian returns. The rule centers the prior return by the available mean and takes equal-size long or short positions. This example omits costs and bankruptcies.

1.000.98Days 0 to 250

The mean uses earlier data, and the previous day's return determines the position.

Variant
Final / initial capital1.003
Compare synthetic variants on the same sample and observe how the curve changes.

The universe variant retrospectively chooses the best-performing assets; it does not simulate every cause of a real delisting. Using full-sample statistics for normalization also leaks future information, although it does not always inflate results. Publication dates, time zones, dividend and split adjustments, revisions and different market closes need explicit conventions. Tests perturbing later data detect some improper dependencies; they do not prove a strategy is free of all leakage.

Costs and capacity

A cost model can add commission, half-spread, size-dependent impact, short borrow and financing. For example, for a trade of QQ units and forecast volume VV, reference impact YσQ/VY\sigma\sqrt{Q/V} is an assumption about relative movement. Applying it as average cost of the entire trade makes an additional assumption; final impact and mean execution price need not coincide. Volume and spread estimates must be available at decision time or used as scenarios, not foreknowledge.

Fill and slippage simulation should distinguish an aggressive order consuming the opposite side from a passive order behind others in the queue. Touching a price does not guarantee execution. An open, VWAP or close may not be available for the requested size. Novy-Marx and Velikov show costs and turnover-reduction rules affect anomaly profitability in their sample; their results do not determine the cost of another strategy.

Capacity is an operational definition: for example, capital at which expected net Sharpe reaches zero or half the gross value. It depends on flows, liquidity, financing, limits and risk. It is not a unique physical property of the signal. The figure holds gross return and volatility constant and applies an explicit impact rule to show a hypothetical curve.

InteractiveCosts and capital

The assumptions are an 8% annual gross return, 15% volatility, 252 days, 10 M in reference daily volume, 2% daily volatility, 2 bp of commission, and an average impact cost of Yσ√(Q/V). Turnover is annual traded notional divided by capital.

0.44−1.22Capital: 0 to 100 millionNet Sharpe

The average daily trade is capital × turnover / 252, with constant volume and risk and an impact formula applied as average cost. The curve is a model capacity estimate. A root outside the plotted range extrapolates this same model.

20
5
0.7
10
Assumed net Sharpe−0.086
Capital at zero Sharpe7.001 M
Capital at half the gross return1.086 M
Change turnover and impact; the displayed capacity belongs only to the model.

Walking forward

Walk-forward validation fits on a past block, freezes the rule and evaluates the next block. An anchored window keeps all available history; a rolling one discards older data. It then updates and concatenates only out-of-sample results. If labels or features use windows crossing the split, purge that overlap and, where appropriate, impose an embargo.

InteractiveWindows over time

180 synthetic signals with a change in the relationship at step 90. The model fits a slope in each window and uses the sign of its forecast. Position changes cost 4 bp per unit. The example demonstrates the methodology using synthetic performance.

Training blue · test orange1.270.98Decisions 0 to 180

Training [0, 40) and test [40, 60). The last training label is already available when the test starts. The curve joins OOS results only and keeps capital constant during the initial window.

Window
40
20
0
OOS blocks7
OOS / initial capital1.217
Change training length and mode; the orange block is test.

A single walk-forward path remains one sample, and changing windows or rules after seeing results makes those results part of the search. Record every attempt and keep a separate final evaluation. Bailey and coauthors study how selection among configurations can create overfitting even when each simulation seems precise.

Lab: event-driven engine

We generate synthetic daily prices with different opens and closes. The signal observes closes through day tt and sends a target position for the open of t+1t+1. Each day the pending order executes first, then the portfolio is marked at close, and finally the signal is calculated. The example trades one long or short unit, not a portfolio with real limits; there are no dividend, split or delisting adjustments. Optional costs are declared approximations.

[ ]Data and engine with an explicit clockBrowser
import numpy as np
rng=np.random.default_rng(282501); T=500
apertura=np.empty(T); cierre=np.empty(T); volumen=rng.uniform(5000,15000,T); ultimo=100.
for t in range(T):
    apertura[t]=ultimo*np.exp(rng.normal(0,.004)); cierre[t]=apertura[t]*np.exp(rng.normal(0,.01)); ultimo=cierre[t]
def regla(historia):
    if len(historia)<6: return 0
    return 1 if historia[-1]>np.mean(historia[-6:]) else -1

def motor(opens,closes,vols,regla,comision=0.,medio_spread=0.,Y=0.,sigma_dia=.02,prestamo=0.,financiacion=0.,ejecutor=None):
    opens=np.asarray(opens,float); closes=np.asarray(closes,float); vols=np.asarray(vols,float)
    if not (len(opens)==len(closes)==len(vols)) or len(opens)==0 or not np.isfinite(np.r_[opens,closes,vols]).all() or np.any(opens<=0) or np.any(closes<=0) or np.any(vols<=0): raise ValueError('Datos inválidos')
    if not np.isfinite([comision,medio_spread,Y,sigma_dia,prestamo,financiacion]).all() or min(comision,medio_spread,Y,sigma_dia,prestamo,financiacion)<0: raise ValueError('Costes inválidos')
    efectivo=1000.; posicion=0.; pendiente=0.; capital=[]; decisiones=[]; operaciones=[]
    for t in range(len(opens)):
        cambio=pendiente-posicion
        if cambio:
            if ejecutor is None:
                volumen_previsto=vols[t-1] if t>0 else vols[0]
                impacto=Y*sigma_dia*np.sqrt(abs(cambio)/volumen_previsto)
                llenado,precio=cambio,opens[t]
                coste=abs(llenado)*precio*(comision+medio_spread+impacto)
            else:
                llenado,precio,coste=ejecutor(t,cambio,opens[t])
                if not np.isfinite([llenado,precio,coste]).all() or precio<=0 or coste<0 or abs(llenado)>abs(cambio) or (llenado and np.sign(llenado)!=np.sign(cambio)): raise ValueError('Fill incoherente')
            if llenado:
                efectivo-=llenado*precio+coste; posicion+=llenado; operaciones.append((t,llenado,precio,coste))
        efectivo-=max(-posicion,0)*closes[t]*prestamo/252+max(-efectivo,0)*financiacion/252
        capital.append(efectivo+posicion*closes[t])
        pendiente=float(regla(closes[:t+1].copy()))
        if not np.isfinite(pendiente): raise ValueError('Señal inválida')
        decisiones.append(pendiente)
    return np.array(capital),np.array(decisiones),operaciones

equity,decisiones,ops=motor(apertura,cierre,volumen,regla)
print('Operaciones:',len(ops),'| capital final:',equity[-1],'| primer fill:',ops[0])

First-day volume is used only if there is an initial order; here there is none because the signal starts flat. For later orders, prior-day volume is used as a proxy, not future volume on execution day. Impact, spread and commission are charged as costs on notional; borrow accrues on the short position at close and financing on negative cash. Margins, constraints and price changes caused by the fill itself are omitted.

[ ]Vectorized benchmark without costsBrowser
objetivos=np.array([regla(cierre[:t+1]) for t in range(T)])
tenencia=np.r_[0.,objetivos[:-1]]; cambios=np.diff(np.r_[0.,tenencia])
efectivo=1000.-np.cumsum(cambios*apertura); vector=efectivo+tenencia*cierre
print('Máxima diferencia evento/vector:',np.max(np.abs(equity-vector)))
assert np.allclose(equity,vector)

Equality checks this accounting and clock for a costless case. It does not check actual data availability or fill quality. Now alter prices after a cutoff; if earlier decisions or capital change, there is improper dependence in that particular test. We also test a deliberately forward-looking function.

[ ]Perturb the futureBrowser
def invariante_futuro(funcion,serie,corte):
    original=np.asarray(funcion(serie.copy())); alternativa=serie.copy()
    alternativa[corte+1:]=alternativa[corte+1:][::-1]+3.
    cambiado=np.asarray(funcion(alternativa))
    return np.allclose(original[:corte+1],cambiado[:corte+1],equal_nan=True)
def causal(serie): return np.cumsum(serie)
def anticipa(serie): return np.r_[serie[1:],serie[-1]]
assert invariante_futuro(causal,cierre,200)
assert not invariante_futuro(anticipa,cierre,200)
alt_cierre=cierre.copy(); alt_apertura=apertura.copy(); alt_cierre[201:]*=1.1; alt_apertura[201:]*=.9
equity_alt,dec_alt,_=motor(alt_apertura,alt_cierre,volumen,regla)
assert np.allclose(equity[:201],equity_alt[:201]) and np.array_equal(decisiones[:201],dec_alt[:201])
print('Invariante causal y fallo anticipativo detectados en corte 200.')

A particular perturbation may not activate every branch of a rule or affect data the strategy uses; passing only means that perturbation did not change the past. Use more cutoffs, publication and price changes, code review and event tests. Shifting a signal into the future and observing a spectacular result is a useful alarm in a planted simulation; no universal threshold proves leakage for every strategy.

[ ]Deliberate look-ahead shiftBrowser
ret_diario=np.diff(cierre)/cierre[:-1]
senal_pasada=np.sign(np.r_[0.,ret_diario[:-1]])
senal_futura=np.sign(ret_diario)
def ratio_simple(r): return float(np.mean(r)/np.std(r,ddof=1)*np.sqrt(252))
print('Ratio causal / con señal del mismo retorno:',ratio_simple(senal_pasada*ret_diario),ratio_simple(senal_futura*ret_diario))

The second rule knows exactly the return it earns and is deliberately impossible. Its result is a sensitivity test of the example, not a criterion for automatically rejecting any real signal that improves when shifted: temporal dependence and parameter selection can also produce differences.

Available vintages and costs

In this example each record has period, publication date and value. Select the latest published period and, for that period, the most recent revision already available. The first value is not replaced by a later revision. Integer dates are a toy clock; in production they need time zone, source and calendar.

[ ]Point-in-time dataBrowser
registros=[(5,8,100.),(5,12,90.),(10,15,102.)]
def disponible(registros,instante):
    candidatos=[r for r in registros if r[0]<=instante and r[1]<=instante]
    if not candidatos: return None
    periodo=max(r[0] for r in candidatos)
    return max((r for r in candidatos if r[0]==periodo),key=lambda r:r[1])[2]
print('Disponible en 9 y en 14:',disponible(registros,9),disponible(registros,14))
assert disponible(registros,9)==100. and disponible(registros,14)==90.
neto,_,ops_neto=motor(apertura,cierre,volumen,regla,comision=.0002,medio_spread=.0005,Y=.7,prestamo=.03,financiacion=.05)
print('Capital sin costes / con costes:',equity[-1],neto[-1],'| coste por fills:',sum(o[3] for o in ops_neto))
larga=lambda hist: 20.
sin_fin,_,_=motor(apertura,cierre,volumen,larga)
con_fin,_,_=motor(apertura,cierre,volumen,larga,financiacion=.05)
corta=lambda hist: -1.
sin_prestamo,_,_=motor(apertura,cierre,volumen,corta)
con_prestamo,_,_=motor(apertura,cierre,volumen,corta,prestamo=.03)
assert con_fin[-1]<sin_fin[-1] and con_prestamo[-1]<sin_prestamo[-1]
print('Financiación y préstamo reducen capital en posiciones de prueba.')

To illustrate selection after the fact, generate returns without an edge and then choose assets with the greatest cumulative return. This is deliberate universe leakage, not a complete model of firms that delist. Comparing the same equal-weight portfolio of all assets with the selected one shows the direction in this experiment.

[ ]Universe chosen using the futureBrowser
rng=np.random.default_rng(282502); panel=rng.normal(0,.01,(250,80)); rendimiento_total=np.prod(1+panel,axis=0)-1
elegidos=np.argsort(rendimiento_total)[-40:]
todo=np.prod(1+panel.mean(axis=1))-1; sesgado=np.prod(1+panel[:,elegidos].mean(axis=1))-1
print('Cartera completa / selección retrospectiva:',todo,sesgado)

Lab: walk-forward and capacity

The following synthetic signal changes its relationship with subsequent return halfway through. Slope is estimated from pairs whose label is already known at the start of each test block. We choose lengths before looking at outputs and compare anchored and rolling windows on the same data. No block is used to optimize lengths; that choice would also be a trial to record.

[ ]Two windows with the same regime changeBrowser
rng=np.random.default_rng(282503); n=320; señal=rng.normal(size=n); futuro=np.zeros(n+1)
for t in range(n): futuro[t+1]=(.002 if t<160 else -.002)*señal[t]+rng.normal(0,.01)
def walk_forward(señal,futuro,entreno,test,anclado):
    resultados=[]; posicion=0.; bloques=[]
    for inicio in range(entreno,len(señal),test):
        fin=min(len(señal),inicio+test); primero=0 if anclado else inicio-entreno
        x=señal[primero:inicio]; y=futuro[primero+1:inicio+1]
        beta=float(x@y/(x@x)); bloques.append((primero,inicio,fin,beta))
        for t in range(inicio,fin):
            nueva=1. if beta*señal[t]>=0 else -1.
            resultados.append(nueva*futuro[t+1]-.0004*abs(nueva-posicion)); posicion=nueva
    return np.asarray(resultados),bloques
def sharpe_anual(r): return np.mean(r)/np.std(r,ddof=1)*np.sqrt(252)
for modo in (True,False):
    r,bloques=walk_forward(señal,futuro,60,20,modo)
    print('Anclado' if modo else 'Móvil','| bloques:',len(bloques),'| Sharpe convencional neto:',sharpe_anual(r),'| capital:',np.prod(1+r))

The example uses fictitious trades at an implicit price, a fixed fee and no capacity constraint. Return is per period and annualization 252\sqrt{252} assumes conditions to review if dependence exists. The regime change is planted to illustrate the difference between windows; it is not a market forecast.

In the following simplified model, annual gross return, volatility and turnover are constant. Average daily trading is capital × turnover / 252 and square-root impact is applied as average cost. A negative result can mean fixed costs already exceed the edge before impact. The calculated root should not be extrapolated as capacity of a real strategy.

[ ]Explicit capacity curveBrowser
bruto=.08; riesgo=.15; rotacion=20.; base=(2+5)*1e-4; Y=.7; sigma_dia=.02; ADV=10_000_000.
def retorno_neto(capital):
    participacion=capital*rotacion/(252*ADV)
    return bruto-rotacion*(base+Y*sigma_dia*np.sqrt(participacion))
def capacidad(objetivo):
    margen=(bruto-objetivo)/rotacion-base
    return (margen/(Y*sigma_dia))**2*252*ADV/rotacion if margen>0 else 0.
for capital in (1e6,10e6,100e6): print('Capital:',capital,'| retorno neto:',retorno_neto(capital),'| Sharpe supuesto:',retorno_neto(capital)/riesgo)
print('Capacidad para cero:',capacidad(0.),'| para mitad del bruto:',capacidad(bruto/2))

Lab: a queue and two alternatives

In each episode a one-unit buy finds an ask at 100.01 and bid at 99.99. The passive order enters behind three units at the bid and executes only if selling flow consumes at least four. The simulation gives informed flow knowledge of the sign of a fictional final change: if it knows midpoint will fall, it sells. Naive execution buys at midpoint, aggressive at ask and passive at bid if its turn arrives. If unexecuted, opportunity is valued at the final midpoint. These are independent simplified episodes without new orders ahead, cancellations, latency or additional impact.

[ ]Midpoint, aggressive and queued passive executionBrowser
rng=np.random.default_rng(282504); episodios=2000; delta=rng.choice([-.02,.02],episodios)
informado=rng.random((episodios,8))<.6; ruido=rng.random((episodios,8))<.5
ventas=np.where(informado,delta[:,None]<0,ruido).sum(axis=1)
fill=ventas>=4
coste_medio=np.zeros(episodios); coste_agresivo=np.full(episodios,.01)
coste_pasivo=np.where(fill,-.01,delta)
for nombre,c in [('medio ingenuo',coste_medio),('agresiva',coste_agresivo),('pasiva con cola',coste_pasivo)]:
    print(nombre,'| coste medio:',c.mean(),'| fracción ejecutada:',fill.mean() if nombre=='pasiva con cola' else 1.)
print('Pasiva: cambio posterior medio cuando ejecuta:',delta[fill].mean())

Passive cost excludes valuation of the position acquired after the fill: the subsequent change is reported separately as markout to study adverse selection. If it does not execute, opportunity cost uses final midpoint. The queue here is one quantity ahead, not a complete reconstruction of the m28-l20 simulator; do not interpret this comparison as an implementable backtest.

Now connect the event engine to three executors on the same synthetic opens and closes. The aggressive executor consumes one unit at each of two levels and pays 0.01 and 0.02 distance from midpoint. The passive executor enters behind three units and can fill partially depending on the day’s flow; the remaining target updates when the next signal arrives. The flow generator knows the sign of that day’s open-to-close move to plant adverse information, but the strategy does not observe it. Passive orders are assumed canceled at close and positions marked at close: price formation and the complete persistent book are not modeled.

[ ]Connect executors to the engineBrowser
rng=np.random.default_rng(282505); info=rng.random((T,8))<.6; ruido=rng.choice([-1,1],size=(T,8))
signo_futuro=np.where(cierre>=apertura,1,-1)
flujo=np.where(info,signo_futuro[:,None],ruido)
def ejecutor_libro(modo):
    def ejecutar(t,cambio,medio):
        lado=np.sign(cambio); pedido=abs(cambio)
        if modo=='medio': return cambio,medio,0.
        if modo=='agresivo':
            primera=min(1.,pedido); segunda=min(1.,pedido-primera); cantidad=primera+segunda
            precio=medio+lado*(.01*primera+.02*segunda)/cantidad
            return lado*cantidad,precio,0.
        if modo=='pasivo':
            opuestas=np.sum(flujo[t]==-lado); cantidad=min(pedido,max(0,int(opuestas)-3))
            return lado*cantidad,medio-lado*.01,0.
        raise ValueError('Modo desconocido')
    return ejecutar
for modo in ('medio','agresivo','pasivo'):
    curva,_,fills=motor(apertura,cierre,volumen,regla,ejecutor=ejecutor_libro(modo))
    print(modo,'| capital final:',curva[-1],'| número de fills:',len(fills),'| unidades ejecutadas:',sum(abs(f[1]) for f in fills))

The comparison keeps the same signal and exogenous path, but a partial order changes position and hence future orders. For this seed final capital is approximately 1010.34 with naive midpoint, 1006.91 with aggressive and 828.60 with passive execution; the latter also executes fewer units. The difference reflects planted adverse flow and specific rules, not a general relationship between passive and aggressive orders. The midpoint executor is an unattainable no-spread benchmark, not a real free alternative. This example charges no fees or financing; remaining exposure is marked at close and is not equivalent to completing a metaorder.

Minimum report for this simulation

The following summary uses net capital from the first engine, not the best variant chosen after observing results. Drawdown is calculated from the previous capital peak and reported as a negative fraction; turnover is total traded notional divided by mean capital over this sample, not an annual rate. Sharpe uses daily-return mean and standard deviation and convention 252\sqrt{252}, which may be inappropriate under dependence.

[ ]Metrics and exposureBrowser
retornos=neto[1:]/neto[:-1]-1; maximo=np.maximum.accumulate(neto)
posiciones=np.zeros(T)
for t,q,_,_ in ops_neto: posiciones[t]+=q
posiciones=np.cumsum(posiciones)
resumen={'capital_final':float(neto[-1]),'retorno_total':float(neto[-1]/1000-1),
         'sharpe_convencional':float(np.mean(retornos)/np.std(retornos,ddof=1)*np.sqrt(252)),
         'max_drawdown':float(np.min(neto/maximo-1)),
         'rotacion_muestra':float(sum(abs(q)*p for _,q,p,_ in ops_neto)/np.mean(neto)),
         'exposicion_absoluta_media':float(np.mean(np.abs(posiciones*cierre/neto))),
         'coste_fills':float(sum(c for _,_,_,c in ops_neto)),
         'semilla_datos':282501,'ensayos':1}
print(resumen)

The trial count refers only to the first engine’s rule with costs defined in this example; other variants and windows must also be recorded if used to select a strategy. The summary is not a real-product report and does not include all costs, factor exposures, taxes or delisting episodes.

Exercises

NumericGross to net
Annual gross return is 8%, annual turnover is 20 times measured as total traded notional over capital, and one-way cost is 10 basis points per notional. What is annual net return in percent?
NumericParticipation and impact
With Y=1 and daily volatility 2%, what is assumed final impact in basis points when trading 16% of daily volume?
QuizFuture universe
What problem arises from using current index constituents throughout a 20-year backtest?
QuizAnother winning window
Why can a walk-forward result still be overfitted?
CodeLook-ahead test
Implement invariante_futuro(funcion, serie, corte): funcion receives a copy of the array and returns a signal of the same size. Reverse values after the cutoff and add 3; return True if signals up to and including the cutoff do not change, False otherwise. This test detects only the applied perturbation, not all leakage.
def invariante_futuro(funcion,serie,corte):
  raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
A backtest is a simulation with a clock, universe, execution model and decision history. Changing any of them changes the question and can change the outcome.

Executing after knowing the signal, preserving available data vintages, accounting for fills and positions, modeling costs and reserving temporal evaluation are requirements for an interpretable comparison. An isolated test or attractive walk-forward does not eliminate multiple-selection risk; a complete log and assumption review remain necessary.