Here's a Python function that implements the requested trade performance calculation using FIFO matching:
from collections import defaultdict, deque
def calculate_performance(trades):
"""
Calculate trading performance metrics using FIFO matching.
Args:
trades: List of dicts with format {'asset': str, 'amount': float, 'value': float}
Returns:
Dict containing performance metrics
"""
# Initialize buy queues for each asset
buy_queues = defaultdict(deque)
# Initialize metrics
total_rpnl, total_rpnl_pct, winning_trades, total_trades, buy_trades, sell_trades = (0,) * 6
for trade in trades:
asset = trade['asset']
amount = trade['amount']
value = trade['value']
# Skip invalid trades
if amount == 0 or value == 0:
continue
total_trades += 1
if amount > 0: # Buy trade
buy_trades += 1
price_per_unit = value / amount
buy_queues[asset].append((amount, value, price_per_unit))
else: # Sell trade
sell_trades += 1
remaining_sell_amount = abs(amount)
sell_value = abs(value)
sell_price_per_unit = sell_value / remaining_sell_amount
trade_rpnl = 0
# Try to match against buy queue
while remaining_sell_amount > 0 and buy_queues[asset]:
buy_amount, buy_value, buy_price_per_unit = buy_queues[asset][0]
# Calculate matched amount
matched_amount = min(remaining_sell_amount, buy_amount)
# Calculate realized PnL for matched portion
matched_sell_value = matched_amount * sell_price_per_unit
matched_buy_value = matched_amount * buy_price_per_unit
matched_rpnl = matched_sell_value - matched_buy_value
trade_rpnl += matched_rpnl
# Update total metrics
total_rpnl += matched_rpnl
# Update buy queue
if matched_amount == buy_amount:
buy_queues[asset].popleft()
else:
remaining_buy_amount = buy_amount - matched_amount
remaining_buy_value = remaining_buy_amount * buy_price_per_unit
buy_queues[asset][0] = (remaining_buy_amount, remaining_buy_value, buy_price_per_unit)
remaining_sell_amount -= matched_amount
# Update winning trades count if trade was fully or partially matched
if trade_rpnl != 0:
if trade_rpnl > 0:
winning_trades += 1
# Calculate cost basis for matched portion
matched_amount = abs(amount) - remaining_sell_amount
if matched_amount > 0:
cost_basis = (sell_value * matched_amount) / abs(amount)
if cost_basis != 0: # Prevent division by zero
trade_rpnl_pct = (trade_rpnl / cost_basis) * 100
total_rpnl_pct += trade_rpnl_pct
# Calculate win rate
win_rate = (winning_trades / sell_trades * 100) if sell_trades > 0 else 0
return {
'total_rpnl': round(total_rpnl, 2),
'total_rpnl_pct': round(total_rpnl_pct, 2),
'win_rate': round(win_rate, 2),
'total_trades': total_trades,
'buy_trades': buy_trades,
'sell_trades': sell_trades
}
# Example usage and testing
if __name__ == "__main__":
# Test trades
test_trades = [
{'asset': 'AAPL', 'amount': 100, 'value': 1000}, # Buy 100 @ $10
{'asset': 'AAPL', 'amount': 50, 'value': 600}, # Buy 50 @ $12
{'asset': 'AAPL', 'amount': -75, 'value': -975}, # Sell 75 @ $13
{'asset': 'GOOG', 'amount': 200, 'value': 2000}, # Buy 200 @ $10
{'asset': 'GOOG', 'amount': -100, 'value': -900}, # Sell 100 @ $9
{'asset': 'AAPL', 'amount': -100, 'value': -1400} # Sell 100 @ $14 (only 75 available)
]
results = calculate_performance(test_trades)
print("Performance Metrics:")
for metric, value in results.items():
print(f"{metric}: {value}")
This implementation:
-
Uses defaultdict(deque) for efficient FIFO queue management of buy trades per asset.
-
Processes trades sequentially, handling:
- Buy trades: Adds to the asset's buy queue with amount, value, and price per unit
- Sell trades: Attempts to match against existing buys using FIFO
-
For each sell trade:
- Matches against buy queue entries until the sell amount is fulfilled or buys are exhausted
- Calculates realized PnL for matched portions
- Tracks partial matches by updating queue entries
- Skips unmatched sell amounts
-
Calculates metrics:
total_rpnl: Sum of all realized gains/losses
total_rpnl_pct: Sum of percentage returns based on cost basis
win_rate: Percentage of sell trades with positive PnL
- Trade counts: Total, buy, and sell trades
-
Includes error handling:
- Skips trades with zero amount or value
- Handles division by zero cases
- Rounds results to 2 decimal places
-
Uses tuple unpacking for efficient multiple variable initialization
The example usage demonstrates how the function handles:
- Multiple assets
- Partial matches
- Unmatched sells
- Both profitable and losing trades
Sample output might look like:
Performance Metrics:
total_rpnl: 175.0
total_rpnl_pct: 23.33
win_rate: 50.0
total_trades: 6
buy_trades: 3
sell_trades: 3
The function is efficient with O(n) time complexity where n is the number of trades, as each trade is processed once and deque operations are O(1).