Implement volume bars sampling for financial time series. Volume bars sample a new bar every time a fixed volume threshold is reached, providing bars that normalize for trading volume.
def volume_bars(trades: list[dict], volume_threshold: float) -> list[dict]:
"""
trades: list of dicts with keys 'price' and 'volume'
volume_threshold: cumulative volume required to form a bar
"""
bars = []
current_prices = []
current_volume = 0.0
for trade in trades:
current_prices.append(trade["price"])
current_volume += trade["volume"]
if current_volume >= volume_threshold:
bar = {
"open": current_prices[0],
"high": max(current_prices),
"low": min(current_prices),
"close": current_prices[-1],
"volume": current_volume,
"num_ticks": len(current_prices),
}
bars.append(bar)
current_prices = []
current_volume = 0.0
# Handle remaining trades
if current_prices:
bar = {
"open": current_prices[0],
"high": max(current_prices),
"low": min(current_prices),
"close": current_prices[-1],
"volume": current_volume,
"num_ticks": len(current_prices),
}
bars.append(bar)
return bars