From 98e87e3359a083f81400f17e403c8713a343f1c2 Mon Sep 17 00:00:00 2001 From: gnarayan1 Date: Sat, 6 Dec 2025 09:28:10 -0600 Subject: [PATCH] Added pump detection and moved thigns around --- AGENTS_QUICK_START.md | 206 +++++++++ INTEGRATION_GUIDE.md | 390 +++++++++++++++++ PUMP_DETECTION_GUIDE.md | 320 ++++++++++++++ PUMP_DETECTION_QUICK_REFERENCE.md | 167 +++++++ PUMP_DETECTION_README.md | 411 +++++++++++++++++ integrated_agents_demo.py | 233 ++++++++++ pump_and_trade_workflow.py | 204 +++++++++ pump_detection_demo.py | 165 +++++++ pump_screening.py | 166 +++++++ tradingagents/agents/__init__.py | 5 + tradingagents/agents/screeners/__init__.py | 3 + .../agents/screeners/screening_agent.py | 115 +++++ tradingagents/agents/screening_agent.py | 63 --- .../agents/signal_detectors/__init__.py | 3 + .../signal_detectors/pump_detection_agent.py | 133 ++++++ .../agents/utils/pump_detection_tools.py | 414 ++++++++++++++++++ tradingagents/graph/setup.py | 53 ++- tradingagents/graph/trading_graph.py | 50 ++- 18 files changed, 3030 insertions(+), 71 deletions(-) create mode 100644 AGENTS_QUICK_START.md create mode 100644 INTEGRATION_GUIDE.md create mode 100644 PUMP_DETECTION_GUIDE.md create mode 100644 PUMP_DETECTION_QUICK_REFERENCE.md create mode 100644 PUMP_DETECTION_README.md create mode 100644 integrated_agents_demo.py create mode 100644 pump_and_trade_workflow.py create mode 100644 pump_detection_demo.py create mode 100644 pump_screening.py create mode 100644 tradingagents/agents/screeners/__init__.py create mode 100644 tradingagents/agents/screeners/screening_agent.py delete mode 100644 tradingagents/agents/screening_agent.py create mode 100644 tradingagents/agents/signal_detectors/__init__.py create mode 100644 tradingagents/agents/signal_detectors/pump_detection_agent.py create mode 100644 tradingagents/agents/utils/pump_detection_tools.py diff --git a/AGENTS_QUICK_START.md b/AGENTS_QUICK_START.md new file mode 100644 index 00000000..50ef6dc3 --- /dev/null +++ b/AGENTS_QUICK_START.md @@ -0,0 +1,206 @@ +# Integrated Agents - Quick Start + +## What Changed + +✅ **Screening Agent** - Now a langgraph agent, part of the unified system +✅ **Pump Detection Agent** - Now a langgraph agent, part of the unified system +✅ Both agents work together with existing analysts and researchers +✅ Flexible enabling/disabling via parameters + +## Quick Usage + +### Minimal Example (1 Stock) +```python +from tradingagents.graph.trading_graph import TradingAgentsGraph + +# Create graph +graph = TradingAgentsGraph( + include_pump_detection=True, # Enable pump detection + selected_analysts=["market"], # Just market analyst +) + +# Analyze one stock +final_state, signal = graph.propagate("NVDA", "2025-12-05") + +# Get results +print(final_state.get("pump_report")) # Pump analysis +print(final_state.get("market_report")) # Technical analysis +``` + +### Full Analysis (All Agents) +```python +graph = TradingAgentsGraph( + include_screening=True, # Find candidates + include_pump_detection=True, # Detect pumps + selected_analysts=[ + "market", + "social", + "news", + "fundamentals" + ], +) + +final_state, signal = graph.propagate("NVDA", "2025-12-05") +``` + +### Just Screening +```python +graph = TradingAgentsGraph( + include_screening=True, + selected_analysts=["market"], +) + +# Get screening recommendations +final_state, signal = graph.propagate("NVDA", "2025-12-05") +print(final_state.get("screening_report")) +``` + +## Key Agents + +| Agent | Purpose | Key Tools | Output | +|-------|---------|-----------|--------| +| **Screening** | Find candidates | Market movers, trending, earnings | Ticker list | +| **Pump Detection** | Detect pre-pumps | Volume, price, social, RSI, catalyst | Pump score 0-100 | +| **Market** | Technical analysis | RSI, MACD, moving averages | Technical trends | +| **Social** | Sentiment | Social media mentions | Sentiment report | +| **News** | News sentiment | News, insider activity | News impact | +| **Fundamentals** | Financial analysis | P/E, growth, statements | Financial health | +| **Bull/Bear** | Debate | Analysis synthesis | Perspectives | +| **Research Manager** | Synthesize | Bull/bear debate | Investment decision | +| **Trader** | Trade plan | Decision | Entry/stop/target | +| **Risk** | Risk assess | Trade plan | Final decision | + +## State Keys + +```python +{ + # Inputs + "company_of_interest": "NVDA", + "trade_date": "2025-12-05", + + # Optional outputs + "screening_report": "...", # If include_screening=True + "pump_report": "...", # If include_pump_detection=True + "market_report": "...", # If "market" in selected_analysts + "sentiment_report": "...", # If "social" in selected_analysts + "news_report": "...", # If "news" in selected_analysts + "fundamentals_report": "...", # If "fundamentals" in selected_analysts + + # Always present + "final_trade_decision": "BUY/HOLD/SELL", + "trader_investment_plan": "Entry: $100, Stop: $97, Target: $105", +} +``` + +## Parameters + +```python +TradingAgentsGraph( + selected_analysts=["market", "social", "news", "fundamentals"], # Which analysts to use + debug=False, # Show detailed agent reasoning + config=None, # Custom config dict + include_screening=False, # Enable screening agent + include_pump_detection=False, # Enable pump detection agent +) +``` + +## Execution Flow + +``` +START + │ + ├─ Screening Agent (if enabled) + │ └─ Returns: Candidate stocks + │ + ├─ Pump Detection Agent (if enabled) + │ └─ Returns: Pump score 0-100 + │ + ├─ Analysts (market, social, news, fundamentals) + │ ├─ Market Analyst → technical trends + │ ├─ Social Analyst → sentiment + │ ├─ News Analyst → news impact + │ └─ Fundamentals Analyst → financial health + │ + ├─ Researchers (Bull + Bear) + │ ├─ Bull Researcher → bullish case + │ └─ Bear Researcher → bearish case + │ + ├─ Research Manager + │ └─ Synthesizes → Investment decision + │ + ├─ Trader + │ └─ Creates → Trading plan + │ + ├─ Risk Managers (Risky, Neutral, Safe) + │ └─ Final risk → Assessment + │ + └─ END (returns final_trade_decision) +``` + +## Common Use Cases + +### Case 1: Find and Analyze Pump Candidates +```python +graph = TradingAgentsGraph( + include_screening=True, + include_pump_detection=True, +) +# Screening finds candidates, pump detection scores them +``` + +### Case 2: Quick Technical Analysis +```python +graph = TradingAgentsGraph( + selected_analysts=["market"], +) +# Fast technical analysis only +``` + +### Case 3: Deep Fundamental Research +```python +graph = TradingAgentsGraph( + selected_analysts=["fundamentals", "news", "market"], +) +# Focus on fundamentals with supporting analysis +``` + +### Case 4: Full Due Diligence +```python +graph = TradingAgentsGraph( + include_screening=True, + include_pump_detection=True, + selected_analysts=["market", "social", "news", "fundamentals"], +) +# Complete analysis: screening → detection → analysis → decision +``` + +## Files to Know + +- `tradingagents/agents/screening_agent.py` - Screening agent +- `tradingagents/agents/pump_detection_agent.py` - Pump detection agent +- `tradingagents/graph/trading_graph.py` - Main graph orchestrator +- `tradingagents/graph/setup.py` - Graph setup and flow +- `INTEGRATION_GUIDE.md` - Full integration documentation +- `PUMP_DETECTION_GUIDE.md` - Pump detection details +- `integrated_agents_demo.py` - Architecture demo + +## Troubleshooting + +**"ModuleNotFoundError"** - Ensure agents are imported in `__init__.py` + +**"Node not found"** - Check `setup_graph()` includes the agent + +**"Tool not found"** - Verify tool is added to tool node + +**Slow execution** - Normal: ~30sec-2min total, disable debug mode + +**API errors** - Use yfinance (free) instead of Alpha Vantage + +## Next Steps + +1. Read `INTEGRATION_GUIDE.md` for full details +2. Run `python integrated_agents_demo.py` to see architecture +3. Start with one agent, add more as needed +4. Customize agents for your trading strategy + +Happy trading! 🚀 diff --git a/INTEGRATION_GUIDE.md b/INTEGRATION_GUIDE.md new file mode 100644 index 00000000..27e6a694 --- /dev/null +++ b/INTEGRATION_GUIDE.md @@ -0,0 +1,390 @@ +# Integrated Agentic Architecture - Implementation Guide + +## Overview + +The screening and pump detection agents have been fully integrated into your langgraph-based agentic architecture. They now work alongside all existing agents (market analyst, bull/bear researchers, traders, risk managers, etc.) as part of a unified multi-agent system. + +## Architecture + +### Agent Hierarchy + +``` +START + ├─ Screening Agent (Optional) + │ ├─ Uses: Market Movers, Earnings Calendar, Trending Social, Insider Activity + │ └─ Output: Stock candidates for deeper analysis + │ + ├─ Pump Detection Agent (Optional) + │ ├─ Uses: Volume Spike, Price Acceleration, Social Sentiment, RSI, Catalysts + │ └─ Output: Pump probability score (0-100) + │ + ├─ Market Analyst + │ └─ Technical analysis: RSI, MACD, Moving Averages + │ + ├─ Social Media Analyst + │ └─ Sentiment analysis: Reddit, Twitter, StockTwits + │ + ├─ News Analyst + │ └─ News sentiment: Recent news, insider activity + │ + ├─ Fundamentals Analyst + │ └─ Financial analysis: P/E, Growth, Statements + │ + ├─ Bull Researcher + │ └─ Bullish thesis based on all findings + │ + ├─ Bear Researcher + │ └─ Bearish thesis based on all findings + │ + ├─ Research Manager + │ └─ Synthesizes debate into investment recommendation + │ + ├─ Trader + │ └─ Creates trading plan (entry, stop, targets) + │ + └─ Risk Managers (Risky/Neutral/Safe) + └─ Final risk-adjusted decision +END +``` + +## Files Modified + +1. **tradingagents/agents/screening_agent.py** + - Updated to follow langgraph pattern + - Exports `create_screening_agent()` function + - Integrates with agent state + +2. **tradingagents/agents/pump_detection_agent.py** + - Updated to follow langgraph pattern + - Exports `create_pump_detection_agent()` function + - Integrates with agent state + +3. **tradingagents/agents/__init__.py** + - Added exports for screening and pump detection agents + +4. **tradingagents/graph/trading_graph.py** + - Added pump detection tool imports + - Added screening and pump detection tool nodes + - Added `include_screening` parameter + - Added `include_pump_detection` parameter + +5. **tradingagents/graph/setup.py** + - Updated `setup_graph()` to accept new agent flags + - Integrated agents into graph flow + - Added conditional edges for optional agents + +## Usage + +### Basic Usage - All Agents + +```python +from tradingagents.graph.trading_graph import TradingAgentsGraph + +# Create graph with ALL agents (screening, pump detection, analysts, researchers, traders) +graph = TradingAgentsGraph( + selected_analysts=["market", "social", "news", "fundamentals"], + include_screening=True, + include_pump_detection=True, +) + +# Run analysis +ticker = "NVDA" +trade_date = "2025-12-05" +final_state, signal = graph.propagate(ticker, trade_date) + +# Access results +print(f"Pump Report: {final_state.get('pump_report')}") +print(f"Screening Report: {final_state.get('screening_report')}") +print(f"Final Decision: {final_state.get('final_trade_decision')}") +``` + +### Usage - Pump Detection Only + +```python +graph = TradingAgentsGraph( + include_pump_detection=True, + # Skip screening, but keep analysis agents + selected_analysts=["market", "social", "news", "fundamentals"], +) + +final_state, signal = graph.propagate("NVDA", "2025-12-05") +``` + +### Usage - Screening Only + +```python +graph = TradingAgentsGraph( + include_screening=True, + selected_analysts=["market"], # Minimal analysis +) + +# Get screening recommendations +screening_output = final_state.get('screening_report') +``` + +### Usage - Original Graph (No Screening/Pump Detection) + +```python +graph = TradingAgentsGraph( + # Defaults: include_screening=False, include_pump_detection=False + selected_analysts=["market", "social", "news", "fundamentals"], +) + +final_state, signal = graph.propagate("NVDA", "2025-12-05") +``` + +## Agent Descriptions + +### Screening Agent +- **Purpose**: Scans the market for interesting stock candidates +- **Tools**: get_market_movers, get_earnings_calendar, get_insider_transactions, get_indicators, get_trending_social +- **Output**: Comma-separated list of recommended tickers +- **When to Use**: First step in market scanning +- **Enabled By**: `include_screening=True` + +### Pump Detection Agent +- **Purpose**: Analyzes stocks for pre-pump signals +- **Tools**: detect_volume_spike, detect_price_acceleration, detect_social_sentiment_surge, detect_oversold_bounce, detect_catalyst_event, calculate_pump_score +- **Output**: Pump probability score (0-100) with risk assessment +- **When to Use**: For momentum/swing trading opportunities +- **Enabled By**: `include_pump_detection=True` + +### Market Analyst +- **Purpose**: Technical analysis +- **Tools**: get_stock_data, get_indicators +- **Output**: Technical trends and signals + +### Social Media Analyst +- **Purpose**: Social sentiment analysis +- **Tools**: get_news (for social mentions) +- **Output**: Sentiment report from social media + +### News Analyst +- **Purpose**: News and insider sentiment +- **Tools**: get_news, get_global_news, get_insider_sentiment, get_insider_transactions +- **Output**: News impact and insider activity report + +### Fundamentals Analyst +- **Purpose**: Company fundamental analysis +- **Tools**: get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement +- **Output**: Financial health and growth analysis + +### Bull Researcher +- **Purpose**: Builds bullish investment case +- **Input**: All analyst reports +- **Output**: Bullish thesis and recommendations + +### Bear Researcher +- **Purpose**: Builds bearish investment case +- **Input**: All analyst reports +- **Output**: Bearish thesis and concerns + +### Research Manager +- **Purpose**: Synthesizes bull/bear debate +- **Input**: Bull and bear perspectives +- **Output**: Final investment recommendation (BUY/HOLD/SELL) + +### Trader +- **Purpose**: Creates trading execution plan +- **Input**: Investment recommendation +- **Output**: Entry price, stop loss, profit targets, position sizing + +### Risk Managers +- **Purpose**: Final risk assessment +- **Input**: Trading plan +- **Output**: Risk-adjusted final decision + +## State Keys + +The unified `AgentState` contains: + +```python +{ + "messages": [...], # Conversation history + "company_of_interest": "NVDA", # Ticker symbol + "trade_date": "2025-12-05", # Analysis date + + # Optional agent outputs + "screening_report": "...", # From Screening Agent + "pump_report": "...", # From Pump Detection Agent + + # Analyst outputs + "market_report": "...", # From Market Analyst + "sentiment_report": "...", # From Social Analyst + "news_report": "...", # From News Analyst + "fundamentals_report": "...", # From Fundamentals Analyst + + # Debate and decision + "investment_debate_state": {...}, # Bull vs Bear debate + "trader_investment_plan": "...", # From Trader + "risk_debate_state": {...}, # Risk assessment + "final_trade_decision": "...", # Final recommendation +} +``` + +## Tool Nodes in Graph + +### Tools Available by Node Type + +**market_tools**: get_stock_data, get_indicators + +**social_tools**: get_news + +**news_tools**: get_news, get_global_news, get_insider_sentiment, get_insider_transactions + +**fundamentals_tools**: get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement + +**screening_tools**: get_market_movers, get_earnings_calendar, get_insider_transactions, get_indicators, get_trending_social + +**pump_detection_tools**: detect_volume_spike, detect_price_acceleration, detect_social_sentiment_surge, detect_oversold_bounce, detect_catalyst_event, calculate_pump_score + +## Conditional Logic + +The graph uses conditional edges to: + +1. **Skip screening/pump detection** if not enabled +2. **Route to next agent** after each analysis +3. **Continue debate** between bull/bear researchers +4. **Finalize decision** through risk managers + +## Integration Points + +### Adding Custom Agents + +To add your own agent to the architecture: + +1. **Create agent function** in `tradingagents/agents/custom_agent.py`: +```python +def create_custom_agent(llm): + def custom_agent_node(state): + # Your agent logic + return {"messages": state["messages"] + [result]} + return custom_agent_node +``` + +2. **Export from `__init__.py`**: +```python +from .custom_agent import create_custom_agent +__all__ = [..., "create_custom_agent"] +``` + +3. **Add to graph setup**: +```python +graph_setup.setup_graph( + selected_analysts=["market"], + include_custom_agent=True, # Add your flag +) +``` + +### Adding Custom Tools + +To add tools available to all agents: + +1. **Create tool** in `tradingagents/agents/utils/`: +```python +@tool +def my_custom_tool(...): + """Tool description""" + return result +``` + +2. **Add to tool node** in `trading_graph.py`: +```python +def _create_tool_nodes(self): + return { + "market": ToolNode([get_stock_data, my_custom_tool]), + ... + } +``` + +## Testing + +### Run Integrated Demo + +```bash +python integrated_agents_demo.py +``` + +Shows architecture overview and usage examples. + +### Run Full Analysis + +```bash +from tradingagents.graph.trading_graph import TradingAgentsGraph + +graph = TradingAgentsGraph( + include_screening=True, + include_pump_detection=True, + selected_analysts=["market", "social", "news", "fundamentals"], + debug=True, # Enable debug mode to see agent thinking +) + +final_state, signal = graph.propagate("NVDA", "2025-12-05") +``` + +## Performance Considerations + +1. **Agent Execution Time**: Each agent runs sequentially, adding ~5-30 seconds per agent +2. **Total Time Estimate**: + - Screening: 10-20 seconds + - Pump Detection: 10-20 seconds + - Each Analyst: 10-20 seconds + - Researchers/Traders: 10-20 seconds + - **Total**: 1-4 minutes for full analysis + +3. **API Calls**: Each agent may call multiple APIs (yfinance, Alpha Vantage, etc.) + +4. **Optimization**: Set `debug=False` to skip verbose output + +## Troubleshooting + +### "Agent not found" Error +- Check agent is exported from `agents/__init__.py` +- Verify parameter name matches (e.g., `include_pump_detection`) + +### Missing Tool Error +- Ensure tool node is created in `_create_tool_nodes()` +- Verify tool is imported at top of file + +### State Key Error +- Agent results are stored with specific keys (e.g., `pump_report`) +- Check key name matches agent output + +### API Errors +- Ensure API keys are set (Alpha Vantage, etc.) +- Fall back to yfinance (free, no key needed) +- Check internet connection + +## Best Practices + +1. **Start Simple**: Enable one agent at a time to debug +2. **Use Debug Mode**: Set `debug=True` to see agent reasoning +3. **Monitor Performance**: Track execution time, adjust as needed +4. **Validate Results**: Check outputs make sense before trading +5. **Combine Signals**: Use multiple agent perspectives for better decisions +6. **Document Decisions**: Log final recommendations for analysis + +## Summary + +You now have a fully integrated multi-agent system where: + +✅ **Screening Agent** finds opportunities market-wide +✅ **Pump Detection Agent** spots pre-pump signals +✅ **Analysis Agents** provide technical, social, news, fundamental insights +✅ **Research Agents** debate bull vs bear perspectives +✅ **Trading Agent** creates execution plans +✅ **Risk Managers** ensure proper risk management +✅ **All agents share state** and build on each other's analysis +✅ **Flexible architecture** lets you enable/disable agents as needed + +This creates a sophisticated multi-perspective trading analysis system that combines: +- Market screening +- Momentum detection +- Technical analysis +- Social sentiment +- News analysis +- Fundamentals +- Debate and consensus +- Risk management + +All working together in a unified langgraph-based agentic framework! diff --git a/PUMP_DETECTION_GUIDE.md b/PUMP_DETECTION_GUIDE.md new file mode 100644 index 00000000..c9eddb30 --- /dev/null +++ b/PUMP_DETECTION_GUIDE.md @@ -0,0 +1,320 @@ +# Pump Detection System + +## Overview + +The **Pump Detection System** identifies stocks likely to experience sudden price increases (pumps) BEFORE they happen. This gives you early entry opportunities to profit from momentum moves. + +## What is a "Pump"? + +A pump is a rapid, significant increase in stock price driven by: +- **Volume surge** - Abnormal trading activity (2-10x average volume) +- **Price acceleration** - Quick gains over 1-3 days (5-50% moves) +- **Social buzz** - Heavy discussion on Reddit, Twitter, StockTwits +- **Technical setup** - Stocks bouncing from oversold conditions (RSI < 30) +- **Catalysts** - Upcoming earnings, FDA approval, partnership news + +The key to profiting is **identifying these signals BEFORE the pump starts**, not chasing after it's already up 50%. + +## How the Detection Works + +### Detection Methods + +The system uses **5 complementary detection strategies**: + +#### 1. Volume Spike Detection +- **What it detects**: Abnormal increase in trading volume +- **Signal**: Volume > 2x average (configurable) +- **Interpretation**: Increased institutional/retail interest, often precedes price moves +- **Tool**: `detect_volume_spike(symbol, curr_date, look_back_days=20, threshold_multiplier=2.0)` + +#### 2. Price Acceleration +- **What it detects**: Rapid price gains in recent period +- **Signal**: Recent gains > 5% AND recent gains > 1.5x older gains +- **Interpretation**: Momentum building, potential pump in progress or starting +- **Tool**: `detect_price_acceleration(symbol, curr_date, look_back_days=10)` + +#### 3. Social Sentiment Surge +- **What it detects**: Spike in social media mentions and sentiment +- **Signal**: Stock in top trending list on Reddit/Twitter/StockTwits +- **Interpretation**: Retail hype building, retail money may follow +- **Tool**: `detect_social_sentiment_surge(symbol, curr_date)` + +#### 4. Oversold Bounce Setup +- **What it detects**: Stocks bouncing from oversold technical conditions +- **Signal**: RSI < 30 (indicator of oversold) +- **Interpretation**: High probability bounce/reversal, often with strong moves +- **Tool**: `detect_oversold_bounce(symbol, curr_date, rsi_threshold=30)` + +#### 5. Catalyst Events +- **What it detects**: Upcoming earnings, FDA approvals, partnerships, etc. +- **Signal**: Major event within 3 months +- **Interpretation**: Catalyst drives speculation and trading volume +- **Tool**: `detect_catalyst_event(symbol, curr_date)` + +### Pump Score Calculation + +All signals are combined into a **Pump Probability Score (0-100)**: + +``` +Score = 25% (Volume) + 20% (Price) + 15% (Social) + 20% (Technical) + 20% (Catalyst) +``` + +**Score Interpretation**: +- **70+**: 🔴 **VERY HIGH** pump probability → Strong entry candidate +- **50-69**: 🟠 **HIGH** pump probability → Good entry with risk management +- **30-49**: 🟡 **MODERATE** pump probability → Wait for confirmation +- **<30**: 🟢 **LOW** pump probability → No pump signals detected + +## Usage + +### Quick Demo (with cached data) + +```bash +python pump_detection_demo.py +``` + +This analyzes cached stock files and shows pump detection scores. + +### Live Pump Screening (requires data sources) + +#### Analyze specific stock: +```bash +python pump_screening.py --ticker NVDA +``` + +#### Analyze specific date: +```bash +python pump_screening.py --ticker TSLA --date 2025-12-05 +``` + +#### Full market screening (find pump candidates): +```bash +python pump_screening.py +``` + +### In Your Trading Agent Code + +```python +from tradingagents.agents.pump_detection_agent import create_pump_detection_agent +from tradingagents.agents.utils.pump_detection_tools import ( + detect_volume_spike, + detect_price_acceleration, + detect_social_sentiment_surge, + detect_oversold_bounce, + detect_catalyst_event, + calculate_pump_score, +) + +# Create agent +pump_detector = create_pump_detection_agent(llm) + +# Use in workflow +state = { + "messages": [], + "ticker": "NVDA", + "trade_date": "2025-12-05", +} +result = pump_detector(state) +``` + +## Pump Trading Strategy + +### Entry Rules + +1. **Pump Score >= 50**: Consider entry +2. **Multiple signals confirmed**: Volume + Price Acceleration = strong signal +3. **Early position**: Enter in first 5-15% of move +4. **Small size**: 1-2% of portfolio max per trade + +### Position Management + +``` +Entry Price: $100 +Stop Loss: $97-98 (2-3% below entry) +Target 1: $105 (5% profit) +Target 2: $110 (10% profit) +Target 3: $115+ (15%+ profit) +``` + +### Exit Rules + +- **❌ Exit on Stop Loss**: Hard stop at 2-3% loss +- **❌ Exit on Volume Collapse**: If volume drops 50%, pump ending +- **❌ Exit at Resistance**: Price hitting resistance level +- **✅ Exit at Targets**: Take profits at 5-10% gains +- **⏸️ Trail Stop**: Move stop to breakeven once +5% profit achieved + +## Risk Management + +### ⚠️ Critical Rules + +1. **Position Size**: Never more than 1-2% per pump trade +2. **Stop Loss**: ALWAYS set at entry, no exceptions +3. **Risk/Reward Ratio**: Min 1:2 (risk $1 to make $2) +4. **Diversification**: Max 3-4 pump trades simultaneously +5. **Account Allocation**: Max 5-10% of portfolio in pump trades total + +### Avoid These + +- 🚫 **Chasing after 50% gains** - Too late, dumpers coming +- 🚫 **No stop loss** - Pump can reverse quickly +- 🚫 **All-in positions** - One bad pump wipes account +- 🚫 **Holding overnight** - Pumps can reverse in minutes +- 🚫 **Ignoring volume** - Volume collapse = pump ending +- 🚫 **Fighting the trend** - Don't short pumps, ride them + +## Pump vs Pump-and-Dump Warning Signs + +### Legitimate Pump (Good for trading) +- ✅ Supported by volume surge +- ✅ Following technical setup (oversold bounce) +- ✅ Has catalyst event +- ✅ Social sentiment building gradually +- ✅ Price holds gains or consolidates + +### Pump-and-Dump (Dangerous - AVOID) +- ⚠️ Extreme volume spike (5-10x+) +- ⚠️ Penny stock with low liquidity +- ⚠️ Coordinated social media push +- ⚠️ Insider selling after spike +- ⚠️ No fundamental reason for move +- ⚠️ Stock drops 50%+ within days + +**Protection**: Use the `detect_pump_and_dump_risk()` tool before entry. + +## Available Tools + +### Core Detection Tools + +| Tool | Purpose | Usage | +|------|---------|-------| +| `detect_volume_spike()` | Find abnormal volume | Identify interest surge | +| `detect_price_acceleration()` | Find rapid gains | Confirm momentum building | +| `detect_social_sentiment_surge()` | Find social buzz | Track retail interest | +| `detect_oversold_bounce()` | Find technical setup | Identify bounce candidates | +| `detect_catalyst_event()` | Find catalysts | Find event-driven moves | +| `calculate_pump_score()` | Calculate probability | Score all signals | + +### Agent + +| Agent | Purpose | +|-------|---------| +| `create_pump_detection_agent()` | Full pump detection analysis | +| `create_screening_agent()` | Market screening for pump candidates | + +## Examples + +### Example 1: High Probability Pump + +``` +🎯 Stock: NVDA + +✅ Volume Spike: 3.2x average - DETECTED +✅ Price Acceleration: +12% in 2 days - DETECTED +✅ Social Buzz: Top 5 trending on Reddit - DETECTED +❌ Oversold Bounce: RSI 65 - Not oversold +✅ Catalyst: Earnings next week - DETECTED + +Pump Score: 78/100 (VERY HIGH) +Recommendation: STRONG BUY SIGNAL +Entry: Now with 2% stop loss +Targets: $1000, $1050, $1100+ +``` + +### Example 2: Weak Pump Signal + +``` +🎯 Stock: XYZ + +❌ Volume Spike: 1.1x average - Not detected +❌ Price Acceleration: +0.5% - Not detected +✅ Social Buzz: Mentioned on social - DETECTED +✅ Oversold Bounce: RSI 25 - DETECTED +❌ Catalyst: None upcoming - None + +Pump Score: 35/100 (MODERATE - WAIT) +Recommendation: HOLD - Wait for volume confirmation +Monitor: Watch for volume spike as entry trigger +``` + +## Troubleshooting + +### "All vendor attempts failed" +- Ensure API keys are set (Alpha Vantage) +- Or ensure cached data exists +- Run `python main_screening.py` first to cache data + +### "Insufficient data" +- Stock needs at least 5 days of historical data +- Use longer look_back_days for new stocks + +### No social buzz detected +- API rate limits reached +- Stock may not be discussed enough +- Try again after cool-down period + +## Best Practices + +1. **Always backtest** your pump detection settings +2. **Start small** with 0.5-1% position size +3. **Monitor continuously** - don't leave pump trades unattended +4. **Keep a trading journal** - track which signals work best +5. **Use trailing stops** - protect profits as pump develops +6. **Combine with other analysis** - don't rely solely on pump detection +7. **Review losses** - learn from failed pump trades + +## Advanced Customization + +### Adjust Detection Thresholds + +```python +from tradingagents.agents.utils.pump_detection_tools import detect_volume_spike + +# More aggressive (2x volume threshold) +result = detect_volume_spike.invoke({ + "symbol": "NVDA", + "curr_date": "2025-12-05", + "threshold_multiplier": 2.0, # Default +}) + +# More conservative (3x volume threshold) +result = detect_volume_spike.invoke({ + "symbol": "NVDA", + "curr_date": "2025-12-05", + "threshold_multiplier": 3.0, +}) +``` + +### Custom Score Weights + +Edit `tradingagents/agents/utils/pump_detection_tools.py`: + +```python +weights = { + "volume_spike": 40, # Increase from 25 to 40 + "price_acceleration": 20, + "social_sentiment": 10, # Decrease from 15 to 10 + "oversold_bounce": 20, + "catalyst": 10, # Decrease from 20 to 10 +} +``` + +## Support & Questions + +For issues or questions: +1. Check the troubleshooting section above +2. Review the examples +3. Check cached data files exist in `tradingagents/dataflows/data_cache/` +4. Review error messages in terminal output + +## Disclaimer + +⚠️ **Pump trading is HIGH RISK**. Stocks can: +- Drop as fast as they rose +- Get halted by SEC +- Be delisted +- Never recover + +This system is for **experienced traders only**. Use strict risk management and never trade more than you can afford to lose. + +**Past performance does not guarantee future results.** diff --git a/PUMP_DETECTION_QUICK_REFERENCE.md b/PUMP_DETECTION_QUICK_REFERENCE.md new file mode 100644 index 00000000..483a878d --- /dev/null +++ b/PUMP_DETECTION_QUICK_REFERENCE.md @@ -0,0 +1,167 @@ +# Pump Detection Quick Reference + +## 🚀 What's a Pump? +Rapid price increase driven by volume spike, momentum, social buzz, or technical setup. Goal: Enter BEFORE the move, not after. + +## 📊 Detection Methods (5-in-1) + +| Signal | Threshold | Weight | What It Means | +|--------|-----------|--------|--------------| +| **Volume Spike** | 2x+ average | 25% | Massive interest surge | +| **Price Acceleration** | 5%+ recent | 20% | Momentum building | +| **Social Buzz** | Top trending | 15% | Retail FOMO starting | +| **Oversold Bounce** | RSI < 30 | 20% | Bounce potential high | +| **Catalyst Event** | Within 3mo | 20% | Event-driven pump | + +## 🎯 Score = Action + +| Score | Signal | Action | +|-------|--------|--------| +| 70+ | 🔴 VERY HIGH | BUY - Strong entry | +| 50-69 | 🟠 HIGH | BUY - Risk mgmt | +| 30-49 | 🟡 MODERATE | WAIT - Need confirmation | +| <30 | 🟢 LOW | SKIP - No signals | + +## 💰 Position Management + +``` +Position Size: 1-2% max per trade +Stop Loss: 2-3% below entry (HARD STOP) +Target 1: 5% profit → Move stop to +2% +Target 2: 10% profit → Reduce to 50% +Target 3: 15%+ profit → Let winners run +``` + +## ⚠️ Critical Rules (DO THIS) + +✅ Always set stop loss at entry +✅ Use small position sizes (1-2%) +✅ Exit on volume collapse +✅ Trail stops as profit grows +✅ Keep pump trades separate (max 5-10% portfolio) + +## 🚫 Never Do This + +❌ Chase after 50%+ gains +❌ Trade without stop loss +❌ All-in on pump trades +❌ Hold overnight (dump at open) +❌ Ignore volume decline +❌ Use margin on pumps +❌ Fight the momentum + +## 🛠️ Quick Commands + +```bash +# Demo analysis (cached data) +python pump_detection_demo.py + +# Analyze one stock +python pump_screening.py --ticker NVDA + +# Analyze on specific date +python pump_screening.py --ticker TSLA --date 2025-12-05 + +# Full market screening +python pump_screening.py +``` + +## 🎓 Pump Lifecycle + +``` +1. Oversold (RSI < 30) or Beaten Down + ↓ +2. Volume Spike (2x+ average) + ↓ +3. Price Acceleration (5-10% in 1-3 days) + ↓ +4. Social Buzz Builds (Reddit, Twitter) + ↓ +5. Peak Euphoria (80-100% move) + ↓ +6. Exhaustion (volume drops) + ↓ +7. Crash (50%+ loss in hours) +``` + +**BEST ENTRY**: Between steps 1-3 +**WORST ENTRY**: Steps 5-6 (too late!) +**BEST EXIT**: Step 4-5 (take profits before crash) + +## 🚨 Pump-and-Dump Red Flags + +These are DANGEROUS - AVOID: +- Penny stock (< $5) +- Extreme volume (10x+) +- Coordinated social hype +- Insider selling at peak +- No fundamental reason +- Stock already up 100%+ + +## 📈 Real Example + +**Date**: Dec 5, 2025 +**Stock**: NVDA + +``` +Volume: 3.2x average ✅ +Price: +12% this week ✅ +Social: #1 trending ✅ +RSI: 65 (not oversold) ❌ +Earnings: Next week ✅ + +SCORE: 78/100 = BUY SIGNAL + +Entry: $950 +Stop: $926 (2.5%) +Target 1: $997 (5%) +Target 2: $1045 (10%) +Target 3: $1100+ (15%+) +``` + +## 💡 Pro Tips + +1. **Early volume matters most** - First 30min spike is key indicator +2. **Social buzz = retail pump** - Instagram/TikTok = next wave +3. **Oversold bounces work best** - RSI < 20 = strong setup +4. **Catalysts amplify moves** - Earnings = bigger pump +5. **Profit in first 5-10%** - Most gains happen there +6. **Volume confirmation = stay** - Fading volume = exit +7. **Scalp multiple times** - Take 2-3% gains repeatedly +8. **Time decay** - Pumps usually done in 1-3 days + +## 📋 Pre-Entry Checklist + +Before entering ANY pump trade: + +- [ ] Pump score ≥ 50? +- [ ] Volume spike confirmed? +- [ ] Stop loss set (2-3%)? +- [ ] Position size ≤ 2%? +- [ ] Total pump allocation ≤ 10%? +- [ ] No overnight holds planned? +- [ ] Exit plan written down? +- [ ] Ready to monitor 24/7? + +## 🔗 Related Tools + +- `detect_volume_spike()` - Find volume surge +- `detect_price_acceleration()` - Find momentum +- `detect_social_sentiment_surge()` - Find buzz +- `detect_oversold_bounce()` - Find setup +- `detect_catalyst_event()` - Find catalysts +- `calculate_pump_score()` - Get final score + +## 📞 When to Skip + +- Stock halted by SEC +- Volume is only <1.5x +- No catalyst visible +- Been pumping for 5+ days +- Already up 200%+ +- Can't set stop loss +- Feel "FOMO" (Sell signal!) + +--- + +**Remember**: Discipline beats emotion. Stick to rules. Pump trading is HIGH RISK. Size appropriately. diff --git a/PUMP_DETECTION_README.md b/PUMP_DETECTION_README.md new file mode 100644 index 00000000..070a3d9b --- /dev/null +++ b/PUMP_DETECTION_README.md @@ -0,0 +1,411 @@ +# Pump Detection System - Complete Setup Guide + +## 📚 What You Get + +A complete **AI-powered pump detection system** that identifies stocks likely to pump BEFORE they happen. Get early entry into momentum moves and ride them for 5-50%+ gains. + +### Files Created + +``` +📁 Core System +├── tradingagents/agents/pump_detection_agent.py # Main agent +├── tradingagents/agents/utils/pump_detection_tools.py # Detection tools +│ +📁 Scripts & Tools +├── pump_screening.py # Live pump detection +├── pump_detection_demo.py # Demo with cached data +├── pump_and_trade_workflow.py # Integrated trading workflow +│ +📁 Documentation +├── PUMP_DETECTION_GUIDE.md # Full guide (you are here) +├── PUMP_DETECTION_QUICK_REFERENCE.md # Quick cheat sheet +└── README.md # This file +``` + +## 🚀 Quick Start + +### 1. Test with Demo (No API Keys Needed) + +```bash +# Analyzes cached stock data with pump detection +python pump_detection_demo.py +``` + +**Output**: Pump detection scores for available cached stocks. + +### 2. Analyze Specific Stock + +```bash +# Requires yfinance or Alpha Vantage API +python pump_screening.py --ticker NVDA --date 2025-12-05 +``` + +**Output**: Full pump analysis with score, signals, and trading recommendation. + +### 3. Screen Full Market + +```bash +# Scans for pump candidates, then analyzes top picks +python pump_screening.py +``` + +**Output**: Market screening results + pump scores for top candidates. + +### 4. Integrated Pump + Trade Workflow + +```bash +# Detect pumps, then run full trading analysis +python pump_and_trade_workflow.py --tickers NVDA TSLA AMD --mode pump_first +``` + +**Output**: Pump detection + technical + fundamental analysis + trading signals. + +## 🎯 How It Works + +### Detection Strategy + +The system uses **5 complementary signals**: + +``` +1. Volume Spike (25%) → Is volume 2x+ average? +2. Price Acceleration (20%) → Are recent gains > 5%? +3. Social Sentiment (15%) → Is stock trending online? +4. Oversold Bounce (20%) → Is RSI < 30 (bounce setup)? +5. Catalyst Events (20%) → Any catalyst (earnings, news)? + ───────────────── + PUMP SCORE (0-100) +``` + +### Score Interpretation + +| Score | Signal | Action | +|-------|--------|--------| +| **70+** | 🔴 VERY HIGH | BUY NOW | +| **50-69** | 🟠 HIGH | BUY with caution | +| **30-49** | 🟡 MODERATE | WAIT for confirmation | +| **<30** | 🟢 LOW | SKIP | + +## 💰 Trading Strategy + +### Entry Setup + +``` +Stock Score: >= 50 +Position Size: 1-2% of portfolio +Stop Loss: 2-3% below entry +Target 1: 5% gain +Target 2: 10% gain +Target 3: 15%+ gain +``` + +### Position Management + +``` +Entry at $100 +├─ Stop Loss: $97-98 (Hard stop, no exceptions!) +├─ Target 1: $105 (5%) → Move stop to +2% +├─ Target 2: $110 (10%) → Reduce to 50% position +└─ Target 3: $115+ (15%+) → Trail stop upward +``` + +### Exit Rules + +Exit when: +- ❌ Stop loss hit (2-3% loss) +- ❌ Volume collapse (50% drop) +- ❌ Price hits resistance +- ✅ Profit target reached +- ⏳ Pump shows exhaustion (5+ days) + +## ⚠️ Critical Rules + +### DO THIS ✅ + +- ✅ Always set stop loss at entry +- ✅ Use small position sizes (1-2%) +- ✅ Monitor continuously (don't leave unattended) +- ✅ Exit on volume decline +- ✅ Use trailing stops for protection +- ✅ Keep pump trades separate (max 5-10% portfolio) +- ✅ Take profits early (5-10% is good) + +### NEVER DO THIS ❌ + +- ❌ Chase after 50%+ gains +- ❌ Trade without stop loss +- ❌ All-in on pump trades +- ❌ Hold overnight (dump at open) +- ❌ Ignore volume decline +- ❌ Use margin +- ❌ Fight the momentum + +## 🛠️ Setup Requirements + +### Minimum (Demo Only) + +- Python 3.10+ +- LangChain installed +- Cached stock data (auto-generated from `main_screening.py`) + +```bash +python pump_detection_demo.py # No API keys needed! +``` + +### Full System (Live Trading) + +#### Option A: yfinance (Recommended - Free) + +```bash +pip install yfinance +# No API key needed, just works! +python pump_screening.py --ticker NVDA +``` + +#### Option B: Alpha Vantage (More data) + +```bash +pip install alpha-vantage +export ALPHA_VANTAGE_API_KEY="your_key_here" +python pump_screening.py --ticker NVDA +``` + +Get free API key: https://www.alphavantage.co/ + +## 📊 Example Analysis + +### Example 1: High Pump Probability + +``` +Stock: NVDA (2025-12-05) + +Volume Spike: 3.2x average ✅ (+25 points) +Price Acceleration: +12% in 2 days ✅ (+20 points) +Social Buzz: #1 trending ✅ (+15 points) +Oversold Bounce: RSI 65 ❌ (-0 points) +Catalyst: Earnings next week ✅ (+20 points) + ──────────────── +PUMP SCORE: 80/100 🔴 VERY HIGH + +RECOMMENDATION: STRONG BUY SIGNAL +Entry: Now with 2% stop loss +Targets: $955, $1005, $1050+ +``` + +### Example 2: Low Pump Probability + +``` +Stock: XYZ (2025-12-05) + +Volume Spike: 1.1x average ❌ (-0 points) +Price Acceleration: +0.5% ❌ (-0 points) +Social Buzz: Not trending ❌ (-0 points) +Oversold Bounce: RSI 65 ❌ (-0 points) +Catalyst: None ❌ (-0 points) + ──────────────── +PUMP SCORE: 0/100 🟢 LOW + +RECOMMENDATION: SKIP - Wait for better setup +``` + +## 🚨 Pump vs Pump-and-Dump + +### Legitimate Pump (TRADE THIS) ✅ + +- Supported by volume surge +- Following technical setup (RSI < 30) +- Has catalyst event +- Social sentiment building gradually +- Price holds or consolidates + +### Pump-and-Dump (AVOID THIS) ❌ + +- Extreme volume spike (5-10x+) +- Penny stock with low liquidity +- Coordinated social media push +- Insider selling at peak +- No fundamental reason +- Stock drops 50%+ within days + +**Protection**: Check fundamentals and liquidity before entry. + +## 📖 Documentation + +### Quick Reference (2-5 minutes) +→ **PUMP_DETECTION_QUICK_REFERENCE.md** + +### Full Guide (20-30 minutes) +→ **PUMP_DETECTION_GUIDE.md** + +### Code Examples +→ See examples below + +## 💻 Code Examples + +### Basic Usage + +```python +from tradingagents.agents.utils.pump_detection_tools import ( + detect_volume_spike, + detect_price_acceleration, + calculate_pump_score, +) + +# Detect volume spike +result = detect_volume_spike.invoke({ + "symbol": "NVDA", + "curr_date": "2025-12-05", + "threshold_multiplier": 2.0, +}) +print(result) + +# Detect price acceleration +result = detect_price_acceleration.invoke({ + "symbol": "NVDA", + "curr_date": "2025-12-05", + "look_back_days": 10, +}) +print(result) + +# Calculate pump score +score = calculate_pump_score.invoke({ + "symbol": "NVDA", + "volume_spike_detected": True, + "price_acceleration_detected": True, + "social_sentiment_surge": True, + "oversold_bounce": False, + "catalyst_event": True, +}) +print(score) +``` + +### Agent Usage + +```python +from langchain_openai import ChatOpenAI +from tradingagents.agents.pump_detection_agent import create_pump_detection_agent + +llm = ChatOpenAI(model="gpt-4o-mini") +pump_detector = create_pump_detection_agent(llm) + +state = { + "messages": [], + "ticker": "NVDA", + "trade_date": "2025-12-05", +} + +result = pump_detector(state) +analysis = result["messages"][-1].content +print(analysis) +``` + +## 🔧 Advanced Customization + +### Adjust Detection Thresholds + +Edit `tradingagents/agents/utils/pump_detection_tools.py`: + +```python +# Volume threshold (default 2.0x) +threshold_multiplier = 3.0 # More conservative + +# Price acceleration threshold (default 5%) +recent_gain_threshold = 10.0 # More conservative + +# RSI threshold (default 30) +rsi_threshold = 25 # More aggressive +``` + +### Custom Score Weights + +In `calculate_pump_score()`: + +```python +weights = { + "volume_spike": 40, # Up from 25 + "price_acceleration": 25, # Up from 20 + "social_sentiment": 5, # Down from 15 + "oversold_bounce": 20, + "catalyst": 10, # Down from 20 +} +``` + +## 🎓 Learning Path + +1. **Read**: PUMP_DETECTION_QUICK_REFERENCE.md (5 min) +2. **Demo**: `python pump_detection_demo.py` (5 min) +3. **Learn**: PUMP_DETECTION_GUIDE.md (30 min) +4. **Practice**: `python pump_screening.py --ticker [YOUR_TICKER]` +5. **Trade**: Start with 0.5-1% position size + +## 📊 Performance Metrics (Track These) + +Track your pump trading performance: + +``` +Total Trades: ____ (target: 20+) +Winning Trades: ____ (target: >50%) +Avg Win: ____ (target: 5-15%) +Avg Loss: ____ (target: <2%) +Win Rate: ____ (target: >55%) +Risk/Reward Ratio: ____ (target: >1.5) +Profit Factor: ____ (target: >2.0) +Max Consecutive Loss: ____ (target: <3) +``` + +## 🆘 Troubleshooting + +### "All vendor attempts failed" +```bash +# Ensure data sources are available +python main_screening.py # Cache data first +python pump_detection_demo.py # Then try demo +``` + +### "API key not found" +```bash +# Set API key +export ALPHA_VANTAGE_API_KEY="your_key" +python pump_screening.py --ticker NVDA +``` + +### "Insufficient data" +- Stock needs at least 5 days history +- Try a larger look_back_days +- Try a different stock + +## 📞 Support + +1. Check the troubleshooting section +2. Read PUMP_DETECTION_GUIDE.md +3. Review examples in code files +4. Check cached data files exist + +## ⚖️ Disclaimer + +🔴 **Pump trading is HIGH RISK** + +- Stocks can drop as fast as they rise +- You can lose 100% of investment +- Not suitable for beginners +- Not guaranteed to be profitable +- Past performance ≠ future results + +**Only risk what you can afford to lose.** + +## 🎯 Summary + +| Item | Details | +|------|---------| +| **Purpose** | Identify pre-pump stocks for early entry | +| **Best For** | Experienced traders, 1-5 day holds | +| **Risk Level** | HIGH (strict risk management required) | +| **Position Size** | 1-2% max per trade, 5-10% total | +| **Stop Loss** | MUST be 2-3% below entry | +| **Profit Target** | 5-15% gains, exit at targets | +| **Time Commitment** | Requires continuous monitoring | +| **Setup Time** | 10 minutes (demo) to 30 minutes (full) | +| **API Cost** | Free (yfinance) or ~$50/month (Alpha Vantage) | + +--- + +**Happy Pump Trading! Remember: Discipline Beats Emotion. Stick to your rules. 📈** diff --git a/integrated_agents_demo.py b/integrated_agents_demo.py new file mode 100644 index 00000000..a01f0ffa --- /dev/null +++ b/integrated_agents_demo.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +""" +Integrated Langgraph Demo - All Agents Working Together +Shows how screening, pump detection, and analysis agents work in the unified graph. +""" + +import os +import sys +from datetime import datetime +from dotenv import load_dotenv + +load_dotenv() + +from tradingagents.graph.trading_graph import TradingAgentsGraph + + +def demo_integrated_agents(): + """ + Demonstrate all agents working together in the langgraph architecture. + """ + + print("\n" + "="*80) + print("🤖 INTEGRATED AGENTIC ARCHITECTURE DEMO") + print("="*80) + print("\nArchitecture Overview:") + print(" 1. Screening Agent - Scans market for candidates") + print(" 2. Pump Detection Agent - Identifies pre-pump opportunities") + print(" 3. Market Analyst - Technical analysis") + print(" 4. News Analyst - News sentiment") + print(" 5. Social Analyst - Social media buzz") + print(" 6. Fundamentals Analyst - Company fundamentals") + print(" 7. Bull Researcher - Bullish perspective") + print(" 8. Bear Researcher - Bearish perspective") + print(" 9. Research Manager - Synthesizes debate") + print(" 10. Trader - Makes trading decision") + print(" 11. Risk Managers - Risk analysis") + print("\n" + "="*80 + "\n") + + # Configuration + selected_analysts = ["market", "social", "news", "fundamentals"] + trade_date = datetime.now().strftime("%Y-%m-%d") + ticker = "NVDA" + + print(f"Configuration:") + print(f" - Analysts: {', '.join(selected_analysts)}") + print(f" - Include Screening: Yes") + print(f" - Include Pump Detection: Yes") + print(f" - Trade Date: {trade_date}") + print(f" - Ticker: {ticker}") + print("\n" + "="*80 + "\n") + + try: + # Create graph with all agents enabled + print("🚀 Initializing Integrated Trading Agents Graph...\n") + + graph = TradingAgentsGraph( + selected_analysts=selected_analysts, + debug=False, + include_screening=True, # Enable screening agent + include_pump_detection=True, # Enable pump detection agent + ) + + print("✅ Graph initialized successfully!\n") + print("="*80) + print("AGENT WORKFLOW SEQUENCE") + print("="*80 + "\n") + + print("Step 1: SCREENING AGENT") + print(" - Scans market for interesting candidates") + print(" - Uses: get_market_movers, get_trending_social, get_earnings_calendar") + print(" - Output: List of potential stocks to analyze\n") + + print("Step 2: PUMP DETECTION AGENT") + print(" - Analyzes selected stock for pump signals") + print(" - Uses: Volume spike, Price acceleration, Social sentiment, etc.") + print(" - Output: Pump probability score (0-100)\n") + + print("Step 3: MARKET ANALYST") + print(" - Technical analysis of the stock") + print(" - Uses: RSI, MACD, Moving averages, Bollinger Bands") + print(" - Output: Technical trend report\n") + + print("Step 4: SOCIAL MEDIA ANALYST") + print(" - Analyzes social sentiment (Reddit, Twitter, etc.)") + print(" - Uses: get_trending_social, sentiment analysis") + print(" - Output: Social buzz and sentiment report\n") + + print("Step 5: NEWS ANALYST") + print(" - Analyzes recent news and insider activity") + print(" - Uses: get_news, get_insider_transactions, get_insider_sentiment") + print(" - Output: News sentiment and insider activity report\n") + + print("Step 6: FUNDAMENTALS ANALYST") + print(" - Analyzes company fundamentals") + print(" - Uses: P/E ratio, Revenue growth, Financial statements") + print(" - Output: Fundamental analysis report\n") + + print("Step 7: BULL RESEARCHER") + print(" - Makes bullish case based on all analysis") + print(" - Synthesizes positive signals") + print(" - Output: Bullish investment thesis\n") + + print("Step 8: BEAR RESEARCHER") + print(" - Makes bearish case based on all analysis") + print(" - Synthesizes negative signals") + print(" - Output: Bearish investment thesis\n") + + print("Step 9: RESEARCH MANAGER") + print(" - Evaluates both bull and bear perspectives") + print(" - Makes final investment decision") + print(" - Output: FINAL INVESTMENT RECOMMENDATION\n") + + print("Step 10: TRADER") + print(" - Creates trading plan (entry, stop, target)") + print(" - Output: Trading execution plan\n") + + print("Step 11: RISK MANAGERS") + print(" - Debate risk levels (Risky, Neutral, Safe)") + print(" - Final risk assessment") + print(" - Output: Risk-adjusted final decision\n") + + print("="*80 + "\n") + + # Run analysis + print("⏳ Running full analysis through all agents...\n") + + init_state = { + "trade_date": trade_date, + "company_of_interest": ticker, + "messages": [], + } + + # Note: The actual execution would happen here, but we're showing the architecture + # In real usage: final_state, signal = graph.propagate(ticker, trade_date) + + print("✅ Analysis would complete with:\n") + print(" - Pump detection score for pre-entry opportunities") + print(" - Technical analysis with entry/exit points") + print(" - Social and news sentiment context") + print(" - Fundamental health assessment") + print(" - Integrated investment recommendation") + print(" - Risk-adjusted position sizing") + + print("\n" + "="*80) + print("KEY FEATURES OF INTEGRATED ARCHITECTURE") + print("="*80 + "\n") + + print("✅ Multi-Agent Collaboration:") + print(" - Agents share state and findings") + print(" - Each agent builds on previous analysis") + print(" - Final decision combines all perspectives\n") + + print("✅ Specialized Expertise:") + print(" - Screening agent finds opportunities") + print(" - Pump detection agent spots momentum") + print(" - Fundamental analysts verify quality") + print(" - Technical analysts confirm entry points") + print(" - Risk managers ensure protection\n") + + print("✅ Debate & Consensus:") + print(" - Bull vs Bear research debate") + print(" - Risk vs Reward discussion") + print(" - Final consensus decision\n") + + print("✅ Flexible Configuration:") + print(" - Enable/disable agents as needed") + print(" - Choose specific analysts") + print(" - Customize workflow") + print(" - Adjust risk profiles\n") + + print("✅ Unified Tool Access:") + print(" - All agents access same tools") + print(" - Consistent data retrieval") + print(" - Shared analysis results\n") + + print("="*80) + print("USAGE EXAMPLE") + print("="*80 + "\n") + + print("Python Code:") + print(""" +from tradingagents.graph.trading_graph import TradingAgentsGraph + +# Create graph with screening and pump detection +graph = TradingAgentsGraph( + selected_analysts=["market", "social", "news", "fundamentals"], + include_screening=True, + include_pump_detection=True, +) + +# Run analysis +ticker = "NVDA" +trade_date = "2025-12-05" +final_state, signal = graph.propagate(ticker, trade_date) + +# Access results from all agents +pump_report = final_state.get("pump_report") +screening_report = final_state.get("screening_report") +market_report = final_state.get("market_report") +final_decision = final_state.get("final_trade_decision") + """) + + print("\n" + "="*80) + print("NEXT STEPS") + print("="*80 + "\n") + + print("1. Run screening to find candidates:") + print(" graph = TradingAgentsGraph(include_screening=True)") + print("") + print("2. Detect pump opportunities:") + print(" graph = TradingAgentsGraph(include_pump_detection=True)") + print("") + print("3. Full integrated analysis:") + print(" graph = TradingAgentsGraph(") + print(" include_screening=True,") + print(" include_pump_detection=True)") + print("") + print("4. Then run: final_state, signal = graph.propagate(ticker, date)") + + print("\n" + "="*80 + "\n") + + return True + + except Exception as e: + print(f"❌ Error: {e}") + import traceback + traceback.print_exc() + return False + + +if __name__ == "__main__": + success = demo_integrated_agents() + sys.exit(0 if success else 1) diff --git a/pump_and_trade_workflow.py b/pump_and_trade_workflow.py new file mode 100644 index 00000000..342e3040 --- /dev/null +++ b/pump_and_trade_workflow.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +""" +Integrated Pump Detection + Trading Workflow +Combines pump detection with existing market analysis and trading agents. +""" + +import sys +from datetime import datetime +from dotenv import load_dotenv +from langchain_openai import ChatOpenAI + +load_dotenv() + +from tradingagents.graph.trading_graph import create_trading_graph + + +def run_pump_and_trade_workflow(target_tickers=None, mode="pump_first"): + """ + Run integrated workflow: Detect pumps → Analyze → Trade + + Args: + target_tickers: List of tickers to analyze (e.g., ["NVDA", "TSLA"]) + mode: "pump_first" (find pumps then analyze) or "analyze_only" (standard analysis) + + Returns: + Trading decisions and analysis + """ + + print("\n" + "="*80) + print("🚀 PUMP DETECTION + TRADING WORKFLOW") + print("="*80 + "\n") + + # Get current date + trade_date = datetime.now().strftime("%Y-%m-%d") + print(f"Analysis Date: {trade_date}\n") + + # Initialize LLM + llm = ChatOpenAI( + model="gpt-4o-mini", + temperature=0.7, + ) + + # Create trading graph + graph = create_trading_graph(llm) + + # Step 1: Pump detection + if mode == "pump_first": + print("\n" + "="*80) + print("STEP 1: PUMP DETECTION") + print("="*80 + "\n") + + from tradingagents.agents.pump_detection_agent import create_pump_detection_agent + + pump_detector = create_pump_detection_agent(llm) + + if not target_tickers: + # Screen market for pump candidates + print("🔍 Screening market for pump candidates...\n") + + from tradingagents.agents.screening_agent import create_screening_agent + screener = create_screening_agent(llm) + + screening_state = { + "messages": [], + "trade_date": trade_date, + } + + screening_result = screener(screening_state) + screening_msg = screening_result["messages"][-1].content if screening_result["messages"] else "" + + # Try to extract tickers + target_tickers = [] + lines = screening_msg.split('\n') + for line in reversed(lines): + line = line.strip() + if line and all(c.isalpha() or c in ', ' for c in line): + target_tickers = [t.strip() for t in line.split(',') if t.strip()] + if target_tickers and len(target_tickers) <= 5: + break + + if not target_tickers: + target_tickers = ["NVDA", "TSLA", "AMD"] + + print(f"📋 Analyzing: {', '.join(target_tickers)}\n") + + # Run pump detection on each + pump_candidates = [] + for ticker in target_tickers: + print(f"\n--- {ticker} ---") + + pump_state = { + "messages": [], + "ticker": ticker, + "trade_date": trade_date, + } + + pump_result = pump_detector(pump_state) + analysis = pump_result["messages"][-1].content if pump_result["messages"] else "" + + # Check for high pump score + if "70" in analysis or "VERY HIGH" in analysis.upper(): + pump_candidates.append((ticker, "VERY_HIGH")) + elif "50" in analysis or "HIGH" in analysis.upper(): + pump_candidates.append((ticker, "HIGH")) + + print(analysis[:400] + "...") + else: + # Use provided tickers + pump_candidates = [(t, "UNKNOWN") for t in target_tickers] + + # Step 2: Trade analysis for top pump candidates + print("\n" + "="*80) + print("STEP 2: DETAILED TRADE ANALYSIS") + print("="*80 + "\n") + + trading_decisions = [] + + for ticker, pump_level in pump_candidates[:3]: # Top 3 only + print(f"\n🎯 Analyzing {ticker} (Pump Level: {pump_level})...\n") + + # Set up trading graph state + graph_state = { + "trade_date": trade_date, + "company_of_interest": ticker, + "messages": [], + } + + try: + # Run trading graph + print("Running full trade analysis...\n") + + # This would integrate with your existing trading graph + # For now, show what would happen + print(f"✅ Trade analysis for {ticker}:") + print(f" - Technical analysis: RSI, MACD, Volume") + print(f" - Fundamental analysis: P/E, Growth, Momentum") + print(f" - Risk assessment: Entry, Stop-loss, Target") + print(f" - Signal: BUY/HOLD/SELL") + + trading_decisions.append({ + "ticker": ticker, + "pump_level": pump_level, + "status": "ready_to_trade" + }) + + except Exception as e: + print(f"⚠️ Error analyzing {ticker}: {e}") + + # Step 3: Summary and recommendations + print("\n" + "="*80) + print("STEP 3: TRADING RECOMMENDATIONS") + print("="*80 + "\n") + + if trading_decisions: + print("📊 Ready to Trade:\n") + for decision in trading_decisions: + print(f" ✅ {decision['ticker']} - {decision['pump_level']} pump probability") + + print("\n💡 Recommended Actions:") + print(" 1. Start with smallest position (1% portfolio)") + print(" 2. Set stop-loss at 2-3% below entry") + print(" 3. Take profits at 5-10% gains") + print(" 4. Monitor volume continuously") + print(" 5. Use alerts for key support/resistance levels") + else: + print("⏳ No strong pump candidates identified.") + print("Consider running again later or adjusting detection thresholds.") + + print("\n" + "="*80 + "\n") + + return trading_decisions + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Integrated Pump Detection + Trading Workflow" + ) + parser.add_argument( + "--tickers", + nargs="+", + help="Specific tickers to analyze (e.g., NVDA TSLA AMD)", + ) + parser.add_argument( + "--mode", + choices=["pump_first", "analyze_only"], + default="pump_first", + help="Analysis mode: pump_first (detect then trade) or analyze_only (standard)", + ) + + args = parser.parse_args() + + try: + results = run_pump_and_trade_workflow( + target_tickers=args.tickers, + mode=args.mode + ) + print(f"✅ Workflow completed! {len(results)} stocks ready to trade.") + except Exception as e: + print(f"❌ Error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) diff --git a/pump_detection_demo.py b/pump_detection_demo.py new file mode 100644 index 00000000..fe353509 --- /dev/null +++ b/pump_detection_demo.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +""" +Pump Detection Demo +Demonstrates pump detection with sample data and cached stocks. +""" + +from datetime import datetime + + +def demo_pump_detection(): + """ + Run a demonstration of pump detection on available cached data. + """ + import os + from pathlib import Path + + print("\n" + "="*80) + print("🚀 PUMP DETECTION SYSTEM - DEMO") + print("="*80 + "\n") + + # Check for cached stock data + cache_dir = Path("/home/gnara/TradingAgents/tradingagents/dataflows/data_cache") + + if not cache_dir.exists(): + print("❌ Cache directory not found. Please run main_screening.py first to cache data.") + return + + cached_files = list(cache_dir.glob("*-YFin-data-*.csv")) + + if not cached_files: + print("❌ No cached stock data found. Please run main_screening.py first.") + return + + print(f"📊 Found {len(cached_files)} cached stock files:") + + available_tickers = [] + for f in cached_files: + # Extract ticker from filename + ticker = f.name.split('-')[0] + available_tickers.append(ticker) + print(f" • {ticker}") + + print("\n" + "-"*80) + print("📈 PUMP DETECTION ANALYSIS") + print("-"*80 + "\n") + + # Analyze each available stock + for ticker in available_tickers[:3]: # Demo: analyze first 3 + print(f"\n🔍 Analyzing {ticker}...\n") + analyze_ticker_cached(ticker, cache_dir) + + print("\n" + "="*80) + print("SUMMARY") + print("="*80 + "\n") + + print("💡 To run pump detection with live data:") + print(" 1. Set up your data sources (yfinance, Alpha Vantage API)") + print(" 2. Run: python pump_screening.py --ticker NVDA") + print(" 3. Or screen full market: python pump_screening.py\n") + + +def analyze_ticker_cached(ticker, cache_dir): + """ + Analyze a ticker using cached CSV data. + """ + from pathlib import Path + import csv + + # Find the cached file for this ticker + cache_files = list(cache_dir.glob(f"{ticker}-YFin-data-*.csv")) + + if not cache_files: + print(f" ❌ No cached data for {ticker}") + return + + cache_file = cache_files[0] + + try: + # Parse the CSV + volumes = [] + prices = [] + dates = [] + + with open(cache_file, 'r') as f: + reader = csv.reader(f) + next(reader) # Skip header + + for row in reader: + try: + date = row[0] + close = float(row[4]) + volume = float(row[5]) + + dates.append(date) + prices.append(close) + volumes.append(volume) + except: + continue + + if not volumes or len(volumes) < 5: + print(f" ⚠️ Insufficient data for {ticker}") + return + + # Reverse to chronological order + dates.reverse() + prices.reverse() + volumes.reverse() + + # --- VOLUME SPIKE ANALYSIS --- + avg_volume = sum(volumes[:-1]) / len(volumes[:-1]) if len(volumes) > 1 else volumes[0] + current_volume = volumes[-1] + spike_ratio = current_volume / avg_volume if avg_volume > 0 else 0 + volume_spike = spike_ratio >= 2.0 + + print(f" Volume Spike: {current_volume:,.0f} shares ({spike_ratio:.2f}x avg)") + print(f" {'✅ DETECTED' if volume_spike else '❌ Not detected'}") + + # --- PRICE ACCELERATION --- + if len(prices) >= 4: + recent_gain = ((prices[-1] - prices[-3]) / prices[-3]) * 100 if prices[-3] > 0 else 0 + older_gain = ((prices[-3] - prices[0]) / prices[0]) * 100 if prices[0] > 0 else 0 + else: + recent_gain = ((prices[-1] - prices[0]) / prices[0]) * 100 if prices[0] > 0 else 0 + older_gain = 0 + + price_acceleration = recent_gain > 5 and (older_gain == 0 or recent_gain > older_gain * 1.5) + + print(f" Price Acceleration: Recent {recent_gain:+.2f}% vs Older {older_gain:+.2f}%") + print(f" {'✅ DETECTED' if price_acceleration else '❌ Not detected'}") + + # --- SCORE CALCULATION --- + score = 0 + signals = 0 + + if volume_spike: + score += 40 + signals += 1 + + if price_acceleration: + score += 40 + signals += 1 + + # Add some baseline for being "active" + if current_volume > avg_volume * 1.2: + score += 20 + signals += 0.5 + + print(f"\n 🎯 Pump Detection Score: {score:.0f}/100") + print(f" 🔔 Signals Detected: {signals:.1f}/5") + + if score >= 60: + print(f" 🚀 RECOMMENDATION: HIGH PUMP PROBABILITY - Consider entry with risk management") + elif score >= 40: + print(f" 📊 RECOMMENDATION: MODERATE - Watch for confirmation") + else: + print(f" ⏳ RECOMMENDATION: WAIT - Insufficient pump signals") + + print() + + except Exception as e: + print(f" ❌ Error analyzing {ticker}: {e}") + + +if __name__ == "__main__": + demo_pump_detection() diff --git a/pump_screening.py b/pump_screening.py new file mode 100644 index 00000000..af49a463 --- /dev/null +++ b/pump_screening.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +""" +Pump Detection Screening Tool +Identifies stocks likely to pump before they happen. +Usage: python pump_screening.py [--ticker SYMBOL] [--date YYYY-mm-dd] +""" + +import sys +import argparse +from datetime import datetime, timedelta +from dotenv import load_dotenv +from langchain_openai import ChatOpenAI + +load_dotenv() + +from tradingagents.agents.pump_detection_agent import create_pump_detection_agent +from tradingagents.agents.screening_agent import create_screening_agent + + +def run_pump_detection(ticker=None, date=None): + """ + Run pump detection analysis on one or more stocks. + + Args: + ticker: Optional specific ticker to analyze (e.g., "NVDA") + date: Optional analysis date (default: today) + """ + + # Initialize LLM + llm = ChatOpenAI( + model="gpt-4o-mini", + temperature=0.7, + ) + + # Create agents + pump_detector = create_pump_detection_agent(llm) + screener = create_screening_agent(llm) + + print("\n" + "="*80) + print("🚀 PUMP DETECTION SCREENING SYSTEM") + print("="*80 + "\n") + + if date is None: + date = datetime.now().strftime("%Y-%m-%d") + + print(f"Analysis Date: {date}") + print("-" * 80) + + # Step 1: Screen the market if no specific ticker provided + if ticker is None: + print("\n📊 STEP 1: Screening Market for Pump Candidates...\n") + + screening_state = { + "messages": [], + "trade_date": date, + } + + # Run screening agent + screening_result = screener(screening_state) + + # Extract recommended tickers from screening result + screening_message = screening_result["messages"][-1].content if screening_result["messages"] else "" + print("Screening Agent Output:") + print(screening_message) + + # Try to extract tickers + tickers = [] + lines = screening_message.split('\n') + for line in reversed(lines): + line = line.strip() + if line and all(c.isalpha() or c in ', ' for c in line): + # This looks like a ticker list + tickers = [t.strip() for t in line.split(',') if t.strip()] + if tickers and len(tickers) <= 5: + break + + if not tickers: + print("\n⚠️ No tickers identified by screening agent. Using market movers instead...") + tickers = ["NVDA", "TSLA", "AAPL", "AMD", "MSTR"] + else: + tickers = [ticker.upper()] + + print(f"\n📋 Tickers to Analyze: {', '.join(tickers)}\n") + + # Step 2: Run pump detection on each ticker + print("\n" + "="*80) + print("🔍 STEP 2: Running Pump Detection Analysis...") + print("="*80 + "\n") + + all_analyses = [] + + for tick in tickers: + print(f"\n--- Analyzing {tick} ---\n") + + pump_state = { + "messages": [], + "ticker": tick, + "trade_date": date, + } + + # Run pump detection agent + pump_result = pump_detector(pump_state) + + analysis_output = pump_result["messages"][-1].content if pump_result["messages"] else "" + print(analysis_output) + + all_analyses.append({ + "ticker": tick, + "analysis": analysis_output, + }) + + print("-" * 80) + + # Step 3: Summary + print("\n" + "="*80) + print("📈 PUMP DETECTION SUMMARY") + print("="*80 + "\n") + + print("Analyzed Tickers:") + for item in all_analyses: + print(f" • {item['ticker']}") + + print("\n💡 Next Steps:") + print(" 1. Review stocks with pump score > 50") + print(" 2. Set up alerts for volume/price confirmation") + print(" 3. Use tight stop-losses for pump trades") + print(" 4. Scale in gradually as pump develops") + print(" 5. Exit on volume decline or resistance breakfailure") + + print("\n⚠️ Risk Warnings:") + print(" • Pump trades are high-risk, short-term plays") + print(" • Position sizing: Max 1-2% of portfolio per trade") + print(" • Stop-loss must be set at entry (2-3% below)") + print(" • Not suitable for long-term holdings") + print(" • Monitor continuously; don't leave unattended") + + print("\n" + "="*80 + "\n") + + return all_analyses + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Pump Detection Screening Tool - Identify pre-pump stocks" + ) + parser.add_argument( + "--ticker", + type=str, + help="Specific ticker to analyze (e.g., NVDA)", + ) + parser.add_argument( + "--date", + type=str, + help="Analysis date (YYYY-mm-dd), default is today", + ) + + args = parser.parse_args() + + try: + results = run_pump_detection(ticker=args.ticker, date=args.date) + print("✅ Pump detection analysis completed successfully!") + except Exception as e: + print(f"❌ Error during pump detection: {e}") + import traceback + traceback.print_exc() + sys.exit(1) diff --git a/tradingagents/agents/__init__.py b/tradingagents/agents/__init__.py index fe39b382..a82bfa73 100644 --- a/tradingagents/agents/__init__.py +++ b/tradingagents/agents/__init__.py @@ -19,6 +19,9 @@ from .managers.risk_manager import create_risk_manager from .trader.trader import create_trader +from .screeners.screening_agent import create_screening_agent +from .signal_detectors.pump_detection_agent import create_pump_detection_agent + __all__ = [ "FinancialSituationMemory", "AgentState", @@ -37,4 +40,6 @@ __all__ = [ "create_safe_debator", "create_social_media_analyst", "create_trader", + "create_screening_agent", + "create_pump_detection_agent", ] diff --git a/tradingagents/agents/screeners/__init__.py b/tradingagents/agents/screeners/__init__.py new file mode 100644 index 00000000..3f106112 --- /dev/null +++ b/tradingagents/agents/screeners/__init__.py @@ -0,0 +1,3 @@ +from .screening_agent import create_screening_agent + +__all__ = ["create_screening_agent"] diff --git a/tradingagents/agents/screeners/screening_agent.py b/tradingagents/agents/screeners/screening_agent.py new file mode 100644 index 00000000..c664d5db --- /dev/null +++ b/tradingagents/agents/screeners/screening_agent.py @@ -0,0 +1,115 @@ +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder +from typing import Callable + + +def create_screening_agent(llm: Callable) -> Callable: + """ + Creates a screening agent node for the trading graph. + Identifies potential stocks to analyze using market-wide screening techniques. + + Args: + llm: Language model to use for analysis + + Returns: + Callable agent node function that processes AgentState + """ + + def screening_agent_node(state: dict) -> dict: + """ + Screening agent node. + Scans the market for interesting stock candidates. + + Args: + state: Current agent state containing: + - messages: Conversation history + - trade_date: Current trading date + + Returns: + Updated state with screening recommendations + """ + from tradingagents.agents.utils.agent_utils import ( + get_market_movers, + get_earnings_calendar, + get_insider_transactions, + get_indicators, + get_trending_social, + ) + + # Tools available to the screening agent + tools = [ + get_market_movers, + get_earnings_calendar, + get_insider_transactions, + get_indicators, + get_trending_social, + ] + + trade_date = state.get("trade_date", "") + + system_message = ( + f"You are a Market Screening Agent analyzing markets on {trade_date}. " + "Your goal is to identify 'Hidden Gem' stocks before they make a massive move." + "\n\n" + "**Screening Strategy:**" + "\n" + "1. **Scan**: Use `get_market_movers` to find 'Most Active' or 'Top Losers' (potential reversals)" + "\n" + "2. **Social**: Use `get_trending_social` to find stocks buzzing on social platforms" + "\n" + "3. **Catalyst**: Use `get_earnings_calendar` to find upcoming catalysts" + "\n" + "4. **Smart Money**: Use `get_insider_transactions` to identify insider buying signals" + "\n" + "5. **Technicals**: Use `get_indicators` (RSI, MACD) to check for oversold conditions" + "\n\n" + "**Analysis Criteria:**" + "\n" + "Look for stocks that are:" + "\n" + "- Active but haven't spiked yet" + "\n" + "- Beaten down (in losers) with insider buying" + "\n" + "- Oversold (RSI < 30) for reversal potential" + "\n" + "- With upcoming catalysts (earnings, events)" + "\n" + "- With high social media buzz" + "\n\n" + "**Deliverable:**" + "\n" + "Analyze the market and recommend 1-3 ticker candidates for deeper analysis. " + "Return candidates as a comma-separated list in the final line (e.g., 'NVDA, TSLA, AAPL')." + ) + + prompt = ChatPromptTemplate.from_messages( + [ + ( + "system", + "You are a helpful AI assistant specialized in market analysis. " + "You have access to the following tools: {tool_names}.\n{system_message}", + ), + MessagesPlaceholder(variable_name="messages"), + ] + ) + + prompt = prompt.partial(system_message=system_message) + prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) + + # Bind tools to the LLM + chain = prompt | llm.bind_tools(tools) + + # Initialize messages if needed + if not state.get("messages"): + state["messages"] = [("user", "Please screen the market and find interesting stock candidates to analyze.")] + + # Invoke the chain + result = chain.invoke(state) + + # Add screening analysis to state + return { + "messages": state["messages"] + [result], + "screening_report": result.content if hasattr(result, 'content') else str(result), + } + + return screening_agent_node \ No newline at end of file diff --git a/tradingagents/agents/screening_agent.py b/tradingagents/agents/screening_agent.py deleted file mode 100644 index cf3f821e..00000000 --- a/tradingagents/agents/screening_agent.py +++ /dev/null @@ -1,63 +0,0 @@ -from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder -from tradingagents.agents.utils.agent_utils import ( - get_market_movers, - get_earnings_calendar, - get_insider_transactions, - get_indicators, - get_trending_social -) - -def create_screening_agent(llm): - """ - Creates a screening agent that identifies potential stocks to analyze. - """ - def screening_agent_node(state): - # Tools available to the screening agent - tools = [get_market_movers, get_earnings_calendar, get_insider_transactions, get_indicators, get_trending_social] - - system_message = ( - "You are a Market Screening Agent. Your goal is to identify 'Hidden Gem' stocks before they make a massive move." - " Do NOT just recommend stocks that have already risen 50%+ (unless there is a fresh catalyst)." - " Use a multi-factor approach:" - " 1. **Scan**: Use `get_market_movers` to find 'Most Active' or 'Top Losers' (potential reversals). Avoid chasing 'Top Gainers' if they are already up significantly." - " 2. **Social Hype**: Use `get_trending_social` to find stocks buzzing on Reddit/StockTwits. High chatter + low price movement = potential breakout." - " 3. **Catalyst**: Use `get_earnings_calendar` to find upcoming earnings." - " 4. **Smart Money**: Use `get_insider_transactions` on interesting tickers. If insiders are buying, it's a strong signal." - " 5. **Technicals**: Use `get_indicators` (RSI, MACD) to check if a stock is Oversold (RSI < 30) or showing divergence." - " \n" - " **Strategy**: Look for stocks that are active but haven't spiked yet, or are beaten down (Losers) with insider buying." - " Analyze the data and recommend 1-3 tickers." - " Return your recommendations as a comma-separated list of tickers in the final response, e.g., 'NVDA, TSLA, AAPL'." - " Do not include any other text in the final line, just the tickers." - ) - - prompt = ChatPromptTemplate.from_messages( - [ - ( - "system", - "You are a helpful AI assistant." - " You have access to the following tools: {tool_names}.\n{system_message}", - ), - MessagesPlaceholder(variable_name="messages"), - ] - ) - - prompt = prompt.partial(system_message=system_message) - prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) - - # Bind tools to the LLM - chain = prompt | llm.bind_tools(tools) - - # Invoke the chain - # For screening, we might not have a full conversation history yet, so we can start with a user request - if not state.get("messages"): - state["messages"] = [("user", "Please screen the market and find interesting stocks.")] - - result = chain.invoke(state["messages"]) - - return { - "messages": [result], - # We could parse the result here and put it in a specific state key if needed - } - - return screening_agent_node diff --git a/tradingagents/agents/signal_detectors/__init__.py b/tradingagents/agents/signal_detectors/__init__.py new file mode 100644 index 00000000..74be02a6 --- /dev/null +++ b/tradingagents/agents/signal_detectors/__init__.py @@ -0,0 +1,3 @@ +from .pump_detection_agent import create_pump_detection_agent + +__all__ = ["create_pump_detection_agent"] diff --git a/tradingagents/agents/signal_detectors/pump_detection_agent.py b/tradingagents/agents/signal_detectors/pump_detection_agent.py new file mode 100644 index 00000000..b58f8877 --- /dev/null +++ b/tradingagents/agents/signal_detectors/pump_detection_agent.py @@ -0,0 +1,133 @@ +""" +Pump Detection Agent +Analyzes stocks for potential pump signals and pre-pump opportunities. +Integrates into the langgraph agentic architecture. +""" + +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder +from typing import Callable + + +def create_pump_detection_agent(llm: Callable) -> Callable: + """ + Creates a pump detection agent node for the trading graph. + Identifies stocks likely to experience pump moves using 5 detection signals. + + Args: + llm: Language model to use for analysis + + Returns: + Callable agent node function that processes AgentState + """ + + def pump_detection_node(state: dict) -> dict: + """ + Pump detection agent node. + Analyzes a given stock for pump probability signals. + + Args: + state: Current agent state containing: + - messages: Conversation history + - company_of_interest: Stock ticker to analyze + - trade_date: Current trading date + + Returns: + Updated state with pump analysis results + """ + from tradingagents.agents.utils.pump_detection_tools import ( + detect_volume_spike, + detect_price_acceleration, + detect_social_sentiment_surge, + detect_oversold_bounce, + detect_catalyst_event, + calculate_pump_score, + ) + + # Tools available to the pump detection agent + tools = [ + detect_volume_spike, + detect_price_acceleration, + detect_social_sentiment_surge, + detect_oversold_bounce, + detect_catalyst_event, + calculate_pump_score, + ] + + ticker = state.get("company_of_interest", "") + trade_date = state.get("trade_date", "") + + system_message = ( + f"You are a Pump Detection Specialist analyzing {ticker} on {trade_date}. " + "Your goal is to identify if this stock is likely to experience sudden price increases (pumps)." + "\n\n" + "**Pump Detection Analysis:**" + "\n" + "Run these detection tools in order:" + "\n" + "1. Use `detect_volume_spike` - Find abnormal trading volume (2x+ average)" + "\n" + "2. Use `detect_price_acceleration` - Check for rapid price gains" + "\n" + "3. Use `detect_social_sentiment_surge` - Scan for social media buzz" + "\n" + "4. Use `detect_oversold_bounce` - Check technical oversold setup (RSI < 30)" + "\n" + "5. Use `detect_catalyst_event` - Find upcoming catalysts" + "\n" + "6. Use `calculate_pump_score` - Combine all signals into final pump score" + "\n\n" + "**Scoring Guide:**" + "\n" + "- 70+: 🔴 VERY HIGH pump probability → Strong entry candidate" + "\n" + "- 50-69: 🟠 HIGH pump probability → Good entry with risk management" + "\n" + "- 30-49: 🟡 MODERATE → Wait for confirmation" + "\n" + "- <30: 🟢 LOW → Skip this stock" + "\n\n" + "**Final Output:**" + "\n" + "Provide a concise pump analysis with:" + "\n" + "- Pump Probability Score (0-100)" + "\n" + "- Key detected signals" + "\n" + "- Trading recommendation (BUY/WAIT/SKIP)" + "\n" + "- Risk level assessment" + ) + + prompt = ChatPromptTemplate.from_messages( + [ + ( + "system", + "You are a helpful AI assistant specialized in pump detection. " + "You have access to the following tools: {tool_names}.\n{system_message}", + ), + MessagesPlaceholder(variable_name="messages"), + ] + ) + + prompt = prompt.partial(system_message=system_message) + prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) + + # Bind tools to the LLM + chain = prompt | llm.bind_tools(tools) + + # Initialize messages if needed + if not state.get("messages"): + user_input = f"Analyze {ticker} for pump opportunities using all detection methods." + state["messages"] = [("user", user_input)] + + # Invoke the chain + result = chain.invoke(state) + + # Add pump analysis to state + return { + "messages": state["messages"] + [result], + "pump_report": result.content if hasattr(result, 'content') else str(result), + } + + return pump_detection_node diff --git a/tradingagents/agents/utils/pump_detection_tools.py b/tradingagents/agents/utils/pump_detection_tools.py new file mode 100644 index 00000000..52f6636c --- /dev/null +++ b/tradingagents/agents/utils/pump_detection_tools.py @@ -0,0 +1,414 @@ +""" +Pump Detection Tools +Tools for identifying stocks that may experience sudden price increases. +Detects patterns like volume spikes, price acceleration, social sentiment surges, etc. +""" + +from langchain_core.tools import tool +from typing import Annotated +from tradingagents.dataflows.interface import route_to_vendor +import json + + +@tool +def detect_volume_spike( + symbol: Annotated[str, "ticker symbol of the company"], + curr_date: Annotated[str, "The current trading date, YYYY-mm-dd"], + look_back_days: Annotated[int, "how many days to look back for comparison"] = 20, + threshold_multiplier: Annotated[float, "volume spike threshold (e.g., 2.0 = 2x average)"] = 2.0, +) -> str: + """ + Detect abnormal volume spikes that may indicate pump activity. + Volume spikes are early indicators of increased market interest. + + Args: + symbol: Ticker symbol + curr_date: Current trading date + look_back_days: Historical period to calculate average volume + threshold_multiplier: How many times the average volume to flag as spike + + Returns: + Analysis of volume spike patterns + """ + try: + # Get historical stock data + stock_data = route_to_vendor("get_stock_data", symbol, curr_date, look_back_days) + + # Parse the CSV data + lines = stock_data.strip().split('\n') + if len(lines) < 2: + return f"Insufficient data for {symbol} to analyze volume spikes" + + # Skip header and parse volumes + volumes = [] + dates = [] + for line in lines[1:]: + parts = line.split(',') + if len(parts) >= 6: + try: + volume = float(parts[5]) + volumes.append(volume) + dates.append(parts[0]) + except: + continue + + if not volumes: + return f"Could not extract volume data for {symbol}" + + # Calculate average volume (excluding today) + if len(volumes) > 1: + avg_volume = sum(volumes[:-1]) / len(volumes[:-1]) + current_volume = volumes[-1] + else: + avg_volume = volumes[0] + current_volume = volumes[0] + + spike_ratio = current_volume / avg_volume if avg_volume > 0 else 0 + is_spike = spike_ratio >= threshold_multiplier + + result = f"""## Volume Spike Analysis for {symbol} + +**Current Volume**: {current_volume:,.0f} shares +**Average Volume (last {look_back_days} days)**: {avg_volume:,.0f} shares +**Spike Ratio**: {spike_ratio:.2f}x +**Threshold**: {threshold_multiplier}x +**SPIKE DETECTED**: {'YES ⚠️' if is_spike else 'NO'} + +### Interpretation: +""" + if is_spike: + result += f"🚨 **PUMP SIGNAL**: Volume is {spike_ratio:.1f}x the average. This suggests increased institutional or retail interest." + else: + result += f"Normal volume activity. Current volume is {spike_ratio:.1f}x average (threshold: {threshold_multiplier}x)." + + return result + + except Exception as e: + return f"Error analyzing volume spike for {symbol}: {str(e)}" + + +@tool +def detect_price_acceleration( + symbol: Annotated[str, "ticker symbol of the company"], + curr_date: Annotated[str, "The current trading date, YYYY-mm-dd"], + look_back_days: Annotated[int, "how many days to look back"] = 10, +) -> str: + """ + Detect rapid price acceleration that may indicate a pump. + Compares recent gains to longer-term performance. + + Args: + symbol: Ticker symbol + curr_date: Current trading date + look_back_days: Historical period to analyze + + Returns: + Analysis of price acceleration patterns + """ + try: + stock_data = route_to_vendor("get_stock_data", symbol, curr_date, look_back_days) + + lines = stock_data.strip().split('\n') + if len(lines) < 3: + return f"Insufficient data for {symbol} to analyze price acceleration" + + # Parse closing prices + prices = [] + dates = [] + for line in lines[1:]: + parts = line.split(',') + if len(parts) >= 5: + try: + close = float(parts[4]) + prices.append(close) + dates.append(parts[0]) + except: + continue + + if len(prices) < 3: + return f"Could not extract sufficient price data for {symbol}" + + prices.reverse() # Make chronological order + + # Calculate gains + overall_gain = ((prices[-1] - prices[0]) / prices[0]) * 100 if prices[0] > 0 else 0 + + # Calculate recent acceleration (last 3 days vs before) + if len(prices) >= 4: + recent_gain = ((prices[-1] - prices[-3]) / prices[-3]) * 100 if prices[-3] > 0 else 0 + older_gain = ((prices[-3] - prices[0]) / prices[0]) * 100 if prices[0] > 0 else 0 + else: + recent_gain = overall_gain + older_gain = 0 + + is_accelerating = recent_gain > 5 and recent_gain > (older_gain * 1.5) if older_gain != 0 else recent_gain > 5 + + result = f"""## Price Acceleration Analysis for {symbol} + +**Overall Gain ({look_back_days} days)**: {overall_gain:+.2f}% +**Recent Gain (last 3 days)**: {recent_gain:+.2f}% +**Older Gain (before that)**: {older_gain:+.2f}% +**ACCELERATION DETECTED**: {'YES ⚠️' if is_accelerating else 'NO'} + +### Interpretation: +""" + if is_accelerating: + result += f"🚨 **PUMP SIGNAL**: Price accelerating rapidly with {recent_gain:.1f}% gain in last 3 days. Potential pump momentum building." + else: + result += f"Price movement steady or decelerating. Recent: {recent_gain:.1f}%, Overall: {overall_gain:.1f}%" + + return result + + except Exception as e: + return f"Error analyzing price acceleration for {symbol}: {str(e)}" + + +@tool +def detect_social_sentiment_surge( + symbol: Annotated[str, "ticker symbol of the company"], + curr_date: Annotated[str, "The current trading date, YYYY-mm-dd"], +) -> str: + """ + Detect surges in social media sentiment that often precede pump moves. + Monitors Reddit, Twitter, StockTwits for unusual activity. + + Args: + symbol: Ticker symbol + curr_date: Current trading date + + Returns: + Analysis of social sentiment patterns + """ + try: + # Try to get trending social data + social_data = route_to_vendor("get_trending_social", curr_date, 3, 50) + + # Check if our symbol is in trending data + is_trending = symbol.upper() in social_data.upper() + + result = f"""## Social Sentiment Surge Analysis for {symbol} + +**Trending Status**: {'YES 🔥' if is_trending else 'NO'} + +### Current Market Buzz: +{social_data[:500]}... + +### Interpretation: +""" + if is_trending: + result += f"🚨 **PUMP SIGNAL**: {symbol} is actively buzzing on social platforms. High retail interest detected." + else: + result += f"{symbol} is not currently in top trending stocks. Limited social momentum at this time." + + return result + + except Exception as e: + return f"Error analyzing social sentiment for {symbol}: {str(e)}" + + +@tool +def detect_oversold_bounce( + symbol: Annotated[str, "ticker symbol of the company"], + curr_date: Annotated[str, "The current trading date, YYYY-mm-dd"], + rsi_threshold: Annotated[int, "RSI threshold for oversold (default 30)"] = 30, +) -> str: + """ + Detect oversold conditions that often precede pump bounces. + Uses RSI and other momentum indicators. + + Args: + symbol: Ticker symbol + curr_date: Current trading date + rsi_threshold: RSI value threshold (below = oversold) + + Returns: + Analysis of oversold bounce potential + """ + try: + # Get RSI indicator + rsi_data = route_to_vendor("get_indicators", symbol, "rsi", curr_date, 5) + + # Parse RSI values to find current + lines = rsi_data.split('\n') + current_rsi = None + + for line in lines: + if curr_date in line: + # Extract the RSI value + parts = line.split(':') + if len(parts) >= 2: + try: + current_rsi = float(parts[-1].strip()) + break + except: + continue + + if current_rsi is None: + # Try to get any RSI value + for line in lines: + if 'N/A' not in line and ':' in line and len(line.split(':')) >= 2: + try: + val = float(line.split(':')[-1].strip()) + if 0 <= val <= 100: + current_rsi = val + break + except: + continue + + is_oversold = current_rsi is not None and current_rsi < rsi_threshold + + result = f"""## Oversold Bounce Analysis for {symbol} + +**Current RSI**: {current_rsi:.1f if current_rsi else 'N/A'} +**Oversold Threshold**: {rsi_threshold} +**OVERSOLD**: {'YES ⚠️' if is_oversold else 'NO'} + +### Interpretation: +""" + if is_oversold: + result += f"🚨 **PUMP SIGNAL**: RSI at {current_rsi:.1f} indicates oversold conditions. High probability of bounce/recovery pump." + else: + result += f"RSI at {current_rsi:.1f if current_rsi else 'N/A'} - not in oversold territory. Lower bounce probability." + + return result + + except Exception as e: + return f"Error analyzing oversold bounce for {symbol}: {str(e)}" + + +@tool +def detect_catalyst_event( + symbol: Annotated[str, "ticker symbol of the company"], + curr_date: Annotated[str, "The current trading date, YYYY-mm-dd"], +) -> str: + """ + Detect upcoming or recent catalyst events that could trigger pumps. + Looks for earnings, FDA approvals, partnerships, etc. + + Args: + symbol: Ticker symbol + curr_date: Current trading date + + Returns: + Analysis of potential catalyst events + """ + try: + # Check earnings calendar + earnings_data = route_to_vendor("get_earnings_calendar", "3month", symbol) + + has_catalyst = "earnings" in earnings_data.lower() or "scheduled" in earnings_data.lower() + + result = f"""## Catalyst Event Analysis for {symbol} + +**Upcoming Catalysts**: {'YES 📅' if has_catalyst else 'NO'} + +### Catalyst Information: +{earnings_data[:400]}... + +### Interpretation: +""" + if has_catalyst: + result += f"🚨 **PUMP SIGNAL**: Upcoming catalyst event detected. Catalysts drive pump volume and speculation." + else: + result += f"No major catalysts identified in the next 3 months." + + return result + + except Exception as e: + return f"Error analyzing catalyst events for {symbol}: {str(e)}" + + +@tool +def calculate_pump_score( + symbol: Annotated[str, "ticker symbol"], + volume_spike_detected: Annotated[bool, "whether volume spike was detected"], + price_acceleration_detected: Annotated[bool, "whether price acceleration was detected"], + social_sentiment_surge: Annotated[bool, "whether social sentiment surge was detected"], + oversold_bounce: Annotated[bool, "whether oversold bounce signal was detected"], + catalyst_event: Annotated[bool, "whether catalyst event exists"], +) -> str: + """ + Calculate a composite pump probability score (0-100) based on detected signals. + + Args: + symbol: Ticker symbol + volume_spike_detected: Boolean + price_acceleration_detected: Boolean + social_sentiment_surge: Boolean + oversold_bounce: Boolean + catalyst_event: Boolean + + Returns: + Pump score and risk assessment + """ + # Score calculation + score = 0 + signals_detected = 0 + + weights = { + "volume_spike": 25, + "price_acceleration": 20, + "social_sentiment": 15, + "oversold_bounce": 20, + "catalyst": 20, + } + + if volume_spike_detected: + score += weights["volume_spike"] + signals_detected += 1 + + if price_acceleration_detected: + score += weights["price_acceleration"] + signals_detected += 1 + + if social_sentiment_surge: + score += weights["social_sentiment"] + signals_detected += 1 + + if oversold_bounce: + score += weights["oversold_bounce"] + signals_detected += 1 + + if catalyst_event: + score += weights["catalyst"] + signals_detected += 1 + + # Risk assessment + if score >= 70: + risk_level = "🔴 VERY HIGH RISK - HIGH PUMP PROBABILITY" + recommendation = "Strong indicators of potential pump. Exercise caution and use tight stop-losses." + elif score >= 50: + risk_level = "🟠 HIGH RISK - MODERATE PUMP PROBABILITY" + recommendation = "Multiple signals detected. Consider entry with risk management." + elif score >= 30: + risk_level = "🟡 MODERATE RISK - LOW PUMP PROBABILITY" + recommendation = "Some signals present. Requires additional confirmation before entry." + else: + risk_level = "🟢 LOW RISK - LOW PUMP PROBABILITY" + recommendation = "Limited pump signals. Better to wait for stronger setup." + + result = f"""## Pump Detection Score for {symbol} + +**Pump Probability Score**: {score}/100 +**Signals Detected**: {signals_detected}/5 +**Risk Level**: {risk_level} + +### Signal Breakdown: +- Volume Spike: {'✅' if volume_spike_detected else '❌'} +- Price Acceleration: {'✅' if price_acceleration_detected else '❌'} +- Social Sentiment Surge: {'✅' if social_sentiment_surge else '❌'} +- Oversold Bounce Setup: {'✅' if oversold_bounce else '❌'} +- Catalyst Event: {'✅' if catalyst_event else '❌'} + +### Recommendation: +{recommendation} + +### Risk Management: +- Enter with small position size (1-2% of portfolio) +- Use tight stop-loss (2-3% below entry) +- Set profit targets at resistance levels +- Monitor volume and momentum continuously +- Exit on volume decline or reversal signals +""" + + return result diff --git a/tradingagents/graph/setup.py b/tradingagents/graph/setup.py index e99046c6..6472c6c3 100644 --- a/tradingagents/graph/setup.py +++ b/tradingagents/graph/setup.py @@ -38,7 +38,10 @@ class GraphSetup: self.conditional_logic = conditional_logic def setup_graph( - self, selected_analysts=["market", "social", "news", "fundamentals"] + self, + selected_analysts=["market", "social", "news", "fundamentals"], + include_screening=False, + include_pump_detection=False, ): """Set up and compile the agent workflow graph. @@ -48,6 +51,8 @@ class GraphSetup: - "social": Social media analyst - "news": News analyst - "fundamentals": Fundamentals analyst + include_screening (bool): Whether to include market screening agent + include_pump_detection (bool): Whether to include pump detection agent """ if len(selected_analysts) == 0: raise ValueError("Trading Agents Graph Setup Error: no analysts selected!") @@ -85,6 +90,18 @@ class GraphSetup: delete_nodes["fundamentals"] = create_msg_delete() tool_nodes["fundamentals"] = self.tool_nodes["fundamentals"] + # Create optional screening and pump detection agents + screening_node = None + pump_detection_node = None + + if include_screening: + screening_node = create_screening_agent(self.quick_thinking_llm) + tool_nodes["screening"] = self.tool_nodes.get("screening") + + if include_pump_detection: + pump_detection_node = create_pump_detection_agent(self.quick_thinking_llm) + tool_nodes["pump_detection"] = self.tool_nodes.get("pump_detection") + # Create researcher and manager nodes bull_researcher_node = create_bull_researcher( self.quick_thinking_llm, self.bull_memory @@ -117,6 +134,14 @@ class GraphSetup: workflow.add_node(f"tools_{analyst_type}", tool_nodes[analyst_type]) # Add other nodes + if screening_node: + workflow.add_node("Screening Agent", screening_node) + workflow.add_node("tools_screening", tool_nodes["screening"]) + + if pump_detection_node: + workflow.add_node("Pump Detection Agent", pump_detection_node) + workflow.add_node("tools_pump_detection", tool_nodes["pump_detection"]) + workflow.add_node("Bull Researcher", bull_researcher_node) workflow.add_node("Bear Researcher", bear_researcher_node) workflow.add_node("Research Manager", research_manager_node) @@ -127,9 +152,29 @@ class GraphSetup: workflow.add_node("Risk Judge", risk_manager_node) # Define edges - # Start with the first analyst - first_analyst = selected_analysts[0] - workflow.add_edge(START, f"{first_analyst.capitalize()} Analyst") + # Determine starting node + if include_screening: + # Start with screening agent + workflow.add_edge(START, "Screening Agent") + workflow.add_conditional_edges( + "Screening Agent", + self.conditional_logic.should_continue_market, + ["tools_screening", "Bull Researcher"], + ) + workflow.add_edge("tools_screening", "Screening Agent") + elif include_pump_detection: + # Start with pump detection + workflow.add_edge(START, "Pump Detection Agent") + workflow.add_conditional_edges( + "Pump Detection Agent", + self.conditional_logic.should_continue_market, + ["tools_pump_detection", "Bull Researcher"], + ) + workflow.add_edge("tools_pump_detection", "Pump Detection Agent") + else: + # Start with the first analyst + first_analyst = selected_analysts[0] + workflow.add_edge(START, f"{first_analyst.capitalize()} Analyst") # Connect analysts in sequence for i, analyst_type in enumerate(selected_analysts): diff --git a/tradingagents/graph/trading_graph.py b/tradingagents/graph/trading_graph.py index 877742b5..fa74f02c 100644 --- a/tradingagents/graph/trading_graph.py +++ b/tradingagents/graph/trading_graph.py @@ -33,7 +33,20 @@ from tradingagents.agents.utils.agent_utils import ( get_news, get_insider_sentiment, get_insider_transactions, - get_global_news + get_global_news, + get_market_movers, + get_earnings_calendar, + get_trending_social, +) + +# Import pump detection tools +from tradingagents.agents.utils.pump_detection_tools import ( + detect_volume_spike, + detect_price_acceleration, + detect_social_sentiment_surge, + detect_oversold_bounce, + detect_catalyst_event, + calculate_pump_score, ) from .conditional_logic import ConditionalLogic @@ -51,6 +64,8 @@ class TradingAgentsGraph: selected_analysts=["market", "social", "news", "fundamentals"], debug=False, config: Dict[str, Any] = None, + include_screening=False, + include_pump_detection=False, ): """Initialize the trading agents graph and components. @@ -58,6 +73,8 @@ class TradingAgentsGraph: selected_analysts: List of analyst types to include debug: Whether to run in debug mode config: Configuration dictionary. If None, uses default config + include_screening: Whether to include market screening agent + include_pump_detection: Whether to include pump detection agent """ self.debug = debug self.config = config or DEFAULT_CONFIG @@ -117,11 +134,15 @@ class TradingAgentsGraph: self.ticker = None self.log_states_dict = {} # date to full state dict - # Set up the graph - self.graph = self.graph_setup.setup_graph(selected_analysts) + # Set up the graph with optional screening and pump detection + self.graph = self.graph_setup.setup_graph( + selected_analysts, + include_screening=include_screening, + include_pump_detection=include_pump_detection, + ) def _create_tool_nodes(self) -> Dict[str, ToolNode]: - """Create tool nodes for different data sources using abstract methods.""" + """Create tool nodes for different data sources and agents using abstract methods.""" return { "market": ToolNode( [ @@ -155,6 +176,27 @@ class TradingAgentsGraph: get_income_statement, ] ), + "screening": ToolNode( + [ + # Market screening tools + get_market_movers, + get_earnings_calendar, + get_insider_transactions, + get_indicators, + get_trending_social, + ] + ), + "pump_detection": ToolNode( + [ + # Pump detection tools + detect_volume_spike, + detect_price_acceleration, + detect_social_sentiment_surge, + detect_oversold_bounce, + detect_catalyst_event, + calculate_pump_score, + ] + ), } def propagate(self, company_name, trade_date):