Skip to main content

TradingAgents: Multi-Agents LLM Financial Trading Framework

Project description

TradingAgents

PyPI version python uv Ruff Pydantic v2 tests code-quality Ask DeepWiki license PRs contributors

๐Ÿš€ TradingAgents is a multi-agent LLM financial trading framework that leverages large language models to simulate analyst teams, research debates, and portfolio management decisions for stock trading analysis.

Other Languages: English | ็น้ซ”ไธญๆ–‡ | ็ฎ€ไฝ“ไธญๆ–‡

โœจ Highlights

  • Built on LangGraph for robust multi-agent orchestration
  • Multi-agent architecture: Analyst Team โ†’ Research Team โ†’ Trader โ†’ Risk Management โ†’ Portfolio Management
  • Powered by langchain.chat_models.init_chat_model; supports any provider keyed via an explicit llm_provider field plus a model name (OpenAI, Anthropic, Google Gemini, xAI (Grok), OpenRouter, Ollama, HuggingFace, LiteLLM)
  • Unified reasoning_effort knob (low / medium / high / xhigh / max) mapped per provider to native parameters (Anthropic effort, OpenAI reasoning_effort, Google thinking_level)
  • Market data powered by yfinance for OHLCV, fundamentals, technical indicators, news, and insider transactions
  • Pydantic-based configuration with strict typing and validation
  • Analysis results automatically saved to results/ with organized subfolders
  • Modern src/ layout with full type-annotated code
  • Fast dependency management via uv
  • Pre-commit suite: ruff, mdformat, codespell, mypy, uv hooks
  • Pytest with coverage; MkDocs Material documentation

๐Ÿš€ Quick Start

git clone https://github.com/Mai0313/TradingAgents.git
cd TradingAgents
make uv-install               # Install uv (only needed once)
uv sync                       # Install dependencies
cp .env.example .env          # Configure your API keys

Configure API Keys

Edit .env and set your LLM provider keys:

# LLM Providers (set the one you use)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_API_KEY=AIza...
XAI_API_KEY=...
OPENROUTER_API_KEY=...

Usage

from tradingagents.config import TradingAgentsConfig
from tradingagents.graph.trading_graph import TradingAgentsGraph

config = TradingAgentsConfig(
    llm_provider="openai",
    deep_think_llm="gpt-5",
    quick_think_llm="gpt-5-mini",
    max_debate_rounds=1,
    max_risk_discuss_rounds=1,
    max_recur_limit=100,
    reasoning_effort="medium",
    response_language="en",
)

ta = TradingAgentsGraph(debug=True, config=config)
_, decision = ta.propagate("NVDA", "2024-05-10")
print(decision)

llm_provider is one of the langchain.chat_models.init_chat_model registry keys (openai, anthropic, google_genai, xai, openrouter, ollama, huggingface, litellm); deep_think_llm / quick_think_llm take the model name as accepted by that provider (gpt-5, claude-sonnet-4-6, gemini-3-pro-preview, grok-4, ...).

Set response_language to control the language requested in all agent prompts. Tickers without exchange suffixes are resolved automatically with Yahoo Finance Search. For Taiwan stocks, pass the numeric stock code directly, such as 2330, 2408, or 8069; explicit Yahoo Finance symbols such as 2330.TW, 8069.TWO, AAPL, and TSM are also supported.

config = TradingAgentsConfig(
    llm_provider="openai",
    deep_think_llm="gpt-5",
    quick_think_llm="gpt-5-mini",
    max_debate_rounds=1,
    max_risk_discuss_rounds=1,
    max_recur_limit=100,
    response_language="zh-TW",
)

ta = TradingAgentsGraph(config=config)
_, decision = ta.propagate("2330", "2024-05-10")

๐Ÿ“ Project Structure

src/
โ””โ”€โ”€ tradingagents/
    โ”œโ”€โ”€ agents/           # Agent implementations
    โ”‚   โ”œโ”€โ”€ analysts/     # Market, News, Social, Fundamentals analysts
    โ”‚   โ”œโ”€โ”€ managers/     # Research & Portfolio managers
    โ”‚   โ”œโ”€โ”€ researchers/  # Bull & Bear researchers
    โ”‚   โ”œโ”€โ”€ risk_mgmt/    # Risk management agents
    โ”‚   โ”œโ”€โ”€ trader/       # Trader agent
    โ”‚   โ””โ”€โ”€ utils/        # Shared agent utilities
    โ”œโ”€โ”€ dataflows/        # Data ingestion via yfinance
    โ”œโ”€โ”€ graph/            # LangGraph trading graph setup
    โ”œโ”€โ”€ llm.py            # Chat model construction (init_chat_model wrapper + reasoning_effort mapping)
    โ”œโ”€โ”€ config.py         # TradingAgentsConfig schema + global singleton
    โ””โ”€โ”€ cli.py            # Entry point

๐Ÿค– Agent Workflow

TradingAgents orchestrates 12 LLM agents plus 2 supporting components through a LangGraph StateGraph. Every run goes through 4 sequential phases, and the state (reports, debate transcripts, trade decisions) is persisted through a Pydantic AgentState shared across all nodes.

Phase 1 โ€” Analyst Team (Data Collection)

Four analysts run in sequence. Each analyst has its LLM bound to a specific set of yfinance-backed @tool functions, and loops with its own ToolNode until no more tool calls are emitted. Between analysts a Msg Clear node resets the conversation history (emitting RemoveMessage + a HumanMessage("Continue") placeholder for Anthropic compatibility).

Analyst LLM-bound tools Writes to state
Market Analyst get_stock_data, get_indicators market_report
Social Media Analyst get_news sentiment_report
News Analyst get_news, get_global_news news_report
Fundamentals Analyst get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement fundamentals_report

Supported technical indicators (selected by the Market Analyst, up to 8 per run): close_50_sma, close_200_sma, close_10_ema, macd, macds, macdh, rsi, boll, boll_ub, boll_lb, atr, vwma.

Phase 2 โ€” Research Debate

  • Bull Researcher and Bear Researcher debate for max_debate_rounds rounds (default: 1 round each), taking turns based on who spoke last. Each researcher retrieves top-k BM25 matches from its own FinancialSituationMemory before arguing.
  • Termination: count >= 2 * max_debate_rounds routes the graph to Research Manager (deep-thinking LLM), which evaluates the full debate, produces the investment_plan, and populates investment_debate_state.judge_decision.

Phase 3 โ€” Trader

Trader (quick-thinking LLM) consumes investment_plan plus the top-k trader_memory matches and produces trader_investment_plan. Its output must end with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**.

Phase 4 โ€” Risk Control Debate

Three debators rotate in a fixed order โ€” Aggressive โ†’ Conservative โ†’ Neutral โ†’ Aggressive โ†’ โ€ฆ โ€” for max_risk_discuss_rounds rounds (default: 1 round per stance). Termination: count >= 3 * max_risk_discuss_rounds routes to the Risk Judge (deep-thinking LLM via create_risk_manager), which revises the trader's plan and writes the final_trade_decision. A lightweight SignalProcessor LLM then extracts the canonical BUY / SELL / HOLD token from that natural-language decision.

Supporting components

  • FinancialSituationMemory โ€” BM25Okapi-backed per-agent memory (5 instances: bull, bear, trader, invest_judge, risk_manager). Purely lexical, no external embeddings API required.
  • Reflector โ€” After the trade outcome is known, TradingAgentsGraph.reflect_and_remember(returns_losses) runs post-trade reflection against each of the 5 memories so future runs can learn from past decisions.

Flow Diagram

START
  โ”‚
  โ–ผ
[Market Analyst โ‡„ tools_market] โ†’ Msg Clear
  โ”‚
  โ–ผ
[Social Analyst โ‡„ tools_social] โ†’ Msg Clear
  โ”‚
  โ–ผ
[News Analyst โ‡„ tools_news] โ†’ Msg Clear
  โ”‚
  โ–ผ
[Fundamentals Analyst โ‡„ tools_fundamentals] โ†’ Msg Clear
  โ”‚
  โ–ผ
[Bull Researcher โ‡„ Bear Researcher] ร— max_debate_rounds
  โ”‚
  โ–ผ
Research Manager  โ†’  Trader
                        โ”‚
                        โ–ผ
[Aggressive โ†’ Conservative โ†’ Neutral] ร— max_risk_discuss_rounds
  โ”‚
  โ–ผ
Risk Judge  โ†’  SignalProcessor  โ†’  END

Per-run logs are written to results/<TICKER>/TradingAgentsStrategy_logs/full_states_log_<DATE>.json (the path resolves from TradingAgentsConfig.results_dir, which defaults to ./results).

๐Ÿค Contributing

For development instructions including documentation, testing, and Docker services, please see CONTRIBUTING.md.

  • Open issues/PRs
  • Follow the coding style (ruff, type hints)
  • Use Conventional Commit messages and descriptive PR titles

๐Ÿ“„ License

MIT โ€” see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tradingagents-0.3.1.tar.gz (340.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tradingagents-0.3.1-py3-none-any.whl (71.2 kB view details)

Uploaded Python 3

File details

Details for the file tradingagents-0.3.1.tar.gz.

File metadata

  • Download URL: tradingagents-0.3.1.tar.gz
  • Upload date:
  • Size: 340.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for tradingagents-0.3.1.tar.gz
Algorithm Hash digest
SHA256 a70452f12e4b0aed893a75c437e7f542d4f852be8f916248a4d6afc88bf66fcc
MD5 2cc808ed41a12a1631f40a5fbc60e31f
BLAKE2b-256 9414fcb0ef34bec90adff8637c5d1530435d82923cffc30786f02425905fdf41

See more details on using hashes here.

File details

Details for the file tradingagents-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: tradingagents-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 71.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for tradingagents-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9a5d11500bc58192b1a8f460d8eaa15c63054cebd30aa7f82274f035516a6f53
MD5 21610edb641199d04aa6b5b2d52196db
BLAKE2b-256 cc14e02195c4e3d8fe99864866bbd55a363b131ca0f2f7718418edbe043052e3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page