Basic Trading Example
This example demonstrates how to use TradingAgents to analyze a stock and make a trading decision. We'll walk through a complete analysis of NVIDIA (NVDA) stock.
Simple Stock Analysis
Here's a basic example that analyzes NVIDIA stock:
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG
# Initialize TradingAgents
ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())
# Analyze NVIDIA stock
symbol = "NVDA"
date = "2024-05-10"
print(f"Analyzing {symbol} for {date}...")
# Run the multi-agent analysis
state, decision = ta.propagate(symbol, date)
# Display the results
print("\n" + "="*50)
print("TRADING DECISION REPORT")
print("="*50)
print(f"Symbol: {symbol}")
print(f"Date: {date}")
print(f"Decision: {decision['action']}")
print(f"Confidence: {decision['confidence']}/10")
print(f"Risk Level: {decision['risk_level']}")
print("\nKey Reasoning:")
for factor in decision['key_factors']:
print(f"• {factor}")
if decision['risk_warnings']:
print("\nRisk Warnings:")
for warning in decision['risk_warnings']:
print(f"⚠️ {warning}")
Expected Output
When you run this example, you'll see output similar to:
Analyzing NVDA for 2024-05-10...
[Agent Activity]
✓ Fundamentals Analyst: Analyzing company financials...
✓ Sentiment Analyst: Processing market sentiment...
✓ News Analyst: Reviewing recent news...
✓ Technical Analyst: Computing technical indicators...
✓ Bullish Researcher: Building positive case...
✓ Bearish Researcher: Identifying risks...
✓ Trader Agent: Synthesizing analysis...
✓ Risk Manager: Assessing portfolio impact...
==================================================
TRADING DECISION REPORT
==================================================
Symbol: NVDA
Date: 2024-05-10
Decision: BUY
Confidence: 8.5/10
Risk Level: MODERATE
Key Reasoning:
• Strong Q1 earnings beat with 18% revenue growth
• AI chip demand continues to accelerate
• Technical breakout above $900 resistance level
• Positive analyst upgrades following earnings
Risk Warnings:
⚠️ High volatility expected due to AI sector momentum
⚠️ Valuation multiples at historical highs
⚠️ Potential market correction could impact growth stocks
Detailed Analysis Inspection
You can also examine the detailed analysis from each agent:
# Access individual agent analyses
fundamentals = state['fundamentals_analysis']
sentiment = state['sentiment_analysis']
technical = state['technical_analysis']
debate = state['debate_results']
print("FUNDAMENTALS ANALYSIS:")
print(f"Revenue Growth: {fundamentals['revenue_growth']}")
print(f"Profit Margins: {fundamentals['profit_margins']}")
print(f"Valuation Score: {fundamentals['valuation_score']}")
print("\nSENTIMENT ANALYSIS:")
print(f"Overall Sentiment: {sentiment['overall_sentiment']}")
print(f"Social Media Score: {sentiment['social_media_score']}")
print(f"News Sentiment: {sentiment['news_sentiment']}")
print("\nTECHNICAL ANALYSIS:")
print(f"RSI: {technical['rsi']}")
print(f"MACD Signal: {technical['macd_signal']}")
print(f"Support/Resistance: {technical['support_resistance']}")
print("\nRESOURCER DEBATE:")
print(f"Bullish Arguments: {len(debate['bullish_points'])}")
print(f"Bearish Arguments: {len(debate['bearish_points'])}")
print(f"Consensus: {debate['consensus']}")
Multiple Stock Comparison
Compare analysis across multiple stocks:
# Analyze multiple tech stocks
stocks = ["NVDA", "AAPL", "GOOGL", "MSFT", "TSLA"]
date = "2024-05-10"
results = {}
for stock in stocks:
print(f"Analyzing {stock}...")
_, decision = ta.propagate(stock, date)
results[stock] = {
'action': decision['action'],
'confidence': decision['confidence'],
'risk_level': decision['risk_level']
}
# Display comparison
print("\nSTOCK COMPARISON:")
print("-" * 60)
print(f"{'Symbol':<8} {'Action':<6} {'Confidence':<12} {'Risk':<10}")
print("-" * 60)
for stock, result in results.items():
print(f"{stock:<8} {result['action']:<6} {result['confidence']:<12.1f} {result['risk_level']:<10}")
Time Series Analysis
Analyze the same stock over multiple dates:
import datetime
symbol = "AAPL"
start_date = datetime.date(2024, 5, 1)
end_date = datetime.date(2024, 5, 10)
# Generate date range (weekdays only)
current_date = start_date
dates = []
while current_date <= end_date:
if current_date.weekday() < 5: # Monday=0, Friday=4
dates.append(current_date.strftime("%Y-%m-%d"))
current_date += datetime.timedelta(days=1)
# Analyze across dates
time_series = {}
for date in dates:
print(f"Analyzing {symbol} for {date}...")
_, decision = ta.propagate(symbol, date)
time_series[date] = decision
# Display time series
print(f"\n{symbol} TIME SERIES ANALYSIS:")
print("-" * 50)
for date, decision in time_series.items():
print(f"{date}: {decision['action']} (Confidence: {decision['confidence']:.1f})")
Custom Configuration Example
Customize the analysis for specific needs:
from tradingagents.default_config import DEFAULT_CONFIG
# Create configuration for cost-effective testing
test_config = DEFAULT_CONFIG.copy()
test_config.update({
"deep_think_llm": "gpt-4o-mini", # Cheaper model
"quick_think_llm": "gpt-4o-mini",
"max_debate_rounds": 1, # Faster execution
"online_tools": False, # Use cached data
"risk_tolerance": "moderate"
})
# Initialize with test configuration
ta_test = TradingAgentsGraph(debug=False, config=test_config)
# Quick analysis
_, decision = ta_test.propagate("AAPL", "2024-05-10")
print(f"Quick Analysis: {decision['action']} with {decision['confidence']:.1f} confidence")
Error Handling Example
Handle common errors gracefully:
from tradingagents.exceptions import TradingAgentsError, InvalidSymbolError
def safe_analysis(symbol, date):
try:
state, decision = ta.propagate(symbol, date)
return decision
except InvalidSymbolError:
print(f"Error: '{symbol}' is not a valid stock symbol")
return None
except TradingAgentsError as e:
print(f"Analysis error: {e}")
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
# Test with invalid symbol
result = safe_analysis("INVALID", "2024-05-10")
if result:
print(f"Decision: {result['action']}")
else:
print("Analysis failed")
# Test with valid symbol
result = safe_analysis("AAPL", "2024-05-10")
if result:
print(f"Decision: {result['action']}")
Portfolio Analysis Example
Analyze a complete portfolio:
def analyze_portfolio(portfolio, date, target_allocation=None):
"""
Analyze a portfolio of stocks
Args:
portfolio: List of stock symbols
date: Analysis date
target_allocation: Optional dict of target allocations
"""
results = {}
total_confidence = 0
buy_recommendations = []
for symbol in portfolio:
print(f"Analyzing {symbol}...")
try:
_, decision = ta.propagate(symbol, date)
results[symbol] = decision
total_confidence += decision['confidence']
if decision['action'] == 'BUY':
buy_recommendations.append({
'symbol': symbol,
'confidence': decision['confidence'],
'risk_level': decision['risk_level']
})
except Exception as e:
print(f"Error analyzing {symbol}: {e}")
results[symbol] = {'error': str(e)}
# Portfolio summary
avg_confidence = total_confidence / len([r for r in results.values() if 'error' not in r])
print(f"\nPORTFOLIO ANALYSIS SUMMARY:")
print(f"Average Confidence: {avg_confidence:.1f}")
print(f"Buy Recommendations: {len(buy_recommendations)}")
# Sort buy recommendations by confidence
buy_recommendations.sort(key=lambda x: x['confidence'], reverse=True)
print("\nTOP BUY RECOMMENDATIONS:")
for i, rec in enumerate(buy_recommendations[:3], 1):
print(f"{i}. {rec['symbol']} (Confidence: {rec['confidence']:.1f}, Risk: {rec['risk_level']})")
return results
# Example portfolio
my_portfolio = ["AAPL", "GOOGL", "MSFT", "NVDA", "TSLA", "AMZN"]
portfolio_results = analyze_portfolio(my_portfolio, "2024-05-10")
Next Steps
After running these examples:
- Experiment with Configuration: Try different configuration options
- Explore Advanced Examples: Check out advanced usage patterns
- Learn About Agents: Understand individual agent roles
- Try the CLI: Use the command-line interface