How do I find the last quote strictly before each trade with NumPy?

Use np.searchsorted on sorted quote times to find, for every trade at once, the last quote strictly before it, without letting a missing match pick a future quote.

After this lesson, you can match each trade to the last quote strictly before it, for a million trades at once, and leave trades without an earlier quote empty.

How does an insertion position give the last earlier quote?

np.searchsorted(quote_ms, trade_ms, side="left") returns, for each trade, the position where its time would go among the sorted quote times, which is the number of quotes strictly before it, so subtracting 1 gives the index of the last earlier quote. The trade at 400 milliseconds would go at position 2, after the quotes at 100 and 250, so its last earlier quote is index 1.

The made-up stock XYZ has three quotes and four trades, with times in milliseconds after the open and quote midpoints, the mean of the bid and the ask, in dollars per share. The quote times must be sorted, with the midpoints in the same order. np.searchsorted finds each position by binary search, halving the range at each step, so it handles all trades in one call.

The following box finds each trade’s last earlier quote.

import numpy as np
import pandas as pd

quote_ms = np.array([100, 250, 900])
quote_mid = np.array([50.11, 50.12, 50.14])
trade_ms = np.array([80, 250, 400, 2000])
last_quote = np.searchsorted(quote_ms, trade_ms, side="left") - 1
print(pd.DataFrame({"trade_ms": trade_ms, "last_quote": last_quote}))
   trade_ms  last_quote
0        80          -1
1       250           0
2       400           1
3      2000           2

How do I keep an unmatched trade empty?

np.where(last_quote >= 0, quote_mid[last_quote], np.nan) takes the midpoint only for trades with an earlier quote and leaves the others missing. The trade at 80 milliseconds comes before every quote and gets the index −1, and quote_mid[-1] would give it 50.14, the quote at 900 milliseconds, from the future.

Python reads a negative index from the end of the array, so −1 raises no error. A real search runs within one stock and one session, so another stock’s quotes or yesterday’s close cannot enter the match.

The following box compares the direct lookup with the masked one.

matched_mid = np.where(last_quote >= 0, quote_mid[last_quote], np.nan)
print(pd.DataFrame({"trade_ms": trade_ms, "direct": quote_mid[last_quote], "matched_mid": matched_mid}))
   trade_ms  direct  matched_mid
0        80   50.14          NaN
1       250   50.11        50.11
2       400   50.12        50.12
3      2000   50.14        50.14

What happens when a quote and a trade share a time?

side="left" leaves a quote at the trade’s own time out, and side="right" counts it as earlier, so the trade at 250 milliseconds gets the quote at 100 with "left" and the quote at 250 with "right". pd.merge_asof with allow_exact_matches=False gives the same midpoints as the masked "left" search.

A timestamp alone cannot tell whether the quote at 250 came before the trade at 250, so the strict rule leaves it out, as in the lesson on merge_asof. When several quotes share the last eligible time, the search takes the last of them in the array’s order.

The following box compares the two sides and checks the result against merge_asof.

at_or_before = np.searchsorted(quote_ms, trade_ms, side="right") - 1
check = pd.merge_asof(pd.DataFrame({"time_ms": trade_ms}), pd.DataFrame({"time_ms": quote_ms, "mid": quote_mid}), on="time_ms", allow_exact_matches=False)
print(pd.DataFrame({"trade_ms": trade_ms, "left": last_quote, "right": at_or_before}))
print(np.array_equal(check["mid"].to_numpy(), matched_mid, equal_nan=True))
   trade_ms  left  right
0        80    -1     -1
1       250     0      1
2       400     1      1
3      2000     2      2
True

How fast is the search for a million trades?

Binary search needs about 21 halvings to place a trade among two million quotes, because \(2^{21} = 2{,}097{,}152\), so one call matches a million trades with about 21 comparisons each. In a simulated session of 6.5 hours with two million quotes and one million trades, only the first trade has no earlier quote.

rng.integers(0, session_ms, size) draws times from 0 to 23,399,999 milliseconds with equal chances, and np.sort orders them. Real activity clusters near the open and the close, and two feeds with different clocks need the lesson on matching trades to quotes.

The following box simulates the session and counts the trades without an earlier quote.

rng = np.random.default_rng(7)
session_ms = int(6.5 * 60 * 60 * 1000)
quote_times = np.sort(rng.integers(0, session_ms, 2_000_000))
trade_times = np.sort(rng.integers(0, session_ms, 1_000_000))
last_quotes = np.searchsorted(quote_times, trade_times, side="left") - 1
print(len(trade_times), last_quotes[0], (last_quotes < 0).sum())
1000000 -1 1

Your turn

For the four XYZ trades, print the age in milliseconds of each trade’s last earlier quote and keep its midpoint only when the quote is at most 1,000 milliseconds old. You should see midpoints on rows 1 and 2 only.

A trade without an earlier quote gets a missing age, and a missing age fails the test.

age_ms = np.where(last_quote >= 0, trade_ms - quote_ms[last_quote], np.nan)
print(pd.DataFrame({"age_ms": age_ms, "kept_mid": np.where(age_ms <= 1000, matched_mid, np.nan)}))
   age_ms  kept_mid
0     NaN       NaN
1   150.0     50.11
2   150.0     50.12
3  1100.0       NaN