Module contents
Lesson 7 of 31Advanced 105 min

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.

InteractiveImmigrants and cascades

There are no previous events at t = 0. Immigrants follow a Poisson process of rate μ; each event generates a Poisson number of direct descendants with mean n and exponential delays of rate β. Only descendants through t = 20.

  • Intensity of this path
  • Theoretical mean from empty history
  • Stationary mean

The kernel is nβ exp(−βs): each arrival produces a jump nβ and its effect decays. The plot shows the value immediately after the jump; predictable intensity at the event time uses the left limit. Mean μ/(1−n) belongs to the stationary regime, not this path or empty start.

Genealogy: each segment connects an event to its direct descendant; height indicates generation.

  • One color per cluster, reused if there are many

The descendant fraction observed in a finite window with empty start need not equal n. The transient mean comes from the model; it is not an empirical mean of the shown cascades.

0.4
0.65
1.0
Immigrants in the window7
Descendants in the window17
Observed descendant fraction70.8 %
Stationary mean μ/(1−n)1.143
Theoretical final mean from zero1.142
Change the branching ratio and observe the intensity and tree of simulated events. The mean μ/(1−n) corresponds to stationarity; a simulation starting without history has an initial transient.

Intensity, compensator and likelihood

The conditional intensity λ∗(t)\lambda^*(t) describes the instantaneous arrival rate given the history available immediately before tt. Informally, under regularity and simplicity conditions, for a deterministic time tt that is almost surely not a jump,

P(Nt+Δ−Nt=1∣Ft)=λ∗(t)Δ+o(Δ).\Pr(N_{t+\Delta}-N_t=1\mid\mathcal F_t)=\lambda^*(t)\Delta+o(\Delta).

The rigorous version uses a predictable intensity and compensator Λ∗(t)=∫0tλ∗(u)  ⁣du\Lambda^*(t)=\int_0^t\lambda^*(u)\,\dd u: under corresponding assumptions, Nt−Λ∗(t)N_t-\Lambda^*(t) 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 0<t1<⋯<tn<T0<t_1<\cdots<t_n<T, the point-process log-likelihood, conditional on initial history and relative to a suitable reference measure, is

ℓ(θ)=∑i=1nlog⁡λθ∗(ti)−∫0Tλθ∗(t)  ⁣dt.\ell(\theta)=\sum_{i=1}^{n}\log\lambda_\theta^*(t_i)-\int_0^T\lambda_\theta^*(t)\,\dd t.

Between arrivals, the conditional probability of observing no further arrival until tt 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:

Zi=∫ti−1tiλ∗(u)  ⁣du.Z_i=\int_{t_{i-1}}^{t_i}\lambda^*(u)\,\dd u.

Under a correct model, suitable intensity and unbounded compensator, a fixed number of these increments are iid exponential with mean one; 1−e−Zi1-e^{-Z_i} 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.

InteractiveCheck the arrival clock
Horizontal: Exp(1) quantiles. Vertical: rescaled-interval quantiles.
  • Fitted Poisson
  • Fitted Hawkes
  • Generating Hawkes
  • 95% DKW band for known reference
  • Equal quantiles

The training path lasts 300 units and begins with empty history. Validation is another path, also without initial history, stopped after 200 complete events. Each compensated interval is calculated with the history observed on that path; no final censored interval is used.

Poisson fits a constant rate. Hawkes numerically fits μ and α with β = 1 fixed, α/β ≤ 0.98 and α/μ ≤ 100; the reference uses true μ = 0.4 and selected α/β. The simultaneous DKW band has at least 95% coverage for 200 independent Exp(1) intervals with known model. Its upper limit is infinite in the right tail and is not drawn. It excludes estimated-parameter uncertainty and thus does not calibrate a test for fitted curves. Even the reference can leave the band; the QQ plot examines marginals, not temporal independence.

0.75
Training events531
Fitted Poisson rate1.770
Fitted Hawkes: μ0.385
Fitted Hawkes: α0.783
Validation200 events
Seed2607
Compare rescaled times with exponential quantiles under the indicated intensities. Interpret deviations alongside fitting method, horizon and sampling uncertainty.

Hawkes: jumps that generate offspring

A univariate linear Hawkes process has intensity

λ∗(t)=μ+∑ti<tϕ(t−ti),ϕ≥0.\lambda^*(t)=\mu+\sum_{t_i<t}\phi(t-t_i),\qquad \phi\ge0.

For exponential kernel ϕ(u)=αe−βu1u>0\phi(u)=\alpha e^{-\beta u}\mathbf1_{u>0}, with μ>0\mu>0, α≥0\alpha\ge0 and β>0\beta>0, each event increases subsequent intensity by α\alpha and that contribution decays on scale 1/β1/\beta. Its mass n=∫0∞ϕ(u)  ⁣du=α/βn=\int_0^\infty\phi(u)\,\dd u=\alpha/\beta 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 μ\mu. Each event generates children according to an independent Poisson process with intensity ϕ(u)\phi(u) in elapsed time since birth; children in turn become parents. The mean number of direct children is nn. If n<1n<1, a cascade has expected size 1+n+n2+⋯=1/(1−n)1+n+n^2+\cdots=1/(1-n) including the immigrant, and expected number of descendants n/(1−n)n/(1-n). In subcritical stationarity,

λˉ=μ1−n,fraccioˊn media de eventos descendientes=n.\bar\lambda=\frac{\mu}{1-n},\qquad \text{fracción media de eventos descendientes}=n.

Equality of intensities follows from λˉ=μ+nλˉ\bar\lambda=\mu+n\bar\lambda; the fraction refers to the model’s genealogy, not observed physical causality. At n=1n=1 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 μ\mu. 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 R1=0R_1=0 and

Ri=e−β(ti−ti−1)(1+Ri−1),λ∗(ti)=μ+αRi.R_i=e^{-\beta(t_i-t_{i-1})}(1+R_{i-1}),\qquad \lambda^*(t_i)=\mu+\alpha R_i.

With empty history at zero,

ℓ=∑ilog⁡(μ+αRi)−μT−αβ∑i(1−e−β(T−ti)).\ell=\sum_i\log(\mu+\alpha R_i)-\mu T- \frac\alpha\beta\sum_i\bigl(1-e^{-\beta(T-t_i)}\bigr).

This recursion costs O(n)O(n) operations; direct pairwise summation costs O(n2)O(n^2). 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 TT.

More than one type: predictive direction and causality

For types i=1,…,di=1,\ldots,d, a multivariate Hawkes process uses

λi∗(t)=μi+∑j∑tk(j)<tϕij(t−tk(j)).\lambda_i^*(t)=\mu_i+\sum_j\sum_{t_k^{(j)}<t}\phi_{ij}(t-t_k^{(j)}).

Column jj indicates the parent’s type and row ii its child’s type. The mass matrix Aij=∫0∞ϕij(u)  ⁣duA_{ij}=\int_0^\infty\phi_{ij}(u)\,\dd u has a stationary regime with finite mean intensities under the usual nonnegativity, integrability and ρ(A)<1\rho(A)<1 assumptions: λˉ=(I−A)−1μ\bar{\boldsymbol\lambda}=(I-A)^{-1}\boldsymbol\mu. With positive immigration, if ρ(A)≥1\rho(A)\ge1, that finite-mean stationary regime does not arise. This alone does not prove infinitely many events in finite time.

InteractiveSelf- and cross-excitation

Two cumulative counts, from empty history. Each jump is an event. The path covers the full requested horizon.

  • Type 1
  • Type 2

Correlation between counts in windows of 2 units: a positive lag compares type 1 with type 2 in a later window.

For each lag, Pearson correlation is calculated over overlapping complete-window pairs, centering each series by its mean over those pairs. A point is omitted if fewer than two pairs exist or either variance is zero. Incomplete windows and events after censoring are excluded. This single-path correlation fluctuates and does not establish causality.

Model: base intensity 0.25 for each type and kernel aᵢⱼ exp(−t), for positive t. Each type-j event increases intensity i by aᵢⱼ; the kernel integral is also aᵢⱼ. The simulation uses Ogata thinning and an empty prior history, so it does not start in stationarity. With ρ < 1 a stationary regime exists, although this path starts from empty history.

0.25
0.15
0.20
0.25
80
1
Spectral radius ρ(A)0.423
Simulation statusFull horizon
Type 1 events34
Type 2 events23
Complete windows40
Zero-lag correlation0.067
Modify the branching matrix and observe simulated series, dependence between counts and spectral radius. The matrix describes prediction under the model and does not by itself identify structural causality.

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 R(t)=∑ti<te−β(t−ti)R(t)=\sum_{t_i<t}e^{-\beta(t-t_i)}. As the clock advances, RR 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.

[ ]Ogata with exponential kernelBrowser
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 [0,T][0,T]. Their mean counts should therefore not be compared with Tμ/(1−n)T\mu/(1-n) as if they started in equilibrium. For the exponential kernel, mean intensity starting without history is m(t)=μ(1−ne−(β−α)t)/(1−n)m(t)=\mu(1-ne^{-(\beta-\alpha)t})/(1-n), which can be integrated exactly. Comparing means does not alone prove equality of laws, but detects gross errors.

[ ]Compare both generatorsBrowser
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 μ\mu, n=α/βn=\alpha/\beta and β\beta by L-BFGS-B, restricting n<1n<1 for the subcritical example. Uncertainty can be considerable, especially in short series; optimizer completion does not certify a global maximum.

[ ]Linear likelihood and fittingBrowser
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 0.38650.3865 for T=100T=100 and 0.35060.3506 for T=500T=500, versus true 0.450.45: 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.

[ ]Recovery across replicationsBrowser
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))
[ ]Recovery with a longer windowBrowser
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 nn is 0.12040.1204 for T=100T=100 and 0.04810.0481 for T=500T=500, 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.

[ ]Rescaling with a fixed number of eventsBrowser
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.

[ ]Changing baseline and false excitationBrowser
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 n=0.8495n=0.8495 although the generator has n=0n=0: 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 ϕij(u)=Aijβe−βu\phi_{ij}(u)=A_{ij}\beta e^{-\beta u} and known β\beta. 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 Ahijo,padreA_{\text{hijo},\text{padre}}.

[ ]Bivariate simulationBrowser
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 kk of type ii is an immigrant is μi/λi(tk)\mu_i/\lambda_i(t_k). The probability that it is a child of earlier event jj is Ai,cjβe−β(tk−tj)/λi(tk)A_{i,c_j}\beta e^{-\beta(t_k-t_j)}/\lambda_i(t_k). For fixed β\beta, the M-step divides child responsibilities by exposure ∑j(1−e−β(T−tj))\sum_j(1-e^{-\beta(T-t_j)}) of each parent type: the boundary factor avoids treating offspring after TT as observed.

[ ]EM with boundary correctionBrowser
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 ρ(A)<1\rho(A)<1 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

NumericStationary mean
A stationary Hawkes process has μ=0.5 and kernel φ(t)=0.8 exp(−2t) for t>0. Calculate its mean intensity.
QuizA clock running too slowly
In a QQ plot, theoretical exponential quantiles are on the horizontal axis and observed rescaled intervals on the vertical axis. If the model systematically underestimates intensity just after events, what local effect should you expect in those intervals?
ProofFrom waits to likelihood
Prove: Derive the log-likelihood of a pattern of n arrivals up to T from conditional intensity.
0
Between arrivals, condition on the history known just after the previous one.

Step 1 of 3. What is the survival probability until the next time t?

ProofThe size of a cascade
Prove: For a branching structure with expected number of children n<1 per parent, calculate the expected number of descendants of an immigrant.
0
Group descendants by generation and exclude the immigrant itself.

Step 1 of 3. What is the expected size of generation k?

CodeLikelihood without summing every pair
Implement 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):
  pass
Shift+Enter to run
Key idea

Conditional 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.