19 KiB
TradingAgents: Multi-Agents LLM Financial Trading Framework
🎉 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 | 📚 API Docs | 🔧 Troubleshooting | 👥 Agent Dev | 🤝 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.
- 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: Utilizes technical indicators (like MACD and RSI) to detect trading patterns and forecast price movements.
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
You will also need the FinnHub API for financial data. All of our code is implemented with the free tier.
export FINNHUB_API_KEY=$YOUR_FINNHUB_API_KEY
You will need the OpenAI API for all the agents.
export OPENAI_API_KEY=$YOUR_OPENAI_API_KEY
CLI Usage
You can also try out the CLI directly by running:
python -m cli.main
You will see a screen where you can select your desired tickers, date, LLMs, research depth, etc.
An interface will appear showing results as they load, letting you track the agent's progress as it runs.
Quick Start
Get up and running with TradingAgents in 3 simple steps:
Step 1: Set API Keys
export OPENAI_API_KEY="your_openai_api_key"
export FINNHUB_API_KEY="your_finnhub_api_key" # Optional for financial data
Step 2: Run Your First Analysis
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.config import TradingAgentsConfig
# Create configuration (uses environment variables)
config = TradingAgentsConfig.from_env()
# Initialize the trading graph
ta = TradingAgentsGraph(debug=True, config=config)
# Analyze a stock
result, decision = ta.propagate("AAPL", "2024-01-15")
print(f"Decision: {decision}")
Step 3: Explore Results
The analysis returns:
- Decision:
BUY,SELL, orHOLD - Result: Detailed analysis from all agents including market data, news sentiment, and risk assessment
Next Steps: Explore the CLI interface, check out usage examples, or dive into the API documentation.
TradingAgents Package
Implementation Details
We built TradingAgents with LangGraph to ensure flexibility and modularity. We utilize o1-preview and gpt-4o as our deep thinking and fast thinking LLMs for our experiments. However, for testing purposes, we recommend you use o4-mini and gpt-4.1-mini to save on costs as our framework makes lots of API calls.
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.config import TradingAgentsConfig
config = TradingAgentsConfig.from_env()
ta = TradingAgentsGraph(debug=True, config=config)
# forward propagate
_, decision = ta.propagate("NVDA", "2024-05-10")
print(decision)
You can also adjust the default configuration to set your own choice of LLMs, debate rounds, etc.
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.config import TradingAgentsConfig
# Create a custom config
config = TradingAgentsConfig(
deep_think_llm="gpt-4.1-nano", # Use a different model
quick_think_llm="gpt-4.1-nano", # Use a different model
max_debate_rounds=3, # Increase debate rounds
online_tools=True # Use online tools or cached data
)
# Initialize with custom config
ta = TradingAgentsGraph(debug=True, config=config)
# forward propagate
_, decision = ta.propagate("NVDA", "2024-05-10")
print(decision)
For
online_tools, we recommend enabling them for experimentation, as they provide access to real-time data. The agents' offline tools rely on cached data from our Tauric TradingDB, a curated dataset we use for backtesting. We're currently in the process of refining this dataset, and we plan to release it soon alongside our upcoming projects. Stay tuned!
You can view the full list of configurations in tradingagents/config.py.
Complete Environment Variables Reference
| Variable | Description | Default | Example |
|---|---|---|---|
LLM_PROVIDER |
LLM provider to use | openai |
anthropic |
DEEP_THINK_LLM |
Model for complex analysis | o4-mini |
claude-3-5-sonnet-latest |
QUICK_THINK_LLM |
Model for fast responses | gpt-4o-mini |
gpt-4o-mini |
BACKEND_URL |
API endpoint | https://api.openai.com/v1 |
https://api.anthropic.com |
MAX_DEBATE_ROUNDS |
Investment debate rounds | 1 |
3 |
MAX_RISK_DISCUSS_ROUNDS |
Risk discussion rounds | 1 |
2 |
ONLINE_TOOLS |
Use live APIs vs cached data | true |
false |
DEFAULT_LOOKBACK_DAYS |
Historical data range | 30 |
60 |
TRADINGAGENTS_RESULTS_DIR |
Output directory | ./results |
./my_results |
TRADINGAGENTS_DATA_DIR |
Data storage directory | System default | ./data |
Multi-LLM Provider Examples
Using Anthropic Claude:
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.config import TradingAgentsConfig
config = TradingAgentsConfig(
llm_provider="anthropic",
deep_think_llm="claude-3-5-sonnet-latest",
quick_think_llm="claude-3-haiku-latest",
max_debate_rounds=2
)
ta = TradingAgentsGraph(debug=True, config=config)
_, decision = ta.propagate("TSLA", "2024-01-15")
Using Google Gemini:
config = TradingAgentsConfig(
llm_provider="google",
deep_think_llm="gemini-1.5-pro",
quick_think_llm="gemini-1.5-flash"
)
See docs/api-reference.md for complete API documentation.
Development Guide
This section provides comprehensive development guidance for contributors working on the TradingAgents codebase.
Common Development Commands
This project uses mise for tool and task management. All development tasks are managed through mise.
Essential Commands
- CLI Application:
mise run dev- Interactive CLI for running trading analysis - Direct Python Usage:
mise run run- Run main.py programmatically - Format code:
mise run format- Auto-format with ruff - Lint code:
mise run lint- Check code quality with ruff - Type checking:
mise run typecheck- Run pyright type checker - Run all tests:
mise run test- Run tests with pytest
Initial Setup
- Install tools:
mise install- Install Python, uv, ruff, pyright - Install dependencies:
mise run install- Install project dependencies with uv
Testing Principles
Pragmatic outside-in TDD - Mock I/O boundaries, test real logic, fast feedback.
Test Structure (Mirror Source)
tests/
├── conftest.py # Shared fixtures
├── domains/
│ ├── __init__.py
│ └── news/
│ ├── __init__.py
│ ├── test_news_service.py # Mock repo + clients
│ ├── test_news_repository.py # Docker test DB
│ └── test_google_news_client.py # pytest-vcr
Mocking Strategy by Layer
- Services: Mock Repository + Clients, test real transformations
- Repositories: Real persistence (temp files/Docker), no mocks
- Clients: Real HTTP with pytest-vcr cassettes
Quality Standards
- 85% coverage minimum
- < 100ms per unit test
- Mock boundaries, test behavior
Configuration
The TradingAgents framework uses a centralized TradingAgentsConfig class for all configuration management.
Core Configuration Options
LLM Settings:
llm_provider: OpenAI, Anthropic, Google, Ollama, or OpenRouter (default: "openai")deep_think_llm: Model for complex reasoning tasks (default: "o4-mini")quick_think_llm: Model for fast responses (default: "gpt-4o-mini")
Debate Parameters:
max_debate_rounds: Maximum rounds in investment debates (default: 1)max_risk_discuss_rounds: Maximum rounds in risk discussions (default: 1)
Data Management:
online_tools: Enable/disable live API calls vs cached data (default: True)default_lookback_days: Historical data range for analysis (default: 30)
Required API Keys
# For OpenAI (default)
export OPENAI_API_KEY="your_openai_api_key"
# For Anthropic Claude
export ANTHROPIC_API_KEY="your_anthropic_api_key"
# For Google Gemini
export GOOGLE_API_KEY="your_google_api_key"
# For financial data (optional)
export FINNHUB_API_KEY="your_finnhub_api_key"
Architecture Overview
Multi-Agent Trading System
TradingAgents uses specialized LLM agents that work together in a trading firm structure:
Agent Workflow: Analysts → Researchers → Trader → Risk Management
Core Components
1. Domain-Driven Architecture
Three main domains with clean separation:
- Financial Data (
tradingagents/domains/marketdata/): Market prices, technical analysis, fundamentals - News (
tradingagents/domains/news/): News articles and sentiment analysis - Social Media (
tradingagents/domains/socialmedia/): Social sentiment from Reddit/Twitter
2. Repository-First Data Strategy
- Services read from local repositories (cached data)
- Separate update operations fetch fresh data from APIs
- Smart caching with gap detection and deduplication
3. Agent Integration (Anti-Corruption Layer)
AgentToolkitmediates between agents and domain services- Converts rich domain models to structured JSON for LLM consumption
- Handles parameter validation and error recovery
Key Design Patterns
- Debate-Driven Decisions: Bull/bear researchers debate before trading
- Memory-Augmented Learning: ChromaDB stores past decisions for context
- Quality-Aware Data: All contexts include data quality metadata
- Structured Outputs: Pydantic models replace error-prone string parsing
File Structure
tradingagents/
├── agents/ # Agent implementations
│ └── libs/ # AgentToolkit and utilities
├── domains/ # Domain-specific services
│ ├── marketdata/ # Financial data domain
│ ├── news/ # News domain
│ └── socialmedia/ # Social media domain
├── graph/ # LangGraph workflow orchestration
└── config.py # Configuration management
Performance Optimization
Caching Strategy:
- Repository-first data access minimizes API calls
- Smart caching with automatic invalidation
- Gap detection for missing data ranges
Model Selection:
quick_think_llmfor data retrieval and formattingdeep_think_llmfor complex analysis and decisions
Cost Optimization:
config = TradingAgentsConfig(
deep_think_llm="gpt-4o-mini", # Lower cost
max_debate_rounds=1, # Fewer debates
online_tools=False, # Use cached data
default_lookback_days=30 # Limit data range
)
Need Help?
- Detailed Architecture:
docs/architecture.md - API Documentation:
docs/api-reference.md - Troubleshooting:
docs/troubleshooting.md - Agent Development:
docs/agent-development.md
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},
}
important-instruction-reminders
Do what has been asked; nothing more, nothing less. NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
- remember what we learnt about testing?