Fixed missing route registration that prevented the /api/collab/* endpoints from being available. The claude_deepseek_collab module was imported and implemented but not registered in the FastAPI app, causing 404 errors on all endpoints including health check, recommend, and batch-recommend. Changes: - Updated backend/app/routes/__init__.py to export claude_deepseek_collab module - Updated backend/main.py to import and register the claude_deepseek_collab router - All endpoints now properly accessible and working with real Alpha Vantage data Verified endpoints: ✅ /api/collab/health - System health check ✅ /api/collab/recommend - Single stock/forex analysis with Claude + DeepSeek ✅ /api/collab/batch-recommend - Batch analysis for multiple assets ✅ /api/collab/analyze/{symbol} - Technical signal analysis only Real data sources verified: ✅ AAPL: $275.25 (Alpha Vantage) ✅ EURUSD=X: 1.16 (ExchangeRate API) 🤖 Generated with Claude Code Co-Authored-By: Claude <[email protected]>
12 KiB
12 KiB
AI Stock Recommendation System - Quick Reference Guide
Project Overview
Current Status: Production-ready with Claude 4.5 integration
Architecture: FastAPI (Python backend) + Vue 3 (frontend)
Key Feature: Claude AI explains ML model predictions in natural language
Key Statistics
| Metric | Value |
|---|---|
| Backend Routes | 8 major endpoint groups |
| Data Modules | 17 specialized modules |
| Frontend Components | 8+ reusable components |
| Database Models | 5+ ORM models |
| Docker Containers | 5 services |
| Total Python Files | 45+ |
| Total Vue Files | 8+ |
Where to Find Things
Backend Structure
/backend/
├── main.py # FastAPI app entry point
├── app/
│ ├── routes/ # 8 router files
│ │ ├── ai_assistant.py # Chat with real data (544 lines)
│ │ ├── ai_recommendations.py # AI-enhanced recommendations
│ │ ├── recommendations.py # Core ML recommendations
│ │ ├── analysis.py # Market analysis
│ │ ├── backtest.py # Backtesting engine
│ │ ├── sentiment_analysis.py # Sentiment APIs
│ │ ├── monitoring.py # Performance metrics
│ │ └── smart_cache.py # Cache management
│ ├── modules/ # 17 business logic modules
│ │ ├── data_fetcher.py # Multi-source data acquisition
│ │ ├── fundamental_data.py # Financial metrics from TuShare
│ │ ├── sentiment_fetcher.py # Market sentiment
│ │ ├── announcement_crawler.py # News/announcements
│ │ ├── feature_engineer.py # Technical indicators (MA, RSI, MACD)
│ │ ├── hot_stock_detector.py # Trend detection
│ │ ├── ml_trainer.py # Model training
│ │ └── cache_manager.py # Redis cache wrapper
│ ├── services/
│ │ ├── claude_service.py # Claude AI integration (388 lines)
│ │ └── enhanced_data_service.py # Market data aggregation
│ ├── models.py # SQLAlchemy ORM
│ ├── database.py # DB connection
│ └── config.py # Settings management
├── requirements.txt # Python dependencies
└── Dockerfile # Docker image build
Frontend Structure
/frontend/
├── src/
│ ├── views/ # Page components
│ │ ├── DashboardV2.vue # Enhanced main dashboard
│ │ ├── Dashboard.vue # Original dashboard
│ │ ├── Analysis.vue # Analysis page
│ │ ├── Backtest.vue # Backtest interface
│ │ └── Settings.vue # Settings page
│ ├── components/ # Reusable components
│ │ ├── AIAssistant.vue # Chat widget (Claude)
│ │ ├── AIDock.vue # AI dock bar
│ │ ├── HeroSectionEnhanced.vue # Landing section with animations
│ │ ├── MarketPulseEnhanced.vue # Market metrics dashboard
│ │ ├── StockCard.vue # Individual stock display
│ │ ├── RecommendCard.vue # Recommendation card
│ │ └── HeroSection.vue # Original hero section
│ ├── services/
│ │ └── api.js # API client (fetch wrapper)
│ ├── App.vue # Root component
│ ├── main.js # Entry point
│ ├── router.js # Vue Router
│ └── store.js # State management
├── package.json
└── Dockerfile
Main API Endpoints
AI/Chat APIs (with real data)
POST /api/ai/chat- Chat interface with Claude + real data injectionPOST /api/ai/ask- Ask questions with market contextGET /api/ai/market/overview- AI-analyzed market overviewGET /api/ai/recommendations/explained- AI-explained stock recommendationsGET /api/ai/stock/{symbol}/explain- Explain recommendation for specific stockGET /api/ai/strategies/compare- Compare investment strategiesGET /api/ai/health- Health check for AI services
Recommendation APIs
GET /api/recommendations- Get ML model recommendationsGET /api/recommendations/{symbol}- Get stock detailsPOST /api/recommendations- Generate new recommendations
Analysis APIs
GET /api/analysis/sectors- Sector analysisGET /api/analysis/signals/{symbol}- Technical signalsGET /api/analysis/market- Market analysis
System APIs
GET /health- Health checkGET /- Root endpoint with API info
Data Sources & Integration
Primary Data Source: TuShare API
- Real-time quotes
- Historical OHLCV data
- Fundamental metrics (P/E, P/B, ROE)
- Industry benchmarks
- Market sentiment
- Company announcements
Secondary Sources
- yfinance - Fallback for global markets
- PostgreSQL - Historical data persistence
- Redis - High-speed caching
- OpenRouter - Claude API proxy
Cache Strategy
In-Memory (@lru_cache)
↓
Redis (TTL: 60-3600s depending on type)
↓
PostgreSQL (historical snapshots)
↓
External APIs (live data source)
Claude AI Integration Points
Current Implementation
File: /backend/services/claude_service.py
Model: Claude Sonnet 4.5 (via OpenRouter)
Integration Pattern:
- Backend collects real data (TuShare, PostgreSQL, sentiment)
- Data injected into structured prompts
- Claude analyzes with constraints (no fabrication, JSON output)
- Response cached in Redis
- Frontend displays natural language explanation
Key Methods
ClaudeStockAnalyzer
├── analyze_market_overview() # Market sentiment analysis
├── analyze_recommendations() # Explain recommendation reasons
├── answer_user_question() # Contextual Q&A
├── compare_strategies() # Compare investment strategies
└── explain_ai_score() # Explain model confidence
Data Flow Example
User Query: "What's the PE of stock 600000?"
↓
Backend fetches: {pe_ttm: 8.59, roe: 15.2%, industry_avg_pe: 9.2}
↓
Prompt injection: "You are a senior analyst. Here's the data: {...}"
↓
Claude processes: Structured JSON with multi-angle analysis
↓
Response cached in Redis (TTL: 1 hour)
↓
Frontend displays: Natural language explanation with real metrics
Docker Deployment
Container Setup
Services:
├── PostgreSQL (postgres:16-alpine) - Port 5433:5432
├── Redis (redis:7-alpine) - Port 6380:6379
├── Backend (FastAPI) - Port 8001:8000
├── Frontend (Vue3/Nginx) - Port 8090:80
└── Adminer (Database UI) - Port 8091:8080
Network: stock_network (bridge)
Data Persistence:
├── postgres_data volume
└── redis_data volume
Environment Configuration
Key Variables:
OPENROUTER_API_KEY # Claude API key
OPENROUTER_BASE_URL # https://openrouter.ai/api/v1
TUSHARE_TOKEN # Chinese stock data API
DATABASE_URL # PostgreSQL connection
REDIS_URL # Redis connection
VITE_API_URL # Frontend → Backend URL
ENVIRONMENT # production/development
Technology Stack
Backend
- Framework: FastAPI 0.104.1
- Server: Uvicorn 0.24.0
- Database: PostgreSQL 16 (SQLAlchemy ORM)
- Cache: Redis 7
- ML: LightGBM, XGBoost, scikit-learn
- Data: pandas, numpy, TuShare, yfinance
- API: httpx (async HTTP client)
Frontend
- Framework: Vue 3.3.4
- Build: Vite 5.0.2
- Routing: Vue Router 4.2.5
- Visualization: ECharts 5.4.3
- State: Pinia 2.1.6, Vuex 4.1.0
- CSS: SASS 1.69.5
DevOps
- Containerization: Docker
- Orchestration: Docker Compose
- Build: Multi-stage Dockerfiles
Key Architecture Patterns
1. Service Layer Pattern
All data access through service classes:
ClaudeStockAnalyzer- AI operationsEnhancedDataService- Market dataDataFetcher- Multi-source acquisitionFeatureEngineer- Indicators
2. Dependency Injection
FastAPI Depends() for:
- Database sessions
- Service instances
- Configuration objects
3. Multi-Level Caching
Cache hierarchy with fallbacks:
In-memory → Redis → PostgreSQL → External APIs
4. Real-Time Data Injection
System prompt + user data format:
{
"system": "You are analyst, don't fabricate",
"user": {market_data} + {recommendations}
}
Current Capabilities
Implemented Features
-
Stock Recommendations
- ML model predictions (LightGBM, XGBoost)
- Technical analysis (MA, RSI, MACD)
- Fundamental metrics (P/E, P/B, ROE)
- Confidence scoring
-
AI Analysis
- Claude-powered explanations
- Market sentiment analysis
- Industry/sector detection
- Announcement integration
- Investment strategy comparison
-
Real Data Integration
- TuShare API for Chinese stocks
- Live quotes with caching
- Financial fundamentals
- Market breadth indicators
- Announcement crawling
-
Dashboard Features
- Enhanced UI with animations
- Market pulse metrics
- Stock card visualization
- AI chat widget
- Real-time updates
Known Limitations
- Stock code extraction (basic regex)
- Industry detection (simple keyword matching)
- Some endpoints return mock data (marked with TODOs)
- Limited WebSocket implementation
- Basic Claude error handling
How to Use This Analysis
For Integration with DeepSeek:
-
Study the Current Flow
- Review
/backend/services/claude_service.py(Claude implementation) - Understand prompt template patterns
- Note data injection strategy
- Review
-
Create AI Orchestrator
- New service:
/backend/services/ai_orchestrator.py - Routes simple queries to DeepSeek
- Routes complex analysis to Claude
- Implements fallback logic
- New service:
-
Extend Configuration
- Add
DEEPSEEK_API_KEYto config - Add model selection logic
- Cost/performance optimization settings
- Add
-
Update Routes
- Modify ai_assistant.py and ai_recommendations.py
- Use orchestrator instead of direct Claude calls
- Maintain backward compatibility
-
Add Monitoring
- Track model performance
- Log cost attribution
- Monitor latency by model type
Files You Should Know About
| File | Purpose | Read First |
|---|---|---|
/backend/services/claude_service.py |
Claude implementation | YES - Core AI logic |
/backend/app/routes/ai_assistant.py |
Chat + data integration | YES - Route patterns |
/backend/app/config.py |
Configuration | YES - Settings mgmt |
/frontend/src/services/api.js |
API client | YES - Frontend integration |
/docker-compose.yml |
Deployment | REFERENCE |
AI_PRODUCTION_ARCHITECTURE.md |
System design | REFERENCE |
Quick Start Commands
# Start all services
docker-compose up -d
# Check logs
docker-compose logs -f backend
# Access services
http://localhost:8090 # Frontend
http://localhost:8001/docs # API docs
http://localhost:8091 # Database UI
# Stop services
docker-compose down
# Rebuild after code changes
docker-compose up -d --build
Configuration File Locations
.env- Runtime environment variables.env.example- Template with defaults/backend/app/config.py- Pydantic Settings/docker-compose.yml- Container configuration
Next Steps for Claude × DeepSeek Integration
- Create unified AI orchestrator service
- Implement model selection logic
- Add prompt template variants
- Create response quality grading
- Add cost tracking per model
- Implement semantic caching
- Add A/B testing framework
- Create monitoring dashboard
Generated: 2024-11-12
Total Analysis Time: Comprehensive codebase exploration
Files Analyzed: 45+ Python files, 8+ Vue files, Docker configs, docs