Implement a function that generates dollar bars from trade data. Dollar bars are an alternative sampling method used in financial machine learning where a new bar (candlestick) is created whenever a specified dollar amount has been traded, rather than at fixed time intervals.
Given a list of trades where each trade is represented as a tuple (price, volume), and a dollar threshold, your function should:
- Calculate the dollar value of each trade as
price * volume - Accumulate dollar values until the threshold is reached or exceeded
- When the threshold is reached, create a bar containing:
- open: The price of the first trade in the bar
- high: The highest price in the bar
- low: The lowest price in the bar
- close: The price of the last trade in the bar
- volume: Total volume traded in the bar
- dollar_value: Total dollar value traded in the bar
- Reset the accumulator and continue with the remaining trades
Return a list of tuples, where each tuple represents a bar in the format (open, high, low, close, volume, dollar_value). All values should be rounded to 4 decimal places.
Note: Trades that do not accumulate enough dollar value to meet the threshold are not included in any bar.
Examples
Example 1:
Input:
trades = [(100.0, 10), (101.0, 15), (99.0, 20), (102.0, 5)], dollar_threshold = 2000.0Output:
[(100.0, 101.0, 100.0, 101.0, 25, 2515.0), (99.0, 102.0, 99.0, 102.0, 25, 2490.0)]Explanation: Processing trades sequentially:
1. Trade 1: price=100.0, volume=10 -> dollar=1000.0, accumulated=1000.0 (below threshold)
2. Trade 2: price=101.0, volume=15 -> dollar=1515.0, accumulated=2515.0 (>= 2000, create bar)
- Bar 1: open=100.0, high=101.0, low=100.0, close=101.0, volume=25, dollar=2515.0
- Reset accumulator
3. Trade 3: price=99.0, volume=20 -> dollar=1980.0, accumulated=1980.0 (below threshold)
4. Trade 4: price=102.0, volume=5 -> dollar=510.0, accumulated=2490.0 (>= 2000, create bar)
- Bar 2: open=99.0, high=102.0, low=99.0, close=102.0, volume=25, dollar=2490.0
Result: Two bars capturing the market activity based on dollar volume traded.
Starter Code
def dollar_bars(trades: list, dollar_threshold: float) -> list:
"""
Generate dollar bars from trade data.
Args:
trades: List of tuples (price, volume) representing individual trades
dollar_threshold: Dollar amount threshold for creating a new bar
Returns:
List of dollar bars as tuples (open, high, low, close, volume, dollar_value)
"""
# Your code here
passPython3
ReadyLines: 1Characters: 0
Ready