Skip to content

Trading graph

TradingAgentsGraph

Bases: BaseModel


              flowchart TD
              src.tradingagents.graph.trading_graph.TradingAgentsGraph[TradingAgentsGraph]

              

              click src.tradingagents.graph.trading_graph.TradingAgentsGraph href "" "src.tradingagents.graph.trading_graph.TradingAgentsGraph"
            

Main class that orchestrates the trading agents framework.

Methods:

Name Description
propagate

Run the trading agents graph for a company on a specific date.

reflect_and_remember

Reflect on decisions and update memory based on returns.

process_signal

Process a signal to extract the core decision.

selected_analysts

selected_analysts: list[str] = Field(
    default=["market", "social", "news", "fundamentals"],
    title="Selected Analysts",
    description="List of analyst types to include in the trading graph",
)

debug

debug: bool = Field(
    default=False,
    title="Debug Mode",
    description="Enable debug mode with step-by-step tracing output",
)

config

config: TradingAgentsConfig = Field(
    ..., title="Configuration", description="Trading agents configuration settings"
)

callbacks

callbacks: list = Field(
    default_factory=list,
    title="Callbacks",
    description="Optional callback handlers for tracking LLM/tool statistics",
)

curr_state

curr_state: AgentState | None = Field(
    default=None,
    title="Current State",
    description="Current graph execution state, populated after propagate()",
)

ticker

ticker: str = Field(
    default="", title="Ticker", description="Current stock ticker symbol being analyzed"
)

log_states_dict

log_states_dict: dict[str, Any] = Field(
    default_factory=dict,
    title="Log States",
    description="Accumulated state logs keyed by trade date",
)

deep_thinking_llm

deep_thinking_llm: ChatModel

Deep thinking LLM instance, derived from config.

Returns:

Name Type Description
ChatModel ChatModel

Deep thinking LLM instance.

quick_thinking_llm

quick_thinking_llm: ChatModel

Quick thinking LLM instance, derived from config.

Returns:

Name Type Description
ChatModel ChatModel

Quick thinking LLM instance.

bull_memory

bull_memory: FinancialSituationMemory

Bull researcher memory instance.

Returns:

Name Type Description
FinancialSituationMemory FinancialSituationMemory

Memory instance for the bull researcher.

bear_memory

bear_memory: FinancialSituationMemory

Bear researcher memory instance.

Returns:

Name Type Description
FinancialSituationMemory FinancialSituationMemory

Memory instance for the bear researcher.

trader_memory

trader_memory: FinancialSituationMemory

Trader memory instance.

Returns:

Name Type Description
FinancialSituationMemory FinancialSituationMemory

Memory instance for the trader.

invest_judge_memory

invest_judge_memory: FinancialSituationMemory

Investment judge memory instance.

Returns:

Name Type Description
FinancialSituationMemory FinancialSituationMemory

Memory instance for the investment judge.

risk_manager_memory

risk_manager_memory: FinancialSituationMemory

Risk manager memory instance.

Returns:

Name Type Description
FinancialSituationMemory FinancialSituationMemory

Memory instance for the risk manager.

tool_nodes

tool_nodes: dict[str, ToolNode]

Tool nodes for different data sources.

Returns:

Type Description
dict[str, ToolNode]

dict[str, ToolNode]: A dictionary mapping data source names to ToolNodes.

graph

graph: CompiledStateGraph

Compiled LangGraph workflow, derived from config and selected analysts.

Returns:

Name Type Description
CompiledStateGraph CompiledStateGraph

The compiled state graph workflow.

propagator

propagator: Propagator

Graph propagator for state initialization.

Returns:

Name Type Description
Propagator Propagator

A Propagator instance.

reflector

reflector: Reflector

Post-trade reflector for memory updates.

Returns:

Name Type Description
Reflector Reflector

A Reflector instance.

signal_processor

signal_processor: SignalProcessor

Signal processor for extracting BUY/SELL/HOLD decisions.

Returns:

Name Type Description
SignalProcessor SignalProcessor

A SignalProcessor instance.

propagate

propagate(
    company_name: str,
    trade_date: str,
    on_message: Callable[[AnyMessage], None] | None = None,
    on_state: Callable[[AgentState], None] | None = None,
) -> tuple[AgentState, str]

Run the trading agents graph for a company on a specific date.

Parameters:

Name Type Description Default

company_name

str

Company name or ticker symbol.

required

trade_date

str

Trading date in YYYY-MM-DD format.

required

on_message

Callable[[AnyMessage], None] | None

Callback invoked once per newly-produced message during the stream. When provided, takes precedence over the default debug print path so callers (CLI, TUI) can route output through Rich panels instead of message.pretty_print(). Defaults to None.

None

on_state

Callable[[AgentState], None] | None

Callback invoked once per stream chunk with the full AgentState snapshot. Used by the Textual TUI to update the phase progress sidebar from analyst-report / debate fields; the CLI does not need this. Defaults to None.

None

Returns:

Type Description
tuple[AgentState, str]

tuple[AgentState, str]: The final agent state and the extracted signal decision.

Raises:

Type Description
RuntimeError

If the graph execution produces no output.

Source code in src/tradingagents/graph/trading_graph.py
def propagate(
    self,
    company_name: str,
    trade_date: str,
    on_message: Callable[[AnyMessage], None] | None = None,
    on_state: Callable[[AgentState], None] | None = None,
) -> tuple[AgentState, str]:
    """Run the trading agents graph for a company on a specific date.

    Args:
        company_name (str): Company name or ticker symbol.
        trade_date (str): Trading date in YYYY-MM-DD format.
        on_message (Callable[[AnyMessage], None] | None, optional):
            Callback invoked once per newly-produced message during the
            stream. When provided, takes precedence over the default
            debug print path so callers (CLI, TUI) can route output
            through Rich panels instead of message.pretty_print().
            Defaults to None.
        on_state (Callable[[AgentState], None] | None, optional):
            Callback invoked once per stream chunk with the full
            AgentState snapshot. Used by the Textual TUI to update the
            phase progress sidebar from analyst-report / debate
            fields; the CLI does not need this. Defaults to None.

    Returns:
        tuple[AgentState, str]: The final agent state and the extracted signal decision.

    Raises:
        RuntimeError: If the graph execution produces no output.
    """
    self.ticker = company_name

    init_agent_state = self.propagator.create_initial_state(company_name, trade_date)
    args = self.propagator.get_graph_args(callbacks=self.callbacks or None)

    # Stream in "values" mode (set by Propagator.get_graph_args) so each chunk
    # is the full state snapshot after a node runs. The graph clears
    # state.messages between analysts via Msg Clear nodes, so the only way
    # to capture every round of LLM dialogue is to collect messages as they
    # appear in stream chunks (deduped by id).
    raw_state = None
    last_emitted_id = None
    collected: dict[str, AnyMessage] = {}
    for chunk in self.graph.stream(init_agent_state, **args):
        last_emitted_id = self._dispatch_messages(
            chunk, collected, last_emitted_id, on_message
        )
        if on_state is not None:
            self._dispatch_state(chunk, on_state)
        raw_state = chunk

    if raw_state is None:
        raise RuntimeError("Graph produced no output")

    final_state = (
        AgentState.model_validate(raw_state) if isinstance(raw_state, dict) else raw_state
    )

    self.curr_state = final_state
    self._log_state(trade_date, final_state, list(collected.values()))
    return final_state, self.process_signal(final_state.final_trade_decision)

reflect_and_remember

reflect_and_remember(returns_losses: float) -> None

Reflect on decisions and update memory based on returns.

Parameters:

Name Type Description Default

returns_losses

float

Actual returns or losses from the trade.

required

Raises:

Type Description
RuntimeError

If there is no current state to reflect on.

Source code in src/tradingagents/graph/trading_graph.py
def reflect_and_remember(self, returns_losses: float) -> None:
    """Reflect on decisions and update memory based on returns.

    Args:
        returns_losses (float): Actual returns or losses from the trade.

    Raises:
        RuntimeError: If there is no current state to reflect on.
    """
    if self.curr_state is None:
        raise RuntimeError("No state available to reflect on. Run propagate() first.")
    self.reflector.reflect_bull_researcher(self.curr_state, returns_losses, self.bull_memory)
    self.reflector.reflect_bear_researcher(self.curr_state, returns_losses, self.bear_memory)
    self.reflector.reflect_trader(self.curr_state, returns_losses, self.trader_memory)
    self.reflector.reflect_invest_judge(
        self.curr_state, returns_losses, self.invest_judge_memory
    )
    self.reflector.reflect_risk_manager(
        self.curr_state, returns_losses, self.risk_manager_memory
    )

process_signal

process_signal(full_signal: str) -> str

Process a signal to extract the core decision.

Parameters:

Name Type Description Default

full_signal

str

The raw text signal.

required

Returns:

Name Type Description
str str

The extracted decision (BUY/SELL/HOLD).

Source code in src/tradingagents/graph/trading_graph.py
def process_signal(self, full_signal: str) -> str:
    """Process a signal to extract the core decision.

    Args:
        full_signal (str): The raw text signal.

    Returns:
        str: The extracted decision (BUY/SELL/HOLD).
    """
    return self.signal_processor.process_signal(full_signal)