Optimal execution and market making
Study execution and market-making control through implementation shortfall, TWAP and VWAP, Almgren-Chriss, and inventory-aware Avellaneda-Stoikov and Guéant-Lehalle-Fernández-Tapia quotes in a book simulator.
After this lesson you can
- Define implementation shortfall and decompose delay, impact, timing and opportunity cost.
- Construct TWAP and VWAP schedules with intraday volume profiles and measure their risk.
- Derive the Almgren-Chriss trajectory and efficient execution frontier under linear impact and risk aversion.
- Derive the HJB equation by continuous-time dynamic programming and solve linear-quadratic and exponential cases with an ansatz.
- Derive Avellaneda-Stoikov reservation price and spread from the HJB with approximations.
- Evaluate execution and market-making strategies in a book simulator with Hawkes flow and informed agents.
Before you start
- 28Square-root impact lawPropagator model of transient impactLimit order bookQueue dynamics and queue positionAdverse selection and spread componentsArrow-Pratt risk aversion, CARA and CRRAHawkes models of order flowMean-variance optimization
- 22Bellman optimality equation
- 26Itô's lemmaInfinitesimal generator of a diffusionNonhomogeneous Poisson process
- 03Second-order linear ODEs with constant coefficients
Deciding how much and when
A large order may pay more by consuming liquidity quickly or bear more price risk by waiting. A liquidity provider faces the complementary decision: it earns spread on execution but accumulates inventory and may trade with an informed counterparty. Both are control problems with different objectives, constraints and models. An optimal solution is optimal within its assumptions.
Measuring execution
For a target buy , decision price , executions , arrival price , final price and fees , implementation shortfall in money is
The second term values opportunity on unexecuted quantity at the final price. It can be negative if price falls; it is not money actually paid. Defining as midpoint before each execution, the identity decomposes into delay , timing , execution , opportunity and fees. Execution combines spread and impact; separating their causes needs further assumptions. Perold frames the comparison between paper and real portfolios.
For example, to buy 100 units from , suppose arrival 100.05, 80 executed at 100.12 with prior midpoint 100.08, final 100.20 and total fee 1. Shortfall is . Its breakdown is 5 delay, 2.4 timing, 3.2 execution, 3 opportunity and 1 fee. Using another reference instead of final price for the outstanding portion changes the measure: state horizon and benchmark before comparing policies.
TWAP and VWAP are benchmarks and also names of schedules. TWAP distributes uniformly over time; a VWAP schedule distributes according to a forecast volume profile. Realized market VWAP uses volumes and prices actually observed. Using future realized volume to choose weights would look ahead. A participation constraint may prevent completing the order if available capacity is insufficient; remaining quantity must be recorded, not disappear from the calculation.
The arena is an explicit model: the passive order waits behind three units and is canceled at each interval’s end; aggressive orders pay spread and impact. The 200 repetitions are simulations, not data or guarantees. Shortfall marks the unexecuted portion to the final midpoint and should be read alongside the completed fraction. The scenario omits fees and latency and does not reproduce a full book.
A fixed participation rule caps each trade at a fraction of observed contemporaneous volume, so progress is uncertain and may leave a remainder. A planned VWAP schedule uses a volume forecast and may deviate from subsequently observed VWAP. Comparing only average execution prices inadvertently favors a rule that executes little in adverse conditions; also comparing shortfall, distribution and completed fraction retains that opportunity cost.
The execution frontier
In continuous liquidation, let be remaining inventory, , , and the selling rate. Assume a driftless arithmetic midpoint with volatility , linear temporary impact with coefficient and a deterministic strategy. A continuous version of the Almgren-Chriss problem minimizes
The first part is expected temporary cost and the second is times variance of price cost. Under these conventions linear permanent impact adds a fixed term for liquidating , so it does not change the optimal schedule. The original model carefully distinguishes impact, units and discretization; see Almgren and Chriss.
The discrete first-order condition as step size decreases gives . With and ,
If , the limit is , i.e. TWAP. Increasing liquidates earlier, usually with higher expected cost and lower variance. Varying traces this model’s efficient frontier. Parameter is a natural scale; half-life corresponds to the very-long-horizon limit. With finite , half-life is .
Linear impact should not be extrapolated to a metaorder of arbitrary size without calibration. Obizhaeva and Wang study a book whose liquidity recovers over time: trade history and resilience matter, and large trades can arise at the start or end under their assumptions. That model and the previous lesson’s square root are not equivalent to linear temporary cost.
Even with final impact , average price paid depends on the path. If a deterministic marginal path is imposed as an example and there is no decay, average impact cost is . That proportion does not follow for a real market with variable participation, information, other agents or resilience; it is another testable assumption.
Bellman and HJB
The HJB equation is the local Bellman condition in continuous time. If is minimum remaining cost and the selling rate, expansion over a small step in the previous problem leads to
With , the quadratic ansatz gives for . The zero terminal-inventory condition produces a singular boundary approaching ; for we obtain . A formal HJB solution needs regularity and admissibility conditions for a verification theorem to identify it with the optimal value. Changing constraints or allowing signals changes the equation and may invalidate this solution.
Quoting with inventory
In the Avellaneda-Stoikov model, midpoint follows Brownian motion, terminal utility is exponential with aversion and arrivals executing a quote at distance have intensity . Inventory risk management shifts the center of quotes. If units are held to the horizon without further trades, their certainty equivalent is . Indifference prices for adding and removing one unit have center
With long inventory, : lowering bid and ask discourages further buying and encourages selling. Under the usual approximation, half-spread is . These formulas come from a model without explicit adverse selection, latency or queue priority. Avellaneda and Stoikov derive and study these quotes.
The first half-spread term increases with inventory uncertainty and remaining time; the second reflects the balance between improving price and receiving fewer executions when arrivals decay with distance. If tends to zero, tends to . In an implementation, ticks, fees, position limits and priority of an existing order can make continuous requoting costly. A theoretical reservation price is not by itself an executable order.
To see the full HJB, write as maximum expected utility. In addition to diffusion term there are two jump terms: an ask sale moves from to and a bid buy moves to . Each value difference is multiplied by its intensity and optimized over distance. The terminal condition is if inventory is valued at final midpoint. The exponential ansatz separates wealth and price; it does not automatically turn reservation approximations into the exact constrained solution.
Guéant, Lehalle and Fernández-Tapia bound and transform the HJB into a finite linear system. At the boundaries the quote that would increase inventory beyond the limit is removed. The lab computes that system using a matrix exponential; its optimality applies to the model’s intensities and assumptions, not an exchange with queues and informed orders.
Lab: schedule and cost
The closed-form solution is discretized into 20 intervals. Volatility is per square root of a day, quantities are units and corresponds to convention . We compare temporary cost and theoretical variance with Monte Carlo driftless arithmetic prices. The same price paths are used for the rules, but impact is added as temporary cost and does not alter midpoint in this model.
import numpy as np
from scipy.linalg import expm
def trayectoria_ac(X,T,N,lam,sigma,eta):
if X<0 or T<=0 or N<1 or lam<0 or sigma<0 or eta<=0: raise ValueError('Parámetros inválidos')
t=np.linspace(0,T,N+1); k=np.sqrt(lam*sigma*sigma/eta)
x=X*(1-t/T) if k<1e-12 else X*np.sinh(k*(T-t))/np.sinh(k*T)
return t,x
def vwap_schedule(perfil,total,cap):
v=np.asarray(perfil,float)
if v.ndim!=1 or len(v)==0 or not np.isfinite(v).all() or np.any(v<0) or total<0 or cap<0: raise ValueError('Datos inválidos')
capacidad=cap*v; cantidad=min(total,float(capacidad.sum()))
return (cantidad*v/v.sum() if v.sum()>0 else np.zeros_like(v)),total-cantidad
X,T,N=100.,1.,20; sigma=.8; eta=.002; perfil=1+2*np.abs(np.linspace(-1,1,N))
t,twap=trayectoria_ac(X,T,N,0.,sigma,eta)
_,ac=trayectoria_ac(X,T,N,.01,sigma,eta)
n_vwap,resto=vwap_schedule(perfil*100, X,.2)
planes={'TWAP':-np.diff(twap),'VWAP':n_vwap,'AC':-np.diff(ac)}
dt=T/N
def riesgo_coste(n):
x=X-np.cumsum(n); return eta*np.sum(n*n)/dt,sigma*sigma*np.sum(x*x)*dt
for nombre,n in planes.items(): print(nombre,'cantidad:',n.sum(),'| coste, varianza:',riesgo_coste(n))
print('Resto VWAP:',resto)The frontier is approximated by evaluating paths for different aversions. Computed costs omit fees, limits and deviations from the rule. Fixed permanent cost is omitted throughout to compare schedules on equal terms.
rng=np.random.default_rng(282301); replicas=2000
shocks=rng.normal(0,sigma*np.sqrt(dt),(replicas,N-1))
medios=np.c_[np.zeros(replicas),np.cumsum(shocks,axis=1)]
for nombre,n in planes.items():
teorico,var=riesgo_coste(n); costes=-medios@n+teorico
print(nombre,'| media y varianza simuladas:',float(costes.mean()),float(costes.var(ddof=1)),'| teoría:',teorico,var)
for lam in (0.,.001,.01,.1):
_,x=trayectoria_ac(X,T,N,lam,sigma,eta); print('λ, coste, varianza:',lam,*riesgo_coste(-np.diff(x)))As a contrasting impact assumption for a symmetric buy, we calculate marginal prices proportional to the square root of cumulative quantity, with scale chosen only for illustration. These are neither observed quotes nor the nonlinear model’s optimal solution. A square-root law for final impact alone does not determine complete cost or subsequent evolution.
volumen=10000.; Y=.7; precio=100.; volatilidad_rel=.02
for nombre,n in planes.items():
acumulado=np.cumsum(n); impacto=precio*Y*volatilidad_rel*np.sqrt(acumulado/volumen)
print(nombre,'| coste supuesto bajo raíz:',float(n@impacto))To connect the schedule to a book, execute each slice against three synthetic ask levels with capacity proportional to that interval’s volume. The book is rebuilt at each step, there is no permanent impact or own queue, and uncompleted orders are not automatically recovered. Benchmark VWAP uses realized midpoint and volume for each interval: it is a benchmark for this simulation, not an actual transaction VWAP.
rng_libro=np.random.default_rng(282304); M=200
vol_real=perfil[None,:]*100*rng_libro.uniform(.7,1.3,(M,N))
terminal=medios[:M,-1]+rng_libro.normal(0,sigma*np.sqrt(dt),M)
def ejecutar_libro(n,medios,vol_real,terminal):
mediciones=[]
for ruta,vol,fin in zip(medios[:M],vol_real,terminal):
llenado=0.; pagado=0.
for i,deseado in enumerate(n):
pendiente=float(deseado); s=100+ruta[i]
for distancia,fraccion in ((.05,.02),(.10,.02),(.15,.03)):
cantidad=min(pendiente,fraccion*vol[i]); llenado+=cantidad; pagado+=cantidad*(s+distancia); pendiente-=cantidad
if pendiente<1e-12: break
referencia=float(np.dot(100+ruta,vol)/vol.sum())
shortfall=pagado-llenado*100+(X-llenado)*fin
deslizamiento=pagado/llenado-referencia if llenado else np.nan
mediciones.append((shortfall,llenado/X,deslizamiento))
return np.mean(mediciones,axis=0)
for nombre,n in planes.items():
print(nombre,'| IS medio, fracción ejecutada, deslizamiento frente a VWAP medio:',ejecutar_libro(n,medios,vol_real,terminal))Shortfall adds to executed cost the opportunity cost of unexecuted quantity valued at terminal midpoint relative to decision price. Slippage versus VWAP is calculated only on what executed, so it should not be compared without looking at completed fraction. Results are 200 simulated paths with the same background liquidity and do not justify an execution recommendation.
Lab: inventory and quotes
The bounded system of Guéant and coauthors has , and . Its equation is , omitting neighbors outside the bounds. With the corresponding tridiagonal , . Optimal distances include , with the neighbor corresponding to the trade. The next cell solves the system and shows that the side violating the bound is not quoted.
def glft_tabla(Q,A,k,gamma,sigma,tau):
estados=np.arange(-Q,Q+1); alpha=k*gamma*sigma*sigma/2
eta_m=A*(1+gamma/k)**(-(1+k/gamma))
M=np.diag(alpha*estados**2)+np.diag(np.full(2*Q,-eta_m),1)+np.diag(np.full(2*Q,-eta_m),-1)
v=expm(-M*tau)@np.ones(2*Q+1)
base=np.log1p(gamma/k)/gamma; bid=np.full(len(estados),np.nan); ask=bid.copy()
for i in range(len(estados)):
if i<len(estados)-1: bid[i]=np.log(v[i]/v[i+1])/k+base
if i>0: ask[i]=np.log(v[i]/v[i-1])/k+base
return estados,bid,ask
estados,bid,ask=glft_tabla(3,4.,1.5,.5,.8,1.)
print('q:',estados,'| distancias bid:',bid,'| ask:',ask)Distances in the exact system can be negative: restricting a quote from crossing the midpoint is an additional decision that changes the problem. The next experiment imposes that constraint, an inventory limit and a simplified queue for all policies. It therefore does not prove exact GLFT or AS optimality in this environment.
We construct paired episodes with 80 steps of 0.05 time units. Candidate flow uses a discrete Hawkes approximation: aggregate intensity is constant within each step, Poisson candidates are generated and their excitation affects the next step. Nominal continuous ratio is not exactly the discretization’s effective ratio: here it is . Each informed candidate knows the sign of a small latent midpoint drift; the rest choose a random sign. The market maker does not know the sign. A quote receives a candidate with probability and stands behind one unit: it executes only if at least two accepted candidates arrive on that side during the step. Outstanding orders are canceled at the end of the step. This mechanism is neither a full book nor a real queue calibration.
We compare fixed symmetric quoting, the AS approximation and bounded GLFT, all with the same inventory limit. To measure terminal inventory cost it is liquidated at midpoint minus 0.05 per absolute unit. There are no fees, latency or market-maker impact on midpoint; Sharpe is reported per episode as mean divided by standard deviation, without annualization or subtracting a risk-free rate. Markout is the midpoint change during the next step, signed from the aggressor side and averaged per execution: it can reflect both imposed informed drift and noise.
rng=np.random.default_rng(282302); episodios=200; pasos=80; dt=.05; A=20.; k=1.5; gamma=.5; sigma=.8; limite=3
T_mm=pasos*dt; trayectorias=[]
for _ in range(episodios):
signo=int(rng.choice([-1,1])); precio=100.; excitacion=0.; secuencia=[]
for j in range(pasos):
tasa=2*A+excitacion; numero=rng.poisson(tasa*dt)
candidatos=[(rng.random(),int(rng.choice([-1,1])),rng.random()) for _ in range(numero)]
precio_siguiente=precio+.12*signo*dt+sigma*np.sqrt(dt)*rng.normal()
secuencia.append((precio,precio_siguiente,candidatos,signo))
precio=precio_siguiente; excitacion=excitacion*np.exp(-2*dt)+.6*numero
trayectorias.append(secuencia)
tabla=[glft_tabla(limite,A,k,gamma,sigma,(pasos-j)*dt)[1:] for j in range(pasos)]
print('Episodios:',len(trayectorias),'| pasos:',pasos,'| razón Hawkes agregada nominal:',.6/2)def evaluar_mm(modo,fraccion):
resultados=[]
for secuencia in trayectorias:
q=0; caja=0.; ejecutadas=0; candidatos_total=0; inventario=0.; markout=0.
for j,(s,siguiente,candidatos,signo) in enumerate(secuencia):
tau=(pasos-j)*dt; base=np.log1p(gamma/k)/gamma
if modo=='simetrico': db=da=base
elif modo=='AS':
reserva=s-q*gamma*sigma*sigma*tau; mitad=gamma*sigma*sigma*tau/2+base
db=s-(reserva-mitad); da=(reserva+mitad)-s
elif modo=='GLFT':
bd,ad=tabla[j]; db=bd[q+limite] if q<limite else np.inf
da=ad[q+limite] if q>-limite else np.inf
else: raise ValueError('Política desconocida')
db=max(0.,db); da=max(0.,da); compras=ventas=0
for u,ruido,aceptar in candidatos:
lado=signo if u<fraccion else ruido; candidatos_total+=1
if lado==1 and aceptar<np.exp(-k*da): compras+=1
if lado==-1 and aceptar<np.exp(-k*db): ventas+=1
if compras>=2 and q>-limite:
q-=1; caja+=s+da; ejecutadas+=1; markout+=siguiente-s
if ventas>=2 and q<limite:
q+=1; caja-=s-db; ejecutadas+=1; markout-=siguiente-s
inventario+=abs(q)
pnl=caja+q*secuencia[-1][1]-.05*abs(q)
resultados.append((pnl,inventario/pasos,ejecutadas,candidatos_total,markout))
r=np.asarray(resultados); promedio=r[:,0].mean(); desv=r[:,0].std(ddof=1)
return promedio,desv,promedio/desv if desv else np.nan,r[:,1].mean(),r[:,2].sum()/r[:,3].sum(),r[:,4].sum()/max(1,r[:,2].sum())
for info in (0.,.6):
for modo in ('simetrico','AS','GLFT'):
print('info, política:',info,modo,'| P&L medio, SD, ratio, |q|, fill/candidatos, markout:',evaluar_mm(modo,info))Candidates and shocks are identical across policies within each episode and informed fraction, but fills depend on the quote. In this run mean P&L of all three rules decreases as the informed fraction rises; nevertheless, mean markout is not positive for all of them. This difference reminds us that quotes, inventory limits and fill selection change the observed sample. The fills-to-candidates fraction is not the probability of executing an individual order with real priority. Comparing markouts helps observe the imposed mechanism; it does not identify all adverse selection or constitute an implementable backtest. Repeat with different seeds, drift, intensity, limits and costs before drawing conclusions.
Exercises
Step 1 of 3. What is the Euler-Lagrange condition?
Step 1 of 3. What is the certainty equivalent of q units?
def vwap_schedule(perfil,total,cap):
raise NotImplementedError()Key takeaways
Shortfall incorporates execution and opportunity; TWAP and VWAP require a profile available before trading. Almgren-Chriss balances temporary cost and variance under specific assumptions. A provider’s reservation price reflects inventory, while quotes and fills depend on flow, queue position and counterparties’ information.