Hawkes Processes for Trade Clustering: Fitting a Self-Exciting Point Process to Tick Data in Python

Fit a self-exciting point process to a session of trades and you will get a branching ratio. It will sit somewhere between zero and one, the optimiser will report success, and the number will look like a measurement of how much trading feeds on itself. In our own runs for this post, a sequence with no clustering whatsoever — 468 timestamps drawn uniformly at random — still produced a converged fit with a branching ratio of 0.217.
That single number is the reason this post spends more time on nulls and recovery studies than on the model’s elegance. The Hawkes process is a genuinely useful description of trade arrivals: Bacry, Mastromatteo and Muzy (2015, arXiv:1502.04592) describe it as “a particular class of multivariate point processes” that “has become very popular in empirical high frequency finance this last decade”. But popularity is not identification. A converged fit is not evidence of clustering, and any pipeline that treats it as such is measuring its own optimism.
So we do the unglamorous thing. We write the simulation, write the log-likelihood twice, prove the two agree to floating-point noise, fit a simulated session, stress the estimator across 20 seeds, and then fit the Poisson null that should embarrass it. Every number in the fitting sections comes from runs we did while writing this.
How This Guide Was Built
This guide was built from documentation and code, not from live trading: every paper and library fact comes from the arXiv works, official repositories, PyPI and docs cited inline, while every number in the fitting sections comes from our own runs on numpy 2.5.5 and scipy 1.18.1, fitting simulations we generated ourselves.
Two consequences follow. First, the library comparison table is a documentation reading, not a benchmark: we ran only the hand-rolled route, and we assign no timing or accuracy figures to hawkeslib, omitakahiro/Hawkes or tick. Second, nothing here is a claim about real markets. The data fitted below are synthetic event streams with known parameters, which is exactly what makes the recovery study and the null control interpretable. We did not trade this, we did not backtest returns, and no P&L appears anywhere.
The Model and the Convention Used Throughout
The model used here is a univariate Hawkes process with an exponential kernel, phi(u) = alpha·exp(−beta·u), whose branching ratio is n = alpha/beta and whose stationary rate is mu/(1−n), following the formulation in Bacry, Mastromatteo and Muzy (2015, arXiv:1502.04592), with 1/beta setting the excitation memory timescale.
phi(u) = alpha * exp(-beta * u)
lambda(t) = mu + sum_i alpha * exp(-beta * (t - t_i))
Lambda(0,T) = mu*T + (alpha/beta) * sum_i (1 - exp(-beta * (T - t_i)))
n = alpha / beta <-- NOT alpha
1/beta = excitation memory timescale
mean rate = mu / (1 - n), valid for n < 1 (sub-critical)
Some papers and libraries fold beta into alpha, writing phi(u) = alpha·beta·exp(−beta·u), in which case their alpha is the branching ratio. This post uses the un-folded convention above, so n = alpha/beta everywhere. If you compare our alpha = 0.737 against a package that uses the folded form, the numbers will not line up and neither will your conclusions. The background rate mu is events per unit time, alpha carries units of inverse time, and beta is inverse time; n is dimensionless, which is why it is the only parameter worth quoting across datasets.
The sub-critical condition n < 1 is what keeps the process stationary. At n → 1 the mean rate diverges and the excitation never dies out; in a finite sample that shows up as an estimate pinned against the boundary rather than as an obvious failure.
Simulating Trade Arrivals with Ogata Thinning
Ogata thinning simulates a Hawkes process by proposing candidate times from an upper-bound rate and accepting each one with probability lambda(t)/lambda_bar, and our seed-7 run at mu=0.5, alpha=0.8, beta=2.0 over 500 seconds produced 451 events at an own rate of 0.902 per second against a theoretical mu/(1−n) of 0.833.
import numpy as np
def simulate_hawkes(mu, alpha, beta, T, seed=7):
"""Ogata thinning for lambda(t) = mu + sum_{t_i<t} alpha*exp(-beta*(t-t_i))."""
rng = np.random.default_rng(seed)
events, t = [], 0.0
while t < T:
lam_bar = mu + alpha * sum(np.exp(-beta * (t - ti)) for ti in events)
t += rng.exponential(1.0 / lam_bar)
if t >= T:
break
lam_t = mu + alpha * sum(np.exp(-beta * (t - ti)) for ti in events)
if rng.random() <= lam_t / lam_bar:
events.append(t)
return np.asarray(events)
T = 500.0
events = simulate_hawkes(mu=0.5, alpha=0.8, beta=2.0, T=T, seed=7)
print(len(events), len(events) / T)
That prints 451 0.902. The gap between 0.902 and the theoretical 0.833 is ordinary finite-sample variation on a single 500-second path, not a bug: the empirical rate of one realisation is itself a random variable. The random number generation uses numpy’s Generator API, so seeding is explicit and reproducible. Note that this implementation re-sums over all past events at every candidate step; it is written for clarity, and a production simulator should carry the excitation state forward instead.
The O(n) Recursion That Makes the Log-Likelihood Evaluable
The O(n) recursion computes the excitation state exc[i] = exp(−beta·dt)·(1 + exc[i−1]), folding the entire event history into a single scalar per event so the log-likelihood costs linear rather than quadratic time, exactly as implemented below and cross-checked against the pairwise loop in the next section.
def loglik_recursion(params, events, T):
"""O(n): exc[i] = exp(-beta*dt)*(1 + exc[i-1]) folds the whole past into one state."""
mu, alpha, beta = params
if mu <= 0 or alpha <= 0 or beta <= 0 or alpha >= beta:
return 1e10
n = len(events)
exc = np.empty(n)
exc[0] = 0.0
for i in range(1, n):
dt = events[i] - events[i - 1]
exc[i] = np.exp(-beta * dt) * (1.0 + exc[i - 1])
ll = np.sum(np.log(mu + alpha * exc))
ll -= mu * T
ll -= (alpha / beta) * np.sum(1.0 - np.exp(-beta * (T - events)))
return -ll
Two details matter. The bound alpha >= beta returns a large penalty instead of raising, which keeps the optimiser inside the sub-critical region without a constrained solver. And the compensator uses the closed form (alpha/beta)·(1 − exp(−beta·(T − t_i))) rather than a numerical integral, so the objective is exact up to floating point. The recursion is the difference between a likelihood you can evaluate inside an optimiser loop and one you cannot.
Cross-Checking Against a Brute-Force Pairwise Loop
A brute-force reference that sums alpha·exp(−beta·(t_i − t_j)) over every ordered pair j < i on the same 451-event sequence agreed with the recursion to an absolute difference of 1.14e-13 in our run, which is floating-point noise rather than a modelling discrepancy.
def loglik_bruteforce(params, events, T):
"""O(n^2) reference: explicit sum over every ordered pair j < i."""
mu, alpha, beta = params
if mu <= 0 or alpha <= 0 or beta <= 0 or alpha >= beta:
return 1e10
n = len(events)
ll = 0.0
for i in range(n):
lam = mu
for j in range(i):
lam += alpha * np.exp(-beta * (events[i] - events[j]))
ll += np.log(lam)
ll -= mu * T
ll -= (alpha / beta) * np.sum(1.0 - np.exp(-beta * (T - events)))
return -ll
p = np.array([0.3, 0.5, 1.0])
print("abs difference: %.2e" %
abs(loglik_recursion(p, events, T) - loglik_bruteforce(p, events, T)))
Output: abs difference: 1.14e-13. This is the cheapest insurance in the whole pipeline. Every time you rewrite an intensity or a compensator — a different kernel, a mark term, a time-varying baseline — the pairwise loop is the oracle you check against on a few hundred events before you trust the fast version on millions.
Fitting One Simulated Session with L-BFGS-B
Fitting the 451-event simulation with L-BFGS-B recovered mu=0.568, alpha=0.737, beta=1.985 and a branching ratio of 0.371 against true values of 0.5, 0.8, 2.0 and 0.40, converging in 14 iterations and cutting the negative log-likelihood from 468.8236 to 452.9725 in our run.
from scipy.optimize import minimize
p0 = np.array([0.3, 0.5, 1.0])
res = minimize(loglik_recursion, p0, args=(events, T), method="L-BFGS-B",
bounds=[(1e-6, None)] * 3)
mu_hat, alpha_hat, beta_hat = res.x
n_hat = alpha_hat / beta_hat
print(f"mu={mu_hat:.3f} alpha={alpha_hat:.3f} beta={beta_hat:.3f} n={n_hat:.3f}")
print(f"success={res.success} nit={res.nit}")
print(f"start nll {loglik_recursion(p0, events, T):.4f} -> final nll {res.fun:.4f}")
That prints mu=0.568 alpha=0.737 beta=1.985 n=0.371, success=True nit=14, and start nll 468.8236 -> final nll 452.9725. The bounds and the in-objective penalty are belt and braces; success=True only means the gradient norm criterion was met, which is precisely why the next two sections exist. The optimiser interface is documented in the scipy.optimize.minimize reference.
The 20-Seed Recovery Study
Across 20 independent simulations every fit converged, the mean event count was 412 with a standard deviation of 23, and the coefficient of variation was 7.2% for mu, 14.1% for alpha, 14.1% for beta and 10.3% for the branching ratio in our runs, with alpha ranging from 0.577 to 1.024.
true = dict(mu=0.5, alpha=0.8, beta=2.0)
rows = []
for seed in range(1, 21):
ev = simulate_hawkes(true["mu"], true["alpha"], true["beta"], T, seed=seed)
fit = minimize(loglik_recursion, np.array([0.3, 0.5, 1.0]), args=(ev, T),
method="L-BFGS-B", bounds=[(1e-6, None)] * 3)
m, a, b = fit.x
rows.append((seed, len(ev), m, a, b, a / b, fit.success))
arr = np.array([r[2:6] for r in rows])
for k, lab in enumerate(["mu", "alpha", "beta", "branching"]):
col = arr[:, k]
print(f"{lab:>9}: mean {col.mean():.3f} sd {col.std(ddof=1):.3f} "
f"CV {100 * col.std(ddof=1) / col.mean():.1f}% "
f"range {col.min():.3f}-{col.max():.3f}")
print("converged:", sum(r[6] for r in rows), "/", len(rows))
print("events: mean %.0f sd %.0f" % (np.mean([r[1] for r in rows]),
np.std([r[1] for r in rows], ddof=1)))
Alpha and beta carry identical 14.1% CVs and ranges of 0.577–1.024 and 1.628–2.838, which is the signature of a strong trade-off between the two: the likelihood barely distinguishes a small alpha with a small beta from a large alpha with a large beta. The ratio is better behaved at 10.3%, but it is still a noisy number, and any downstream rule that thresholds on it inherits that noise. If you are going to quote one parameter from a single session, quote the one with the smallest CV and state the CV alongside it.
This is the same variance problem you fight elsewhere in quant research, and it is treated the same way: hold out data. Section-level splits with purged k-fold cross-validation or a walk-forward analysis tell you whether the fitted intensity generalises, where a single in-sample optimum cannot.
The Poisson Null Control
Fitting 468 uniformly drawn timestamps, which contain no clustering by construction, still returned a converged branching ratio of 0.217 in our run, with alpha collapsing to 0.034 and beta to 0.157, so a plausible-looking n is not by itself evidence that self-excitation exists.
rng = np.random.default_rng(42)
null_events = np.sort(rng.uniform(0.0, T, size=rng.poisson(0.9 * T)))
null_fit = minimize(loglik_recursion, np.array([0.3, 0.5, 1.0]),
args=(null_events, T), method="L-BFGS-B",
bounds=[(1e-6, None)] * 3)
mu0, a0, b0 = null_fit.x
print("mu=%.3f alpha=%.3f beta=%.3f n=%.3f stationary=%.3f observed=%.3f"
% (mu0, a0, b0, a0 / b0, mu0 / (1 - a0 / b0), 468 / T))
Output: mu=0.735 alpha=0.034 beta=0.157 n=0.217 stationary=0.938 observed=0.936. Read that slowly. The data are uniform, the fit converged, the branching ratio is 0.217 — larger than half the true value in the simulated clustered session — and the implied stationary rate matches the observed rate almost exactly. Nothing about the fit looks wrong.
The mechanism is the alpha–beta trade-off seen in the recovery study, pushed to its limit. With no clustering to explain, the likelihood can lower the objective slightly by spreading a small amount of excitation over a long memory (beta = 0.157 means a memory timescale near 6.4 seconds) rather than by fitting real bursts. Alpha collapses toward zero and beta follows it down, leaving a slow, low-amplitude kernel that mimics clustering in aggregate rate without any pairwise structure. The control is what turns a branching ratio into evidence: fit the null on shuffled or uniform timestamps, and compare. If your fitted n does not clearly separate from the null distribution, you have measured the optimiser, not the market.
What the Literature Establishes and What It Does Not
Bacry, Mastromatteo and Muzy (2015, arXiv:1502.04592) survey Hawkes applications spanning transaction-level volatility, market stability, systemic risk contagion, optimal execution and full order-book dynamics, while Hardiman, Bercot and Bouchaud (2013, arXiv:1302.1405) report a power-law kernel specifically for E-mini S&P futures mid-price changes.
The 2015 review is the right entry point because it is explicit about scope: it lists applications as “estimating the volatility at the level of transaction data, estimating the market stability, accounting for systemic risk contagion, devising optimal execution strategies or capturing the dynamics of the full order book”. The earlier Bacry, Delattre, Hoffmann and Muzy paper (2011, arXiv:1101.3422) does something more specific and more useful for microstructure work: it couples counting processes of positive and negative price jumps so that a single model reproduces both the strong microscopic mean reversion seen at seconds-to-a-few-minutes scale and the Epps effect, while preserving ordinary Brownian diffusion at large scales, fitted on Euro-Bund and Euro-Bobl futures.
Hardiman, Bercot and Bouchaud (2013, arXiv:1302.1405; published in Eur. Phys. J. B 86, 442) model arrivals of mid-price changes in the E-mini S&P futures contract as a self-exciting Hawkes process and find a power-law kernel with a decay exponent close to −1.15 at short times (below roughly 10^3 s), crossing over to a second power-law regime with an exponent near −1.45 above that scale. Scope that finding carefully: it concerns mid-price changes in one futures contract. It is not a statement that power-law kernels dominate exponential ones for equities in general, and the exponential kernel used above remains a deliberate, tractable choice rather than a claim about the true shape.
Four Implementation Routes Compared
Four routes cover the space — a hand-rolled recursion, hawkeslib, the omitakahiro/Hawkes package on PyPI and tick — and we ran only the hand-rolled route, so the library columns below come from official repositories and documentation rather than our own benchmarks.
| Route | Kernels supported | Model scope | Estimation extras | License & footprint | Maturity signals | Sweet spot |
|---|---|---|---|---|---|---|
| Hand-rolled recursion (this post) | exponential only, as written | univariate | MLE via scipy.optimize.minimize; sub-criticality enforced by a penalty inside the objective |
no package; a few dozen lines on numpy + scipy | validated against a brute-force loop to 1.14e-13 in our run | one or two parameters, full control, teaching and cross-checks |
| hawkeslib | exponential | univariate and multivariate Hawkes, plus Poisson models | log-likelihood, MLE/MAP estimates, posterior sampling (API docs) | MIT; PyPI v0.2.2 published 2019-06-18 | 72 GitHub stars at the time of checking | small exponential-kernel fits where a posterior is more useful than a point estimate |
omitakahiro/Hawkes (PyPI hawkes) |
exponential, sum of multiple exponentials, power-law, non-parametric | not documented in the sources we checked; the docs centre on a single sequence and its baseline | rich kernel and baseline catalogue; baselines constant, piecewise constant, piecewise linear, log-linear, custom | MIT; PyPI v1.0.0 | 72 GitHub stars at the time of checking | when the exponential kernel is too restrictive and you want a power-law or non-parametric shape |
| tick | simulation with standard or exotic kernels; inference with exponential or sum-of-exponential kernels, linear combinations of basis kernels, sparse interactions | multivariate; sparse interaction structures are part of the documented inference options | C++ implementation and optimisation algorithms aimed at fast computation in a single-node multi-core setting (JMLR 18(214), 2018; arXiv:1707.03003) | 3-Clause BSD; Python 3.11+, numpy≥2.0, scipy≥1.13, wheels for Linux/macOS/Windows | started 2016 at the Data Science Initiative of École Polytechnique; 632 stars, 128 forks, 428 commits at fetch on 2026-11-17; docs and examples | production-scale multivariate fits with a compiled backend |
Note on the table: we ran only the hand-rolled route. The hawkeslib, omitakahiro/Hawkes and tick columns are compiled from their repositories, PyPI pages and documentation, not from benchmarks we performed, and we attach no accuracy or speed figures to them. Version numbers and star counts are as stated at the time of checking and will drift.
Seasonality and the Intraday U-Shape
Intraday activity is heavier at the open and close than around midday, and a Hawkes model with a constant baseline will read that recurring diurnal pattern as self-excitation, attributing to event clustering what is really time-of-day seasonality, which is why a time-varying baseline belongs in any serious tick-level fit.
The failure mode is structural, not numerical. A constant mu must average across the whole session; when the true baseline swings with the clock, the excess arrivals in busy periods look exactly like aftershocks of earlier events, and beta absorbs the difference. You recover a branching ratio that partly measures the calendar. The fix is to make mu(t) piecewise constant or smooth over time-of-day — the omitakahiro/Hawkes package documents piecewise-constant, piecewise-linear and log-linear baselines for precisely this reason — and then to re-run the null control, because a time-varying baseline changes what “no clustering” means. Fit the seasonality first, then ask whether anything self-exciting remains.
Where This Belongs in a Research Pipeline
A fitted Hawkes intensity belongs in a research pipeline as a feature or conditioning variable rather than a standalone signal, and it must be evaluated with purged or walk-forward splits, because overlapping event windows otherwise leak information across folds and inflate any apparent edge.
The natural pairing is with order-flow imbalance: signed trade arrival clustering and imbalance both describe the same microsecond-scale process from different angles, and a Hawkes branching ratio adds the temporal dimension that a static imbalance statistic throws away. Before any of it reaches a strategy, run the backtest overfitting check and price the transaction costs — a clustering signal that only survives at zero cost is a signal about the cost model. And keep the null control in the pipeline, not in a notebook you ran once: refit it on every data slice your strategy sees.
FAQ
The questions below cover the five points readers raise most often about fitting Hawkes processes to tick data, and each answer is grounded in our own runs on numpy 2.5.5 and scipy 1.18.1 or in the arXiv papers cited above rather than in general impressions about self-excitation.
Does a branching ratio near one mean the market is unstable?
No. n < 1 is the sub-critical stationary regime, and a value close to one means long excitation memory, not instability. Estimates from a single session are noisy — our 20-seed study gave a 10.3% coefficient of variation on the branching ratio — so a fitted value near the boundary deserves scepticism before interpretation.
Why is my branching ratio alpha/beta and not alpha?
Because this post uses the kernel phi(u) = alpha·exp(−beta·u), where alpha has units of inverse time and the dimensionless ratio alpha/beta is the branching ratio. Some papers and libraries fold beta into alpha, writing phi(u) = alpha·beta·exp(−beta·u), in which case their alpha equals our n.
How much data do I need before the fit is meaningful?
There is no clean threshold, but our 451-event session produced 14.1% coefficients of variation on alpha and beta, which is enough noise to swamp most downstream thresholds. Treat the estimate as a distribution, report the spread across seeds or blocks, and prefer the parameter with the smallest coefficient of variation for any rule.
Can I fit this across several assets at once?
Yes in principle, and that is what multivariate Hawkes models are for: hawkeslib documents multivariate fitting and tick documents sparse interaction structures. We did not run either, and a multivariate fit multiplies the parameter count and the identification problems described here, so the null control and recovery study become more important, not less.
Can a Hawkes model predict when the next trade arrives?
Only in a conditional-intensity sense, and that is a probabilistic statement, not a forecast of the next timestamp. The intensity tells you the instantaneous arrival rate given history; turning it into anything tradable requires out-of-sample evaluation, cost modelling and a genuine edge, none of which the fit itself supplies.
The Bottom Line
The bottom line is that a Hawkes fit to tick data is only as trustworthy as the null it beats; our Poisson control returned a converged branching ratio of 0.217 on data with no clustering at all, so fit the null, check recovery across seeds, and treat the estimate as one noisy number among many.
Three habits carry the weight. Write the log-likelihood twice and check the fast version against the pairwise oracle — a 1.14e-13 agreement costs nothing and catches most coding errors. Measure the estimator’s own noise before you interpret it, because a 14.1% coefficient of variation on alpha means a single session cannot settle a research question. And fit the null every time, because a converged optimiser will happily manufacture a branching ratio out of nothing. The maths is standard, the tooling is mature, and the discipline is the part that decides whether the number means anything.
← Back to all posts

