Files
ljwx-stock/PROJECT_SUMMARY_QUICK_REFERENCE.md
brunoandClaude d364268ca4 fix: Register Claude × DeepSeek collaboration routes in main.py
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]>
2025-11-12 14:55:38 +01:00

12 KiB
Raw Permalink Blame History

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 injection
  • POST /api/ai/ask - Ask questions with market context
  • GET /api/ai/market/overview - AI-analyzed market overview
  • GET /api/ai/recommendations/explained - AI-explained stock recommendations
  • GET /api/ai/stock/{symbol}/explain - Explain recommendation for specific stock
  • GET /api/ai/strategies/compare - Compare investment strategies
  • GET /api/ai/health - Health check for AI services

Recommendation APIs

  • GET /api/recommendations - Get ML model recommendations
  • GET /api/recommendations/{symbol} - Get stock details
  • POST /api/recommendations - Generate new recommendations

Analysis APIs

  • GET /api/analysis/sectors - Sector analysis
  • GET /api/analysis/signals/{symbol} - Technical signals
  • GET /api/analysis/market - Market analysis

System APIs

  • GET /health - Health check
  • GET / - 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:

  1. Backend collects real data (TuShare, PostgreSQL, sentiment)
  2. Data injected into structured prompts
  3. Claude analyzes with constraints (no fabrication, JSON output)
  4. Response cached in Redis
  5. 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 operations
  • EnhancedDataService - Market data
  • DataFetcher - Multi-source acquisition
  • FeatureEngineer - 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

  1. Stock Recommendations

    • ML model predictions (LightGBM, XGBoost)
    • Technical analysis (MA, RSI, MACD)
    • Fundamental metrics (P/E, P/B, ROE)
    • Confidence scoring
  2. AI Analysis

    • Claude-powered explanations
    • Market sentiment analysis
    • Industry/sector detection
    • Announcement integration
    • Investment strategy comparison
  3. Real Data Integration

    • TuShare API for Chinese stocks
    • Live quotes with caching
    • Financial fundamentals
    • Market breadth indicators
    • Announcement crawling
  4. Dashboard Features

    • Enhanced UI with animations
    • Market pulse metrics
    • Stock card visualization
    • AI chat widget
    • Real-time updates

Known Limitations

  1. Stock code extraction (basic regex)
  2. Industry detection (simple keyword matching)
  3. Some endpoints return mock data (marked with TODOs)
  4. Limited WebSocket implementation
  5. Basic Claude error handling

How to Use This Analysis

For Integration with DeepSeek:

  1. Study the Current Flow

    • Review /backend/services/claude_service.py (Claude implementation)
    • Understand prompt template patterns
    • Note data injection strategy
  2. Create AI Orchestrator

    • New service: /backend/services/ai_orchestrator.py
    • Routes simple queries to DeepSeek
    • Routes complex analysis to Claude
    • Implements fallback logic
  3. Extend Configuration

    • Add DEEPSEEK_API_KEY to config
    • Add model selection logic
    • Cost/performance optimization settings
  4. Update Routes

    • Modify ai_assistant.py and ai_recommendations.py
    • Use orchestrator instead of direct Claude calls
    • Maintain backward compatibility
  5. 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

  1. Create unified AI orchestrator service
  2. Implement model selection logic
  3. Add prompt template variants
  4. Create response quality grading
  5. Add cost tracking per model
  6. Implement semantic caching
  7. Add A/B testing framework
  8. Create monitoring dashboard

Generated: 2024-11-12
Total Analysis Time: Comprehensive codebase exploration
Files Analyzed: 45+ Python files, 8+ Vue files, Docker configs, docs