fix: address code review feedback

- Preserve and restore self.ticker and self.curr_state in
  propagate_portfolio() using try/finally to prevent side effects
- Use pathlib.Path for log file construction in _log_portfolio()
- Move traceback import to module level

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Robin Lindbladh 2026-03-24 20:20:46 +01:00
parent dbd2c658e5
commit 85fbc48ede
2 changed files with 14 additions and 12 deletions

View File

@ -1,6 +1,7 @@
# TradingAgents/graph/portfolio_analysis.py
import json
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Tuple
@ -88,7 +89,6 @@ class PortfolioAnalyzer:
"final_trade_decision": final_state["final_trade_decision"],
}
except Exception as e:
import traceback
if debug:
print(f"Error analyzing {ticker}: {e}")
individual_results[ticker] = {
@ -177,9 +177,6 @@ class PortfolioAnalyzer:
"portfolio_summary": portfolio_summary,
}
with open(
f"eval_results/portfolio/portfolio_analysis_{trade_date}.json",
"w",
encoding="utf-8",
) as f:
log_file = directory / f"portfolio_analysis_{trade_date}.json"
with log_file.open("w", encoding="utf-8") as f:
json.dump(log_data, f, indent=4)

View File

@ -278,13 +278,18 @@ class TradingAgentsGraph:
Delegates to PortfolioAnalyzer.analyze see that class for full details.
Note: Each call to propagate() overwrites self.ticker and self.curr_state,
so after this method returns, both reflect only the last ticker analyzed.
Calling reflect_and_remember() afterward will only apply to that last ticker.
This method preserves the instance's ticker and curr_state attributes,
restoring them after the portfolio analysis is complete.
"""
return self.portfolio_analyzer.analyze(
tickers, trade_date, self.propagate, debug=self.debug
)
original_ticker = self.ticker
original_curr_state = self.curr_state
try:
return self.portfolio_analyzer.analyze(
tickers, trade_date, self.propagate, debug=self.debug
)
finally:
self.ticker = original_ticker
self.curr_state = original_curr_state
def reflect_and_remember(self, returns_losses):
"""Reflect on decisions and update memory based on returns."""