ChandraVardhan97/MCP-Stock-Analyzer
If you are the rightful owner of MCP-Stock-Analyzer 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.
A secure, production-ready Model Context Protocol (MCP) server and client for stock analysis, integrating Alpha Vantage API for market data and Azure OpenAI for intelligent analysis.
Stock Analysis MCP System with Azure OpenAI
A secure, production-ready Model Context Protocol (MCP) server and client for stock analysis, integrating Alpha Vantage API for market data and Azure OpenAI for intelligent analysis.
Features
- MCP Server: Fetches real-time and historical stock data from Alpha Vantage
- Azure OpenAI Integration: Provides AI-powered stock analysis and investment insights
- Comprehensive Analysis: Technical indicators, fundamentals, and 6-month historical trends
- Security Best Practices: Environment-based configuration, input validation, rate limiting
- Interactive CLI: User-friendly command-line interface for stock queries
Architecture
User Query → MCP Client + Azure OpenAI → MCP Server → Alpha Vantage API
↓
Azure OpenAI
↓
Analysis Result
Prerequisites
- Python 3.9+ installed
- Alpha Vantage API Key (free tier available at https://www.alphavantage.co/support/#api-key)
- Azure OpenAI Service deployment with API access. Note - I have used Azure OpenAI, you can technically use any model/provider. You just need to change the environments variables (API Key, URL and Deployment Name). If you are using any model provider apart from OpenAI, you will need to modify the MCP client and server files accordingly and ensure you are using the apprpriate SDK library to make calls to the model.
- Virtual Environment (recommended)
Installation
- Clone the repository:
git clone <repository-url>
cd mcp-project
- Create virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install dependencies:
pip install -r requirements.txt
- Configure environment variables:
cp .env.example .env
Edit .env with your credentials:
# Alpha Vantage API Configuration
ALPHA_VANTAGE_API_KEY=your_alpha_vantage_key
# Azure OpenAI Configuration
AZURE_OPENAI_API_KEY=your_azure_key
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4
AZURE_OPENAI_API_VERSION=2024-02-15-preview
Usage
Starting the MCP Server
Run the server in one terminal:
python mcp_stock_server.py or ./run_server.sh
The server will:
- Listen for MCP client connections via stdio
- Fetch data from Alpha Vantage API
- Provide tools:
get_current_stock_priceandget_stock_analysis
Using the Client
Interactive Mode
python mcp_client.py or ./run_client.sh
Commands:
ask compare AAPL and MSFT- Detailed comparison of stock fundamentals and technical information with investment recommendation (AI decided what tools to call)analyze AAPL- Full AI-powered analysis of Apple stock (legacy - MCP server provides data to AI so that model can analyze it)price MSFT- Get current Microsoft stock price (Direct call to the AlphaVantage API to get just the price)help- Show available commandsquit- Exit the program
Command-Line Mode
python mcp_client.py --analyze AAPL
Example Interaction
> analyze TSLA
Analyzing TSLA... This may take a moment...
============================================================
AI ANALYSIS FOR TSLA
============================================================
COMPREHENSIVE ANALYSIS:
Current Market Position:
Tesla is currently trading at $242.56, showing strong momentum...
Technical Analysis:
- The stock is trading above its 20-day SMA ($235.40)
- 30-day momentum is positive at +8.5%
- Volatility remains elevated at 42.3
Fundamental Strength:
- P/E Ratio: 58.2 (growth premium justified by expansion)
- Profit Margin: 8.2% (improving quarter-over-quarter)
- Strong revenue growth: +25% YoY
Investment Outlook:
MODERATE BUY - Tesla shows strong growth potential with
expansion into energy storage and autonomous driving...
Risk Factors:
- High valuation multiples
- Regulatory challenges in key markets
- Intense competition in EV space
Recommendation:
Suitable for growth-oriented investors with higher risk tolerance.
Consider dollar-cost averaging given current volatility.
============================================================
Security Features
- Environment-Based Configuration: All sensitive data in
.envfiles - Input Validation: Pydantic models validate all inputs
- Rate Limiting: Configurable request limits to prevent API abuse
- Error Handling: Comprehensive exception handling with logging
- Secure Communication: HTTPS for all external API calls
- No Hardcoded Secrets: All credentials loaded from environment
API Rate Limits
- Alpha Vantage Free Tier: 25 API requests per day. Get the premium plan if you need more.
- Azure OpenAI: Varies by subscription tier/TPM set for the model.
- Configure
MAX_REQUESTS_PER_MINUTEin.envto respect limits
Project Structure
mcp-project/
├── mcp_stock_server.py # MCP server implementation
├── mcp_client.py # Client with Azure OpenAI integration
├── requirements.txt # Python dependencies
├── setup.py # Package setup script
├── .env.example # Environment template
├── .env # Your configuration (git-ignored)
├── .gitignore # Git ignore rules
└── README.md # This file
Testing
Run the test suite:
pytest tests/ -v --cov=.
Troubleshooting
Common Issues
-
"API rate limit reached"
- Wait 60 seconds for Alpha Vantage rate limit reset
- Consider upgrading to premium API plan
-
"Invalid stock"
- Ensure the stock is listed on major US exchanges
-
"Azure OpenAI connection failed"
- Check endpoint URL format (should end with
/) - Verify deployment name matches your Azure configuration
- Ensure API key has proper permissions
- Check endpoint URL format (should end with
-
"MCP server not responding"
- Ensure the server is running before starting the client
- Check Python version compatibility (3.9+)
Best Practices
-
API Key Security:
- Never commit
.envfiles to version control - Rotate API keys regularly
- Use Azure Key Vault for production deployments
- Never commit
-
Error Handling:
- Always handle API failures gracefully
- Implement exponential backoff for retries
- Log errors for debugging
-
Performance:
- Cache frequently requested stock data
- Batch API requests when possible
- Use async operations for concurrent requests
Contributing
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Submit a pull request
Support
For issues or questions:
- Open an issue on GitHub
- Check Alpha Vantage documentation: https://www.alphavantage.co/documentation/
- Azure OpenAI docs: https://learn.microsoft.com/azure/ai-services/openai/
Disclaimer
This tool is for informational purposes only. Always conduct your own research and consult with financial advisors before making investment decisions. Past performance does not guarantee future results.