Python
docs: drop comments that narrate the next line
Yijia-Xiao825e6321aeca
diff --git a/cli/display.py b/cli/display.pyindex c6173c061..cba992cc9 100644--- a/cli/display.py+++ b/cli/display.py@@ -20,8 +20,6 @@ from tradingagents.graph.analyst_execution import (AnalystExecutionPlan,)-# Create a deque to store recent messages with a maximum length-console = Console()@@ -72,20 +70,16 @@ class MessageBuffer:"""self.selected_analysts = [a.lower() for a in selected_analysts]- # Build agent_status dynamicallyself.agent_status = {}- # Add selected analystsfor analyst_key in self.selected_analysts:if analyst_key in self.ANALYST_MAPPING:self.agent_status[self.ANALYST_MAPPING[analyst_key]] = "pending"- # Add fixed teamsfor team_agents in self.FIXED_AGENTS.values():for agent in team_agents:self.agent_status[agent] = "pending"- # Build report_sections dynamicallyself.report_sections = {}for section, (analyst_key, _) in self.REPORT_SECTIONS.items():if analyst_key is None or analyst_key in self.selected_analysts:@@ -140,14 +134,12 @@ class MessageBuffer:latest_section = Nonelatest_content = None- # Find the most recently updated sectionfor section, content in self.report_sections.items():if content is not None:latest_section = sectionlatest_content = contentif latest_section and latest_content:- # Format the current section for displaysection_titles = {"market_report": "Market Analysis","sentiment_report": "Social Sentiment",@@ -229,7 +221,6 @@ def update_display(layout, spinner_text=None, stats_handler=None, start_time=Non"Portfolio Management": ["Portfolio Manager"],}- # Filter teams to only include agents that are in agent_statusteams = {}for team, agents in all_teams.items():active_agents = [a for a in agents if a in message_buffer.agent_status]@@ -237,7 +228,6 @@ def update_display(layout, spinner_text=None, stats_handler=None, start_time=Nonteams[team] = active_agentsfor team, agents in teams.items():- # Add first agent with team namefirst_agent = agents[0]status = message_buffer.agent_status.get(first_agent, "pending")if status == "in_progress":@@ -254,7 +244,6 @@ def update_display(layout, spinner_text=None, stats_handler=None, start_time=Nonstatus_cell = f"[{status_color}]{status}[/{status_color}]"progress_table.add_row(team, first_agent, status_cell)- # Add remaining agents in teamfor agent in agents[1:]:status = message_buffer.agent_status.get(agent, "pending")if status == "in_progress":@@ -271,7 +260,6 @@ def update_display(layout, spinner_text=None, stats_handler=None, start_time=Nonstatus_cell = f"[{status_color}]{status}[/{status_color}]"progress_table.add_row("", agent, status_cell)- # Add horizontal line after each teamprogress_table.add_row("─" * 20, "─" * 20, "─" * 20, style="dim")layout["progress"].update(@@ -297,12 +285,10 @@ def update_display(layout, spinner_text=None, stats_handler=None, start_time=Non# Combine tool calls and messagesall_messages = []- # Add tool callsfor timestamp, tool_name, args in message_buffer.tool_calls:formatted_args = format_tool_args(args)all_messages.append((timestamp, "Tool", f"{tool_name}: {formatted_args}"))- # Add regular messagesfor timestamp, msg_type, content in message_buffer.messages:content_str = str(content) if content else ""if len(content_str) > 200:@@ -312,15 +298,11 @@ def update_display(layout, spinner_text=None, stats_handler=None, start_time=Non# Sort by timestamp descending (newest first)all_messages.sort(key=lambda x: x[0], reverse=True)- # Calculate how many messages we can show based on available spacemax_messages = 12- # Get the first N messages (newest ones)recent_messages = all_messages[:max_messages]- # Add messages to table (already in newest-first order)for timestamp, msg_type, content in recent_messages:- # Format content with word wrappingwrapped_content = Text(content, overflow="fold")messages_table.add_row(timestamp, msg_type, wrapped_content)@@ -364,7 +346,6 @@ def update_display(layout, spinner_text=None, stats_handler=None, start_time=Nonreports_completed = message_buffer.get_completed_reports_count()reports_total = len(message_buffer.report_sections)- # Build stats partsstats_parts = [f"Agents: {agents_completed}/{agents_total}"]# LLM and tool stats from callback handlerdiff --git a/cli/prompts.py b/cli/prompts.pyindex be481de5b..3eacb3cad 100644--- a/cli/prompts.py+++ b/cli/prompts.py@@ -140,7 +140,6 @@ def select_analysts(asset_type: AssetType = AssetType.STOCK, default=None) -> lidef select_research_depth(default=None) -> int:"""Select research depth using an interactive selection."""- # Define research depth options with their corresponding valuesDEPTH_OPTIONS = [("Shallow - Quick research, few debate and strategy discussion rounds", 1),("Medium - Middle ground, moderate debate rounds and strategy discussion", 3),diff --git a/cli/run.py b/cli/run.pyindex 3018d125e..08896cf2e 100644--- a/cli/run.py+++ b/cli/run.py@@ -99,7 +99,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):config = _build_run_config(selections, checkpoint)- # Create stats callback handler for tracking LLM/tool callsstats_handler = StatsCallbackHandler()# Normalize analyst selection to predefined order (selection is a 'set', order is fixed)@@ -108,7 +107,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):analyst_execution_plan = build_analyst_execution_plan(selected_analyst_keys)analyst_wall_time_tracker = AnalystWallTimeTracker(analyst_execution_plan)- # Initialize the graph with callbacks bound to LLMsgraph = TradingAgentsGraph(selected_analyst_keys,config=config,@@ -116,13 +114,11 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):callbacks=[stats_handler],)- # Initialize message buffer with selected analystsmessage_buffer.init_for_analysis(selected_analyst_keys)# Track start time for elapsed displaystart_time = time.time()- # Create result directoryresults_dir = _run_directory(config, selections["ticker"], selections["analysis_date"])results_dir.mkdir(parents=True, exist_ok=True)report_dir = results_dir / "reports"@@ -173,7 +169,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):message_buffer.add_tool_call = save_tool_call_decorator(message_buffer, "add_tool_call")message_buffer.update_report_section = save_report_section_decorator(message_buffer, "update_report_section")- # Now start the display layoutlayout = create_layout()# The alternate screen keeps a layout taller than the window from redrawing@@ -182,7 +177,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):# Initial displayupdate_display(layout, stats_handler=stats_handler, start_time=start_time)- # Add initial messagesmessage_buffer.add_message("System", f"Selected ticker: {selections['ticker']}")if selections["asset_type"] != "stock":message_buffer.add_message("System", f"Detected asset type: {selections['asset_type']}")@@ -195,13 +189,11 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):)update_display(layout, stats_handler=stats_handler, start_time=start_time)- # Update agent status to in_progress for the first analystfirst_analyst = analyst_execution_plan.specs[0].agent_nodemessage_buffer.update_agent_status(first_analyst, "in_progress")analyst_wall_time_tracker.mark_started(selected_analyst_keys[0])update_display(layout, stats_handler=stats_handler, start_time=start_time)- # Create spinner textspinner_text = (f"Analyzing {selections['ticker']} on {selections['analysis_date']}...")@@ -232,7 +224,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):trace = []try:for chunk in graph.graph.stream(graph.checkpoint_input(init_agent_state), **args):- # Process all messages in chunk, deduplicating by message IDfor message in chunk.get("messages", []):msg_id = getattr(message, "id", None)if msg_id is not None:@@ -251,7 +242,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):else:message_buffer.add_tool_call(tool_call.name, tool_call.args)- # Update analyst statuses based on report state (runs on every chunk)update_analyst_statuses(message_buffer,chunk,@@ -328,7 +318,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):message_buffer.update_agent_status("Neutral Analyst", "completed")message_buffer.update_agent_status("Portfolio Manager", "completed")- # Update the displayupdate_display(layout, stats_handler=stats_handler, start_time=start_time)trace.append(chunk)@@ -350,7 +339,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):# Always restore the plain uncheckpointed graph, even on failure.graph.end_checkpoint()- # Update all agent statuses to completedfor agent in message_buffer.agent_status:message_buffer.update_agent_status(agent, "completed")@@ -359,7 +347,6 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):)message_buffer.add_message("System", analyst_wall_time_tracker.format_summary())- # Update final report sectionsfor section in message_buffer.report_sections:if section in final_state:message_buffer.update_report_section(section, final_state[section])diff --git a/cli/selections.py b/cli/selections.pyindex ec263ac56..df7640481 100644--- a/cli/selections.py+++ b/cli/selections.py@@ -45,11 +45,9 @@ def get_user_selections():def _prompt_selections(prefs):"""Walk the selection steps. ``prefs`` prefills, the environment skips."""- # Display ASCII art welcome messagewith open(Path(__file__).parent / "static" / "welcome.txt", encoding="utf-8") as f:welcome_ascii = f.read()- # Create welcome box contentwelcome_content = f"{welcome_ascii}\n"welcome_content += "[bold green]TradingAgents: Multi-Agents LLM Financial Trading Framework - CLI[/bold green]\n\n"welcome_content += "[bold]Workflow Steps:[/bold]\n"@@ -58,7 +56,6 @@ def _prompt_selections(prefs):"[dim]Built by [Tauric Research](https://github.com/TauricResearch)[/dim]")- # Create and center the welcome boxwelcome_box = Panel(welcome_content,border_style="green",@@ -74,7 +71,6 @@ def _prompt_selections(prefs):announcements = fetch_announcements()display_announcements(console, announcements)- # Create a boxed questionnaire for each stepdef create_question_box(title, prompt, default=None):box_content = f"[bold]{title}[/bold]\n"box_content += f"[dim]{prompt}[/dim]"diff --git a/tradingagents/dataflows/config.py b/tradingagents/dataflows/config.pyindex 27d6785c6..19a640a43 100644--- a/tradingagents/dataflows/config.py+++ b/tradingagents/dataflows/config.py@@ -61,5 +61,4 @@ def get_config() -> dict:return deepcopy(_config)-# Initialize with default configinitialize_config()diff --git a/tradingagents/dataflows/vendors/alpha_vantage/indicator.py b/tradingagents/dataflows/vendors/alpha_vantage/indicator.pyindex a40a1594b..20ab45e9b 100644--- a/tradingagents/dataflows/vendors/alpha_vantage/indicator.py+++ b/tradingagents/dataflows/vendors/alpha_vantage/indicator.py@@ -83,7 +83,6 @@ def get_indicator(series_type = required_series_typetry:- # Get indicator data for the periodif indicator == "close_50_sma":data = _make_api_request("SMA", {"symbol": symbol,@@ -146,12 +145,10 @@ def get_indicator(symbol, symbol, f"Alpha Vantage does not serve the {indicator} indicator")- # Parse CSV data and extract values for the date rangelines = data.strip().split('\n')if len(lines) < 2:return f"Error: No data returned for {indicator}"- # Parse header and dataheader = [col.strip() for col in lines[0].split(',')]try:date_col_idx = header.index('time')@@ -185,10 +182,8 @@ def get_indicator(if len(values) > value_col_idx:try:date_str = values[date_col_idx].strip()- # Parse the datedate_dt = datetime.strptime(date_str, "%Y-%m-%d")- # Check if date is in our rangeif before <= date_dt <= curr_date_dt:value = values[value_col_idx].strip()result_data.append((date_dt, value))diff --git a/tradingagents/dataflows/vendors/alpha_vantage/stock.py b/tradingagents/dataflows/vendors/alpha_vantage/stock.pyindex b42923e58..2a0671671 100644--- a/tradingagents/dataflows/vendors/alpha_vantage/stock.py+++ b/tradingagents/dataflows/vendors/alpha_vantage/stock.py@@ -23,7 +23,6 @@ def get_stock(Returns:CSV string containing the daily adjusted time series data filtered to the date range."""- # Parse dates to determine the rangestart_dt = datetime.strptime(start_date, "%Y-%m-%d")today = datetime.now()diff --git a/tradingagents/dataflows/vendors/yahoo/market.py b/tradingagents/dataflows/vendors/yahoo/market.pyindex 31a0784da..900b1dbbe 100644--- a/tradingagents/dataflows/vendors/yahoo/market.py+++ b/tradingagents/dataflows/vendors/yahoo/market.py@@ -180,7 +180,6 @@ def get_stock_stats_indicators_window(date_values.append((date_str, indicator_value))current_dt = current_dt - relativedelta(days=1)- # Build the result stringind_string = ""for date_str, value in date_values:ind_string += f"{date_str}: {value}\n"@@ -225,16 +224,13 @@ def _get_stock_stats_bulk(df = wrap(data)df["Date"] = df["Date"].dt.strftime("%Y-%m-%d")- # Calculate the indicator for all rows at oncedf[indicator] # This triggers stockstats to calculate the indicator- # Create a dictionary mapping date strings to indicator valuesresult_dict = {}for _, row in df.iterrows():date_str = row["Date"]indicator_value = row[indicator]- # Handle NaN/None valuesif pd.isna(indicator_value):result_dict[date_str] = "N/A"else:@@ -274,7 +270,6 @@ def get_stockstats_indicator(-def get_closes(symbol: str, start_date: str, end_date: str) -> pd.Series:"""Daily closes from ``start_date`` up to, not including, ``end_date``."""canonical = normalize_symbol(symbol)diff --git a/tradingagents/dataflows/vendors/yahoo/news.py b/tradingagents/dataflows/vendors/yahoo/news.pyindex b97a77ab0..9f0498b9a 100644--- a/tradingagents/dataflows/vendors/yahoo/news.py+++ b/tradingagents/dataflows/vendors/yahoo/news.py@@ -15,7 +15,6 @@ from tradingagents.dataflows.vendors.yahoo.ohlcv import yf_retrydef _extract_article_data(article: dict) -> dict:"""Extract article data from yfinance news format (handles nested 'content' structure)."""- # Handle nested content structureif "content" in article:content = article["content"]title = content.get("title", "No title")@@ -23,11 +22,9 @@ def _extract_article_data(article: dict) -> dict:provider = content.get("provider", {})publisher = provider.get("displayName", "Unknown")- # Get URL from canonicalUrl or clickThroughUrlurl_obj = content.get("canonicalUrl") or content.get("clickThroughUrl") or {}link = url_obj.get("url", "")- # Get publish datepub_date_str = content.get("pubDate", "")pub_date = Noneif pub_date_str:@@ -87,7 +84,6 @@ def get_news_yfinance(stock = yf.Ticker(canonical)news = yf_retry(lambda: stock.get_news(count=article_limit)) or []- # Parse date range for filteringstart_dt = datetime.strptime(start_date, "%Y-%m-%d")end_dt = datetime.strptime(end_date, "%Y-%m-%d")diff --git a/tradingagents/decision_log.py b/tradingagents/decision_log.pyindex d7a7a9a1a..ca5afb47f 100644--- a/tradingagents/decision_log.py+++ b/tradingagents/decision_log.py@@ -154,7 +154,6 @@ class TradingMemoryLog:and tag_line.startswith(pending_prefix)and tag_line.endswith("| pending]")):- # Parse rating from the existing pending tagfields = [f.strip() for f in tag_line[1:-1].split("|")]rating = fields[2]new_tag = self._resolved_tag(@@ -189,7 +188,6 @@ class TradingMemoryLog:text = self._log_path.read_text(encoding="utf-8")blocks = text.split(self._SEPARATOR)- # Build lookup keyed by (trade_date, ticker) for O(1) dispatchupdate_map = {(u["trade_date"], u["ticker"]): u for u in updates}new_blocks = []diff --git a/tradingagents/graph/__init__.py b/tradingagents/graph/__init__.pyindex ac66fceda..54f3037fc 100644--- a/tradingagents/graph/__init__.py+++ b/tradingagents/graph/__init__.py@@ -1,5 +1,3 @@-# TradingAgents/graph/__init__.py-from .conditional_logic import ConditionalLogicfrom .propagation import Propagatorfrom .reflection import Reflectordiff --git a/tradingagents/graph/conditional_logic.py b/tradingagents/graph/conditional_logic.pyindex ba8543769..9d41160a0 100644--- a/tradingagents/graph/conditional_logic.py+++ b/tradingagents/graph/conditional_logic.py@@ -1,5 +1,3 @@-# TradingAgents/graph/conditional_logic.py-from tradingagents.agents.state import AgentStatediff --git a/tradingagents/graph/propagation.py b/tradingagents/graph/propagation.pyindex 50e387d35..775ddc3ae 100644--- a/tradingagents/graph/propagation.py+++ b/tradingagents/graph/propagation.py@@ -1,5 +1,3 @@-# TradingAgents/graph/propagation.py-from typing import Anyfrom tradingagents.agents.state import InvestDebateState, RiskDebateStatediff --git a/tradingagents/graph/reflection.py b/tradingagents/graph/reflection.pyindex 094da1b51..198333ffe 100644--- a/tradingagents/graph/reflection.py+++ b/tradingagents/graph/reflection.py@@ -1,5 +1,3 @@-# TradingAgents/graph/reflection.py-from typing import Anydiff --git a/tradingagents/graph/setup.py b/tradingagents/graph/setup.pyindex 7277cb26f..df4577fa0 100644--- a/tradingagents/graph/setup.py+++ b/tradingagents/graph/setup.py@@ -1,5 +1,3 @@-# TradingAgents/graph/setup.py-from typing import Anyfrom langgraph.graph import END, START, StateGraph@@ -84,29 +82,24 @@ class GraphSetup:"fundamentals": lambda: create_fundamentals_analyst(self.quick_thinking_llm),}- # Create researcher and manager nodesbull_researcher_node = create_bull_researcher(self.quick_thinking_llm)bear_researcher_node = create_bear_researcher(self.quick_thinking_llm)research_manager_node = create_research_manager(self.deep_thinking_llm)trader_node = create_trader(self.quick_thinking_llm)- # Create risk analysis nodesaggressive_analyst = create_aggressive_debator(self.quick_thinking_llm)neutral_analyst = create_neutral_debator(self.quick_thinking_llm)conservative_analyst = create_conservative_debator(self.quick_thinking_llm)portfolio_manager_node = create_portfolio_manager(self.deep_thinking_llm)- # Create workflowworkflow = StateGraph(AgentState)- # Add analyst nodes to the graphfor spec in plan.specs:workflow.add_node(spec.agent_node, analyst_factories[spec.key]())workflow.add_node(spec.clear_node, create_msg_delete())if spec.tools:workflow.add_node(spec.tool_node, ToolNode(list(spec.tools)))- # Add other nodesworkflow.add_node("Bull Researcher", bull_researcher_node)workflow.add_node("Bear Researcher", bear_researcher_node)workflow.add_node("Research Manager", research_manager_node)@@ -116,11 +109,8 @@ class GraphSetup:workflow.add_node("Conservative Analyst", conservative_analyst)workflow.add_node("Portfolio Manager", portfolio_manager_node)- # Define edges- # Start with the first analystworkflow.add_edge(START, plan.specs[0].agent_node)- # Connect analysts in sequencefor i, spec in enumerate(plan.specs):if spec.tools:workflow.add_conditional_edges(diff --git a/tradingagents/graph/trading_graph.py b/tradingagents/graph/trading_graph.pyindex 9ba2bc496..8169decc4 100644--- a/tradingagents/graph/trading_graph.py+++ b/tradingagents/graph/trading_graph.py@@ -1,5 +1,3 @@-# TradingAgents/graph/trading_graph.py-import jsonimport loggingimport os@@ -64,17 +62,13 @@ class TradingAgentsGraph:self.config = config or DEFAULT_CONFIGself.callbacks = callbacks or []- # Update the interface's configset_config(self.config)- # Create necessary directoriesos.makedirs(self.config["data_cache_dir"], exist_ok=True)os.makedirs(self.config["results_dir"], exist_ok=True)- # Initialize LLMs with provider-specific thinking configurationllm_kwargs = build_llm_kwargs(self.config)- # Add callbacks to kwargs if provided (passed to LLM constructor)if self.callbacks:llm_kwargs["callbacks"] = self.callbacks@@ -96,7 +90,6 @@ class TradingAgentsGraph:self.memory_log = TradingMemoryLog(self.config)- # Initialize componentsself.conditional_logic = ConditionalLogic(max_debate_rounds=self.config["max_debate_rounds"],max_risk_discuss_rounds=self.config["max_risk_discuss_rounds"],