5 min read
Aggregating market time series: as-of joins, bars and forward fill
Trades and quotes never share timestamps, so combining them is a question of alignment. As-of joins instead of interpolation, OHLCV bars on half-open buckets, forward fill with a staleness limit, and the numeric pitfalls of doing it in TypeScript.
Combining two market time series looks like a merge and is a modelling decision. Trades and quotes arrive at irregular times and almost never share a timestamp. Two instruments tick at different rates. One venue's session overlaps another's by three hours. Every method of putting such series on a common footing answers the question "what was the value of B at the time of A?", and several of the obvious answers are wrong in ways that do not raise errors.
Do not interpolate prices
The generic recipe for misaligned series is to build a uniform grid and interpolate linearly between neighbouring points. For market data that has two defects.
It invents prices. If an instrument trades at 100 and then at 102 a minute later, the value 101 at the half-minute mark never existed and could not have been traded.
It uses the future. The interpolated value at time t depends on the next observation after t. Any signal, backtest or chart built on it contains information that was not available at t, which is look-ahead bias. A backtest contaminated this way looks excellent and fails live.
The correct default for prices is the last known value at or before t. Interpolation remains legitimate for curve construction and for quantities that really do vary smoothly; it is not a way to align ticks.
The as-of join
"For each row in A, the latest row in B at or before A's timestamp" is an as-of join, the workhorse of tick analytics (aj in kdb+, merge_asof in pandas, ASOF JOIN in several SQL engines). With both inputs sorted by time it is a single merge pass:
type Trade = { ts: number; px: number; qty: number }; // ts in ms, px in ticks
type Quote = { ts: number; bid: number; ask: number };
/** For each trade, the last quote at or before it. Both inputs sorted by ts. O(n + m). */
function asofJoin(trades: Trade[], quotes: Quote[], maxAgeMs: number) {
const out: { trade: Trade; quote: Quote | null }[] = [];
let q = -1;
for (const trade of trades) {
while (q + 1 < quotes.length && quotes[q + 1].ts <= trade.ts) q++;
const quote =
q >= 0 && trade.ts - quotes[q].ts <= maxAgeMs ? quotes[q] : null;
out.push({ trade, quote });
}
return out;
}Five trades against three quotes, with a staleness limit of 1500 ms:
trade ts px prevailing quote
1000 10010 mid 10010 (quote @900)
1400 10012 mid 10011 (quote @1400)
1999 10009 mid 10011 (quote @1400)
2000 10011 mid 10011 (quote @1400)
4200 10015 no fresh quoteThree decisions are hidden in that small function.
<= or <. With <=, a quote carrying the same timestamp as the trade is treated as known at the trade. When the two come from different feeds at millisecond resolution, the order of two events within the same millisecond is unknown, and the quote may be the reaction to the trade. Transaction-cost analysis that wants the quote prevailing before the trade should use strict <, or a small lag. The choice moves measured spreads and slippage.
The staleness limit. The last trade above has a quote from 2.1 seconds earlier. Carrying it forward indefinitely would report a mid for a market that may have been halted, closed or simply disconnected. A missing value is more useful than a confident stale one.
Which clock. Exchange timestamps say when the event happened; receive timestamps say when you knew. Research on market behaviour wants the first. Anything simulating your own decisions needs the second, because you could not have acted on data before it arrived.
The figure applies all three choices to one small tape. Switching from <= to < moves the trade at 2.4 s, which shares its timestamp with a quote, onto the earlier quote. Tightening the staleness limit rejects the trades in the long gap after 3 s. Linear interpolation gives every trade a plausible-looking value, each of which is computed from a quote that arrives later.
This interactive figure needs JavaScript.
Bars
Fixed-interval OHLCV bars are the commonest aggregation and most of the bugs are at bucket edges.
type Bar = {
start: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
notional: number;
};
/** OHLCV bars over half-open buckets [start, start + width). Input sorted by ts. */
function bars(trades: Trade[], width: number): Bar[] {
const out: Bar[] = [];
let bar: Bar | undefined;
for (const { ts, px, qty } of trades) {
const start = Math.floor(ts / width) * width;
if (!bar || bar.start !== start) {
bar = {
start,
open: px,
high: px,
low: px,
close: px,
volume: 0,
notional: 0,
};
out.push(bar);
}
if (px > bar.high) bar.high = px;
if (px < bar.low) bar.low = px;
bar.close = px;
bar.volume += qty;
bar.notional += px * qty;
}
return out;
}The same five trades in one-second bars:
start open high low close volume vwap
1000 10010 10012 10009 10009 8 10010.38
2000 10011 10011 10011 10011 4 10011.00
4000 10015 10015 10015 10015 3 10015.00- Buckets are half-open. The trade at 1999 closes the first bar and the trade at 2000 opens the second. With closed intervals a trade on the boundary lands in two bars or in neither, and volumes stop adding up to the tape.
- There is no bar at 3000. Nothing traded. Whether to emit an empty bar is a choice for the consumer: a chart may want a flat bar at the previous close with zero volume, while a volatility estimate must not treat it as a zero-return observation.
- VWAP is
notional / volume, so bars store notional, not VWAP. Sums combine: one-minute bars roll up to five-minute bars by adding volume and notional, taking the first open, last close, maximum high and minimum low. An average of averages does not. - Alignment is to the session, not to the epoch, for anything longer than an hour. A daily bar is an exchange trading day in the exchange's time zone, with its daylight-saving changes and half days.
Math.floor(ts / 86_400_000)produces UTC days, which is rarely what anyone means.
Not every trade print belongs in a bar. Auction prints, off-book and late-reported trades, and cancelled or corrected trades carry condition codes, and which of them update last price, high and low, and volume differs by venue. Filtering on those codes is part of the aggregation.
Forward fill, with a limit
Putting several instruments on a common grid, for a correlation or a spread, means sampling each one's last value at every grid point: an as-of join against a clock. The same staleness rule applies. Forward filling across a halt, a venue outage or the hours when one market is closed produces a perfectly flat series, which shows up downstream as understated volatility and spurious correlation. Sample only where both markets are open, and carry an age or a validity flag with every filled value.
TypeScript specifics
Timestamps. A number is a double with 53 bits of integer precision. Milliseconds and microseconds since the epoch fit. Nanoseconds do not: the current epoch time in nanoseconds is around 1.8 × 10¹⁸, well past Number.MAX_SAFE_INTEGER (about 9 × 10¹⁵), and silently loses its low digits. Keep nanosecond timestamps as bigint or BigInt64Array, or as a pair of numbers. Never sort on parsed ISO strings in a hot loop.
Prices. 0.1 + 0.2 evaluates to 0.30000000000000004. Convert prices to integer ticks at the edge, as in the examples above, and aggregate integers. Running sums of floating-point notional drift over a day of trades, and comparisons for high and low become unreliable at the last digit.
Streaming. Both functions above are batch code over sorted arrays. Live data arrives late and out of order, so a streaming aggregator must define when a bar is final. The usual scheme is a watermark: a bar closes when event time has passed its end by an allowed lateness, and later arrivals either amend a published bar or are counted and dropped. Decide which, and publish the bar's state (forming, final, amended) with it.
Layout. For anything beyond a few thousand points, parallel typed arrays (ts, px, qty) are faster to scan than arrays of objects and create no garbage, which matters when the aggregation feeds a chart at frame rate.
Summary
Align with as-of semantics, not interpolation. Bound how stale a carried value may be. Use half-open buckets aligned to the session, and store sums so bars compose. Keep prices in integer ticks and nanoseconds out of doubles. Each of these is a place where the simple version runs without error and gives a subtly wrong answer.