Fix the running VWAP for a trade feed
Your task
Your trading desk needs a rolling intraday VWAP (volume weighted average price) for every symbol in an interleaved trade feed. Asked for VWAP, an AI first returned one number for the whole table, then one number per symbol. You need a running value on every trade that starts over each trading day.
An assistant wrote rolling_vwap(symbols, days, prices, volumes). It is in the editor. It has a bug. Find it and fix it.
Input and output:
symbols,days,prices,volumes: one trade per position, already in time order: the symbol, the trading day, the price and the volume.- Return one VWAP per trade, as a float, in input order.
Rules the tests check:
- If the lists differ in length, use only the positions all four have.
- Group trades by symbol and trading day together. Symbols and days compare exactly, case included. A group continues where it left off when other trades come between its trades.
- A trade's VWAP is the sum of price times volume over its group's trades so far, this one included, divided by the sum of their volumes.
- When that volume sum is 0, the VWAP is 0.
- Answers within 0.000001 of the expected value pass.
Examples
rolling_vwap(symbols: list[str], days: list[str], prices: list[float], volumes: list[int]) -> list[float]Example 1
Input
rolling_vwap(["AAPL", "AAPL", "MSFT", "AAPL"], ["2024-03-01", "2024-03-01", "2024-03-01", "2024-03-02"], [10, 20, 5, 30], [100, 100, 50, 10])Output
[10, 15, 5, 30]Example 2
Input
rolling_vwap(["A", "A"], ["2024-01-01", "2024-01-01"], [10, 12], [100, 300])Output
[10, 11.5]Example 3
Input
rolling_vwap(["A", "A"], ["2024-01-01", "2024-01-02"], [10, 20], [100, 100])Output
[10, 20]