Order Flow Imbalance in Python: The Cont–Kukanov–Stoikov Price-Impact Signal, Rebuilt Correctly

Best-bid-and-offer quotes alone can explain much of the short-horizon movement in a stock’s mid-price, but only if the signal is built with exact sign conventions. Cont, Kukanov and Stoikov report an average in-sample R² of 65% for order flow imbalance (OFI) over 10-second intervals, against 32% for trade imbalance (arXiv:1011.6402). Those results come from April 2010, measured on a 10-second grid of best-quote updates. This article rebuilds the signal in pandas on synthetic data so every step can be checked.

Sourcing and limits. This article is built on the arXiv paper by Cont, Kukanov and Stoikov (arXiv:1011.6402; full-text HTML), its tables and appendix, the Databento schema documentation for MBP-1 and MBO, and the statsmodels OLS docs. No data vendor was tested hands-on, and no code was run against real market data. The code below runs on a seeded synthetic book, so its printed numbers are a mechanics check rather than a market result.

What the e_n formula counts, and where it breaks

Each book event contributes a signed amount e_n: size added or removed at the best bid counts positively or negatively, a bid price rise adds the new size, and the ask side enters with all signs reversed. The comparisons must be weak inequalities, because a tie in price is where naive code breaks. The paper’s Section 2.1 defines the contribution using the book state after event n, with P and q denoting best prices and sizes in shares (arXiv:1011.6402).

e_n = 1{P^B_n >= P^B_{n-1}} * q^B_n
    - 1{P^B_n <= P^B_{n-1}} * q^B_{n-1}
    - 1{P^A_n <= P^A_{n-1}} * q^A_n
    + 1{P^A_n >= P^A_{n-1}} * q^A_{n-1}

When the bid price is unchanged, P^B_n = P^B_{n−1}, both bid indicators equal 1 and the bid contribution collapses to q^B_n − q^B_{n−1}. The definition uses weak inequalities, so a tie in price contributes both the new and the old queue size; strict > or < would drop one term.

Book change Contribution e_n (shares) Reading
Bid price unchanged, size changes q^B_n − q^B_{n−1} Size added or removed; L1 cannot tell a cancel from a market sell
Bid price up +q^B_n Price-improving buy
Bid price down −q^B_{n−1} Old best-bid size removed
Ask price unchanged, size changes −(q^A_n − q^A_{n−1}) Same structure, signs reversed
Ask price down (improvement) −q^A_n Net seller signal
Ask price up +q^A_{n−1} Old best-ask size removed; buy-side signal

Table: case table from the paper’s Section 2.1 (arXiv:1011.6402). The paper treats cancels and market orders at the same price as equivalent, and L1 data cannot separate them.

Turning events into a tested pipeline

Build the event contributions first, test them against hand-computed cases, then aggregate. The four blocks below run top to bottom on a seeded synthetic book, and their printed output illustrates mechanics only. Each test asserts one row of the case table, so a sign error fails loudly before any regression runs.

# SYNTHETIC DEMO DATA — illustrative only, not market results.
import numpy as np
import pandas as pd
import statsmodels.api as sm

TICK = 0.01  # tick size in currency units; sizes are in shares
# If prices arrive as int64 at 1 unit = 1e-9 (Databento MBP-1 encoding),
# convert with px * 1e-9 BEFORE dividing by TICK.

def make_synthetic_l1(n_events=200_000, seed=7):
    """SYNTHETIC — for demonstrating sign conventions and pipeline mechanics only;
    outputs are not comparable to Cont–Kukanov–Stoikov's statistics."""
    rng = np.random.default_rng(seed)
    bid_px, ask_px, bid_sz, ask_sz = 100.00, 100.02, 500, 500
    ts, rows = 1_700_000_000_000_000_000, []  # ns timestamps, monotonic
    for _ in range(n_events):
        ts += int(rng.integers(1_000_000, 300_000_000))
        u = rng.random()
        if u < 0.45:                                           # size add/remove at bid
            bid_sz = max(1, bid_sz + int(rng.integers(-150, 151)))
        elif u < 0.90:                                         # size add/remove at ask
            ask_sz = max(1, ask_sz + int(rng.integers(-150, 151)))
        elif u < 0.96:                                         # mid moves one tick, either way
            step = TICK if rng.random() < 0.5 else -TICK
            bid_px = round(bid_px + step, 2)
            ask_px = round(bid_px + 2 * TICK, 2)               # keep a two-tick spread
            bid_sz = int(rng.integers(100, 800)); ask_sz = int(rng.integers(100, 800))
        else:                                                  # two-sided update: ONE event
            bid_sz = max(1, bid_sz + int(rng.integers(-100, 101)))
            ask_sz = max(1, ask_sz + int(rng.integers(-100, 101)))
        rows.append((ts, bid_px, ask_px, bid_sz, ask_sz))
    return pd.DataFrame(rows, columns=["ts_event", "bid_px", "ask_px", "bid_sz", "ask_sz"])

def ofi_events(df):
    """Event contributions e_n (shares). First row = 0 (no prior state)."""
    assert df["ts_event"].is_monotonic_increasing, "sort by ts_event first"
    bp, bs, ap, as_ = df["bid_px"], df["bid_sz"], df["ask_px"], df["ask_sz"]
    pbp, pbs, pap, pas = bp.shift(), bs.shift(), ap.shift(), as_.shift()
    # Weak inequalities (>=, <=): a tie P_n = P_{n-1} fires BOTH bid terms,
    # collapsing to q_n - q_{n-1}. Strict > / < would zero same-price size changes.
    e_bid = np.where(bp >= pbp, bs, 0) - np.where(bp <= pbp, pbs, 0)
    # Ask side: same structure, ALL signs reversed. An ask downtick is a seller signal.
    e_ask = -np.where(ap <= pap, as_, 0) + np.where(ap >= pap, pas, 0)
    return pd.Series(e_bid + e_ask, index=df.index, name="e_n")
# Deterministic case-table tests: no randomness, no data.
def _pair(prev, cur):
    df = pd.DataFrame([prev, cur], columns=["bid_px", "bid_sz", "ask_px", "ask_sz"])
    df.insert(0, "ts_event", [1, 2])
    return ofi_events(df).iloc[1]

B = (100.00, 500, 100.02, 500)  # baseline book
cases = {
    "bid size add":    ((100.00, 600, 100.02, 500), 100),   # q_n - q_{n-1}
    "bid size remove": ((100.00, 350, 100.02, 500), -150),
    "bid uptick":      ((100.01, 300, 100.02, 500), 300),   # +q^B_n
    "bid downtick":    ((99.99, 400, 100.02, 500), -500),   # -q^B_{n-1}
    "ask downtick":    ((100.00, 500, 100.01, 200), -200),  # -q^A_n
    "tie both sides":  ((100.00, 600, 100.02, 350), 250),   # 100 + (500 - 350)
}
for name, (cur, expected) in cases.items():
    got = _pair(B, cur)
    assert got == expected, (name, got, expected)
    print(f"PASS {name:16s} e_n = {got:+.0f} (synthetic check)")

From events to regression: grid, windows, and the recipe

Sum e_n into OFI over a 10-second clock grid, sample the mid at each grid instant by last observation, and regress the tick change in mid on OFI within half-hour windows. The paper estimates each window by OLS with White heteroscedasticity-consistent errors (arXiv:1011.6402). Keeping events on the clock side and prices on the last-observation side is what keeps the signal honest.

The base grid is Δt = 10 seconds. The paper reports fits from 10 quote updates (usually under half a second) up to 10 minutes and says the fit generally increases with Δt (arXiv:1011.6402). The target is ΔP_k = (P_k − P_{k−1})/δ with δ = $0.01. Each stock has 273 half-hour subsamples with about 180 observations each (full-text HTML). By our own arithmetic, 180 × 10 s is 30 minutes, which matches the window (DERIVED). The demo starts its windows at the first timestamp as a stand-in for the 9:30 session open used in the paper’s filters.

# Grid aggregation: event-indexed e_n -> clock-indexed OFI_k on [t_{k-1}, t_k).
df = make_synthetic_l1()

def aggregate_and_regress(df, e, grid_s=10, window_min=30):
    ts = df["ts_event"].to_numpy()
    grid = np.arange(ts[0], ts[-1], grid_s * 10**9)         # 10-second clock grid, ns
    pos = np.searchsorted(ts, grid, side="left")             # events strictly before t_k
    cum = np.concatenate([[0.0], np.cumsum(e.to_numpy())])
    ofi = np.diff(cum[pos])                                  # OFI_k in shares; empty bins = 0
    k = np.searchsorted(ts, grid, side="right") - 1          # last observation at or before t_k
    assert k.min() >= 0
    mid = ((df["bid_px"] + df["ask_px"]) / 2).to_numpy()[k] # last-observation mid, no averaging
    dP = np.diff(mid) / TICK                                 # ΔP_k in ticks
    win = (grid[1:] - grid[0]) // (window_min * 60 * 10**9)  # half-hour windows from session start
    rows = []
    for w in np.unique(win):
        m = win == w
        if m.sum() < 30 or ofi[m].std() == 0:
            continue
        res = sm.OLS(dP[m], sm.add_constant(ofi[m])).fit(cov_type="HC3")  # paper: "White" HC; variant UNVERIFIED
        rows.append((w, m.sum(), res.params[1], res.tvalues[1], res.pvalues[1], res.rsquared))
    out = pd.DataFrame(rows, columns=["window", "n_obs", "beta_ticks_per_share", "t_beta", "p_beta", "r2"])
    print("SYNTHETIC DEMO DATA — illustrative only, not market results")
    print(out.round(4).to_string(index=False))
    print("SYNTHETIC grand mean beta:", round(out.beta_ticks_per_share.mean(), 4),
          "| mean R2:", round(out.r2.mean(), 3),
          "| share significant at 5%:", round((out.p_beta < 0.05).mean(), 2))
    return out

out = aggregate_and_regress(df, ofi_events(df))

The headline numbers, and why there is no typical beta

The grand means are strong: β = 0.0398 ticks per share, t = 11.47, significant in 97% of subsamples, with an average R² of 65%. The per-stock values are not uniform. β runs from 0.0002 for BAC to 0.6262 for CME, so a single pooled coefficient hides more than three orders of magnitude of variation (arXiv:1011.6402).

Coefficient Value (ticks, or ticks per share) t-stat Subsamples significant at 5% (%) Average R² (%)
α (intercept) 0.0002 (ticks) — 6 —
β (OFI slope) 0.0398 (ticks per share) 11.47 97 65

Table: grand means, as reported in the paper’s Table 2 (full-text HTML).

Stock β (ticks per share) t(β) R² (%)
AMD 0.0008 9.96 64
BAC 0.0002 18.36 79
SLB 0.0198 16.76 76
CME 0.6262 4.98 35
WIN 0.0009 3.12 44

Table: per-stock values from the paper’s Section 3.2 (arXiv:1011.6402). APOL, AZO and CME fit worst, which the authors attribute to wide spreads and low depth.

How much of the 65% is a tautology?

Part of it, and the paper’s own test shows how much. Price-changing events are built from the same quotes that define e_n, so they can inflate the fit. When the authors exclude price-changing events, R² “remained in the 35%–60% region” (full-text HTML). A quadratic term lifts the average from 65% to 68% with a statistically insignificant coefficient in most samples, which supports the linear form.

The 65% is an in-sample fit that the authors themselves flag as a possible tautology, since OFI includes price-changing events. By our arithmetic, the exclusion test implies a decline of roughly 5 to 30 percentage points (DERIVED, not the authors’ wording). The paper reports no out-of-sample forecasting performance, Sharpe ratios, turnover or transaction costs (arXiv:1011.6402).

Why β scales with depth

The slope behaves roughly like the inverse of displayed depth. The paper fits β = c/AD^λ; averaged across stocks, its estimates are c = 0.45 (t = 20.74, Newey–West), λ = 0.98 (t = 29.53, Newey–West) with R² = 74%, where AD is half the average of bid plus ask size per event (full-text HTML, Table 3). The hypothesis λ = 1 cannot be rejected for 35 of 50 stocks. A stylized model with constant depth implies c = 1/2, and the authors attribute the gap to AD being “only a rough measure of market depth” (full-text HTML).

Parameter Estimate t-stat Regression R² (%)
c (scale) 0.45 20.74 74
λ (depth exponent) 0.98 29.53 74 (same fit)

Table: depth-scaling results from the paper’s Table 3 (arXiv:1011.6402). The stylized model implies c = 1/2.

Intraday, the paper reports depth two times lower near the open, price impact two times higher, and impact five times higher at the open than at the close (arXiv:1011.6402).

OFI versus trade imbalance: quotes beat prints

Quotes win clearly. OFI alone explains an average 65% of 10-second mid-price changes, against 32% for trade imbalance alone. When both enter together, trade imbalance’s t-statistic falls by a factor of four and it is significant in only 31% of subsamples. Under trade-time sampling, OFI stays ahead at every trade count the paper tests (arXiv:1011.6402).

Specification Average R² (%) t-stat Subsamples significant (%)
Trade imbalance (TI) alone 32 4.18 81
OFI alone 65 11.47 97
OFI + TI jointly 67 OFI 8.49; TI 1.16 TI: 31

Table: from the paper’s Table 4, Panel A (full-text HTML).

Trades per interval (L) OFI R² (%) TI R² (%)
2 14 1
5 38 8
10 51 13

Table: trade-time sampling on 5 stocks, from the paper’s Table 4, Panel B (arXiv:1011.6402). The paper signs trades with a quote test matched within 1 second; tick test and Lee-Ready gave “virtually the same” results.

What data you need: MBP-1 or MBO

Level-1 data is enough for the paper’s formula. Databento’s MBP-1 schema documents every event that updates the best bid and offer, with nanosecond timestamps, while its MBO schema is order-keyed Level-3 data that exposes queue position and cancel-versus-fill attribution (Databento MBP-1 docs; Databento MBO docs). The points below come from that documentation only.

  • MBP-1 (L1): every event updating the top level, “often called ‘L1 data’” in the vendor’s words. Fields include bid_px_00, ask_px_00, bid_sz_00, ask_sz_00, ts_event and ts_recv, with action codes A/C/M/R/T and side codes A/B/N (MBP-1 docs).
  • Side N: indeterminate two-sided BBO updates arrive in one message, so count them as one event, not two (MBP-1 docs).
  • Prices: int64 at 1 unit = 1e-9 currency units, so convert before dividing by tick. Bucket by ts_event, not ts_recv.
  • MBO (L3): adds, cancels, modifies and fills keyed by order ID, which gives queue position and per-order cancel-versus-fill attribution.
  • L2: depth beyond the best quote, needed if you want true depth instead of the AD proxy.
  • UNVERIFIED: whether MBP-1 trade prints carry current BBO fields, per-venue sequence and flags semantics, and how the paper ordered events within a TAQ second. The paper’s TAQ timestamps are nearest-second, so sub-second grids rest on timestamps that are not truly sub-second.

How a pandas OFI implementation silently breaks

Four failure modes cause most wrong OFI numbers: non-strict tie handling, look-ahead in trade-quote joins, collapsing same-second updates, and averaging mids over intervals. Each has a one-line fix, and the code above already applies them. A fifth, dividing integer prices by tick before unit conversion, is covered in the MBP-1 notes above.

  • Strict comparisons drop the tie case; use >= and <=.
  • Backward-only joins: merge_asof with direction="backward" attaches only quotes at or before each trade.
  • Same-second collapse: groupby(second).last() picks one update and destroys event order, which e_n depends on.
  • Mean mids: sample last observations at grid instants; averaging understates ΔP_k.
  • NaN sizes filled with 0 after an outer join create false removals.
  • Halt rows and summary messages (action == "R", or side N treated as two events) produce phantom size deltas.
# Look-ahead-safe trade alignment, using synthetic trades sampled from the book above.
trades = df.sample(500, random_state=1)[["ts_event"]].sort_values("ts_event")
trades["trade_sz"] = 100
quotes = df[["ts_event", "bid_px", "ask_px"]]
aligned = pd.merge_asof(trades, quotes, on="ts_event",
                        direction="backward", allow_exact_matches=True)
# backward: only quotes at or before each trade. A forward join would attach
# a later quote and leak the post-trade mid into the signal.
# Avoid: df.groupby(df.ts_event // 10**9).last() collapses same-second updates.
print("SYNTHETIC DEMO DATA — trade-to-quote alignment, illustrative only")
print(aligned.head())

Practical uses and what the paper does not prove

Three uses follow from the paper: sizing child orders from β ≈ c/AD, decomposing intraday variance into flow-driven and residual parts, and timing around the open, where impact runs five times the close (arXiv:1011.6402). None has been validated out of sample here. Treat each as a hypothesis to test on your own licensed data.

  • Execution sizing: the linear model is calibrated on individual L1 events, not metaorders. Large parent orders follow different impact behaviour, described as a square-root law in Tóth et al., arXiv:1105.1694, which is a separate scaling argument and not a microdata result from this paper.
  • Limits of the result: the sample is 50 stocks in April 2010 on nearest-second TAQ data, with R² computed in-sample and refit every half-hour.
  • Population: the appendix filters remove the widest 5% of spreads and exclude several quote modes and trade conditions, so results are conditional on that cleaned sample (full-text HTML).
  • Not established: tradability, net-of-cost performance, or applicability to other venues, asset classes or eras, including today’s markets.

How to check this yourself

Read the paper rather than trusting this summary. Open the full-text HTML to locate Tables 2 to 4 and the appendix filters, then rerun the same estimation on data you are licensed to use. Your numbers will differ from the paper’s, and that difference is information, not a failure of the method.

  1. Read Section 2.1 and the Table 2 window structure in the full-text HTML.
  2. Apply the appendix filters: 9:30–16:00 timestamps; excluded quote modes (4, 7, 9, 11, 13, 14, 15, 19, 20, 27, 28); excluded trade conditions (O, Z, B, T, L, G, W, J, K); correction indicator ≤ 2; quotes above the stock’s 95th-percentile spread removed; NBBO sizes summed across exchanges.
  3. Run the case-table tests first. If they fail, do not run the regression.
  4. Run the grid and half-hour code on your data, then compare the distributions of β sign, t and R², not single values.
  5. For the robust covariance step, use sm.OLS(y, sm.add_constant(X)).fit(cov_type="HC3"), per the statsmodels OLS docs. The paper says only “White heteroscedasticity-consistent”, so its exact variant is UNVERIFIED.

FAQ

Three questions come up most often. Each answer restates the decisive figure from the paper and names the step that implements it. The short version: quotes beat prints, Level-1 data is sufficient for the formula, and look-ahead is avoided with a backward join.

Why does OFI predict price changes better than trade imbalance?

In the paper’s April 2010 sample, OFI alone explains an average 65% of 10-second mid-price changes, against 32% for trade imbalance (arXiv:1011.6402). OFI counts every best-quote size change, including size added and removed without any trade, while trade imbalance sees only executed volume. The gap persists under trade-time sampling, where OFI reaches 51% at 10 trades against 13% for trade imbalance.

Is Level-1 (MBP-1) data enough, or do I need L2 or L3?

For the paper’s formula, Level-1 is enough, because e_n uses only the best bid and offer, their prices and sizes. Databento’s MBP-1 schema documents that stream, including the side code N for a two-sided update that counts as one event (Databento MBP-1 docs). MBO (L3) is needed only for queue position, hidden size or cancel-versus-fill attribution (Databento MBO docs). Whether an MBP-1 trade print carries BBO fields is UNVERIFIED here.

How do I compute OFI in pandas without look-ahead bias?

Sort by ts_event, compute e_n with weak inequalities so ties are handled, and sum contributions by clock interval. Attach quotes to trades with pd.merge_asof using direction="backward", so only information available at trade time is used. Sample mids by last observation at grid instants rather than interval means, because averaging distorts ΔP_k. The pipeline above implements each step on synthetic data.

Disclosure: all paper numbers are as reported by its authors, in arXiv:1011.6402. This is educational content, not investment advice.

← Back to all posts