Skip to content

yangou-hash/TradingAgents

 
 

Repository files navigation

arXiv Discord WeChat X Follow
Community

TradingAgents: Multi-Agents LLM Financial Trading Framework

News

  • [2026-04] Indicator Calculation Separation (#542) — Technical indicators are now pre-computed in pure Python code before passing to the Market Analyst LLM. Eliminates 8-16 tool call round trips per analysis, reducing analysis time from 2-4 minutes to under 60 seconds.
  • [2026-04] YFinance Rate Limit Fix (#555) — Added exponential backoff retry and in-memory TTL caching for all yfinance API calls. Automatic vendor fallback to Alpha Vantage when rate limits persist.
  • [2026-04] LLM Model Updates — Updated model lists across all 6 providers to April 2026 latest, including Claude Opus 4.6, GPT-5.4 series, Gemini 3.1 Pro, and Grok 4.20.
  • [2026-03] KIS Broker Integration — Real-time trade execution via Korea Investment & Securities (한국투자증권) API. Supports both paper trading (모의투자) and real trading (실투자) with multi-layer safety guards.
  • [2026-03] Investment Persona System — Trade like Warren Buffett, Ray Dalio, or Peter Lynch. Persona-specific strategies are injected into Trader, Research Manager, and Risk Manager agents.
  • [2026-02] TradingAgents v0.2.0 released with multi-provider LLM support (GPT-5.x, Gemini 3.x, Claude 4.x, Grok 4.x) and improved system architecture.
  • [2026-01] Trading-R1 Technical Report released, with Terminal expected to land soon.

🎉 TradingAgents officially released! We have received numerous inquiries about the work, and we would like to express our thanks for the enthusiasm in our community.

So we decided to fully open-source the framework. Looking forward to building impactful projects with you!

🚀 TradingAgents | ⚡ Installation & CLI | 🎬 Demo | 📦 Package Usage | 🎭 Personas | 📈 Broker Execution | 🤝 Contributing | 📄 Citation

TradingAgents Framework

TradingAgents is a multi-agent trading framework that mirrors the dynamics of real-world trading firms. By deploying specialized LLM-powered agents: from fundamental analysts, sentiment experts, and technical analysts, to trader, risk management team, the platform collaboratively evaluates market conditions and informs trading decisions. Moreover, these agents engage in dynamic discussions to pinpoint the optimal strategy.

TradingAgents framework is designed for research purposes. Trading performance may vary based on many factors, including the chosen backbone language models, model temperature, trading periods, the quality of data, and other non-deterministic factors. It is not intended as financial, investment, or trading advice.

Our framework decomposes complex trading tasks into specialized roles. This ensures the system achieves a robust, scalable approach to market analysis and decision-making.

Analyst Team

  • Fundamentals Analyst: Evaluates company financials and performance metrics, identifying intrinsic values and potential red flags. For Korean-listed companies, it also leverages OpenDART data including official financial statements and regulatory disclosures.
  • Sentiment Analyst: Analyzes social media and public sentiment using sentiment scoring algorithms to gauge short-term market mood.
  • News Analyst: Monitors global news and macroeconomic indicators, interpreting the impact of events on market conditions.
  • Technical Analyst: Pre-computes all technical indicators (MACD, RSI, Bollinger Bands, ATR, moving averages, etc.) in pure code, then passes the structured summary to the LLM for contextual interpretation and trend analysis.

Researcher Team

  • Comprises both bullish and bearish researchers who critically assess the insights provided by the Analyst Team. Through structured debates, they balance potential gains against inherent risks.

Trader Agent

  • Composes reports from the analysts and researchers to make informed trading decisions. It determines the timing and magnitude of trades based on comprehensive market insights.

Risk Management and Portfolio Manager

  • Continuously evaluates portfolio risk by assessing market volatility, liquidity, and other risk factors. The risk management team evaluates and adjusts trading strategies, providing assessment reports to the Portfolio Manager for final decision.
  • The Portfolio Manager approves/rejects the transaction proposal. If approved, the order will be sent to the simulated exchange and executed.

Installation and CLI

Installation

Clone TradingAgents:

git clone https://github.com/TauricResearch/TradingAgents.git
cd TradingAgents

Create a virtual environment in any of your favorite environment managers:

conda create -n tradingagents python=3.13
conda activate tradingagents

Install dependencies:

pip install -r requirements.txt

Required APIs

TradingAgents supports multiple LLM providers. Set the API key for your chosen provider:

# LLM Providers (set the one you use)
export OPENAI_API_KEY=...          # OpenAI (GPT)
export GOOGLE_API_KEY=...          # Google (Gemini)
export ANTHROPIC_API_KEY=...       # Anthropic (Claude)
export XAI_API_KEY=...             # xAI (Grok)
export OPENROUTER_API_KEY=...      # OpenRouter

# Data Providers
export ALPHA_VANTAGE_API_KEY=...   # Alpha Vantage (alternative to yfinance)
export OPENDART_API_KEY=...        # OpenDART (Korean DART disclosures)

# KIS Broker (한국투자증권) — only needed for trade execution
export KIS_APP_KEY=...             # KIS Open API app key
export KIS_APP_SECRET=...          # KIS Open API app secret
export KIS_ACCOUNT_NO=...          # Account number (format: XXXXXXXX-XX)

For local models, configure Ollama with llm_provider: "ollama" in your config.

Alternatively, copy .env.example to .env and fill in your keys:

cp .env.example .env

CLI Usage

You can also try out the CLI directly by running:

python -m cli.main

The CLI guides you through a 9-step interactive setup: ticker, date, analysts, LLM provider & models, research depth, investment persona, and broker execution mode.

An interface will appear showing results as they load, letting you track the agent's progress as it runs.

TradingAgents Package

Implementation Details

We built TradingAgents with LangGraph to ensure flexibility and modularity. The framework supports multiple LLM providers: OpenAI, Google, Anthropic, xAI, OpenRouter, and Ollama.

Python Usage

To use TradingAgents inside your code, you can import the tradingagents module and initialize a TradingAgentsGraph() object. The .propagate() function will return a decision. You can run main.py, here's also a quick example:

from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG

ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())

# forward propagate
_, decision = ta.propagate("NVDA", "2026-01-15")
print(decision)

You can also adjust the default configuration to set your own choice of LLMs, debate rounds, personas, and more:

from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG

config = DEFAULT_CONFIG.copy()
config["llm_provider"] = "openai"        # openai, google, anthropic, xai, openrouter, ollama
config["deep_think_llm"] = "gpt-5.2"     # Model for complex reasoning
config["quick_think_llm"] = "gpt-5-mini" # Model for quick tasks
config["max_debate_rounds"] = 2

# Apply an investment persona (optional)
config["persona"] = "warren_buffett"     # None, "warren_buffett", "ray_dalio", "peter_lynch"

ta = TradingAgentsGraph(debug=True, config=config)
_, decision = ta.propagate("NVDA", "2026-01-15")
print(decision)

To enable live trade execution with KIS broker:

config["broker"] = {
    "enabled": True,
    "provider": "kis",
    "mode": "paper",                 # "paper" (모의투자) or "real" (실투자)
    "default_position_pct": 0.05,    # 5% of portfolio per trade
}

ta = TradingAgentsGraph(debug=True, config=config)
final_state, decision = ta.propagate("005930", "2026-03-15")
print(decision)
print(final_state.get("execution_result", ""))  # Order execution result

See tradingagents/default_config.py for all configuration options.

Korean Market Support (OpenDART)

TradingAgents supports Korean-listed companies through the OpenDART API, which provides official financial statements and regulatory disclosures from Korea's DART (Data Analysis, Retrieval and Transfer) system.

To enable Korean market support:

  1. Get an API key from OpenDART
  2. Set the environment variable:
    export OPENDART_API_KEY=your_api_key_here
  3. Use 6-digit Korean stock ticker codes (e.g., 005930 for Samsung Electronics):
    _, decision = ta.propagate("005930", "2026-03-08")

The Fundamentals Analyst will automatically use get_dart_financials and get_dart_disclosures tools when analyzing Korean stocks, retrieving:

  • Financial Statements: Revenue, operating profit, net income, and OPM from quarterly/annual DART filings
  • Disclosures: Recent regulatory filings, earnings reports, and corporate actions from the last 30 days

Investment Personas

TradingAgents supports investment personas that shape how the Trader, Research Manager, and Risk Manager approach their decisions. Analysts remain objective and unaffected by personas.

Persona Strategy Key Principles
Warren Buffett Value investing Long-term holding, margin of safety, intrinsic value, moat analysis
Ray Dalio Systematic macro Diversified ETF allocation, rebalancing, macro-driven decisions
Peter Lynch Growth investing PEG ratio focus, invest in what you know, growth at reasonable price
config["persona"] = "warren_buffett"  # or "ray_dalio", "peter_lynch", None (default)

In CLI mode, the persona selection appears as Step 8 in the interactive wizard.

To add a custom persona, add an entry to the PERSONAS dict in tradingagents/agents/personas.py with prompt fragments for "trader", "research_manager", and "risk_manager" roles.

Broker Execution (KIS)

TradingAgents can execute real trades through the Korea Investment & Securities (한국투자증권) REST API. When enabled, an Executor node is added to the graph after the Risk Judge, automatically placing orders based on the final trading decision.

Setup

  1. Register for a KIS Open API account at KIS Developers
  2. Create an app to get your APP_KEY and APP_SECRET
  3. Set environment variables:
    export KIS_APP_KEY=your_app_key
    export KIS_APP_SECRET=your_app_secret
    export KIS_ACCOUNT_NO=12345678-01    # Format: XXXXXXXX-XX

Trading Modes

Mode Description Use Case
Paper ("paper") Simulated trading via KIS virtual trading server Testing, development, strategy validation
Real ("real") Live trading with real money Production use (requires explicit opt-in)

Safety Guards

Multiple layers of protection are built into the execution engine:

Guard Default Description
Paper trading default mode: "paper" Real trading requires explicit opt-in
Double confirmation require_confirmation: True CLI prompts twice before enabling real trades
Position limit max_position_pct: 10% Maximum portfolio weight per single stock
Order amount limit max_order_amount: 5,000,000 KRW Maximum amount per single order
Daily loss limit daily_loss_limit: -500,000 KRW Stops trading when daily loss exceeds limit
Market hours enforce_market_hours: True Orders blocked outside KRX hours (09:00-15:30 KST)

Configuration

config["broker"] = {
    "enabled": True,
    "provider": "kis",
    "mode": "paper",                     # "paper" or "real"
    "default_order_type": "market",      # "market" or "limit"
    "default_position_pct": 0.05,        # 5% of portfolio per trade
    "safety": {
        "max_position_pct": 0.10,
        "max_order_amount": 5_000_000,
        "daily_loss_limit": -500_000,
        "enforce_market_hours": True,
        "require_confirmation": True,
    },
}

Architecture

The broker system uses an abstract BaseBroker interface, making it extensible to other Korean brokers (Kiwoom, eBest, etc.) in the future:

ExecutionEngine (safety + orchestration)
  └── BaseBroker (abstract interface)
        └── KISBroker (KIS REST API implementation)
              └── KISClient (HTTP client + token management + rate limiting)

When the broker is enabled, the Trader agent also receives portfolio context (current holdings, cash balance, unrealized P&L) to make more informed decisions.

All Configuration Options

Option Default Description
llm_provider "anthropic" LLM provider: openai, google, anthropic, xai, openrouter, ollama
deep_think_llm "claude-sonnet-4-6" Model for complex reasoning tasks
quick_think_llm "claude-haiku-4-5-20251001" Model for quick analysis tasks
backend_url None API endpoint URL (auto-configured per provider)
max_debate_rounds 1 Bull/Bear debate rounds
max_risk_discuss_rounds 1 Risk management discussion rounds
data_vendors {"core_stock_apis": "yfinance", ...} Category-level data vendor selection
persona None Investment persona
broker.enabled False Enable trade execution
broker.mode "paper" Paper or real trading
yfinance_retry {max_retries: 3, base_delay: 2.0, ...} YFinance retry/backoff configuration
cache_ttl {fundamentals: 3600, news: 900, ...} In-memory cache TTL per data category (seconds)
google_thinking_level None Gemini thinking config: "high", "minimal"
openai_reasoning_effort None OpenAI reasoning effort: "low", "medium", "high"

Contributing

We welcome contributions from the community! Whether it's fixing a bug, improving documentation, or suggesting a new feature, your input helps make this project better. If you are interested in this line of research, please consider joining our open-source financial AI research community Tauric Research.

Citation

Please reference our work if you find TradingAgents provides you with some help :)

@misc{xiao2025tradingagentsmultiagentsllmfinancial,
      title={TradingAgents: Multi-Agents LLM Financial Trading Framework}, 
      author={Yijia Xiao and Edward Sun and Di Luo and Wei Wang},
      year={2025},
      eprint={2412.20138},
      archivePrefix={arXiv},
      primaryClass={q-fin.TR},
      url={https://arxiv.org/abs/2412.20138}, 
}

About

TradingAgents: Multi-Agents LLM Financial Trading Framework

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages

  • Python 100.0%