How do I match trades to quotes when the two feeds disagree on time?

Find the prevailing quote of each trade with merge_asof, find the quote update each trade left in the order book, match trades to these footprints by price and volume, and compare the effective spreads of the two methods.

After this lesson, you can match each trade to the quote update it caused and measure how much the match changes its effective spread.

Which quote does the last-quote rule give each trade?

The last-quote rule of Lee and Ready (1991) gives each trade the last quote before its timestamp, which pd.merge_asof finds, as in the lesson on merge_asof. When the two feeds stamp time differently, that quote can be stale. T2 at 102 ms gets the quote from 94 ms, with a midpoint of 100.10 pence, although it traded against the book of the update at 104 ms, with a bid of 100.00 and an ask of 100.04 pence.

\[ M = \frac{B + A}{2} \]

Here \(B\) is the best bid, \(A\) the best ask and \(M\) the midpoint, in pence.

The example has made-up quotes and trades of one stock, with times in milliseconds after 09:05:43 on 12 May 2025, prices in pence and volumes in shares. The quote feed holds the best bid and ask and the shares displayed at each, the depths. In the events behind the data, T1, T2 and T3 are buys whose quote updates come at 94, 106 and 120 ms, T4 is a buy against hidden liquidity with no displayed update, and T5 is a sell whose update comes at 134 ms. The update at 108 ms is a cancellation of 40 shares.

direction="backward" searches earlier quotes, and allow_exact_matches=False skips a quote with the trade’s own timestamp. .round(2) removes floating-point noise from the midpoints.

The following box builds both feeds and finds each trade’s prevailing midpoint.

import numpy as np
import pandas as pd

quotes = pd.DataFrame({
    "quote_ms": [90, 94, 104, 106, 108, 120, 130, 134],
    "bid": [100.08, 100.08, 100.00, 100.00, 100.00, 100.00, 100.02, 100.02],
    "ask": [100.12, 100.12, 100.04, 100.04, 100.04, 100.08, 100.08, 100.08],
    "bid_depth": [120, 120, 90, 90, 90, 90, 110, 85],
    "ask_depth": [100, 80, 100, 70, 30, 80, 80, 80],
})
quotes["mid"] = ((quotes["bid"] + quotes["ask"]) / 2).round(2)

trades = pd.DataFrame({
    "trade": ["T1", "T2", "T3", "T4", "T5"],
    "trade_ms": [92, 102, 122, 125, 134],
    "price": [100.12, 100.04, 100.04, 100.04, 100.02],
    "volume": [20, 30, 30, 15, 25],
})

prevailing = pd.merge_asof(trades, quotes[["quote_ms", "mid"]].rename(columns={"mid": "mid_prev"}), left_on="trade_ms", right_on="quote_ms", direction="backward", allow_exact_matches=False)
print(prevailing)
  trade  trade_ms   price  volume  quote_ms  mid_prev
0    T1        92  100.12      20        90    100.10
1    T2       102  100.04      30        94    100.10
2    T3       122  100.04      30       120    100.04
3    T4       125  100.04      15       120    100.04
4    T5       134  100.02      25       130    100.05

T2 trades at 100.04 pence, below its stale midpoint of 100.10, so the quote test, the sign of price minus midpoint, would call this buy a sell.

How do I find the footprint of a trade?

A trade removes shares at the best price, so the next quote update shows a lower depth there, the trade’s footprint, as in Jurkatis (2022). At 106 ms, the ask depth at 100.04 pence falls from 100 to 70 shares, the price and volume of T2.

Change in the best price Shares removed
None The fall in depth
Ask rises or bid falls The whole previous depth
Ask falls or bid rises None

.diff() gives the change in the best price and .shift() the previous depth, as in the lesson on shifting rows. np.select() returns, on each row, the choice of the first condition that is True, or default=0, and .clip(lower=0) turns a rise in depth into zero. Each footprint takes its price and midpoint from the quote before it, because the quote after it already reflects the trade, and d_fp is 1 for the ask side, a buy, and −1 for the bid side. pd.concat stacks the two sides, and the rows without removed shares are dropped.

The following box builds the table of footprints.

ask_move = quotes["ask"].diff()
bid_move = quotes["bid"].diff()
ask_removed = np.select([ask_move.gt(0), ask_move.eq(0)], [quotes["ask_depth"].shift(), (quotes["ask_depth"].shift() - quotes["ask_depth"]).clip(lower=0)], default=0).astype(int)
bid_removed = np.select([bid_move.lt(0), bid_move.eq(0)], [quotes["bid_depth"].shift(), (quotes["bid_depth"].shift() - quotes["bid_depth"]).clip(lower=0)], default=0).astype(int)

footprints = pd.concat([
    pd.DataFrame({"footprint_ms": quotes["quote_ms"], "price": quotes["ask"].shift(), "volume": ask_removed, "d_fp": 1, "mid_fp": quotes["mid"].shift()}),
    pd.DataFrame({"footprint_ms": quotes["quote_ms"], "price": quotes["bid"].shift(), "volume": bid_removed, "d_fp": -1, "mid_fp": quotes["mid"].shift()}),
])
footprints = footprints[footprints["volume"] > 0].sort_values("footprint_ms", ignore_index=True)
print(footprints)
   footprint_ms   price  volume  d_fp  mid_fp
0            94  100.12      20     1  100.10
1           104  100.08     120    -1  100.10
2           106  100.04      30     1  100.02
3           108  100.04      40     1  100.02
4           120  100.04      30     1  100.02
5           134  100.02      25    -1  100.05

The cancellation at 108 ms leaves the same kind of trace as a trade, so each row is only a candidate footprint.

How do I match each trade to its footprint?

pd.merge_asof with direction="nearest" and by=["price", "volume"] gives each trade the closest footprint with its own price and volume, before or after the trade. T2 gets the footprint at 106 ms, 4 ms after its timestamp, so the quote feed stamped it 4 ms later than the trade feed.

\[ L_i = t_i^F - t_i^T \]

Here \(t_i^F\) is the time of trade \(i\)’s footprint and \(t_i^T\) its trade time, in milliseconds, so \(L_i\) is the relative latency of the two feeds for that trade.

by=["price", "volume"] allows only footprints with the trade’s price and volume, so the cancellation of 40 shares cannot match T2, and tolerance=1000 limits the gap to 1,000 ms. Prices are compared for exact equality, so real data are safer in integer price units.

The following box matches the trades to their footprints and computes the latency.

pair = pd.merge_asof(prevailing, footprints, left_on="trade_ms", right_on="footprint_ms", by=["price", "volume"], direction="nearest", tolerance=1000)
pair["latency_ms"] = pair["footprint_ms"] - pair["trade_ms"]
print(pair[["trade", "trade_ms", "footprint_ms", "latency_ms", "mid_prev", "mid_fp", "d_fp"]])
  trade  trade_ms  footprint_ms  latency_ms  mid_prev  mid_fp  d_fp
0    T1        92          94.0         2.0    100.10  100.10   1.0
1    T2       102         106.0         4.0    100.10  100.02   1.0
2    T3       122         120.0        -2.0    100.04  100.02   1.0
3    T4       125           NaN         NaN    100.04     NaN   NaN
4    T5       134         134.0         0.0    100.05  100.05  -1.0

T4 traded against hidden liquidity, so it has no footprint. With several stocks, by also needs the stock, and the matches stay within one trading day.

How much does the match change the effective spread?

The effective spread is twice the signed distance between the trade price and the benchmark midpoint. Averaged over the four trades with both measures, it is 0.055 pence with the prevailing quote and 0.045 pence with the footprint, because the stale quote overstates T2’s spread and understates T3’s.

\[ ES_i = 2\,d_i\,(P_i - M_i) \]

Here \(d_i\) is 1 for a buy and −1 for a sell, \(P_i\) the trade price and \(M_i\) the midpoint.

For the prevailing quote, the direction is the sign of price minus midpoint, and a trade at the midpoint takes the sign of the last price change, the tick test. np.sign() gives 1, −1 or 0, .replace(0, np.nan).ffill() carries the last nonzero price change forward, and .mask() replaces the zero directions with the tick directions. .dropna() keeps the trades with both spreads.

The following box computes both spreads and their averages.

tick_direction = np.sign(pair["price"].diff()).replace(0, np.nan).ffill()
quote_direction = np.sign(pair["price"] - pair["mid_prev"])
pair["d_prev"] = quote_direction.mask(quote_direction.eq(0), tick_direction)
pair["es_prev"] = 2 * pair["d_prev"] * (pair["price"] - pair["mid_prev"])
pair["es_fp"] = 2 * pair["d_fp"] * (pair["price"] - pair["mid_fp"])
print(pair[["trade", "d_prev", "d_fp", "es_prev", "es_fp"]].round(4))
print(pair[["es_prev", "es_fp"]].dropna().mean().round(4))
  trade  d_prev  d_fp  es_prev  es_fp
0    T1     1.0   1.0     0.04   0.04
1    T2    -1.0   1.0     0.12   0.04
2    T3    -1.0   1.0    -0.00   0.04
3    T4    -1.0   NaN    -0.00    NaN
4    T5    -1.0  -1.0     0.06   0.06
es_prev    0.055
es_fp      0.045
dtype: float64

The prevailing quote calls T2 and T3 sells, and their footprints show they were buys. A printed -0.0 is a zero with the sign of a negative direction.

Your turn

Print the trades whose footprint comes after their trade timestamp. You should see T1 and T2, with latencies of 2 and 4 ms.

pair["latency_ms"] > 0 keeps the positive latencies, and a missing latency fails the test.

print(pair.loc[pair["latency_ms"] > 0, ["trade", "trade_ms", "footprint_ms", "latency_ms"]])
  trade  trade_ms  footprint_ms  latency_ms
0    T1        92          94.0         2.0
1    T2       102         106.0         4.0