股票市场分析协议

一个全面的股票市场模型上下文协议提供商,为LLM代理、RAG系统和Claude Desktop提供高级市场分析、AI驱动的预测和实时金融数据。

  • by abdullahhsalman-dev
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 abdullahhsalman-dev/stocks-mcp

使用说明

🚀 增强型股票市场MCP(模型上下文协议)

一个全面而先进的股票市场模型上下文协议提供商,使LLM代理、RAG系统和Claude Desktop能够访问复杂的市场分析、人工智能驱动的预测和实时财务数据。

✨ 增强功能

🧠 AI驱动的分析

  • 高级股票预测 -具有ChatGPT集成的LSTM/GRU神经网络
  • 综合风险评估 -波动性分析、最大回撤、相关性指标
  • 投资组合优化 -具有多样化评分的多股票配置建议
  • 智能信号生成 -具有22+个指标的高级技术分析

🔧 增强型MCP工具(共17个)

  • get_comprehensive_analysis -使用混合数据源完成库存分析
  • get_enhanced_technical_analysis -先进的技术指标和信号
  • get_risk_assessment -全面的风险度量和波动性分析
  • get_portfolio_recommendations -投资组合配置与多元化分析
  • predict_stock_price -人工智能驱动的价格预测(神经网络+ChatGPT)
  • get_stock_price -实时和历史股价
  • get_company_overview -公司基本面和财务指标
  • get_market_news -增强情绪分析的新闻标题
  • analyze_news_impact -近期新闻中的股票影响分析
  • get_trending_news -来自谷歌新闻的热门财经新闻
  • get_sector_news -特定行业的市场新闻
  • get_technical_indicators -22+技术指标(RSI、MACD、布林带等)
  • compare_stocks -多股票比较分析
  • search_stocks -增强匹配的语义搜索
  • get_top_gainers -市场推动者和趋势股
  • get_prediction_history -历史AI预测跟踪
  • get_model_performance -AI模型准确性指标和性能

🎯 高级数据集成

  • 混合数据服务 -一级:财务(可靠)+二级:增强刮擦
  • 22+技术指标 -移动平均线、动量、波动率、成交量分析
  • 综合基础 -市盈率、市盈率、净资产收益率、债务比率、市值、增长指标
  • 实时市场数据 -当前价格、交易量、市场状况、货币兑换
  • 增强新闻分析 -谷歌新闻与情绪评分的整合
  • AI特征工程 -35+机器学习模型训练功能

🧮 高级分析

  • 风险度量 -年化波动率、最大回撤、市场相关性
  • 投资组合分析 -相关矩阵、多样化评分、再平衡
  • 信号强度 -技术指标置信度评分
  • 绩效追踪 -预测精度、模型性能监控
  • 市场背景 -标准普尔500指数相关性、行业分析、基于时间的特征

🏗️ 增强架构

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Claude        │    │   Enhanced      │    │  PostgreSQL     │
│   Desktop       │◄───┤   MCP Server    ├────┤  + pgvector     │
│   Integration   │    │   (17 Tools)    │    │  + AI Models    │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                │                        │
                                │                        │
                       ┌─────────────────┐    ┌─────────────────┐
                       │  Hybrid Data    │    │   AI Training   │
                       │  Service        │    │   Pipeline      │
                       │ (yfinance +     │    │ (LSTM/GRU +     │
                       │  Enhanced)      │    │  ChatGPT)       │
                       └─────────────────┘    └─────────────────┘
                                │                        │
                                │                        │
                       ┌─────────────────┐    ┌─────────────────┐
                       │   Google News   │    │     Redis       │
                       │   Sentiment     │    │    Cache        │
                       │   Analysis      │    │  (Performance)  │
                       └─────────────────┘    └─────────────────┘

🚀 快速开始

先决条件

  • Python 3.11+(用于后端)
  • Node.js 18+(用于前端)
  • 带pgvector扩展的PostgreSQL
  • OpenAI API密钥(用于ChatGPT预测)
  • Docker和Docker Compose(推荐)

使用Docker(推荐)

  1. 克隆和设置

    git clone <repository-url>
    cd mcp-stock
    cp backend/.env.example backend/.env
    # Edit backend/.env with your API keys
    
  2. 启动所有服务

    docker-compose up -d
    
  3. 访问应用程序

    • 后端API:http://localhost:8000
    • API文件:http://localhost:8000/docs
    • Claude桌面集成:配置MCP服务器

手动设置

后端设置

cd backend

# Install enhanced dependencies
pip install -r requirements.txt

# Configure environment
cp .env.example .env
# Edit .env with database URL and API keys

# Initialize database with AI models support
python scripts/setup_database.py
alembic upgrade head

# Train initial AI models (optional)
python scripts/train_models.py --popular

# Start enhanced MCP server
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

Claude桌面版MCP服务器

# Run MCP server directly for Claude Desktop
python run_mcp_server.py

🔧 增强配置

所需的环境变量

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/stock_mcp
REDIS_URL=redis://localhost:6379/0

# AI & Analysis APIs
OPENAI_API_KEY=your_openai_key_for_predictions
ALPHA_VANTAGE_API_KEY=your_alpha_vantage_key
NEWS_API_KEY=your_news_api_key

# Security
SECRET_KEY=your_secret_key_here

# Optional: Enhanced Features
ENABLE_AI_PREDICTIONS=true
ENABLE_PORTFOLIO_OPTIMIZATION=true
CACHE_EXPIRY_MINUTES=15

Claude桌面集成

添加到您的Claude Desktop MCP配置中:

{
  "mcpServers": {
    "stock-market": {
      "command": "python",
      "args": ["/path/to/mcp-stock/backend/run_mcp_server.py"],
      "cwd": "/path/to/mcp-stock/backend"
    }
  }
}

📊 高级MCP工具使用

综合库存分析

# Get complete analysis with all data sources
analysis = await get_comprehensive_analysis("AAPL")
# Returns: company info, technical signals, fundamental metrics, 
# recent performance, data quality assessment

人工智能驱动的价格预测

# Neural network prediction (development)
prediction = await predict_stock_price("TSLA", timeframe="1w", use_production=False)

# ChatGPT prediction (production) 
prediction = await predict_stock_price("TSLA", timeframe="1w", use_production=True)
# Returns: predicted price, confidence score, reasoning, key factors

投资组合优化

# Get portfolio recommendations
portfolio = await get_portfolio_recommendations(
    symbols=["AAPL", "GOOGL", "MSFT", "TSLA"], 
    allocation_type="moderate"
)
# Returns: optimal allocation, correlation matrix, risk-return analysis, 
# diversification score, rebalancing suggestions

风险评估

# Comprehensive risk analysis
risk = await get_risk_assessment("NVDA")
# Returns: volatility metrics, drawdown analysis, correlation risk,
# fundamental risk factors, overall risk score

🧠 AI模型训练

训练个人模型

# Train LSTM model for specific stock
python scripts/train_models.py --symbol AAPL --model LSTM --timeframes 1d,1w,1m

# Batch train popular stocks
python scripts/train_models.py --popular

# Retrain underperforming models
python scripts/train_models.py --retrain-underperforming --threshold 0.6

模型性能监控

# Check model performance
performance = await get_model_performance("LSTM")
# Returns: accuracy metrics, prediction history, model status

# Get prediction accuracy history
history = await get_prediction_history("AAPL", limit=20)
# Returns: historical predictions vs actual prices

📈 增强的API端点

人工智能与分析

  • POST /api/v1/ai/predict/{symbol} -人工智能股价预测
  • GET /api/v1/analysis/comprehensive/{symbol} -完整的库存分析
  • GET /api/v1/analysis/risk/{symbol} -风险评估
  • POST /api/v1/portfolio/recommendations -投资组合优化

模型管理

  • POST /api/v1/models/train/{symbol} -训练AI模型
  • POST /api/v1/models/batch-train -批量模型训练
  • GET /api/v1/models/performance -模型性能指标
  • DELETE /api/v1/models/{symbol} -删除训练过的模型

增强技术分析

  • GET /api/v1/technical/enhanced/{symbol} -22+高级指标
  • GET /api/v1/technical/signals/{symbol} -信号强度分析
  • GET /api/v1/technical/support-resistance/{symbol} -支撑/阻力位

🎯 高级用例

AI投资顾问

async def ai_investment_advisor(symbol: str):
    # Comprehensive analysis
    analysis = await get_comprehensive_analysis(symbol)
    
    # AI prediction
    prediction = await predict_stock_price(symbol, "1w", use_production=True)
    
    # Risk assessment
    risk = await get_risk_assessment(symbol)
    
    # Generate recommendation
    recommendation = f"""
    Stock: {symbol}
    Current Price: ${analysis['current_price']}
    AI Prediction (1 week): ${prediction['predicted_price']} 
    Confidence: {prediction['confidence_score']:.1%}
    Risk Score: {risk['overall_risk_score']}/100
    
    Technical Signal: {analysis['technical_summary']['overall']}
    Fundamental: {analysis['fundamental_summary']['valuation']}
    
    Recommendation: {prediction['reasoning']}
    """
    return recommendation

投资组合风险经理

async def portfolio_risk_manager(symbols: List[str]):
    portfolio = await get_portfolio_recommendations(symbols, "conservative")
    
    high_risk_stocks = []
    for symbol in symbols:
        risk = await get_risk_assessment(symbol)
        if risk['overall_risk_score'] > 70:
            high_risk_stocks.append(symbol)
    
    return {
        "optimal_allocation": portfolio['recommended_allocation'],
        "diversification_score": portfolio['diversification_score'],
        "high_risk_positions": high_risk_stocks,
        "rebalancing_needed": len(high_risk_stocks) > 0
    }

市场情绪监测

async def sentiment_monitor(watchlist: List[str]):
    sentiment_summary = {}
    
    for symbol in watchlist:
        news_impact = await analyze_news_impact(symbol)
        sentiment_summary[symbol] = {
            "sentiment_score": news_impact['overall_sentiment'],
            "news_volume": news_impact['total_articles'],
            "impact_level": news_impact['potential_impact']
        }
    
    # Alert on negative sentiment
    alerts = [
        symbol for symbol, data in sentiment_summary.items()
        if data['sentiment_score'] < -0.3
    ]
    
    return {"sentiment_summary": sentiment_summary, "alerts": alerts}

🛠️ 加强发展

项目结构

mcp-stock/
├── backend/
│   ├── app/
│   │   ├── api/              # FastAPI routes
│   │   │   ├── stocks.py     # Stock data endpoints
│   │   │   ├── ai_predictions.py  # AI prediction endpoints
│   │   │   ├── model_management.py # Model training endpoints
│   │   │   └── portfolio.py  # Portfolio management
│   │   ├── core/             # Configuration & database
│   │   ├── mcp/              # Enhanced MCP server (17 tools)
│   │   ├── models/           # SQLAlchemy models + AI models
│   │   ├── schemas/          # Pydantic schemas + AI schemas
│   │   └── services/         # Business logic
│   │       ├── hybrid_data_service.py     # Primary data service
│   │       ├── ai_prediction_service.py   # AI predictions
│   │       ├── model_training_service.py  # Model training
│   │       ├── google_news_service.py     # News analysis
│   │       └── portfolio_service.py       # Portfolio optimization
│   ├── migrations/           # Alembic migrations
│   ├── scripts/              # Enhanced utility scripts
│   │   ├── train_models.py   # AI model training
│   │   └── setup_database.py # Database initialization
│   └── models/               # Trained AI models storage
├── docs/
│   ├── MODEL_TRAINING_STRATEGY.md  # AI training documentation
│   ├── API_DOCUMENTATION.md        # Complete API docs
│   └── MCP_INTEGRATION.md          # Claude Desktop setup
└── docker-compose.yml              # Enhanced Docker setup

测试增强功能

# Test enhanced MCP tools
python simple_final_test.py

# Test AI prediction accuracy
python scripts/test_predictions.py

# Test portfolio optimization
python scripts/test_portfolio.py

🧪 绩效和基准

增强的数据性能

  • 数据收集:~2.5秒用于综合分析(22+指标)
  • AI预测:~3-5s(神经网络)/~8-12s(ChatGPT)
  • 投资组合优化:5只股票约5-10秒
  • 风险评估:每份库存约1-2s

准确性指标(经过测试)

  • 神经网络:65%+方向精度
  • ChatGPT预测:推理的方向准确率超过75%
  • 风险评估:波动率预测准确率超过80%
  • 技术信号:70%以上的信号可靠性

📋 增强路线图

第1阶段(当前)✅

  • [x] 配备17个工具的增强型MCP服务器
  • [x] 人工智能预测模型(LSTM/GRU+ChatGPT)
  • [x] 综合技术分析(22+指标)
  • [x] 投资组合优化算法
  • [x] 风险评估框架

第二阶段(下)

  • []实时WebSocket流媒体
  • []高级投资组合优化(现代投资组合理论)
  • []期权定价模型(Black-Scholes)
  • []加密货币集成
  • []社交情绪分析(推特/红迪)
  • []回溯测试框架

第三阶段(未来)

  • []交易策略的深度强化学习
  • []与经纪商API集成,用于实时交易
  • []带有推送通知的移动应用程序
  • []高级衍生品支持
  • []ESG(环境、社会、治理)分析

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

⚠️ 增强免责声明

此软件仅用于教育和研究目的。人工智能预测和投资组合建议不是财务建议。神经网络和ChatGPT集成是实验特征。在做出投资决策之前,始终咨询合格的财务顾问。过去的表现并不能保证未来的结果。开发人员对使用该软件或其人工智能预测所造成的任何经济损失不承担任何责任。

🏆 主要成就

  • 17个增强型MCP工具 进行全面的市场分析
  • 双AI架构 将神经网络与ChatGPT相结合
  • 22+技术指标 具有先进的信号生成功能
  • 混合数据服务 确保可靠和全面的数据
  • 投资组合优化 现代风险管理
  • 生产准备就绪 与Claude Desktop完全集成
  • 综合测试 具有经过验证的准确性指标

🙏 增强致谢


🚀 准备生产

增强型股票市场MCP现在 生产准备就绪 与:

  • 全面的市场分析能力
  • 人工智能驱动的预测和投资组合优化
  • 无缝集成Claude桌面
  • 强大的错误处理和性能优化
  • 广泛的文档和测试

从今天开始 并将先进的金融人工智能带入您的法学硕士工作流程! 🎯