Skip to main content

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)

ParameterTypeDefaultDescription
debugboolFalseEnable detailed logging and debug output
configdictNoneConfiguration 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 outputs
  • decision (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

ParameterDescriptionDefaultOptions
deep_think_llmModel for complex analysis"o1-preview""o1-preview", "gpt-4o", "gpt-4o-mini"
quick_think_llmModel for quick responses"gpt-4o""gpt-4o", "gpt-4o-mini"
temperatureModel creativity level0.70.0-2.0

Agent Behavior

ParameterDescriptionDefaultOptions
max_debate_roundsResearcher debate rounds31-5
consensus_thresholdAgreement threshold0.60.0-1.0
risk_toleranceRisk acceptance level"moderate""low", "moderate", "high"

Data Sources

ParameterDescriptionDefaultOptions
online_toolsUse real-time dataFalseTrue, False
data_cache_ttlCache time-to-live3600Seconds
fallback_to_cacheUse cache if API failsTrueTrue, 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