Price each API call with the rate in effect at that time using merge_asof

HardpandasPro

Why it matters 'As of' joins are how billing, feature stores and backtests avoid using information from the future.

Model prices change over time. Each call must be billed at the price that was in effect when the call happened, which means the latest price change at or before the call, for the same model. A normal merge cannot do 'latest before'; merge_asof can.

Write price_calls(calls, prices). calls has columns ts ('YYYY-MM-DD HH:MM' string), model (str), tokens (int). prices has columns effective_ts (same format), model and usd_per_1k (float). Both are in arbitrary order.

Return a DataFrame with columns exactly [ts, model, tokens, cost], one row per call, sorted by ts ascending (ties keep input order), plain 0..n-1 index, ts kept as the original string. cost = tokens / 1000 * usd_per_1k using the price of the same model with the largest effective_ts <= ts (a price that starts exactly at ts applies). If the model has no price yet at that time, cost is NaN.

Signaturedef price_calls(calls, prices)

Example

prices for 'm': 1.0 from 2026-01-01 00:00 and 2.0 from 2026-01-10 00:00; calls of 1000 tokens at 2026-01-05 12:00 and 2026-01-10 00:00 cost [1.0, 2.0].

Understand the idea

An as-of join matches each row to the most recent row of another table at or before its time, instead of an exact key match. Think of looking up the price list that was on the wall when you bought something.

Worked example: price 1.0 from Jan 1 and 2.0 from Jan 10. A call on Jan 5 sees only the Jan 1 price, so 1000 tokens cost 1000 / 1000 * 1.0 = 1.0. A call exactly at Jan 10 00:00 sees the new price (at or before counts), so it costs 2.0. A call before Jan 1 has no price and gets NaN.

Rule: price(call) = price row with the largest effective_ts <= call ts and the same model. In pandas: pd.merge_asof(left, right, on=time, by=key, direction='backward'), both sides sorted by time.

Feature stores and backtests use as-of joins to avoid leaking future data into training.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleprice_calls(_c(_c1), _p(_p1)).to_dict('list')
  • Sample 2: two models, price cut just after a callprice_calls(_c(_c2), _p(_p2)).to_dict('list')