fix: Improve trade performance calculation and add debug logging
This commit is contained in:
parent
47b58faddd
commit
3bc111288e
@ -24,13 +24,25 @@ def calculate_position_performance(trades):
|
|||||||
total_cost += shares * price
|
total_cost += shares * price
|
||||||
elif trade['direction'] == 'sell':
|
elif trade['direction'] == 'sell':
|
||||||
shares = float(trade['shares'])
|
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_sold += shares
|
||||||
total_proceeds += shares * price
|
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
|
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
|
remaining_shares = total_bought - total_sold
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -339,6 +351,12 @@ def trading_journal_page():
|
|||||||
|
|
||||||
# Display trades grouped by position
|
# Display trades grouped by position
|
||||||
for position_id, trades in positions.items():
|
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
|
# 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))
|
trades.sort(key=lambda x: (x['entry_date'], 0 if x.get('direction') == 'buy' else 1))
|
||||||
first_trade = trades[0]
|
first_trade = trades[0]
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user