In pandas, how does merge_asof match each trade to the latest quote for the same ticker, and what must be true of the inputs?
answer
- nearest key, not equal key
- both sides sorted on the key
- exact match on by first
- backward is the default direction
- a tolerance caps how stale
basics
~20 spd.merge_asof(trades, quotes, on='time', by='ticker') keeps every trade and attaches the last quote at or before its time for the same ticker. Both frames must be sorted by the on key, which must be numeric or datetime with no nulls.
solid answer
~40 s`pd.merge_asof` is a left join on the **nearest** key instead of an equal one: for each left row it picks one right row. With the default `direction="backward"` that is the last right row whose `on` value is less than or equal to the left value; `"forward"` takes the first one at or after it and `"nearest"` the closest either way. `by="ticker"` first restricts candidates to the same ticker by exact match. Both frames must be sorted ascending by the `on` column, otherwise pandas raises `ValueError: left keys must be sorted`; the key must be numeric or datetime-like, null-free and of the same dtype on both sides. `tolerance=pd.Timedelta("100ms")` leaves the right columns missing when the nearest quote is older than that, and `allow_exact_matches=False` excludes quotes stamped at exactly the trade time.
code
python · 24 linesimport pandas as pd
trades = pd.DataFrame({
"time": pd.to_datetime(["2026-03-02 09:30:00.010", "2026-03-02 09:30:00.050",
"2026-03-02 09:30:00.300"]),
"ticker": ["ABC", "XYZ", "ABC"],
"qty": [100, 50, 200],
})
quotes = pd.DataFrame({
"time": pd.to_datetime(["2026-03-02 09:30:00.000", "2026-03-02 09:30:00.020",
"2026-03-02 09:30:00.040", "2026-03-02 09:30:00.250"]),
"ticker": ["ABC", "XYZ", "ABC", "XYZ"],
"bid": [10.00, 20.00, 10.05, 20.10],
})
matched = pd.merge_asof(
trades.sort_values("time"),
quotes.sort_values("time"),
on="time",
by="ticker",
direction="backward",
tolerance=pd.Timedelta("100ms"),
)
print(matched) # bids 10.00, 20.00, then NaN: the last ABC quote is 260 ms oldgo deeper
Recall that merge_asof matches the nearest earlier key per left row and needs both frames sorted on that key.
Explain backward, forward and nearest, the role of by, and how tolerance and allow_exact_matches change which right row qualifies.
Diagnose the failure modes: unsorted or null keys, mismatched datetime units, missing by, and look-ahead leaks from nearest in time-ordered analysis.
Decide where as-of joins belong in a pipeline and how unmatched-row counts are monitored, since stale or missing feeds degrade them silently.
## The problem an equality join cannot solve Trades and quotes are stamped by different systems, so a trade at `09:30:00.050` almost never has a quote at exactly the same instant. What the analysis needs is the **prevailing quote**: the most recent one at or before the trade, for the same instrument. An equality `merge` on time would match nothing. `pd.merge_asof` exists for this "as of" lookup. ## How the match is chosen `merge_asof` behaves like a **left join on the nearest key**: every left row appears exactly once in the result, in its original order, with the columns of at most one right row attached. | `direction` | Picks, for each left row | Typical use | |---|---|---| | `"backward"` (default) | the last right row with `on` value <= the left value | the latest quote, the price in force | | `"forward"` | the first right row with `on` value >= the left value | the next event after a signal | | `"nearest"` | the right row closest in absolute distance | aligning two sensors' readings | Further arguments refine the choice: - `by="ticker"` (or `left_by` / `right_by`) requires an **exact** match on those columns before the nearest-key search, so an `ABC` trade never picks up an `XYZ` quote. The frames do not need to be sorted by the `by` columns. - `tolerance` sets the largest allowed distance. It must suit the key's dtype: a `Timedelta` (or `datetime.timedelta`) for datetime keys, an integer for integer keys, a number for float keys. When the nearest candidate is farther away, the right-hand columns are missing for that row. - `allow_exact_matches=True` (default) lets a quote at exactly the trade time match; `False` makes the comparison strict, which matters when a quote stamped at the trade time may have been caused by that trade. - `suffixes` works as in `merge` for clashing column names. ## What the inputs must satisfy pandas checks these before matching, and each failure has its own message: 1. **Sorted keys.** Both frames must be sorted ascending by the `on` column; otherwise `ValueError: left keys must be sorted` (or `right`). Sort with `sort_values("time")` first. The docstring wording for `left_on`/`right_on` can read as if pandas sorts for you; the implementation raises instead. 2. **No nulls in the key.** A missing timestamp raises `ValueError: Merge keys contain null values on left side` (or right). Drop or repair those rows first. 3. **A numeric or datetime-like key.** A string or object `on` column raises `MergeError` saying both sides must have a numeric dtype; parse timestamps with `pd.to_datetime` before merging. 4. **Identical key dtypes.** Unlike `merge`, `merge_asof` requires the key dtypes to match exactly, so a `datetime64[us]` column on one side and `datetime64[ns]` on the other raises `MergeError: incompatible merge keys`. Align them with `.dt.as_unit(...)`. The `by` columns are checked the same way. 5. **A single `on` key.** `merge_asof` matches on one ordered key; extra equality conditions go into `by`. ## Reading the result - Row count equals the left frame's, always: `merge_asof` never multiplies rows, even if several quotes share a timestamp, and never drops trades. - Trades with no eligible quote, because none came earlier or the nearest is beyond `tolerance`, keep missing values in the quote columns, so integer right-hand columns come back as `float64`. - Count those rows after every run: a sudden jump in unmatched trades usually means a feed gap or a time-zone mismatch between the two sources. ## Pitfalls interviewers probe - Sorting by `ticker, time` instead of by `time` alone: the `on` column is then not globally ascending and pandas raises. - Forgetting `by`, which silently matches each trade to the latest quote of **any** instrument. - Using `direction="nearest"` for prices, which can attach a quote from the future and leak information into a backtest. - Using `merge` followed by a forward fill: it needs an outer join and a fill per group, and it is easy to fill across instruments.
- Why can merge_asof raise MergeError for two datetime columns that print identically?`merge_asof` requires the `on` (and `by`) key dtypes to be identical, and a datetime column carries its resolution in the dtype. If one side is `datetime64[us]` and the other `datetime64[ns]`, it raises `incompatible merge keys ... must be the same type`. Convert one side with `.dt.as_unit("ns")` (or the other unit) before merging.
- When would you set allow_exact_matches=False?When a right row stamped at exactly the left time might be a consequence of the left event, for example a quote update triggered by the trade itself. With `False`, `backward` takes the last quote strictly before the trade, giving the market state the trader actually saw.
- Does merge_asof ever return more rows than the left frame?No. It attaches at most one right row to each left row, so the result has exactly the left frame's row count, in left order. Unmatched left rows remain with missing right-hand values.
- Believes merge_asof sorts both frames itself before matching.
- Uses the default direction and expects it to look forward in time.
- Omits by='ticker' and assumes quotes are matched per instrument anyway.
- Thinks tolerance drops trades that have no recent quote.
- Expects merge_asof to return every quote that falls inside the tolerance.