Premium problem137. Attach the Last Known Price to Each Trade

Hard Locked

trades has columns stock, trade_time (datetime) and quantity. quotes has columns stock, quote_time (datetime) and price.

For every trade, attach the price of the most recent quote for the same stock at or before the trade time. A trade with no earlier quote gets NaN.

Return a DataFrame with columns stock, trade_time, quantity and price, sorted by trade_time then stock, with the index renumbered from 0.

This is an as-of join rather than an equality join, and pandas has a dedicated function for it that requires both sides sorted by the time key.

Input

trades =
  stock          trade_time  quantity
0   AAA 2022-01-01 10:05:00        10
1   BBB 2022-01-01 10:05:00        20
2   AAA 2022-01-01 09:00:00        30
quotes =
  stock          quote_time  price
0   AAA 2022-01-01 10:00:00  101.0
1   AAA 2022-01-01 10:04:00  102.0
2   BBB 2022-01-01 09:30:00   55.0

Output

  stock          trade_time  quantity  price
0   AAA 2022-01-01 09:00:00        30    NaN
1   AAA 2022-01-01 10:05:00        10  102.0
2   BBB 2022-01-01 10:05:00        20   55.0

Premium problem

This one's part of Premium. Unlock the full Pandas track plus every other premium problem on the site.

Implement solve(...)