From 3bc111288ed084ab31bba6fdb16b3a12af5b2481 Mon Sep 17 00:00:00 2001 From: "Bobby (aider)" Date: Thu, 13 Feb 2025 09:00:17 -0800 Subject: [PATCH] fix: Improve trade performance calculation and add debug logging --- src/pages/journal/trading_journal_page.py | 24 ++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/pages/journal/trading_journal_page.py b/src/pages/journal/trading_journal_page.py index 95e8cbd..657a2bd 100644 --- a/src/pages/journal/trading_journal_page.py +++ b/src/pages/journal/trading_journal_page.py @@ -24,13 +24,25 @@ def calculate_position_performance(trades): total_cost += shares * price elif trade['direction'] == 'sell': shares = float(trade['shares']) - price = float(trade['entry_price']) # For sells, entry_price is the exit price + # For sells, use exit_price if available, otherwise use entry_price + price = float(trade['exit_price']) if trade.get('exit_price') else float(trade['entry_price']) total_sold += shares total_proceeds += shares * price - avg_entry = total_cost / total_bought if total_bought > 0 else 0 + # Avoid division by zero + if total_bought == 0: + return { + 'total_bought': 0, + 'total_sold': 0, + 'avg_entry': 0, + 'avg_exit': 0, + 'realized_pl': 0, + 'remaining_shares': 0 + } + + avg_entry = total_cost / total_bought avg_exit = total_proceeds / total_sold if total_sold > 0 else 0 - realized_pl = total_proceeds - (total_sold / total_bought * total_cost) if total_bought > 0 else 0 + realized_pl = total_proceeds - (total_sold / total_bought * total_cost) if total_sold > 0 else 0 remaining_shares = total_bought - total_sold return { @@ -339,6 +351,12 @@ def trading_journal_page(): # Display trades grouped by position for position_id, trades in positions.items(): + # Debug logging + st.write(f"Processing position {position_id}") + st.write(f"Number of trades: {len(trades)}") + for trade in trades: + st.write(f"Trade: {trade['direction']} {trade['shares']} shares at {trade['entry_price']}") + # Sort trades by entry_date and put sells after buys trades.sort(key=lambda x: (x['entry_date'], 0 if x.get('direction') == 'buy' else 1)) first_trade = trades[0]