How do I match each trade with the last quote before it?

Match each trade to the last quote of its own stock with pandas merge_asof, and set the arguments that the matching rules of the literature need: strictly earlier quotes, a fixed delay and a maximum quote age.

After this lesson, you can give each trade the quote of its own stock that a matching rule from the literature selects.

How do I match each trade to the last quote of its stock?

pd.merge_asof(trades, quotes, on="time_ms", by="ticker") gives each trade the last quote of its own stock at or before the trade’s time, one row per trade. The BBB trade at 300 milliseconds receives BBB’s quote from 150, although AAA quoted later, at 250.

The made-up trades and quotes cover AAA and BBB on one market with one clock, with times in milliseconds after the open. A quote gives a stock’s highest bid and lowest ask, and a trade the price paid, in currency units per share. on="time_ms" names the time column of both tables, by="ticker" restricts the search to the same stock, and the default direction="backward" searches earlier times. Both tables must be sorted by time across all stocks, or the match raises a ValueError. The match keeps only the trade’s time, so quote_ms copies the quote’s time first.

The following box builds both tables and matches the trades.

import pandas as pd

quotes = pd.DataFrame({
    "time_ms": [100, 150, 250, 600, 900],
    "ticker": ["AAA", "BBB", "AAA", "BBB", "AAA"],
    "bid": [50.10, 125.40, 50.11, 125.42, 50.13],
    "ask": [50.12, 125.44, 50.13, 125.46, 50.15],
})
quotes["quote_ms"] = quotes["time_ms"]
trades = pd.DataFrame({
    "time_ms": [80, 250, 300, 400, 2000],
    "ticker": ["AAA", "AAA", "BBB", "AAA", "BBB"],
    "price": [50.12, 50.13, 125.44, 50.11, 125.43],
})
print(pd.merge_asof(trades, quotes, on="time_ms", by="ticker"))
   time_ms ticker   price     bid     ask  quote_ms
0       80    AAA   50.12     NaN     NaN       NaN
1      250    AAA   50.13   50.11   50.13     250.0
2      300    BBB  125.44  125.40  125.44     150.0
3      400    AAA   50.11   50.11   50.13     250.0
4     2000    BBB  125.43  125.42  125.46     600.0

The AAA trade at 80 milliseconds gets no quote, because no AAA quote comes before it, and the AAA trade at 250 gets the quote stamped at its own time.

Which quote does each matching rule select?

The matching rules of the literature differ in which quote they compare with a trade, and each rule is a choice of merge_asof arguments. A quote at the trade’s own time may come after the trade, and allow_exact_matches=False skips it. Lee and Ready (1991) found that trades were often recorded after the quote changes they caused and suggested the quote 5 seconds before the trade for 1988 data, which adding the delay to a copy of the quote times does. tolerance drops quotes older than a maximum age.

With exact matches skipped, the AAA trade at 250 milliseconds gets the quote from 100. With a delay of 200 milliseconds, chosen for this example, the AAA trade at 400 also gets the quote from 100. With a maximum age of 1,000 milliseconds, the BBB trade at 2,000 loses its quote from 600, which is 1,400 milliseconds old.

quotes.assign(time_ms=...) returns a copy with the moved times, while quote_ms keeps the original ones. The later lesson on matching trades to quotes uses direction="nearest" on changes in the order book.

The following box applies the three rules and prints each rule’s matched quote time side by side.

strictly_before = pd.merge_asof(trades, quotes, on="time_ms", by="ticker", allow_exact_matches=False)
delayed = pd.merge_asof(trades, quotes.assign(time_ms=quotes["time_ms"] + 200), on="time_ms", by="ticker")
max_age = pd.merge_asof(trades, quotes, on="time_ms", by="ticker", allow_exact_matches=False, tolerance=1000)
print(pd.DataFrame({
    "time_ms": trades["time_ms"],
    "ticker": trades["ticker"],
    "strictly_before": strictly_before["quote_ms"],
    "delay_200": delayed["quote_ms"],
    "max_age_1000": max_age["quote_ms"],
}))
   time_ms ticker  strictly_before  delay_200  max_age_1000
0       80    AAA              NaN        NaN           NaN
1      250    AAA            100.0        NaN         100.0
2      300    BBB            150.0        NaN         150.0
3      400    AAA            250.0      100.0         250.0
4     2000    BBB            600.0      600.0           NaN

The delay also leaves the AAA trade at 250 milliseconds and the BBB trade at 300 without a quote, because no quote of their stock is at least 200 milliseconds older.

Your turn

Print each trade’s ticker and the age in milliseconds of the latest strictly earlier quote of its stock. You should see a missing age for the first AAA trade and 1,400 for the last BBB trade.

The age is the trade’s time minus the quote’s time.

strictly_before["age_ms"] = strictly_before["time_ms"] - strictly_before["quote_ms"]
print(strictly_before[["ticker", "age_ms"]].to_string(index=False))
ticker  age_ms
   AAA     NaN
   AAA   150.0
   BBB   150.0
   AAA   150.0
   BBB  1400.0