AndreChuabio/mcp-yfinance-server
If you are the rightful owner of mcp-yfinance-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
The MCP YFinance Server is a minimal Model Context Protocol server designed to provide stock data tools using yfinance for financial data queries.
MCP YFinance Server - Complete Financial Analysis Suite
A comprehensive MCP (Model Context Protocol) server that combines real-time sentiment analysis, stock data analysis, and paper trading functionality.
🌟 Features
Stock Data Analysis
- Get current stock prices and trading information
- Historical price data with customizable periods
- Detailed company information and financial metrics
Advanced Sentiment Analysis
- Real-time sentiment analysis using Google Gemini AI
- News sentiment from Alpha Vantage and NewsAPI
- Social media sentiment from Reddit (r/wallstreetbets, r/stocks, r/investing)
- Intelligent caching to minimize API calls
- Batch processing for multiple tickers
- Historical sentiment tracking
- Trending ticker detection
Paper Trading (REAL API Integration)
- View your REAL Paper Invest account balance and positions
- Execute REAL buy/sell orders in your Paper Invest account
- JWT authentication with Paper Invest API
- Live order execution and portfolio management
🚀 Quick Start
Prerequisites
- Node.js 16+ for sentiment analysis server
- Python 3.11+ for MCP server (if using Python components)
Installation
-
Clone and navigate to the project:
cd mcp-server -
Install Node.js dependencies:
npm install -
Configure environment variables:
cp .env.example .env -
Add your API keys to
.env:GEMINI_API_KEY: Get from Google AI StudioALPHA_VANTAGE_API_KEY: Get from Alpha VantageNEWS_API_KEY: Get from NewsAPIFMP_API_KEY: Get from Financial Modeling Prep- Reddit credentials (optional): Get from Reddit Apps
-
Start the server:
npm start
📊 Sentiment Analysis API Endpoints
Single Ticker Sentiment
GET /sentiment/ticker/{symbol}?social=true
Analyzes sentiment for a single ticker with comprehensive source breakdown.
Parameters:
symbol: Stock ticker (e.g., AAPL, TSLA)social: Include social media sentiment (optional, default: false)
Response:
{
"ticker": "AAPL",
"timestamp": "2025-12-12T00:00:00Z",
"sentiment_score": 0.45,
"sentiment_label": "positive",
"confidence": 0.78,
"sources_analyzed": 25,
"source_breakdown": {
"news": {"score": 0.52, "count": 15},
"social": {"score": 0.38, "count": 10}
},
"top_headlines": [
{
"title": "Apple announces new product",
"score": 0.8,
"source": "Reuters",
"url": "https://..."
}
]
}
Batch Analysis
POST /sentiment/analyze
Analyzes multiple tickers simultaneously for efficient bulk processing.
Request Body:
{
"tickers": ["AAPL", "MSFT", "GOOGL"],
"includeSocial": false,
"newsLimit": 20,
"socialLimit": 30
}
Trending Sentiment Detection
GET /sentiment/trending?tickers=AAPL,TSLA,NVDA&threshold=0.3
Identifies tickers with significant sentiment shifts and momentum.
🛠 MCP Tools Documentation
Stock Data Tools
get_stock_price
Get current stock price and basic trading information.
Parameters:
symbol(string, required): Stock ticker symbol (e.g., AAPL, GOOGL, TSLA)
get_stock_history
Get historical price data for specified date ranges.
Parameters:
symbol(string, required): Stock ticker symbolperiod(string, optional): 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max (default: 1mo)
get_stock_info
Get detailed company information and key financial metrics.
Parameters:
symbol(string, required): Stock ticker symbol
Paper Trading Tools
get_portfolio_balance
View your current REAL Paper Invest account balance and positions.
Parameters: None
place_buy_order
Execute a REAL buy order in your Paper Invest account.
Parameters:
symbol(string, required): Stock ticker symbolshares(number, required): Number of shares to buy
place_sell_order
Execute a REAL sell order in your Paper Invest account.
Parameters:
symbol(string, required): Stock ticker symbolshares(number, required): Number of shares to sell
📈 Sentiment Scoring System
Sentiment scores range from -1 (very negative) to +1 (very positive):
- 0.2 to 1.0: Positive sentiment - Bullish indicators
- -0.2 to 0.2: Neutral sentiment - Mixed signals
- -1.0 to -0.2: Negative sentiment - Bearish indicators
🧪 Testing
Run Sentiment Analysis Tests:
npm test
Test Individual Components:
# Start sentiment server
npm start
# In another terminal
node tests/sentiment.test.js
node tests/health.test.js
Test Paper Trading:
# Test paper trading functionality
.venv/bin/python tests/test_paper_trading.py
# Complete demo with all features
.venv/bin/python tests/demo_complete.py
🏗 Architecture
mcp-server/
├── src/
│ ├── index.js # Main server with API routes
│ └── sentiment/
│ ├── sentimentAnalyzer.js # Core sentiment logic with Gemini AI
│ ├── newsProvider.js # Financial news integration
│ ├── socialProvider.js # Social media sentiment
│ └── cache.js # Intelligent caching layer
├── tests/ # Comprehensive test suite
├── mcp_yfinance_server.py # MCP server implementation
└── docs/ # Setup and configuration guides
⚡ Performance & Optimization
- Intelligent Caching: Reduces API calls by 60%+ with 30-minute TTL
- Batch Processing: Analyze 5 tickers in under 5 seconds
- Rate Limiting: Respects all API limits and provides fallback strategies
- Async Architecture: Non-blocking operations for optimal performance
🔒 API Rate Limits & Management
Free Tier Limits:
- Gemini AI: 60 requests/minute
- Alpha Vantage: 25 requests/day
- NewsAPI: 100 requests/day
- Reddit: 60 requests/minute
- Financial Modeling Prep: 250 requests/day
Rate Limit Strategies:
- Automatic fallback to VADER sentiment when Gemini is rate limited
- Intelligent caching prevents duplicate API calls
- Batch processing optimizes API usage
- Graceful degradation when services are unavailable
🚨 Error Handling & Reliability
The server provides comprehensive error handling for:
- Invalid stock symbols with helpful suggestions
- Network connectivity issues and timeouts
- API service limitations and outages
- Missing or incomplete financial data
- Authentication failures with clear guidance
🎯 Production Readiness Features
- Real Paper Trading Integration: Live connection to Paper Invest API
- Comprehensive Logging: Full request/response logging for debugging
- Environment Configuration: Secure API key management
- Modular Architecture: Easily extendable for new data sources
- Test Coverage: Full test suite for all major functionality
🔮 Future Enhancements
- Advanced Analytics: Technical indicator integration
- Real-time Streaming: WebSocket support for live updates
- Database Persistence: Historical data storage for backtesting
- Visualization Dashboard: Interactive charts and analytics
- ML Model Integration: Custom sentiment models and predictions
- Multi-broker Support: Additional trading platform integrations
📊 Supported Data Sources
Stock Symbols: All Yahoo Finance supported symbols including:
- US stocks (AAPL, GOOGL, MSFT, etc.)
- International markets with proper suffixes
- ETFs, mutual funds, and indexes
- Cryptocurrencies (BTC-USD, ETH-USD, etc.)
News Sources:
- Alpha Vantage financial news
- NewsAPI comprehensive coverage
- Financial Modeling Prep earnings data
Social Media:
- Reddit (r/wallstreetbets, r/stocks, r/investing)
- Twitter integration (configurable)
👨💻 Author
Andre Chua (andre102599@gmail.com)
GitHub: https://github.com/AndreChuabio
Built for quantitative traders and financial analysts who demand real-time sentiment intelligence combined with seamless trading execution.