realized_gains
Calculate total realized gains using FIFO method by matching sell transactions with earliest buys in trade history.
Instructions
Calculate total realized gains using FIFO method.
This tool goes through the trade history and tracks all buy transactions in a FIFO queue. For each sell, it matches shares with the earliest buys and calculates the realized profit or loss accordingly.
Returns: A float representing the total realized gain or loss (in dollars), rounded to two decimal places.
Example: realized_gains() -> 352.75
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Output Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- trader_tools.py:70-102 (handler)The 'realized_gains' tool function, registered with @mcp.tool(), implements the FIFO calculation for realized gains based on trade history.
def realized_gains() -> float: """Calculate total realized gains using FIFO method. This tool goes through the trade history and tracks all buy transactions in a FIFO queue. For each sell, it matches shares with the earliest buys and calculates the realized profit or loss accordingly. Returns: A float representing the total realized gain or loss (in dollars), rounded to two decimal places. Example: realized_gains() -> 352.75 """ buy_queues = defaultdict(deque) gains = 0.0 for _, row in df.iterrows(): symbol = row['symbol'] shares = row['shares'] price = row['price_per_share'] if row['type'] == 'Buy': buy_queues[symbol].append((shares, price)) else: while shares > 0 and buy_queues[symbol]: buy_shares, buy_price = buy_queues[symbol][0] matched = min(shares, buy_shares) gains += matched * (price - buy_price) shares -= matched if matched == buy_shares: buy_queues[symbol].popleft() else: buy_queues[symbol][0] = (buy_shares - matched, buy_price) return round(gains, 2)