Skip to content

Several series and events

sequential_analysis.procedures.multivariate

Several series at once: vector autoregression, lead-lag correlations, regression on drifting coefficients.

VectorAutoRegressive forecasts d series jointly from the last p values of all of them,

y_t = c + A_1 y_{t-1} + ... + A_p y_{t-p} + e_t,   e_t ~ N(0, Sigma),

so that one series' past can move another's forecast. With fixed coefficients and Sigma (from fit_var) the forecasts are Gaussian. Learnt online, the coefficients and Sigma have the conjugate normal-inverse-Wishart posterior with exponential forgetting lambda: the data's information decays by lambda per step, the ridge prior on the coefficients does not. With x_t = (1, y_{t-1}, ..., y_{t-p}), M = lambda X'X + ridge I, nu the discounted number of observations and S the discounted scatter of the one-step errors, the next value has the multivariate Student t predictive with nu' = lambda nu - d + 1 degrees of freedom and scale matrix (1 + x' M^-1 x) lambda S / nu' -- exact under the model. The recursion is

nu <- lambda nu + 1,   S <- lambda S + e e' / (1 + x' M^-1 x),

the multivariate form of AutoRegressive's (with d = 1 the two are the same model). Forecasts h > 1 steps ahead iterate the point forecast and add the variance the errors propagate, Psi_i Sigma Psi_i', to the one-step variance: a plug-in approximation, as in AutoRegressive.

CrossCorrelation tracks the correlation of a_t with b_{t-l} for every lag l from -L to L, with exponential forgetting: a positive lag with a large correlation says that b leads a by l steps. It describes; it does not test. Test a lead with an AnytimeLinearModel of a on its own lags and the lags of b, under Lagged (an anytime-valid Granger test), and with many pairs and lags control the false discoveries with OnlineFDR.

DynamicRegression regresses y on regressors with coefficients that drift as a random walk -- the hedge ratio of a pair of assets, a time-varying beta. It is the dynamic linear model with discount factor delta and an unknown observation variance learnt alongside (West and Harrison 1997, sections 4.5 and 6.3): the coefficients' covariance is inflated by 1/delta before each observation, and the one-step forecast of y is Student t. The state holds the precision (the inverse covariance), updated as delta P + f f', a sum of positive semi-definite terms: the covariance form loses tiny variances to cancellation when a regressor is huge. Its standardized forecast error z is the spread signal of pairs trading.

Cost per step (PERFORMANCE.md): VectorAutoRegressive is O(k^3 + k^2 d) for k = 1 + d p coefficients per series; CrossCorrelation O(L); DynamicRegression O(k^3) in its k coefficients.

VectorAutoRegressive

Bases: Procedure

VAR(p) forecasts of several series, with fixed coefficients or learnt online; see the module docstring.

series names the inputs, one number each per step. For fixed training give coefficients -- p matrices, coefficients[j][i][k] the effect of series k at lag j + 1 on series i -- with intercept and the noise covariance. Leave them out to learn them, with forgetting and ridge as in AutoRegressive.

forecast(state)

(means, standard deviations, degrees of freedom or None) for 1..horizon steps, or None.

parameters(state)

The intercept, the coefficient matrices and the noise scale matrix the next forecast uses.

CrossCorrelation

Bases: Procedure

Correlations of a_t with b_{t-lag} for lags -max_lag..max_lag, with optional forgetting.

forgetting lambda in (0, 1] weights a pair lag steps old by lambda^age (1: plain correlations). Descriptive only: see the module docstring for how to test a lead.

DynamicRegression

Bases: Procedure

Regression of y on regressors with coefficients that drift; see the module docstring.

discount delta in (0, 1]: the coefficients' covariance grows by 1/delta per step (1: fixed coefficients, recursive least squares; 0.99 lets them move by about a tenth of their uncertainty per step). variance_discount does the same for the noise variance. The prior is centred at 0 with covariance prior_scale times the noise variance.

multivariate_t_log_density(error, low, df)

Log density at error from the location of a normal (df None) or Student t law with scale L L'.

sequential_analysis.procedures.events

Streams of events: self-exciting arrivals and the market's reaction to events.

HawkesProcess is the exact filter of a Hawkes process with exponential kernel, the standard model of arrivals that come in bursts (news that breeds news, trades that breed trades):

lambda(t) = mu + sum over events t_i < t of alpha exp(-beta (t - t_i)),

baseline mu, each event raising the intensity by alpha, the excess decaying at rate beta; n = alpha / beta is the branching ratio, the expected number of events each event triggers (n < 1 for a stationary process). The excess decays geometrically between events, so the intensity, the log-likelihood

sum_i log lambda(t_i-) - integral of lambda from start to the last event,

and the compensator of each gap, the integral of lambda over it, are updated exactly in constant time per event (Ozaki 1979). Under the model the compensators are independent standard exponentials (time rescaling, Brown et al. 2002): a monitor of them -- a QuantileEDetector, say -- detects when the process stops behaving as fitted. The expected number of events in the next window time units, with all the cascades they trigger, is exact: the mean intensity relaxes to mu / (1 - n) at rate beta - alpha. Fit the parameters on a history with fit_hawkes.

EventStudy measures how a series moves after events: for each event, the cumulative sum of the next horizon values of r (abnormal returns: the return minus what the market explains, e.g. the error of a DynamicRegression on the market) at 1..horizon steps, averaged over events with an asymptotic confidence sequence for each horizon (as in AsymptoticConfidenceSequence, at level alpha / horizon each, so that all horizons hold together). It assumes the events' reactions are independent with a common mean: with overlap="skip" (the default) an event inside the window of the previous one is skipped and counted, so that no two windows share a value; with "allow" they may, and the intervals are then too narrow when reactions overlap.

HawkesProcess

Bases: Procedure

Exact filter of an exponential-kernel Hawkes process; see the module docstring.

Each step is one event, its time under input; times must not decrease. start is when observation began (the log-likelihood counts the quiet time before the first event).

intensity_at(state, t)

The intensity at time t >= the last event, if no event came in between.

expected_events(intensity, window)

Expected events in the next window time units from current intensity, cascades included.

EventStudy

Bases: Procedure

Average cumulative reaction of r over the horizon steps after an event; see the module docstring.

Inputs: returns (a real number, the abnormal return of the step) and event (1 if an event happened at this step). A window opens at the event's step and collects r from the next step on. The interval for horizon h holds, asymptotically and at all times together with the others, with probability 1 - alpha; there is none before start events (tuned_for as in AsymptoticConfidenceSequence).

sequential_analysis.events

Fitting and simulating Hawkes processes (see procedures.events.HawkesProcess).

fit_hawkes finds the maximum-likelihood baseline, excitation and decay of an exponential-kernel Hawkes process from the event times observed on [start, end]. The log-likelihood is computed exactly in O(n) by the recursion of the filter; it is maximized by Nelder-Mead over (log mu, logit n, log beta), with the branching ratio n = alpha / beta kept in (0, 1), started from the best of a small grid.

simulate_hawkes draws event times by Ogata's thinning, deterministically from a seed: for examples and tests.

hawkes_log_likelihood(times, baseline, excitation, decay, start, end)

Exact log-likelihood of event times on [start, end] under an exponential-kernel Hawkes process.

fit_hawkes(times, *, start=None, end=None, window=None, input='t', max_evaluations=2000)

Maximum-likelihood exponential-kernel Hawkes process; see the module docstring.

start and end bound the observation period (default: the first and last event). The result's model filters the events from start on; run it on to continue live.

simulate_hawkes(baseline, excitation, decay, end, *, start=0.0, seed=0)

Event times on [start, end] by Ogata's thinning (Python's random.Random(seed)).

Composition and topology

sequential_analysis.pipeline.Lagged

Bases: Procedure

Run inner with the recent past of some inputs as extra inputs.

lags maps each source input to a number of lags k: the inner procedure gets source_lag1, ..., source_lagk, the source's values one to k steps ago (lag_name), and must declare them as inputs. Its other inputs pass through unchanged; a source need not be one of them. The first steps, before every source has k past values, only fill the past: the inner procedure does not step and the output is not ready.

A typical use is a test of whether one series leads another: an AnytimeLinearModel of y on its own lags (nuisance) and the lags of x (tested) is an anytime-valid Granger test. The guarantee is the inner procedure's.

sequential_analysis.pipeline.lag_name(source, lag)

The name of an input's value lag steps ago, as Lagged passes it on.

The as-of join of events to bars, AsOfJoin, is with the other topologies in Runs, delivery and topologies.