unrealized_gains
Calculate unrealized profit or loss for current stock holdings by comparing average buy prices against live market prices.
Instructions
Calculate unrealized gains for current holdings.
This tool calculates unrealized profit or loss by comparing the average buy price for currently held shares against the current market price fetched live using yfinance.
Returns: A dictionary mapping each stock symbol to its unrealized gain or loss in dollars.
Example: unrealized_gains() -> {"AAPL": 125.50, "GOOG": -22.15}
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Output Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Implementation Reference
- trader_tools.py:104-143 (handler)The `unrealized_gains` MCP tool handler calculates the unrealized profit or loss for current stock holdings by comparing the average cost basis against the live market price.
@mcp.tool() def unrealized_gains() -> dict[str, float]: """Calculate unrealized gains for current holdings. This tool calculates unrealized profit or loss by comparing the average buy price for currently held shares against the current market price fetched live using yfinance. Returns: A dictionary mapping each stock symbol to its unrealized gain or loss in dollars. Example: unrealized_gains() -> {"AAPL": 125.50, "GOOG": -22.15} """ holdings = defaultdict(list) for _, row in df.iterrows(): if row['type'] == 'Buy': holdings[row['symbol']].append((row['shares'], row['price_per_share'])) else: to_sell = row['shares'] while to_sell > 0 and holdings[row['symbol']]: qty, price = holdings[row['symbol']][0] matched = min(qty, to_sell) if matched == qty: holdings[row['symbol']].pop(0) else: holdings[row['symbol']][0] = (qty - matched, price) to_sell -= matched results = {} for symbol, buys in holdings.items(): total_cost = sum(q * p for q, p in buys) total_shares = sum(q for q, _ in buys) if total_shares == 0: continue avg_price = total_cost / total_shares current = get_live_price(symbol) results[symbol] = round((current - avg_price) * total_shares, 2) return results