trading_agents

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 6, 2025 License: MIT Imports: 6 Imported by: 0

README ยถ

Trading Agents

A multi-agent LLM-powered financial trading framework built with LangGraph Go and LangChain Go. This project is a complete Go implementation inspired by TauricResearch/TradingAgents.

๐Ÿ“Š Overview

Trading Agents simulates a professional trading firm with specialized AI agents working collaboratively to analyze markets and make informed trading decisions. The system combines fundamental analysis, sentiment analysis, technical analysis, and risk management to provide comprehensive trading recommendations.

๐ŸŽฏ What Was Built

1. Core Agent System (7 specialized agents)
  • Fundamentals Analyst: Analyzes company financials and valuation
  • Sentiment Analyst: Evaluates social media and public sentiment
  • Technical Analyst: Performs technical indicator analysis
  • News Analyst: Monitors news and macroeconomic factors
  • Bullish Researcher: Provides optimistic perspective
  • Bearish Researcher: Identifies risks and concerns
  • Risk Manager: Assesses and manages trading risks
  • Trader: Synthesizes all reports for final decision
2. Three Complete Interfaces
  • Backend API Server: RESTful API with health checks and analysis endpoints
  • CLI Tool: Command-line interface for terminal-based analysis
  • Web Dashboard: Modern, responsive web interface
3. Market Data Integration
  • Alpha Vantage API integration
  • Real-time quotes and company information
  • Technical indicators calculation
  • Sentiment data collection

๐Ÿ—๏ธ Architecture

Agent Teams
  1. Analyst Team

    • Fundamentals Analyst: Evaluates company financials and performance metrics
    • Sentiment Analyst: Analyzes social media and public sentiment
    • News Analyst: Monitors global news and macroeconomic indicators
    • Technical Analyst: Uses technical indicators for price trend analysis
  2. Research Team

    • Bullish Researcher: Advocates for buying opportunities
    • Bearish Researcher: Identifies potential risks and selling signals
  3. Trader

    • Synthesizes all analyst and researcher reports
    • Makes final trading decisions
  4. Risk Management Team

    • Monitors portfolio exposure
    • Implements risk mitigation strategies
    • Ensures compliance with risk tolerance
Agent Pipeline Flow
1. Data Collection
   โ”œโ”€> Market quotes
   โ”œโ”€> Company fundamentals
   โ”œโ”€> Technical indicators
   โ””โ”€> Sentiment data

2. Analyst Team (Parallel Conceptually)
   โ”œโ”€> Fundamentals Analyst
   โ”œโ”€> Sentiment Analyst
   โ””โ”€> Technical Analyst

3. Research Team
   โ”œโ”€> Bullish Researcher
   โ””โ”€> Bearish Researcher

4. Risk Management
   โ””โ”€> Risk Manager

5. Final Decision
   โ””โ”€> Trader (synthesizes all reports)

โœจ Features

  • โœ… Multi-agent collaborative analysis
  • โœ… Real-time market data integration
  • โœ… Backend API server
  • โœ… Command-line interface (CLI)
  • โœ… Web-based dashboard
  • โœ… Comprehensive logging and tracing
  • โœ… Configurable risk tolerance
  • โœ… Multiple timeframe support
  • โœ… Verbose mode for detailed agent reports

๐Ÿ“ Project Structure

trading_agents/
โ”œโ”€โ”€ README.md              # This file
โ”œโ”€โ”€ types.go              # Core type definitions
โ”œโ”€โ”€ graph.go              # Main trading graph workflow
โ”œโ”€โ”€ agents/               # Agent implementations
โ”‚   โ”œโ”€โ”€ fundamentals_analyst.go
โ”‚   โ”œโ”€โ”€ sentiment_analyst.go
โ”‚   โ”œโ”€โ”€ technical_analyst.go
โ”‚   โ”œโ”€โ”€ trader.go
โ”‚   โ”œโ”€โ”€ risk_manager.go
โ”‚   โ””โ”€โ”€ researchers.go
โ”œโ”€โ”€ tools/                # Market data tools
โ”‚   โ””โ”€โ”€ market_data.go
โ”œโ”€โ”€ backend/              # API server
โ”‚   โ””โ”€โ”€ main.go
โ”œโ”€โ”€ cli/                  # CLI tool
โ”‚   โ””โ”€โ”€ main.go
โ”œโ”€โ”€ web/                  # Web interface
โ”‚   โ”œโ”€โ”€ index.html
โ”‚   โ”œโ”€โ”€ style.css
โ”‚   โ””โ”€โ”€ app.js
โ””โ”€โ”€ examples/             # Usage examples
    โ””โ”€โ”€ simple_analysis.go

๐Ÿ“ˆ Statistics

  • Total Go Code: ~2,000 lines
  • Number of Files: 17
  • Agents Implemented: 7 specialized agents
  • Interfaces: 3 (API, CLI, Web)
  • Binary Sizes:
    • Backend: 9.2 MB
    • CLI: 8.6 MB

๐Ÿš€ Quick Start

Prerequisites
  • Go 1.21+
  • OpenAI API key (for LLM)
  • Alpha Vantage API key (for market data, optional)
Installation
# Set environment variables
export OPENAI_API_KEY="your-openai-key"
export ALPHA_VANTAGE_API_KEY="your-alpha-vantage-key"  # Optional

# From the langgraphgo root directory
cd showcases/trading_agents

# Build backend server
go build -o ../../bin/trading-agents ./backend

# Build CLI tool
go build -o ../../bin/trading-cli ./cli
Running the Backend
./bin/trading-agents --port 8080

The server will start on http://localhost:8080

Running the CLI
# Analyze a stock
./bin/trading-cli -cmd analyze -symbol AAPL -verbose

# Get trading recommendation
./bin/trading-cli -cmd recommend -symbol AAPL -capital 10000
Running the Web Interface
# Start backend first, then
cd showcases/trading_agents/web
# Open index.html in your browser

Or serve it with a simple HTTP server:

cd showcases/trading_agents/web
python3 -m http.server 3000
# Then open http://localhost:3000 in your browser

๐Ÿ“š Usage Guide

Backend API
Health Check
curl http://localhost:8080/health
Full Analysis
curl -X POST http://localhost:8080/api/analyze \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "AAPL",
    "capital": 10000,
    "risk_tolerance": "moderate",
    "timeframe": "1D"
  }'
Quick Check
curl -X POST http://localhost:8080/api/quick-check \
  -H "Content-Type: application/json" \
  -d '{"symbol": "TSLA"}'
CLI Options
  • -cmd : Command (analyze, recommend, quick)
  • -symbol : Stock symbol (required)
  • -capital : Available capital in dollars (default: 10000)
  • -risk-level : Risk tolerance (low, moderate, high)
  • -timeframe : Trading timeframe (5m, 1H, 1D, 1W)
  • -verbose : Show detailed agent reports
  • -json : Output in JSON format
CLI Examples
Full Analysis
./bin/trading-cli -cmd analyze -symbol AAPL -verbose
Trading Recommendation
./bin/trading-cli -cmd recommend -symbol GOOGL -capital 50000 -risk-level low
Quick Check
./bin/trading-cli -cmd quick -symbol TSLA
Example Workflows
Day Trading Workflow
# Quick checks for multiple stocks
./bin/trading-cli -cmd quick -symbol AAPL
./bin/trading-cli -cmd quick -symbol GOOGL
./bin/trading-cli -cmd quick -symbol TSLA

# Full analysis for best candidate
./bin/trading-cli -cmd analyze -symbol AAPL -timeframe 5m -verbose
Investment Analysis Workflow
# Conservative long-term investment
./bin/trading-cli -cmd recommend \
  -symbol MSFT \
  -capital 100000 \
  -risk-level low \
  -timeframe 1W \
  -verbose
API Integration Example
import requests

# Analyze stock
response = requests.post('http://localhost:8080/api/analyze', json={
    'symbol': 'AAPL',
    'capital': 50000,
    'risk_tolerance': 'moderate'
})

result = response.json()
print(f"Recommendation: {result['recommendation']}")
print(f"Confidence: {result['confidence']}%")
print(f"Position Size: {result['position_size']} shares")

๐Ÿ“Š Understanding the Output

Recommendation Types
  • BUY ๐ŸŸข: Strong buying opportunity identified
  • SELL ๐Ÿ”ด: Sell recommendation or short opportunity
  • HOLD ๐ŸŸก: Maintain current position or stay on sidelines
Confidence Score
  • 80-100%: Very high confidence, strong signals across all agents
  • 60-80%: Good confidence, majority of agents agree
  • 40-60%: Moderate confidence, mixed signals
  • Below 40%: Low confidence, conflicting signals
Risk Score
  • 0-30: Low risk, conservative trade
  • 30-70: Moderate risk, balanced approach
  • 70-100: High risk, aggressive trade
Agent Reports

Each analysis includes reports from:

  1. Fundamentals Analyst: Company financials and valuation
  2. Sentiment Analyst: Social media and public sentiment
  3. Technical Analyst: Chart patterns and indicators
  4. Bullish Researcher: Positive perspective and opportunities
  5. Bearish Researcher: Risks and cautionary signals
  6. Risk Manager: Risk assessment and mitigation strategies

The Trader synthesizes all reports to make the final recommendation.

๐Ÿ› ๏ธ Technical Implementation

State Management
  • Map-based state flowing through pipeline
  • Each agent enriches the state
  • Final state contains all reports and decision
LLM Integration
  • OpenAI GPT-4 for agent reasoning
  • Temperature-controlled responses
  • Structured output parsing
LangGraph Go Integration
  • State management through graph nodes
  • Sequential execution of agent pipeline
  • Clean separation of concerns

๐Ÿ”ง Troubleshooting

"API key is required" Error

Make sure you've set the OpenAI API key:

export OPENAI_API_KEY="your-key-here"
"Analysis failed" Error
  • Check your internet connection
  • Verify the stock symbol is valid
  • Ensure the backend server is running (for web interface)
Backend Server Issues

Check if the server is running:

curl http://localhost:8080/health

View server logs for debugging:

./bin/trading-agents --verbose

๐Ÿ’ก Tips for Best Results

  1. Use Valid Symbols: Make sure to use correct ticker symbols (e.g., AAPL for Apple, not APPLE)

  2. Set Realistic Capital: Use actual capital amounts for accurate position sizing

  3. Match Risk Tolerance: Choose risk level that matches your actual risk tolerance

  4. Review All Reports: Don't just look at the recommendation - read the detailed analysis

  5. Consider Context: The analysis is point-in-time. Market conditions change rapidly.

  6. Combine with Research: Use this as one tool among many in your research process

๐ŸŽ“ Educational Value

This project demonstrates:

  • Multi-agent system architecture
  • LangGraph Go workflow orchestration
  • LangChain Go LLM integration
  • RESTful API design
  • Modern web interface development
  • Production-ready Go application structure

โš ๏ธ Important Disclaimers

  • Educational Purpose Only: Not financial advice
  • Research Tool: For learning and experimentation
  • No Liability: Use at your own risk
  • Professional Advice: Consult qualified financial advisors

This framework is for research and educational purposes only. It is NOT intended as financial, investment, or trading advice. Always consult with qualified financial professionals before making investment decisions.

๐Ÿ”ฎ Future Enhancements

Potential improvements:

  • Real-time WebSocket streaming
  • Historical backtesting
  • Portfolio management
  • Multiple timeframe analysis
  • Machine learning integration
  • Database persistence
  • User authentication
  • Paper trading mode

๐Ÿ™ Acknowledgments

๐Ÿ“ References

๐Ÿ“„ License

MIT License - See LICENSE file for details


Project Status: โœ… Complete and Ready to Use

Last Updated: December 2024

Documentation ยถ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

This section is empty.

Functions ยถ

This section is empty.

Types ยถ

type AgentConfig ยถ

type AgentConfig struct {
	ModelName       string  `json:"model_name"`
	Temperature     float64 `json:"temperature"`
	MaxTokens       int     `json:"max_tokens"`
	Verbose         bool    `json:"verbose"`
	APIKey          string  `json:"-"` // Don't serialize API keys
	AlphaVantageKey string  `json:"-"`
}

AgentConfig represents configuration for agents

func DefaultConfig ยถ

func DefaultConfig() *AgentConfig

DefaultConfig returns default agent configuration

type AnalysisRequest ยถ

type AnalysisRequest struct {
	Symbol        string  `json:"symbol"`
	Timeframe     string  `json:"timeframe,omitempty"`
	Capital       float64 `json:"capital,omitempty"`
	RiskTolerance string  `json:"risk_tolerance,omitempty"`
}

AnalysisRequest represents a request to analyze a stock

type AnalysisResponse ยถ

type AnalysisResponse struct {
	Symbol         string                 `json:"symbol"`
	Recommendation string                 `json:"recommendation"`
	Confidence     float64                `json:"confidence"`
	PositionSize   float64                `json:"position_size"`
	StopLoss       float64                `json:"stop_loss"`
	TakeProfit     float64                `json:"take_profit"`
	Reasoning      string                 `json:"reasoning"`
	RiskScore      float64                `json:"risk_score"`
	Reports        map[string]string      `json:"reports"`
	Metadata       map[string]interface{} `json:"metadata"`
	Timestamp      time.Time              `json:"timestamp"`
}

AnalysisResponse represents the response from analysis

type MarketData ยถ

type MarketData struct {
	Symbol    string             `json:"symbol"`
	Price     float64            `json:"price"`
	Change    float64            `json:"change"`
	ChangeP   float64            `json:"change_percent"`
	Volume    int64              `json:"volume"`
	OHLC      OHLC               `json:"ohlc"`
	Timestamp time.Time          `json:"timestamp"`
	Extra     map[string]float64 `json:"extra"`
}

MarketData represents market data for a symbol

type NewsItem ยถ

type NewsItem struct {
	Title       string    `json:"title"`
	Source      string    `json:"source"`
	URL         string    `json:"url"`
	PublishedAt time.Time `json:"published_at"`
	Summary     string    `json:"summary"`
	Sentiment   string    `json:"sentiment"` // "positive", "negative", "neutral"
}

NewsItem represents a news article

type OHLC ยถ

type OHLC struct {
	Open  float64 `json:"open"`
	High  float64 `json:"high"`
	Low   float64 `json:"low"`
	Close float64 `json:"close"`
}

OHLC represents Open, High, Low, Close prices

type TradingAgentsGraph ยถ

type TradingAgentsGraph struct {
	// contains filtered or unexported fields
}

TradingAgentsGraph represents the main trading agents graph

func NewTradingAgentsGraph ยถ

func NewTradingAgentsGraph(config *AgentConfig) (*TradingAgentsGraph, error)

NewTradingAgentsGraph creates a new trading agents graph

func (*TradingAgentsGraph) Analyze ยถ

Analyze executes the full trading analysis pipeline

type TradingState ยถ

type TradingState struct {
	// Input
	Symbol        string  `json:"symbol"`
	Timeframe     string  `json:"timeframe"`      // e.g., "1D", "1H", "5m"
	Capital       float64 `json:"capital"`        // Available capital
	RiskTolerance string  `json:"risk_tolerance"` // "low", "moderate", "high"

	// Market Data
	CurrentPrice    float64            `json:"current_price"`
	MarketData      map[string]float64 `json:"market_data"`          // OHLCV and other metrics
	CompanyInfo     map[string]string  `json:"company_info"`         // Company fundamentals
	NewsHeadlines   []NewsItem         `json:"news_headlines"`       // Recent news
	SocialSentiment map[string]float64 `json:"social_sentiment"`     // Sentiment scores
	TechnicalIndic  map[string]float64 `json:"technical_indicators"` // Technical analysis

	// Analyst Reports
	FundamentalsReport string `json:"fundamentals_report"`
	SentimentReport    string `json:"sentiment_report"`
	NewsReport         string `json:"news_report"`
	TechnicalReport    string `json:"technical_report"`

	// Research Reports
	BullishResearch string `json:"bullish_research"`
	BearishResearch string `json:"bearish_research"`

	// Risk Assessment
	RiskAnalysis string  `json:"risk_analysis"`
	RiskScore    float64 `json:"risk_score"` // 0-100

	// Trading Decision
	Recommendation string  `json:"recommendation"` // "BUY", "SELL", "HOLD"
	Confidence     float64 `json:"confidence"`     // 0-100
	PositionSize   float64 `json:"position_size"`  // Number of shares
	StopLoss       float64 `json:"stop_loss"`      // Stop loss price
	TakeProfit     float64 `json:"take_profit"`    // Take profit price
	Reasoning      string  `json:"reasoning"`      // Detailed explanation

	// Metadata
	Timestamp time.Time              `json:"timestamp"`
	Metadata  map[string]interface{} `json:"metadata"`
}

TradingState represents the state that flows through the agent graph

Directories ยถ

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL