MCP-Stock-Analyzer

ChandraVardhan97/MCP-Stock-Analyzer

3.2

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.

Tools
2
Resources
0
Prompts
0

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

  1. Python 3.9+ installed
  2. Alpha Vantage API Key (free tier available at https://www.alphavantage.co/support/#api-key)
  3. 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.
  4. Virtual Environment (recommended)

Installation

  1. Clone the repository:
git clone <repository-url>
cd mcp-project
  1. Create virtual environment:
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
  1. 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_price and get_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 commands
  • quit - 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

  1. Environment-Based Configuration: All sensitive data in .env files
  2. Input Validation: Pydantic models validate all inputs
  3. Rate Limiting: Configurable request limits to prevent API abuse
  4. Error Handling: Comprehensive exception handling with logging
  5. Secure Communication: HTTPS for all external API calls
  6. 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_MINUTE in .env to 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

  1. "API rate limit reached"

    • Wait 60 seconds for Alpha Vantage rate limit reset
    • Consider upgrading to premium API plan
  2. "Invalid stock"

    • Ensure the stock is listed on major US exchanges
  3. "Azure OpenAI connection failed"

    • Check endpoint URL format (should end with /)
    • Verify deployment name matches your Azure configuration
    • Ensure API key has proper permissions
  4. "MCP server not responding"

    • Ensure the server is running before starting the client
    • Check Python version compatibility (3.9+)

Best Practices

  1. API Key Security:

    • Never commit .env files to version control
    • Rotate API keys regularly
    • Use Azure Key Vault for production deployments
  2. Error Handling:

    • Always handle API failures gracefully
    • Implement exponential backoff for retries
    • Log errors for debugging
  3. Performance:

    • Cache frequently requested stock data
    • Batch API requests when possible
    • Use async operations for concurrent requests

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes with tests
  4. Submit a pull request

Support

For issues or questions:

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.