Implement tick bars sampling for financial time series. Tick bars sample a new bar (OHLCV summary) every N ticks (trades), providing a time-invariant way to analyze market microstructure data.
import numpy as np
def tick_bars(trades: list[dict], tick_size: int) -> list[dict]:
"""
trades: list of dicts with keys 'price' and 'volume'
tick_size: number of ticks per bar
"""
bars = []
n = len(trades)
for i in range(0, n, tick_size):
chunk = trades[i:i + tick_size]
if len(chunk) == 0:
break
prices = [t["price"] for t in chunk]
volumes = [t["volume"] for t in chunk]
bar = {
"open": prices[0],
"high": max(prices),
"low": min(prices),
"close": prices[-1],
"volume": sum(volumes),
"num_ticks": len(chunk),
}
bars.append(bar)
return barstick_size trades each.