From bd4dce4f42dd27fd2d82c4c2dfc663d4486a78dc Mon Sep 17 00:00:00 2001 From: "Bobby (aider)" Date: Thu, 13 Feb 2025 12:30:17 -0800 Subject: [PATCH] refactor: Improve timezone handling in calculate_weekly_metrics function --- src/pages/journal/trading_journal_page.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/pages/journal/trading_journal_page.py b/src/pages/journal/trading_journal_page.py index 52539ab..5c79695 100644 --- a/src/pages/journal/trading_journal_page.py +++ b/src/pages/journal/trading_journal_page.py @@ -11,9 +11,13 @@ from trading.journal import ( def calculate_weekly_metrics(trades) -> dict: """Calculate weekly performance metrics""" - now = datetime.now(pytz.timezone('US/Pacific')) - week_start = (now - timedelta(days=now.weekday())).replace(hour=0, minute=0, second=0, microsecond=0) - week_start = pytz.timezone('US/Pacific').localize(week_start) + pacific_tz = pytz.timezone('US/Pacific') + now = datetime.now(pacific_tz) + + # Create week_start without timezone first, then localize it + week_start = (now - timedelta(days=now.weekday())).replace( + hour=0, minute=0, second=0, microsecond=0 + ).astimezone(pacific_tz) weekly_pl = 0 weekly_trades = [] @@ -21,8 +25,12 @@ def calculate_weekly_metrics(trades) -> dict: for trade in trades: # Get the trade date and ensure it's timezone aware trade_date = trade.get('exit_date', trade.get('entry_date')) - if trade_date and not trade_date.tzinfo: - trade_date = pytz.timezone('US/Pacific').localize(trade_date) + if trade_date: + # Convert to Pacific timezone if needed + if trade_date.tzinfo is None: + trade_date = pacific_tz.localize(trade_date) + else: + trade_date = trade_date.astimezone(pacific_tz) # For sells/exits that happened this week if (trade.get('direction') == 'sell' or trade.get('exit_price')) and trade_date and trade_date >= week_start: