TradingAgentsGraph API
The TradingAgentsGraph
is the core class of the TradingAgents framework. It orchestrates the multi-agent workflow and provides the main interface for running trading analysis.
Class Overview
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG
# Initialize the graph
ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())
Constructor Parameters
TradingAgentsGraph(debug=False, config=None)
Parameter | Type | Default | Description |
---|---|---|---|
debug | bool | False | Enable detailed logging and debug output |
config | dict | None | Configuration dictionary for customizing behavior |
Core Methods
propagate(symbol, date)
The main method for running trading analysis on a specific stock and date.
state, decision = ta.propagate("NVDA", "2024-05-10")
Parameters:
symbol
(str): Stock ticker symbol (e.g., "NVDA", "AAPL", "GOOGL")date
(str): Analysis date in YYYY-MM-DD format
Returns:
state
(dict): Complete analysis state containing all agent outputsdecision
(dict): Final trading decision and reasoning
Return Value Structure
State Object
The state object contains intermediate results from each agent:
{
"fundamentals_analysis": {...},
"sentiment_analysis": {...},
"news_analysis": {...},
"technical_analysis": {...},
"bullish_research": {...},
"bearish_research": {...},
"debate_results": {...},
"risk_assessment": {...},
"trader_decision": {...}
}
Decision Object
The decision object contains the final trading recommendation:
{
"action": "BUY", # BUY, SELL, or HOLD
"confidence": 8.5, # Confidence score 0-10
"reasoning": "Strong fundamentals and positive sentiment...",
"risk_level": "MODERATE", # LOW, MODERATE, HIGH
"key_factors": [
"Earnings growth acceleration",
"Technical breakout pattern",
"Positive analyst sentiment"
],
"risk_warnings": [
"High market volatility",
"Sector concentration risk"
],
"agent_consensus": {
"bullish_agents": 3,
"bearish_agents": 1,
"neutral_agents": 0
},
"portfolio_impact": {
"position_size": "2-3%",
"expected_volatility": "15-20%",
"correlation_risk": "LOW"
}
}
Configuration Management
Using Default Configuration
from tradingagents.default_config import DEFAULT_CONFIG
# View default settings
print(DEFAULT_CONFIG)
# Use default configuration
ta = TradingAgentsGraph(config=DEFAULT_CONFIG.copy())
Custom Configuration
# Create custom configuration
config = DEFAULT_CONFIG.copy()
# Modify specific settings
config["deep_think_llm"] = "gpt-4o-mini"
config["quick_think_llm"] = "gpt-4o-mini"
config["max_debate_rounds"] = 2
config["online_tools"] = True
# Initialize with custom config
ta = TradingAgentsGraph(debug=True, config=config)
Configuration Options
LLM Settings
Parameter | Description | Default | Options |
---|---|---|---|
deep_think_llm | Model for complex analysis | "o1-preview" | "o1-preview" , "gpt-4o" , "gpt-4o-mini" |
quick_think_llm | Model for quick responses | "gpt-4o" | "gpt-4o" , "gpt-4o-mini" |
temperature | Model creativity level | 0.7 | 0.0-2.0 |
Agent Behavior
Parameter | Description | Default | Options |
---|---|---|---|
max_debate_rounds | Researcher debate rounds | 3 | 1-5 |
consensus_threshold | Agreement threshold | 0.6 | 0.0-1.0 |
risk_tolerance | Risk acceptance level | "moderate" | "low" , "moderate" , "high" |
Data Sources
Parameter | Description | Default | Options |
---|---|---|---|
online_tools | Use real-time data | False | True , False |
data_cache_ttl | Cache time-to-live | 3600 | Seconds |
fallback_to_cache | Use cache if API fails | True | True , False |
Error Handling
Common Exceptions
from tradingagents.exceptions import (
TradingAgentsError,
APIConnectionError,
InvalidSymbolError,
ConfigurationError
)
try:
state, decision = ta.propagate("INVALID", "2024-05-10")
except InvalidSymbolError as e:
print(f"Invalid ticker symbol: {e}")
except APIConnectionError as e:
print(f"API connection failed: {e}")
except TradingAgentsError as e:
print(f"Framework error: {e}")
Retry Logic
import time
from tradingagents.exceptions import APIConnectionError
def robust_analysis(symbol, date, max_retries=3):
for attempt in range(max_retries):
try:
return ta.propagate(symbol, date)
except APIConnectionError:
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
continue
raise
Performance Optimization
Batch Processing
def analyze_portfolio(symbols, date):
results = {}
for symbol in symbols:
try:
_, decision = ta.propagate(symbol, date)
results[symbol] = decision
except Exception as e:
results[symbol] = {"error": str(e)}
return results
# Analyze multiple stocks
portfolio = ["AAPL", "GOOGL", "MSFT", "NVDA"]
results = analyze_portfolio(portfolio, "2024-05-10")
Caching Results
import pickle
from pathlib import Path
def cached_analysis(symbol, date, cache_dir="./cache"):
cache_path = Path(cache_dir) / f"{symbol}_{date}.pkl"
# Check cache
if cache_path.exists():
with open(cache_path, 'rb') as f:
return pickle.load(f)
# Run analysis
state, decision = ta.propagate(symbol, date)
# Save to cache
cache_path.parent.mkdir(exist_ok=True)
with open(cache_path, 'wb') as f:
pickle.dump((state, decision), f)
return state, decision
Advanced Usage
Custom Agent Configuration
# Configure individual agent behavior
config = DEFAULT_CONFIG.copy()
config["agent_configs"] = {
"fundamentals_analyst": {
"focus_areas": ["earnings", "growth", "valuation"],
"analysis_depth": "deep"
},
"technical_analyst": {
"indicators": ["RSI", "MACD", "BB", "SMA"],
"timeframes": ["1d", "1w", "1m"]
}
}
Workflow Customization
# Custom workflow steps
config["workflow_steps"] = [
"data_collection",
"individual_analysis",
"researcher_debate",
"risk_assessment",
"final_decision"
]
# Skip certain steps
config["skip_steps"] = ["researcher_debate"] # Faster execution
Integration Examples
With Pandas
import pandas as pd
def create_analysis_dataframe(symbols, dates):
results = []
for symbol in symbols:
for date in dates:
_, decision = ta.propagate(symbol, date)
results.append({
'symbol': symbol,
'date': date,
'action': decision['action'],
'confidence': decision['confidence'],
'risk_level': decision['risk_level']
})
return pd.DataFrame(results)
# Create analysis DataFrame
df = create_analysis_dataframe(['AAPL', 'GOOGL'], ['2024-05-01', '2024-05-02'])
With Jupyter Notebooks
# Display rich output in notebooks
from IPython.display import display, JSON
state, decision = ta.propagate("NVDA", "2024-05-10")
# Display formatted decision
display(JSON(decision))
Next Steps
- Learn about Configuration Details
- Explore Python Usage Examples
- Understand Data Sources