Module contents
Lesson 22 of 30Advanced 115 min

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

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 bn,anb_n,a_n and quantities qnb,qnaq^b_n,q^a_n, an event contributes

en=1bn≥bn−1qnb−1bn≤bn−1qn−1b−1an≤an−1qna+1an≥an−1qn−1a.e_n=\mathbf{1}_{b_n\ge b_{n-1}}q^b_n-\mathbf{1}_{b_n\le b_{n-1}}q^b_{n-1} -\mathbf{1}_{a_n\le a_{n-1}}q^a_n+\mathbf{1}_{a_n\ge a_{n-1}}q^a_{n-1}.

If prices do not change, en=Δqb−Δqae_n=\Delta q^b-\Delta q^a. 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.

InteractiveOFI and depth

80 synthetic intervals with OFI = trade flow + other changes at the best level, and Δmidpoint = OFI / depth + independent noise. The result follows these equations by construction.

OFIMidpoint change−5.25.22.7

The vertical scale adapts to the chosen depth. A same-interval relationship leaves next-interval prediction and the causal effect of a single order unresolved.

2.0
Estimated slope0.487
R² with OFI0.888
R² with signed volume0.463
Change depth and compare regressions on OFI and transaction volume.

The figure imposes the linear relationship in its synthetic data: the higher R2R^2 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:

I(Q)≈YσQ/V.I(Q)\approx Y\sigma\sqrt{Q/V}.

Here QQ is quantity, VV reference volume, σ\sigma volatility over a compatible window and YY 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.

InteractiveTwo impact scales

On logarithmic axes, the curves show impact divided by Yσ. The square-root model is blue and the linear model is orange. The dot marks the selected participation.

Q/V (log): 0.0001 to 1Impact / (Yσ), log10.0001

If latent density rises in proportion to distance from the midpoint, cumulative volume up to distance Δ is proportional to Δ². This assumption gives Δ proportional to √Q. Applicability and total costs depend on the model and execution path.

2.0
0.7
1.0
Assumed final impact14.0 bp
Compare a square root with a linear relationship and calculate assumed impact for Q/V.

A latent-book intuition assumes available density ρ(x)=kx\rho(x)=kx at distance xx from the midpoint. Consuming up to Δ\Delta requires Q=∫0Δkx dx=kΔ2/2Q=\int_0^\Delta kx\,dx=k\Delta^2/2, so Δ=2Q/k\Delta=\sqrt{2Q/k}. 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:

pt=p0+∑i≤tG(t−i) f(qi)+εt.p_t=p_0+\sum_{i\le t}G(t-i)\,f(q_i)+\varepsilon_t.

Kernel GG describes how impact persists; ff 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.

InteractiveDecaying impacts

500 synthetic signs in blocks with Pareto durations and exponent 1 + persistence. The price accumulates past impacts and the seed is fixed. Confirming theoretical asymptotic persistence requires more than this small sample.

20.7−20.1Events 1 to 500

The round trip buys one unit and sells it 20 events later, with linear impact and half the instantaneous self-impact. Its cost is G(0) − G(20). A positive cost here applies only to this round trip.

Kernel
0.40
0.4
Var(Δ₅₀) / 50 Var(Δ₁)5.05
Simple round-trip cost0.704
Compare kernels and persistence in a synthetic path, and observe a simple cycle.

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 viv_i at times tit_i, linear kernel G(t)=ge−βtG(t)=g e^{-\beta t} and half self-impact, cost is g2∑ijvivje−β∣ti−tj∣\frac{g}{2}\sum_{ij}v_iv_j e^{-\beta|t_i-t_j|}. The symmetric exponential kernel is positive definite: its Fourier transform is 2β/(β2+ω2)>02\beta/(\beta^2+\omega^2)>0. Thus the quadratic form cannot be negative. A linear permanent term γ\gamma adds γ(∑ivi)2/2\gamma(\sum_i v_i)^2/2, 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,

λ(t)=μ+∑ti<tαe−β(t−ti),n=α/β.\lambda(t)=\mu+\sum_{t_i<t}\alpha e^{-\beta(t-t_i)},\qquad n=\alpha/\beta.

With μ>0\mu>0, α≥0\alpha\ge0, β>0\beta>0 and n<1n<1, a stationary version exists with mean intensity μ/(1−n)\mu/(1-n). The branching representation assigns each event an average nn of direct offspring. In that stationary model the expected long-run fraction of descendants is nn; in a short window, with intraday trend or misspecification, an estimated ratio does not automatically measure a causal market property. For two types, matrix KK 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.

InteractiveOrder cascades

Poisson immigrants arrive at rate 0.3 per unit time. Each event has a Poisson(n) number of children with exponential delays of mean one. The plot shows at most 200 events in [0, 30]. Generations 6 and above share a row.

Time 0 to 30Generation 0 to 6+

For a stationary univariate Hawkes process, n is the expected long-run fraction of descendants among all events. A single observation window can produce a different fraction, and ratios near 1 can occur without a flash crash.

0.60
1
Observed events18
Observed descendants7
Maximum generation2
Change the branching ratio and observe descendants in a finite window.

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 KijK_{ij} is the mean number of type ii offspring caused by a type jj event; both types share decay β\beta. For ordered events, maintain an exponential sum by source type and update it between events. The integral of each kernel over [tj,T][t_j,T] is Kij(1−e−β(T−tj))K_{ij}(1-e^{-\beta(T-t_j)}). This calculation costs O(n)O(n) 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.

[ ]Bivariate likelihood in linear timeBrowser
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 μi>0\mu_i>0 and β>0\beta>0. We parameterize each column of KK 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.

[ ]Fit a stable modelBrowser
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.

[ ]One-minute visible AAPL sampleBrowser
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 β\beta reaches the permitted upper bound, e5≈148.4e^5\approx148.4 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.

[ ]Time-change residualsBrowser
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 ϕ(u)=nθcθ/(c+u)1+θ\phi(u)=n\theta c^\theta/(c+u)^{1+\theta}, with c=0.05c=0.05 seconds fixed and 0<n<0.950<n<0.95. Integration of the power kernel to TT is n[1−(c/(c+T−ti))θ]n[1-(c/(c+T-t_i))^\theta]. Both models use the same events and three free parameters. Intensities use all prior history, O(n2)O(n^2) here for 50 timestamps; compare log-likelihoods on the same sample without interpreting them as out-of-sample validation.

[ ]Exponential and power law on the same timestampsBrowser
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 θ≈83\theta\approx83: 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 cc, 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.

[ ]Events and OFIBrowser
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.

[ ]Contemporaneous regression by intervalBrowser
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 R2R^2 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.

[ ]Metaorder versus paired pathBrowser
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 Q=20Q=20 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.

[ ]Fit a synthetic propagatorBrowser
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

NumericMean intensity
A stationary Hawkes process has μ=0.5 per second and n=0.8. What is its mean intensity per second?
NumericA metaorder
Q/V=1%, daily volatility 2% and Y=0.7. What is the assumed impact in basis points?
ProofBuy and sell
Prove: In a model with nonnegative linear permanent impact and transient impact G(t)=g exp(−βt), g,β>0, buy q and sell q after τ>0. Use the half self-impact convention and show that cycle cost is nonnegative.
The proof will appear here as you work.

Step 1 of 3. What is the cost of both trades' self-impacts?

QuizPersistent signs
How can a model with persistent signs avoid impact generating an indefinitely predictable trend?
CodeHawkes recursion
Implement loghawkes1(t,T,mu,alpha,beta) for strictly increasing times in [0,T), mu>0, alpha≥0 and beta>0. Use Rᵢ=exp(−βΔt)(1+Rᵢ₋₁), intensity μ+αRᵢ and integral μT+(α/β)∑(1−exp(−β(T−tᵢ))). Return log-likelihood.
def loghawkes1(t,T,mu,alpha,beta):
  raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
Flow, depth and horizon change observed impact. A useful model states which mechanisms it includes and is tested out of sample.

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.