chore(lint): make the repository ruff-clean under the strict select

Clear the deferred full-repo lint backlog so the whole tree passes the strict
ruff select (E,W,F,I,B,UP,C4,SIM). Mechanical fixes dominate: import sorting,
pep585/604 annotations, dropped dead imports, and whitespace. The few semantic
changes are behavior-preserving: declare __all__ on the agent_utils and
alpha_vantage re-export hubs; expand 'from x import *' to explicit names; use
immutable tuple defaults instead of mutable list defaults; contextlib.suppress
for try/except/pass; and narrow an over-broad assertRaises.
This commit is contained in:
Yijia-Xiao committed 2026-06-14 16:38:36 +00:00
1 parent cbc5f67d42
commit e3bc872982
59 files changed
+315 -293

No files matched your search

+2 -2
View File
@@ -1,11 +1,11 @@
# TradingAgents/graph/__init__.py
from .trading_graph import TradingAgentsGraph
from .conditional_logic import ConditionalLogic
from .setup import GraphSetup
from .propagation import Propagator
from .reflection import Reflector
from .setup import GraphSetup
from .signal_processing import SignalProcessor
from .trading_graph import TradingAgentsGraph
__all__ = [
"TradingAgentsGraph",
+11 -11
View File
@@ -1,6 +1,6 @@
from collections.abc import Iterable
from dataclasses import dataclass
from time import monotonic
from typing import Dict, Iterable, List, Optional
@dataclass(frozen=True)
@@ -14,11 +14,11 @@ class AnalystNodeSpec:
@dataclass(frozen=True)
class AnalystExecutionPlan:
specs: List[AnalystNodeSpec]
specs: list[AnalystNodeSpec]
concurrency_limit: int
ANALYST_NODE_SPECS: Dict[str, AnalystNodeSpec] = {
ANALYST_NODE_SPECS: dict[str, AnalystNodeSpec] = {
"market": AnalystNodeSpec(
key="market",
agent_node="Market Analyst",
@@ -61,7 +61,7 @@ def build_analyst_execution_plan(
if concurrency_limit < 1:
raise ValueError("analyst concurrency limit must be >= 1")
specs: List[AnalystNodeSpec] = []
specs: list[AnalystNodeSpec] = []
for analyst_key in selected_analysts:
spec = ANALYST_NODE_SPECS.get(analyst_key)
if spec is None:
@@ -81,10 +81,10 @@ def get_initial_analyst_node(plan: AnalystExecutionPlan) -> str:
class AnalystWallTimeTracker:
def __init__(self, plan: AnalystExecutionPlan):
self.plan = plan
self._started_at: Dict[str, float] = {}
self._wall_times: Dict[str, float] = {}
self._started_at: dict[str, float] = {}
self._wall_times: dict[str, float] = {}
def mark_started(self, analyst_key: str, started_at: Optional[float] = None) -> None:
def mark_started(self, analyst_key: str, started_at: float | None = None) -> None:
if analyst_key not in ANALYST_NODE_SPECS:
raise ValueError(f"unknown analyst key: {analyst_key}")
self._started_at.setdefault(analyst_key, monotonic() if started_at is None else started_at)
@@ -92,7 +92,7 @@ class AnalystWallTimeTracker:
def mark_completed(
self,
analyst_key: str,
completed_at: Optional[float] = None,
completed_at: float | None = None,
) -> None:
if analyst_key not in ANALYST_NODE_SPECS:
raise ValueError(f"unknown analyst key: {analyst_key}")
@@ -104,7 +104,7 @@ class AnalystWallTimeTracker:
finished_at = monotonic() if completed_at is None else completed_at
self._wall_times[analyst_key] = max(0.0, finished_at - started_at)
def get_wall_times(self) -> Dict[str, float]:
def get_wall_times(self) -> dict[str, float]:
return dict(self._wall_times)
def format_summary(self) -> str:
@@ -121,8 +121,8 @@ class AnalystWallTimeTracker:
def sync_analyst_tracker_from_chunk(
tracker: AnalystWallTimeTracker,
chunk: Dict[str, str],
now: Optional[float] = None,
chunk: dict[str, str],
now: float | None = None,
) -> None:
current_time = monotonic() if now is None else now
active_found = False
+1 -1
View File
@@ -7,9 +7,9 @@ from __future__ import annotations
import hashlib
import sqlite3
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
from typing import Generator
from langgraph.checkpoint.sqlite import SqliteSaver
+4 -4
View File
@@ -1,8 +1,8 @@
# TradingAgents/graph/propagation.py
from typing import Dict, Any, List, Optional
from typing import Any
from tradingagents.agents.utils.agent_states import (
AgentState,
InvestDebateState,
RiskDebateState,
)
@@ -22,7 +22,7 @@ class Propagator:
asset_type: str = "stock",
past_context: str = "",
instrument_context: str = "",
) -> Dict[str, Any]:
) -> dict[str, Any]:
"""Create the initial state for the agent graph.
``instrument_context`` is the deterministic ticker-identity string
@@ -68,7 +68,7 @@ class Propagator:
"news_report": "",
}
def get_graph_args(self, callbacks: Optional[List] = None) -> Dict[str, Any]:
def get_graph_args(self, callbacks: list | None = None) -> dict[str, Any]:
"""Get arguments for the graph invocation.
Args:
+19 -4
View File
@@ -1,10 +1,25 @@
# TradingAgents/graph/setup.py
from typing import Any, Dict
from typing import Any
from langgraph.graph import END, START, StateGraph
from langgraph.prebuilt import ToolNode
from tradingagents.agents import *
from tradingagents.agents import (
create_aggressive_debator,
create_bear_researcher,
create_bull_researcher,
create_conservative_debator,
create_fundamentals_analyst,
create_market_analyst,
create_msg_delete,
create_neutral_debator,
create_news_analyst,
create_portfolio_manager,
create_research_manager,
create_sentiment_analyst,
create_trader,
)
from tradingagents.agents.utils.agent_states import AgentState
from .analyst_execution import build_analyst_execution_plan
@@ -18,7 +33,7 @@ class GraphSetup:
self,
quick_thinking_llm: Any,
deep_thinking_llm: Any,
tool_nodes: Dict[str, ToolNode],
tool_nodes: dict[str, ToolNode],
conditional_logic: ConditionalLogic,
analyst_concurrency_limit: int = 1,
):
@@ -30,7 +45,7 @@ class GraphSetup:
self.analyst_concurrency_limit = analyst_concurrency_limit
def setup_graph(
self, selected_analysts=["market", "social", "news", "fundamentals"]
self, selected_analysts=("market", "social", "news", "fundamentals")
):
"""Set up and compile the agent workflow graph.
+28 -37
View File
@@ -1,66 +1,57 @@
# TradingAgents/graph/trading_graph.py
import json
import logging
import os
from pathlib import Path
import json
from datetime import datetime, timedelta
from typing import Dict, Any, Tuple, List, Optional
from pathlib import Path
from typing import Any
import yfinance as yf
logger = logging.getLogger(__name__)
from langgraph.prebuilt import ToolNode
from tradingagents.llm_clients import create_llm_client
from tradingagents.agents import *
from tradingagents.default_config import DEFAULT_CONFIG
from tradingagents.agents.utils.memory import TradingMemoryLog
from tradingagents.dataflows.utils import safe_ticker_component
from tradingagents.agents.utils.agent_states import (
AgentState,
InvestDebateState,
RiskDebateState,
)
from tradingagents.dataflows.config import set_config
# Import the new abstract tool methods from agent_utils
# Import the abstract tool methods from agent_utils
from tradingagents.agents.utils.agent_utils import (
build_instrument_context,
resolve_instrument_identity,
get_stock_data,
get_indicators,
get_verified_market_snapshot,
get_fundamentals,
get_balance_sheet,
get_cashflow,
get_income_statement,
get_news,
get_insider_transactions,
get_fundamentals,
get_global_news,
get_income_statement,
get_indicators,
get_insider_transactions,
get_macro_indicators,
get_prediction_markets
get_news,
get_prediction_markets,
get_stock_data,
get_verified_market_snapshot,
resolve_instrument_identity,
)
from tradingagents.agents.utils.memory import TradingMemoryLog
from tradingagents.dataflows.config import set_config
from tradingagents.dataflows.utils import safe_ticker_component
from tradingagents.default_config import DEFAULT_CONFIG
from tradingagents.llm_clients import create_llm_client
from .checkpointer import checkpoint_step, clear_checkpoint, get_checkpointer, thread_id
from .conditional_logic import ConditionalLogic
from .setup import GraphSetup
from .propagation import Propagator
from .reflection import Reflector
from .setup import GraphSetup
from .signal_processing import SignalProcessor
logger = logging.getLogger(__name__)
class TradingAgentsGraph:
"""Main class that orchestrates the trading agents framework."""
def __init__(
self,
selected_analysts=["market", "social", "news", "fundamentals"],
selected_analysts=("market", "social", "news", "fundamentals"),
debug=False,
config: Dict[str, Any] = None,
callbacks: Optional[List] = None,
config: dict[str, Any] = None,
callbacks: list | None = None,
):
"""Initialize the trading agents graph and components.
@@ -103,7 +94,7 @@ class TradingAgentsGraph:
self.deep_thinking_llm = deep_client.get_llm()
self.quick_thinking_llm = quick_client.get_llm()
self.memory_log = TradingMemoryLog(self.config)
# Create tool nodes
@@ -138,7 +129,7 @@ class TradingAgentsGraph:
self.graph = self.workflow.compile()
self._checkpointer_ctx = None
def _get_provider_kwargs(self) -> Dict[str, Any]:
def _get_provider_kwargs(self) -> dict[str, Any]:
"""Get provider-specific kwargs for LLM client creation."""
kwargs = {}
provider = self.config.get("llm_provider", "").lower()
@@ -167,7 +158,7 @@ class TradingAgentsGraph:
return kwargs
def _create_tool_nodes(self) -> Dict[str, ToolNode]:
def _create_tool_nodes(self) -> dict[str, ToolNode]:
"""Create tool nodes for different data sources using abstract methods."""
return {
"market": ToolNode(
@@ -233,7 +224,7 @@ class TradingAgentsGraph:
def _fetch_returns(
self, ticker: str, trade_date: str, holding_days: int = 5,
benchmark: str = "SPY",
) -> Tuple[Optional[float], Optional[float], Optional[int]]:
) -> tuple[float | None, float | None, int | None]:
"""Fetch raw and alpha return for ticker over holding_days from trade_date.
``benchmark`` is the index used as the alpha baseline (resolved by the