Market impact and order flow dynamics
Study how orders move prices through order-flow imbalance, square-root impact, transient propagators and no-arbitrage conditions, and model self-exciting order arrivals with Hawkes processes.
After this lesson you can
- Define and calculate order-flow imbalance and estimate its relationship with price changes.
- State the square-root impact law, its empirical evidence and a latent-book argument.
- Implement a propagator and explain the interaction of persistent order signs and diffusive prices.
- Check Gatheral's no-dynamic-arbitrage conditions for impact functions and decay kernels.
- Fit Hawkes processes to order flow, assess fit and interpret the branching ratio.
Before you start
- 28Limit order bookKyle modelZero-intelligence order flowQueue dynamics and queue positionAdverse selection and spread componentsMicroprice and order book imbalance
- 26Hawkes processBranching representation and branching ratioOgata thinning simulationNonhomogeneous Poisson processLewis-Shedler thinning simulationLong memory: ARFIMA and Hurst exponent
- 05Numerically stable maximum likelihood
- 27Heteroskedasticity-consistent standard errors (HC0 to HC3)
Trading also changes the market
A small order may execute close to the displayed quote. A large metaorder, split into many orders, consumes and attracts liquidity over time and can change the price it encounters later. Its cost depends on size, speed, depth and the rest of the market’s response. Measuring the associated move does not by itself prove how much the metaorder caused: the information motivating the trade and other orders can also move price.
Flow imbalance
Order-flow imbalance (OFI) sums changes in supply and demand at the best level, not just executions. For best prices and quantities , an event contributes
If prices do not change, . A bid cancellation reduces OFI just like an execution removing the same quantity at that level; a new ask also reduces it. Contributions are summed by interval. Cont, Kukanov and Stoikov find an approximately linear contemporaneous relationship between midpoint change and OFI in their sample, with a slope inversely related to depth. Signed transaction volume omits additions and cancellations.
The figure imposes the linear relationship in its synthetic data: the higher for OFI is not empirical evidence. Moreover, a regression with price change and OFI in the same interval is contemporaneous. Evaluating a tradable signal requires OFI available before the decision, a subsequent horizon, costs, latency and a time split without leakage.
Metaorder size
The square-root impact law summarizes an empirical regularity for the mean signed move at the end of certain metaorders:
Here is quantity, reference volume, volatility over a compatible window and an estimated coefficient. Tóth and coauthors describe evidence and a latent-liquidity model. Exponents and coefficients vary with data, instrument and definition; this is not an exact universal law. Separating order impact from correlated information is especially difficult.
A latent-book intuition assumes available density at distance from the midpoint. Consuming up to requires , so . Latent density includes invisible intentions and can change during execution: this static calculation does not establish causality in data. Final impact is not average execution cost either: the latter depends on the path of prices paid, fees and waiting risk.
Memory and propagation
The propagator model represents price as the sum of impacts of previous orders:
Kernel describes how impact persists; translates signed flow into an initial response. Signs can persist because a metaorder is fragmented. If every order had an identical permanent effect, a persistent sequence could produce trends. Impact that decays or depends on state can offset some of that predictability. Bouchaud and coauthors study this interaction. The precise balance between exponents depends on assumptions and cannot be inferred from one path.
Permanent impact remains over the long run; transient impact dissipates over time; a temporary cost depends on speed or execution and need not shift the midpoint durably. These categories are model components, not observables that can always be cleanly separated.
Absence of dynamic impact arbitrage requires that no round-trip strategy without information or risk have negative expected cost under the model. Gatheral shows joint restrictions on impact function and decay; in that framework an exponentially decaying kernel requires linear instantaneous impact to avoid manipulation. A particular cycle with positive cost is a necessary check for that cycle, not proof for every path and execution convention.
For example, with signed trades at times , linear kernel and half self-impact, cost is . The symmetric exponential kernel is positive definite: its Fourier transform is . Thus the quadratic form cannot be negative. A linear permanent term adds , which is zero on a round trip. This conclusion depends on linear impact, symmetric execution and nonnegative parameters; it does not justify arbitrarily combining concave impact and decay.
Self-exciting arrivals
A Hawkes process has intensity that rises after past events. For a univariate exponential kernel,
With , , and , a stationary version exists with mean intensity . The branching representation assigns each event an average of direct offspring. In that stationary model the expected long-run fraction of descendants is ; in a short window, with intraday trend or misspecification, an estimated ratio does not automatically measure a causal market property. For two types, matrix contains the expected number of offspring of each type per parent type, and the stability condition is a spectral radius below one. Bacry, Mastromatteo and Muzy review financial applications.
A ratio near one increases expected family duration and size in the idealized model. It does not imply that a particular crash is predictable or that all clustering is self-excitation: common news and a varying base rate also cluster events. Rounded times and partial executions with identical timestamps require explicit treatment before fitting a simple point process.
Lab: bivariate Hawkes
Matrix is the mean number of type offspring caused by a type event; both types share decay . For ordered events, maintain an exponential sum by source type and update it between events. The integral of each kernel over is . This calculation costs for two fixed types, instead of summing all history at every event. Empty history is assumed at time zero: a real excerpt may have unobserved prior history.
import numpy as np
from scipy.optimize import minimize
from scipy.stats import kstest
def loghawkes(t,marca,T,mu,K,beta):
t=np.asarray(t,float); marca=np.asarray(marca,int); mu=np.asarray(mu,float); K=np.asarray(K,float)
if len(t)!=len(marca) or np.any(np.diff(t)<=0) or np.any(t<0) or np.any(t>=T) or np.any((marca<0)|(marca>1)) or np.any(mu<=0) or beta<=0 or np.any(K<0):
raise ValueError('Eventos o parámetros inválidos')
z=np.zeros(2); ultimo=0.; log=0.
for tiempo,tipo in zip(t,marca):
z*=np.exp(-beta*(tiempo-ultimo)); intensidad=mu+beta*K@z
log+=np.log(intensidad[tipo]); z[tipo]+=1; ultimo=tiempo
integral=mu.sum()*T+sum(K[:,tipo].sum()*(1-np.exp(-beta*(T-tiempo))) for tiempo,tipo in zip(t,marca))
return log-integral
def simular_hawkes(mu,K,beta,T,semilla):
rng=np.random.default_rng(semilla); eventos=[]
for tipo in range(2):
for t in rng.uniform(0,T,rng.poisson(mu[tipo]*T)): eventos.append((float(t),tipo))
i=0
while i<len(eventos):
t,tipo=eventos[i]; i+=1
for hijo in range(2):
for demora in rng.exponential(1/beta,rng.poisson(K[hijo,tipo])):
if t+demora<T: eventos.append((float(t+demora),hijo))
if len(eventos)>20000: raise RuntimeError('Demasiados eventos')
eventos.sort(); return np.array([e[0] for e in eventos]),np.array([e[1] for e in eventos])
mu0=np.array([.45,.4]); K0=np.array([[.25,.10],[.08,.20]]); beta0=1.2; T=180.
t_sim,tipo_sim=simular_hawkes(mu0,K0,beta0,T,282201)
print('Eventos simulados:',len(t_sim),'| radio verdadero:',max(abs(np.linalg.eigvals(K0))))
print('Log-verosimilitud en parámetros verdaderos:',loghawkes(t_sim,tipo_sim,T,mu0,K0,beta0))
def log_lenta(t,marca,T,mu,K,beta):
suma=0.
for i,(ti,tipo) in enumerate(zip(t,marca)):
intensidad=mu[tipo]+sum(beta*K[tipo,marca[j]]*np.exp(-beta*(ti-t[j])) for j in range(i))
suma+=np.log(intensidad)
return suma-mu.sum()*T-sum(K[:,m].sum()*(1-np.exp(-beta*(T-ti))) for ti,m in zip(t,marca))
print('Diferencia recursión y suma directa:',loghawkes(t_sim[:50],tipo_sim[:50],T,mu0,K0,beta0)-log_lenta(t_sim[:50],tipo_sim[:50],T,mu0,K0,beta0))For fitting we ensure and . We parameterize each column of with sum below 0.95; this is a sufficient stability condition, more restrictive than requiring only spectral radius below one. Optimizer bounds and empty history are also part of the fit. Estimation from a single path is noisy.
def unpack(theta):
mu=np.exp(theta[:2]); beta=np.exp(theta[2]); K=np.zeros((2,2))
for j in range(2):
z=np.r_[theta[3+2*j:5+2*j],0.]; z=np.exp(z-z.max()); K[:,j]=.95*z[:2]/z.sum()
return mu,K,beta
def fit_hawkes(t,marca,T):
initial=np.array([np.log(.3),np.log(.3),np.log(1.),-1.,-1.,-1.,-1.])
bounds=[(-8,3),(-8,3),(-5,5)]+[(-8,8)]*4
opt=minimize(lambda th:-loghawkes(t,marca,T,*unpack(th)),initial,method='L-BFGS-B',bounds=bounds,
options={'maxiter':300,'ftol':1e-9})
if not opt.success: print('Aviso optimización:',opt.message)
return (*unpack(opt.x),opt.success)
mu_fit,K_fit,beta_fit,ok=fit_hawkes(t_sim,tipo_sim,T)
print('Convergencia:',ok,'| μ estimada:',mu_fit,'| β:',beta_fit)
print('K estimada:',K_fit,'| radio estimado:',max(abs(np.linalg.eigvals(K_fit))))The following real sample is a LOBSTER excerpt, AAPL on 2012-06-21 from 09:35:00 to 09:36:00, from the level 1 message file. We select visible type-4 executions, reverse the passive-order side to obtain the aggressor, and group same-side executions with identical timestamps. The 59 messages yield 50 unique times; there were no simultaneous timestamps with both signs in this window. Hidden executions and events not changing the requested range are excluded, so this is not the complete market-order flow. Selection and aggregation do not guarantee reconstruction of every aggressive order. The fit has no data before the window begins.
observaciones=np.array([[2.089448146,1],[3.039184974,1],[3.650873032,1],[3.65094306,1],[6.462597215,1],[6.462895168,1],[6.482015861,1],[7.960001073,1],[7.960322245,1],[8.78116914,1],[8.781666623,1],[8.783482833,0],[8.783537663,0],[8.784367913,1],[8.784611721,1],[15.825455531,1],[15.8450482,1],[16.614038979,1],[16.614146843,1],[19.79651516,0],[22.603958558,1],[22.604473568,1],[25.321707087,0],[26.512902208,1],[26.515978337,1],[26.547587803,1],[26.864925091,1],[26.865148331,1],[30.98057883,0],[31.145327982,1],[31.480862377,1],[36.797390995,1],[37.736032329,1],[41.300833478,1],[42.472842813,1],[43.070944604,1],[45.326137783,1],[45.439017508,0],[45.439906264,0],[45.439980836,0],[52.014755858,0],[53.015553214,1],[55.164812322,0],[55.164925936,0],[56.611382618,1],[56.635051213,1],[56.649510537,1],[56.649837712,0],[56.650128777,0],[58.20411281,1]])
t_real=observaciones[:,0]; tipo_real=observaciones[:,1].astype(int)
mu_real,K_real,beta_real,ok_real=fit_hawkes(t_real,tipo_real,60.)
print('Eventos:',len(t_real),'| compras y ventas:',np.bincount(tipo_real,minlength=2))
print('Convergencia:',ok_real,'| μ:',mu_real,'| β:',beta_real,'| K:',K_real)
print('Radio espectral:',max(abs(np.linalg.eigvals(K_real))))One minute and 50 timestamps do not support a stable claim about endogeneity or a conclusive comparison with simulation. In this run reaches the permitted upper bound, per second: the optimizer reports convergence, but that does not guarantee parameter identification or the same conclusion under a different bound. The fit has several parameters, truncated history and a constant base rate. Check sensitivity to window, aggregation and bounds; use more sessions and allow seasonality before interpreting parameters. Local CSV reading can be reproduced as follows:
import csv
from collections import defaultdict
marcas=defaultdict(set)
with open('AAPL_2012-06-21_34200000_57600000_message_1.csv',newline='') as f:
for fila in csv.reader(f):
t=float(fila[0]); tipo=int(fila[1]); lado_pasivo=int(fila[5])
if 34500<=t<34560 and tipo==4:
marcas[t].add(0 if lado_pasivo==-1 else 1)
observaciones=[(t-34500,next(iter(lados))) for t,lados in sorted(marcas.items()) if len(lados)==1]
print(len(observaciones),observaciones)
Check the time change
If conditional intensity is correct and known, compensator increments between events of each type follow an exponential distribution with mean one. The following diagnostic integrates both contributions between events. The KS test calculated on the same data used to estimate parameters does not have its usual known-parameter calibration; use it descriptively, or calibrate by simulation and evaluate out of sample. It does not prove residual independence or overall correct specification.
def residuos(t,marca,T,mu,K,beta):
z=np.zeros(2); integral=np.zeros(2); ultimo=0.; por_tipo=[[],[]]
for tiempo,tipo in zip(t,marca):
dt=tiempo-ultimo; dec=np.exp(-beta*dt)
integral+=mu*dt+K@z*(1-dec); z*=dec
por_tipo[tipo].append(integral[tipo]); z[tipo]+=1; ultimo=tiempo
return [np.diff(np.r_[0,lista]) for lista in por_tipo]
for nombre,t,tipos,horizonte,m,k,b in [('simulado',t_sim,tipo_sim,T,mu_fit,K_fit,beta_fit),('LOBSTER',t_real,tipo_real,60.,mu_real,K_real,beta_real)]:
for lado,res in enumerate(residuos(t,tipos,horizonte,m,k,b)):
print(nombre,'tipo',lado,'n',len(res),'media',np.mean(res),'KS descriptivo',kstest(res,'expon').statistic)A power-law kernel can represent slow decay, but requires different normalization and estimation. Next we compare two univariate models of all combined timestamps: exponential and power law , with seconds fixed and . Integration of the power kernel to is . Both models use the same events and three free parameters. Intensities use all prior history, here for 50 timestamps; compare log-likelihoods on the same sample without interpreting them as out-of-sample validation.
def sig(z): return .95/(1+np.exp(-z))
def likelihood_univ(theta,modo,t,T):
mu=np.exp(theta[0]); n=sig(theta[1]); scale=np.exp(theta[2]); c=.05; ll=0.
for i,ti in enumerate(t):
d=ti-t[:i]
if modo=='exp': kernel=n*scale*np.exp(-scale*d)
else: kernel=n*scale*c**scale/(c+d)**(1+scale)
ll+=np.log(mu+kernel.sum())
if modo=='exp': area=n*np.sum(1-np.exp(-scale*(T-t)))
else: area=n*np.sum(1-(c/(c+T-t))**scale)
return ll-mu*T-area
def ajustar_univ(modo):
opt=minimize(lambda th:-likelihood_univ(th,modo,t_real,60.),[-1.,0.,0.],method='L-BFGS-B',
bounds=[(-8,3),(-8,8),(-5,5)],options={'maxiter':300})
return opt.success, -opt.fun, np.exp(opt.x[0]),sig(opt.x[1]),np.exp(opt.x[2])
for modo in ('exp','potencia'): print(modo,'convergencia, logL, μ, n, escala:',ajustar_univ(modo))In this run the exponential again reaches its decay bound, and the power fit gives : higher in-sample log-likelihood does not establish a slow tail or predictive improvement. A mixture of exponentials can approximate slow decay over a finite range; do not identify a power tail merely because it fits one minute well. The fixed value of , omitted history and aggregated timestamps affect the comparison. A bivariate Hawkes remains a simplification of interdependent flows of additions, cancellations and executions.
Lab: price and flow in a simplified book
The following book maintains best-bid and best-ask quantities. Executions from a bivariate Hawkes consume one unit on the opposite side. If a queue is depleted, the quote moves one tick and is replenished with a fixed quantity; background additions and cancellations are independent Poisson processes. This explicit replenishment mechanism replaces the full depth and individual priority of m28-l20. A metaorder buys additional units between two times; it models neither strategic decisions nor hidden liquidity. It suffices to check the OFI formula and explore a path, not to calibrate real impact.
rng=np.random.default_rng(282202); periodo=180.; t_h,tip_h=simular_hawkes(mu0,K0,beta0,periodo,282203)
fondo=np.cumsum(rng.exponential(.5,600)); fondo=fondo[fondo<periodo]
base=[(float(t),'M',int(s)) for t,s in zip(t_h,tip_h)]
base += [(float(t),rng.choice(['L','C']),int(rng.integers(2))) for t in fondo]
def simular_libro(cantidad):
eventos=sorted(base+[(80+i*.2,'M',0) for i in range(cantidad)])
b,a,qb,qa=99,101,8,8; historia=[]
for tiempo,clase,lado in eventos:
b0,a0,qb0,qa0=b,a,qb,qa
if clase=='M':
if lado==0: qa-=1
else: qb-=1
elif clase=='L':
if lado==0: qb+=1
else: qa+=1
elif lado==0: qb=max(1,qb-1)
else: qa=max(1,qa-1)
if qb==0: b-=1; qb=8
if qa==0: a+=1; qa=8
e=(int(b>=b0)*qb-int(b<=b0)*qb0-int(a<=a0)*qa+int(a>=a0)*qa0)
historia.append((tiempo,e,(a+b)/2,1 if clase=='M' and lado==0 else -1 if clase=='M' else 0))
return np.array(historia)
arr=simular_libro(20); print('Eventos:',len(arr),'| OFI total:',arr[:,1].sum(),'| medio final:',arr[-1,2])We group into windows of ten time units and compare OFI and signed volume with the contemporaneous midpoint change. In this artificial book a midpoint change occurs mechanically when a queue is depleted. The experiment does not measure out-of-sample prediction. When inserting a metaorder, comparison with an otherwise identical path without it helps separate the mechanical effect from common fluctuations; even then the result depends on replenishment rules and is not a causal effect in a real market.
filas=[]; previo=100.
for inicio in np.arange(0,periodo,10):
ventana=arr[(arr[:,0]>=inicio)&(arr[:,0]<inicio+10)]
if len(ventana)==0: continue
medio=ventana[-1,2]; filas.append((ventana[:,1].sum(),ventana[:,3].sum(),medio-previo)); previo=medio
filas=np.array(filas)
def r2(x,y):
X=np.c_[np.ones(len(x)),x]; coef=np.linalg.lstsq(X,y,rcond=None)[0]; pred=X@coef
return coef,1-np.sum((y-pred)**2)/np.sum((y-y.mean())**2)
for columna in (0,1): print('OFI' if columna==0 else 'Volumen firmado',r2(filas[:,columna],filas[:,2]))For this seed and simplified book, signed volume’s exceeds OFI’s: that result must not be hidden to reproduce another sample’s conclusion. These are only 18 intervals and a contemporaneous relationship. Replenishment rules and absence of other levels matter.
sin=simular_libro(0)
def medio_en(hist,t):
filas=hist[hist[:,0]<=t]
return 100. if not len(filas) else filas[-1,2]
for Q in (5,10,20,30):
con=simular_libro(Q); fin=80+(Q-1)*.2
pico=medio_en(con,fin)-medio_en(sin,fin)
posterior=medio_en(con,fin+10)-medio_en(sin,fin+10)
print('Q:',Q,'| diferencia al final:',pico,'| 10 unidades después:',posterior)This comparison holds background flow fixed. Here discrete replenishment produces steps, not a guaranteed square-root law. For the difference ten units later increases on this path, so we cannot claim it always decays. Recovering the figure’s latent-density argument requires a different depth rule. Separately, we can check how a propagator is estimated from data with a known kernel; fitting a kernel to the preceding book would require addressing correlated regressors and evaluating fit on later dates.
rng=np.random.default_rng(282205); N=1000; q=rng.choice([-1.,1.],N)
G=np.array([.8,.5,.3,.15]); X=np.zeros((N-len(G)+1,len(G)))
for i in range(len(X)): X[i]=q[i:i+len(G)][::-1]
y=X@G+rng.normal(0,.3,len(X)); corte=int(.7*len(y))
estimado=np.linalg.lstsq(X[:corte],y[:corte],rcond=None)[0]
error=np.mean((y[corte:]-X[corte:]@estimado)**2)
print('Núcleo verdadero:',G,'| estimado:',estimado,'| MSE test:',error)Here signs are independent and the kernel has four known lags; data are generated from the same equation we fit. This is not a real-impact estimate or proof of absence of arbitrage for other kernels.
Exercises
Step 1 of 3. What is the cost of both trades' self-impacts?
def loghawkes1(t,T,mu,alpha,beta):
raise NotImplementedError()Key takeaways
OFI includes liquidity changes as well as trades; the square root is a regularity conditional on definitions and samples; propagators describe persistence and decay; Hawkes represents clustering through conditional intensities. None turns a contemporaneous correlation, a short fit or a simulation into automatic proof of causality or profitability.