KatInterview

Build Candlestick Bars from a Raw Price Feed

SQL & DataModel answer
MediumModel answerSQL & Datatime-seriesaggregationdata-manipulation

Last updated

Parse a string of price-timestamp ticks, bucket them into fixed-width time windows, compute OHLC stats, and forward-fill any empty windows.

Build Candlestick Bars from a Raw Price Feed

A trading system receives price updates as a flat string of price:timestamp tokens, separated by commas. Your job is to turn that raw feed into a sequence of candlestick (OHLC) bars.

Input format

"3:0,2:1,4:2,10:3,10:8,11:8"

Each token is price:timestamp. The price is a number; the timestamp is a non-negative integer representing seconds from some epoch.

What you need to produce

Group ticks into 10-second windows: [0, 10), [10, 20), [20, 30), … For every window from the first occupied one to the last occupied one, output a record with:

fieldmeaning
bucket_startthe window's left edge (0, 10, 20, …)
openprice of the earliest tick in the window (by timestamp; ties broken by arrival order)
closeprice of the latest tick in the window (same ordering)
lowminimum price in the window
highmaximum price in the window

If a window contains no ticks, forward-fill it: copy every field from the previous window's close. Consecutive empty windows must chain (each copies from the one before it, which may itself have been filled).

Example

Input:  "3:0,2:1,4:2,10:3,10:4,10:5,10:6,10:7,10:8,10:9,10:10,11:8"

Output:
bucket_start=0,  open=3,  close=10, low=2,  high=11
bucket_start=10, open=10, close=10, low=10, high=10

Notice that 11:8 arrives late in the string but belongs to timestamp 8, so it does not become the close of window 0; the tick at timestamp 9 (10:9) is later and wins.

Requirements

Write a Python function with this signature:

def ohlc_bars(data: str, interval: int = 10) -> list[dict]:
    ...
  • Raise ValueError on a non-positive interval or a malformed token.
  • Return [] for empty or whitespace-only input.
  • Handle out-of-order ticks and duplicate timestamps correctly.

Hints

Hint 1

A tick belongs to bucket k = timestamp // interval. Python's floor division works for any integer timestamp, including negatives.

Hint 2

Sort ticks by (timestamp, arrival_index) before aggregating so that 'first' and 'last' reflect event time, not the order tokens appeared in the string.

Hint 3

Walk every bucket id from min to max in a single loop. Keep a prev_close variable; when a bucket has no ticks, set all four fields to prev_close. A chain of empty buckets fills itself automatically because you update prev_close after each iteration.