Self-exciting point processes: conditional intensity and Hawkes
Real events cluster: an earthquake triggers aftershocks, a market order triggers others, and an incident can generate cascading alerts. Formalize point processes through conditional intensity, derive their likelihood and time-rescaling validation theorem, and study the Hawkes process via branching, stability, Ogata simulation, maximum-likelihood estimation and its multivariate extension.
After this lesson you can
- Write and maximize the log-likelihood of a point process with parametric intensity.
- Simulate a Hawkes process with exponential kernel using Ogata's method and its branching structure.
- Estimate an exponential Hawkes model by maximum likelihood with the O(n) recursion and validate it using time rescaling.
- Interpret branching ratio as the fraction of endogenous events and diagnose proximity to criticality.
- Fit a bivariate Hawkes model to buys and sells and read its cross-excitation matrix.
Before you start
When an event changes the probability of the next
An earthquake can be followed by aftershocks, a market order by other orders, and a defensive alert by a burst of related alerts. A constant Poisson rate cannot express a recent event changing the immediate probability of another. A self-exciting process can, although observing clustering alone does not prove a causal relationship between events.
In the figure, immigrants generate descendants, which may generate further descendants. The genealogy comes from explicit simulation: in real data it is normally unobserved and inferred under the model.
Intensity, compensator and likelihood
The conditional intensity describes the instantaneous arrival rate given the history available immediately before . Informally, under regularity and simplicity conditions, for a deterministic time that is almost surely not a jump,
The rigorous version uses a predictable intensity and compensator : under corresponding assumptions, is a local martingale, and an integrable martingale when the necessary integrability conditions hold. Intensity depends on the chosen filtration and cannot include a future event.
For an ordered sequence , the point-process log-likelihood, conditional on initial history and relative to a suitable reference measure, is
Between arrivals, the conditional probability of observing no further arrival until is the exponential of minus the intensity integral over that interval. Multiplying each survival probability by intensity at arrival time and adding survival over the final interval gives the expression. The integral term penalizes high intensity even when no events arrive; omitting it pushes the fit toward arbitrarily large rates.
The time-rescaling theorem transforms arrivals using compensator increments:
Under a correct model, suitable intensity and unbounded compensator, a fixed number of these increments are iid exponential with mean one; is uniform. The last wait cut by a fixed horizon is censored and must not be treated as complete. When parameters are estimated from the same data, usual bands and p-values assuming known parameters are not automatically calibrated. A good fit can fall outside a finite band by chance; a QQ plot alone does not prove the model is true.
Hawkes: jumps that generate offspring
A univariate linear Hawkes process has intensity
For exponential kernel , with , and , each event increases subsequent intensity by and that contribution decays on scale . Its mass is the branching ratio. An integrable power kernel can describe slower memory; its total mass, not just initial height, controls the subcritical condition.
The branching representation generates Poisson immigrants at rate . Each event generates children according to an independent Poisson process with intensity in elapsed time since birth; children in turn become parents. The mean number of direct children is . If , a cascade has expected size including the immigrant, and expected number of descendants . In subcritical stationarity,
Equality of intensities follows from ; the fraction refers to the model’s genealogy, not observed physical causality. At the finite stationary mean formula no longer applies. A simulation started without events before zero does not start in the stationary law and has a transient period.
Ogata and the exponential recursion
Ogata thinning simulation uses a bound valid until the next candidate. With constant baseline and positive exponential kernel, current intensity just after an event is a bound: if no further event arrives, it decays monotonically toward . Generate an exponential wait with that bound, decay contributions to the candidate, and accept it with the ratio of intensity there to the bound. After rejection, update time and recompute the bound. A variable baseline or a kernel that can increase requires a different bound; reusing the old one without proving it dominates the future biases the algorithm.
To calculate likelihood without scanning the entire history for every event, define and
With empty history at zero,
This recursion costs operations; direct pairwise summation costs . If history predates zero, its contributions must be included in intensity and compensator. Another estimation approach is EM: the E-step calculates the probability that each event is an immigrant or child of each earlier event, proportional to their intensity contributions; the M-step updates parameters accounting for the observation window and children that could appear after .
More than one type: predictive direction and causality
For types , a multivariate Hawkes process uses
Column indicates the parent’s type and row its child’s type. The mass matrix has a stationary regime with finite mean intensities under the usual nonnegativity, integrability and assumptions: . With positive immigration, if , that finite-mean stationary regime does not arise. This alone does not prove infinitely many events in finite time.
A nonzero cross-kernel can represent Granger-type predictive dependence under the model’s information and specification. An unobserved common factor or varying baseline rate can give the same appearance: this is not enough to claim that one order caused another. In their analysis of E-mini S&P 500 futures from 1998 to 2010, Filimonov and Sornette estimated that the fraction of price changes attributed to exogenous information fell from about 70% in 1998 to below 30% from 2007 onward. In a later study, the same authors showed that mixing Poisson regimes can produce an estimated ratio close to one even when the true ratio is zero. These results depend on data and specification, not a universal figure for all markets.
Lab: two Hawkes simulators
The first simulator maintains . As the clock advances, decays; if an event is accepted it increases by one. The event limit is an explicit safeguard: if reached, the function reports failure rather than returning a truncated path as complete.
import numpy as np
def hawkes_ogata(T, mu, alpha, beta, rng, max_events=100000):
if T < 0 or mu <= 0 or alpha < 0 or beta <= 0:
raise ValueError('parámetros fuera del dominio')
t, R = 0., 0.
tiempos = []
while True:
cota = mu + alpha*R
espera = rng.exponential(1/cota)
if t + espera > T:
return np.array(tiempos)
t += espera
R *= np.exp(-beta*espera)
if rng.random()*cota < mu + alpha*R:
tiempos.append(t)
R += 1
if len(tiempos) >= max_events:
raise RuntimeError('límite de eventos: trayectoria censurada')
def hawkes_cluster(T, mu, alpha, beta, rng, max_events=100000):
if T < 0 or mu <= 0 or alpha < 0 or beta <= 0 or alpha >= beta:
raise ValueError('para este simulador se requiere 0 <= alpha/beta < 1')
eventos = list(rng.uniform(0, T, rng.poisson(mu*T)))
i = 0
while i < len(eventos):
padre = eventos[i]
cantidad = rng.poisson(alpha/beta)
hijos = padre + rng.exponential(1/beta, cantidad)
eventos.extend(hijos[hijos < T])
if len(eventos) >= max_events:
raise RuntimeError('límite de eventos: trayectoria censurada')
i += 1
return np.sort(eventos)Both start with empty history and simulate the same model on . Their mean counts should therefore not be compared with as if they started in equilibrium. For the exponential kernel, mean intensity starting without history is , which can be integrated exactly. Comparing means does not alone prove equality of laws, but detects gross errors.
rng = np.random.default_rng(26071)
T, mu, alpha, beta, M = 30., .6, .7, 1.5, 500
ogata = np.array([len(hawkes_ogata(T, mu, alpha, beta, rng)) for _ in range(M)])
cluster = np.array([len(hawkes_cluster(T, mu, alpha, beta, rng)) for _ in range(M)])
n = alpha/beta
esperado = mu/(1-n)*(T - n*(1-np.exp(-(beta-alpha)*T))/(beta-alpha))
print('conteo medio Ogata y clúster:', round(ogata.mean(), 4), round(cluster.mean(), 4))
print('conteo teórico con historia vacía:', round(esperado, 4))
print('errores estándar de las medias:', round(ogata.std(ddof=1)/np.sqrt(M), 4), round(cluster.std(ddof=1)/np.sqrt(M), 4))Lab: likelihood and clock
The following function implements linear recursion and validates ordered times within the window. Fit , and by L-BFGS-B, restricting for the subcritical example. Uncertainty can be considerable, especially in short series; optimizer completion does not certify a global maximum.
from scipy.optimize import minimize
def hawkes_loglik(times, mu, alpha, beta, T):
times = np.asarray(times, dtype=float)
if mu <= 0 or alpha < 0 or beta <= 0 or T < 0:
raise ValueError('parámetros fuera del dominio')
if np.any(times < 0) or np.any(times > T) or np.any(np.diff(times) <= 0):
raise ValueError('tiempos deben ser crecientes y estar en la ventana')
R, anterior, suma = 0., 0., 0.
for i, t in enumerate(times):
if i:
R = np.exp(-beta*(t-anterior))*(1+R)
suma += np.log(mu+alpha*R)
anterior = t
return suma - mu*T - alpha/beta*np.sum(-np.expm1(-beta*(T-times)))
def ajustar_hawkes(times, T):
def objetivo(x):
mu, n, beta = x
return -hawkes_loglik(times, mu, n*beta, beta, T)
resultado = minimize(objetivo, [.5, .4, 1.], method='L-BFGS-B',
bounds=[(1e-5, 10), (0, .98), (.05, 5)])
if not resultado.success:
raise RuntimeError('optimización no convergió: '+resultado.message)
return resultado.x
rng = np.random.default_rng(26072)
mu0, n0, beta0 = .6, .45, 1.2
for T in (100., 500.):
times = hawkes_ogata(T, mu0, n0*beta0, beta0, rng)
estimado = ajustar_hawkes(times, T)
print('T, sucesos:', T, len(times), 'estimación μ,n,β:', np.round(estimado, 4))
print('parámetros verdaderos μ,n,β:', [mu0, n0, beta0])With this seed, the estimated ratio is for and for , versus true : a longer path does not guarantee that every estimate is closer. To study recovery, repeat the experiment with independent seeds and compare error distributions rather than selecting the best-fitting realization.
The following function performs that comparison with five replications per length. It records optimizer failures and summarizes only converged estimates; if failures occur, the summary should not be interpreted as though every fit succeeded. Five replications are a short check, expandable with parameter replicas.
def estudio_recuperacion(T, replicas, rng):
estimaciones = []
fallos = 0
for _ in range(replicas):
tiempos = hawkes_ogata(T, mu0, n0*beta0, beta0, rng)
try:
estimaciones.append(ajustar_hawkes(tiempos, T))
except RuntimeError:
fallos += 1
if not estimaciones:
raise RuntimeError('ninguna réplica convergió')
estimaciones = np.asarray(estimaciones)
return estimaciones, fallos
rng = np.random.default_rng(26076)
replicas_100, fallos_100 = estudio_recuperacion(100., 5, rng)
print('T=100, media μ,n,β:', np.round(replicas_100.mean(axis=0), 4), 'fallos:', fallos_100)
print('error absoluto medio de n:', round(np.abs(replicas_100[:, 1]-n0).mean(), 4))replicas_500, fallos_500 = estudio_recuperacion(500., 5, rng)
print('T=500, media μ,n,β:', np.round(replicas_500.mean(axis=0), 4), 'fallos:', fallos_500)
print('error absoluto medio de n:', round(np.abs(replicas_500[:, 1]-n0).mean(), 4))In this short run, mean absolute error of is for and for , with no reported failures. The difference is compatible with better recovery in longer windows, but five replications are insufficient to quantify it precisely; repeating and expanding the experiment is part of the work.
To diagnose the clock, simulate an independent sequence with a fixed number of arrivals. The compensator between two events incorporates the baseline plus history contributions that decay between them. Compare true and fitted clocks; because the latter’s parameters were estimated from another series, validation is independent, but fit uncertainty still affects its distribution. KS values diagnose this realization, not a universal certification.
from scipy.stats import kstest
def hawkes_n_eventos(cantidad, mu, alpha, beta, rng):
t, R = 0., 0.
tiempos = []
while len(tiempos) < cantidad:
cota = mu+alpha*R
espera = rng.exponential(1/cota)
t += espera
R *= np.exp(-beta*espera)
if rng.random()*cota < mu+alpha*R:
tiempos.append(t)
R += 1
return np.array(tiempos)
def reescalar(times, mu, alpha, beta):
anterior, R = 0., 0.
resultado = []
for t in times:
dt = t-anterior
resultado.append(mu*dt + alpha*R*(-np.expm1(-beta*dt))/beta)
R = R*np.exp(-beta*dt)+1
anterior = t
return np.array(resultado)
rng = np.random.default_rng(26073)
validacion = hawkes_n_eventos(300, mu0, n0*beta0, beta0, rng)
z_real = reescalar(validacion, mu0, n0*beta0, beta0)
z_ajustado = reescalar(validacion, estimado[0], estimado[1]*estimado[2], estimado[2])
print('medias reloj verdadero y ajustado:', round(z_real.mean(), 4), round(z_ajustado.mean(), 4))
print('KS verdadero:', np.round(kstest(z_real, 'expon')[:2], 4))
print('KS ajustado, diagnóstico:', np.round(kstest(z_ajustado, 'expon')[:2], 4))Recovery depends on length and realization. To study one specific confusion, generate a Poisson process whose baseline alternates between two regimes and fit the preceding constant-baseline Hawkes model. The generator’s true branching ratio is zero; any positive fitted value describes false attribution of that heterogeneity to the self-exciting model. One replication illustrates the mechanism and does not estimate its average bias.
rng = np.random.default_rng(26074)
T_regimen, ancho = 400., 40.
datos = []
for j in range(int(T_regimen/ancho)):
tasa = .2 if j % 2 == 0 else 2.0
eventos = rng.uniform(j*ancho, (j+1)*ancho, rng.poisson(tasa*ancho))
datos.extend(eventos)
datos = np.sort(datos)
ajuste_regimen = ajustar_hawkes(datos, T_regimen)
print('sucesos Poisson con regímenes:', len(datos))
print('ajuste Hawkes μ,n,β:', np.round(ajuste_regimen, 4), 'n verdadero:', 0)In this realization the fit returns although the generator has : the model uses feedback to absorb some rate changes not allowed in its baseline. This is an observation from the cell, not an estimate of how often the bias occurs. The study cited above analyzes this specification problem.
Lab: two types and EM
Simulate synthetic buys and sells with and known . Joint simulation uses the sum of current intensities as its bound; after accepting a candidate it chooses its type proportionally to intensities at that instant. The matrix is indexed as .
def hawkes_bivar(T, mu, A, beta, rng, max_events=100000):
mu, A = np.asarray(mu, float), np.asarray(A, float)
if np.any(mu <= 0) or np.any(A < 0) or beta <= 0 or T < 0:
raise ValueError('parámetros inválidos')
t = 0.
excitacion = np.zeros(2)
tiempos, tipos = [], []
while True:
cota = (mu+excitacion).sum()
dt = rng.exponential(1/cota)
if t+dt > T:
return np.array(tiempos), np.array(tipos, dtype=int)
t += dt
excitacion *= np.exp(-beta*dt)
tasas = mu+excitacion
marca = rng.random()*cota
if marca < tasas.sum():
tipo = 0 if marca < tasas[0] else 1
tiempos.append(t)
tipos.append(tipo)
excitacion += beta*A[:, tipo]
if len(tiempos) >= max_events:
raise RuntimeError('límite de eventos: trayectoria censurada')
mu_bi = np.array([.4, .35])
A_real = np.array([[.3, .12], [.18, .25]])
beta_bi, T_bi = 1.2, 400.
rng = np.random.default_rng(26075)
tiempos_bi, tipos_bi = hawkes_bivar(T_bi, mu_bi, A_real, beta_bi, rng)
print('compras y ventas:', np.bincount(tipos_bi, minlength=2))
print('matriz verdadera:', A_real)
print('radio verdadero:', round(max(abs(np.linalg.eigvals(A_real))), 5))In EM, the probability that event of type is an immigrant is . The probability that it is a child of earlier event is . For fixed , the M-step divides child responsibilities by exposure of each parent type: the boundary factor avoids treating offspring after as observed.
def em_bivar(times, types, T, beta, iteraciones=25):
times, types = np.asarray(times), np.asarray(types, int)
mu = np.full(2, max(len(times)/(4*T), .01))
A = np.full((2, 2), .15)
exposicion = np.array([np.sum(-np.expm1(-beta*(T-times[types == j]))) for j in range(2)])
if np.any(exposicion == 0):
raise ValueError('cada tipo necesita al menos un evento')
for _ in range(iteraciones):
inmigrantes = np.zeros(2)
hijos = np.zeros((2, 2))
for k, (t, tipo) in enumerate(zip(times, types)):
padres = types[:k]
aporte = A[tipo, padres] * beta * np.exp(-beta*(t-times[:k]))
tasa = mu[tipo] + aporte.sum()
inmigrantes[tipo] += mu[tipo]/tasa
for j in range(2):
hijos[tipo, j] += aporte[padres == j].sum()/tasa
mu = inmigrantes/T
A = hijos/exposicion[None, :]
return mu, A
mu_est, A_est = em_bivar(tiempos_bi, tipos_bi, T_bi, beta_bi)
print('base estimada:', np.round(mu_est, 4), 'base verdadera:', mu_bi)
print('matriz estimada:', np.round(A_est, 4))
print('matriz verdadera:', A_real)
print('radio estimado:', round(max(abs(np.linalg.eigvals(A_est))), 5))The window is finite and initial history is empty, as in simulation and likelihood: the estimated matrix fluctuates and may need more data or iterations. The algorithm does not impose during fitting; check the estimated radius before interpreting the result as stationary. Real data would require studying seasonality, effects of events before the window and common factors.
Exercises
Step 1 of 3. What is the survival probability until the next time t?
Step 1 of 3. What is the expected size of generation k?
hawkes_loglik(times, mu, alpha, beta, T) for kernel alpha·exp(−beta t), empty history, valid parameters, and strictly increasing times in [0,T]. Use the O(n) recursion and return the log-likelihood including the compensator.import numpy as np
def hawkes_loglik(times, mu, alpha, beta, T):
passConditional intensity turns history into prediction, and its integral penalizes absences in the likelihood. Hawkes models cascades with kernels whose mass determines offspring and stability. Ogata and the cluster representation give complementary simulators; the rescaled clock and comparisons with alternatives help detect a poor fit.