Uses NumPy for numerical computations in risk metrics calculations including Sharpe ratios, beta calculations, and Value at Risk analysis
Leverages pandas for data manipulation and analysis of stock market data, portfolio tracking, and financial time series operations
Built as a Python-based MCP server providing comprehensive stock market analysis, portfolio management, and risk assessment tools
Stock Market Analysis MCP Server
A comprehensive Model Context Protocol (MCP) server for advanced stock market analysis, trend identification, portfolio management, dividend tracking, sector analysis, and risk metrics.
π Table of Contents
π Features
π Price & Data Tools (price_data.py
)
get_latest_price(ticker)
- Get the most recent market price for any stockget_historical_data(ticker, period)
- Retrieve historical OHLC data (Open, High, Low, Close, Volume)get_stock_info(ticker)
- Comprehensive stock information including fundamentals, P/E ratio, market cap, dividend yield, etc.
πΌ Portfolio Management (portfolio.py
)
add_holding(ticker, shares, purchase_price, purchase_date?)
- Add stocks to your portfolio with automatic cost basis trackingremove_holding(ticker, shares, sale_price, sale_date?)
- Sell stocks with automatic profit/loss calculationview_portfolio()
- See all your holdings with real-time valuations and P&Lview_transactions(limit?)
- Review your transaction history
π Technical Analysis (analysis.py
)
analyze_buy_opportunity(ticker)
- Simple SMA crossover strategy (20/50 day)calculate_rsi(ticker, period?, timeframe?)
- Relative Strength Index to identify overbought/oversold conditionscalculate_macd(ticker, timeframe?)
- Moving Average Convergence Divergence for trend momentumanalyze_trends(ticker, timeframe?)
- Multi-indicator comprehensive trend analysiscompare_stocks(tickers[])
- Side-by-side comparison of multiple stocks
π Alert System (alerts.py
)
set_price_alert(ticker, target_price, alert_type, alert_name?)
- Set price alerts (above/below thresholds)set_rsi_alert(ticker, rsi_threshold, alert_type, alert_name?)
- Set RSI alerts for overbought/oversold conditionscheck_alerts()
- Check all active alerts and see which ones have been triggeredlist_alerts()
- View all configured alertsclear_triggered_alerts()
- Remove triggered alertsdelete_all_alerts()
- Delete all alerts
π° Dividend Tracking (dividends.py
)
get_dividend_history(ticker, period?)
- View dividend payment history with trendsget_dividend_yield(ticker)
- Get current dividend yield and related metricscalculate_portfolio_dividend_income()
- Calculate expected annual dividend income from your portfoliofind_high_dividend_stocks(min_yield?, sector?)
- Discover high-yield dividend stocks
π’ Sector Analysis (sector.py
)
analyze_sector(sector_name)
- Comprehensive analysis of a specific market sectorcompare_sectors()
- Compare performance across all major market sectorsget_sector_leaders(sector_name, metric?)
- Get top performing stocks in a sectoranalyze_portfolio_sector_allocation()
- Analyze your portfolio's sector diversification
β οΈ Risk Metrics (risk.py
)
calculate_sharpe_ratio(ticker, risk_free_rate?, period?)
- Measure risk-adjusted returnscalculate_beta(ticker, benchmark?, period?)
- Calculate stock volatility vs marketcalculate_portfolio_risk()
- Comprehensive portfolio risk analysis with recommendationscalculate_var(ticker, confidence_level?, period?, position_size?)
- Value at Risk calculationcalculate_drawdown(ticker, period?)
- Maximum drawdown and peak-to-trough analysis
π¦ Installation
Prerequisites
Before you begin, ensure you have:
Python 3.8 or higher installed on your system
Cursor IDE (or another MCP-compatible client)
Git (optional, for cloning the repository)
Internet connection for fetching stock market data
Step 1: Get the Code
Option A: Clone from GitHub
Option B: Download ZIP
Download the repository as a ZIP file
Extract it to your desired location
Open a terminal and navigate to the extracted folder
Step 2: Set Up Virtual Environment
Create and activate a virtual environment (recommended):
On macOS/Linux:
On Windows:
Step 3: Install Dependencies
With your virtual environment activated, install the required packages:
This will install:
yfinance
- For real-time stock market datapandas
- For data analysisnumpy
- For numerical computationsfastmcp
- For MCP server functionality
Step 4: Configure MCP in Cursor
To use this server with Cursor IDE, you need to add it to your MCP configuration file.
Locate Your MCP Configuration
The MCP configuration file is typically located at:
macOS/Linux:
~/.cursor/mcp.json
Windows:
%USERPROFILE%\.cursor\mcp.json
Add the Server Configuration
Open the mcp.json
file and add the following configuration (adjust the path to match your installation):
Option A: Using Python Module (Recommended)
Option B: Using fastmcp CLI
Important:
Replace
/absolute/path/to/stock_mcp_server/
with the actual full path to where you installed the serverOn Windows, use backslashes and the appropriate paths (e.g.,
C:\\Users\\YourName\\...
)Make sure to use the Python interpreter from your virtual environment (
.venv/bin/python
)
Example for macOS:
Example for Windows:
Step 5: Restart Cursor
After updating your mcp.json
configuration:
Save the file
Completely restart Cursor (close and reopen)
The MCP server should automatically start when Cursor launches
Step 6: Verify Installation
You can verify the installation by checking the MCP logs in Cursor or by trying to use one of the tools:
In Cursor's AI chat, try:
You should see the server responding with real-time stock data.
Or check available tools:
π§ͺ Testing the Server Manually (Optional)
To test the server outside of Cursor:
You should see output like:
π§ Troubleshooting
Server not starting?
Verify the paths in your
mcp.json
are absolute paths (not relative)Ensure you're using the Python from your virtual environment (
.venv/bin/python
)Check that all dependencies are installed:
pip list
should show yfinance, pandas, numpy, fastmcp
"Module not found" errors?
Make sure your virtual environment is activated
Reinstall dependencies:
pip install -r requirements.txt
Can't fetch stock data?
Check your internet connection
Some stocks may have delayed data or require different ticker symbols
Try a common stock like "AAPL" or "MSFT" first
MCP server not appearing in Cursor?
Ensure the
mcp.json
file is valid JSON (no trailing commas, proper syntax)Check Cursor's MCP logs for error messages
Try restarting Cursor completely
Permission errors on macOS/Linux?
Make sure the Python executable is executable:
chmod +x .venv/bin/python
π± Quick Start After Installation
Once installed and configured, you can immediately start using the tools through Cursor's AI chat:
π― Usage Examples
Portfolio Management
Alert System
Dividend Analysis
Sector Analysis
Risk Analysis
Technical Analysis
π Technical Indicators Explained
RSI (Relative Strength Index)
Above 70: Overbought - potential sell signal
Below 30: Oversold - potential buy opportunity
30-70: Neutral range
MACD (Moving Average Convergence Divergence)
Bullish Crossover: MACD line crosses above signal line
Bearish Crossover: MACD line crosses below signal line
Used to identify momentum and trend changes
SMA Crossover Strategy
Buy Signal: Short-term SMA (20-day) crosses above long-term SMA (50-day)
Sell Signal: Short-term SMA crosses below long-term SMA
Sharpe Ratio
> 2.0: Excellent risk-adjusted returns
1.0-2.0: Good
0-1.0: Fair
< 0: Poor (returns below risk-free rate)
Beta
Ξ² > 1: More volatile than market
Ξ² = 1: Moves with market
0 < Ξ² < 1: Less volatile than market
Ξ² < 0: Moves opposite to market
ποΈ Architecture
Modular Design
Each module is self-contained and can be updated independently:
utils.py
: Shared functions for data persistenceprice_data.py
: Basic stock data retrievalportfolio.py
: Holdings and transaction trackinganalysis.py
: Technical indicators and trend analysisalerts.py
: Price and RSI alert systemdividends.py
: Dividend history and income trackingsector.py
: Sector-wide analysis and comparisonrisk.py
: Risk metrics and portfolio risk management
π Data Storage & Privacy
π Local Storage Only
Your data stays completely private and local:
β All portfolio data is stored on your computer only
β No cloud storage or external servers
β No authentication or account required
β Full control over your data files
β Can backup/edit JSON files directly
What gets stored locally:
Your stock holdings and transactions β
portfolio.json
Your price and RSI alerts β
alerts.json
What goes to the internet:
Only market data requests (stock prices, fundamentals, etc.) via Yahoo Finance API
Your personal portfolio data is NEVER transmitted anywhere
Portfolio Data (portfolio.json
)
Location: Same directory as stock.server.py
Automatically created and saved with:
Current holdings with average cost basis
Complete transaction history (buy/sell)
Profit/loss calculations
Last update dates
Example structure:
Alert Data (alerts.json
)
Location: Same directory as stock.server.py
Automatically created and saved with:
Active price alerts (trigger above/below thresholds)
Active RSI alerts (overbought/oversold conditions)
Alert status and trigger history
Example structure:
Backup Your Data
Since all data is stored locally in JSON files, you can easily:
Backup: Copy
portfolio.json
andalerts.json
to another locationRestore: Replace the files with your backup
Edit: Manually edit the JSON files if needed (be careful with formatting)
Version Control: Add to Git (but remember to add to
.gitignore
if sharing publicly)
π What's New in v0.3.0
New Features
π Alert System - Set price and RSI alerts, check status automatically
π° Dividend Tracking - Track dividend history, yields, and portfolio income
π’ Sector Analysis - Analyze entire sectors, compare performance, check diversification
β οΈ Risk Metrics - Sharpe ratio, beta, VaR, drawdown, comprehensive portfolio risk
Enhanced Features
Modular architecture for better maintainability
Separated concerns into dedicated modules
Improved error handling across all tools
Better data persistence with separate files for alerts
Previous Features (v0.2.0)
Portfolio management with P&L tracking
Technical indicators (RSI, MACD, SMA)
Comprehensive trend analysis
Stock comparison tools
Original Features (v0.1.0)
Basic price data retrieval
Historical data access
Simple SMA crossover analysis
π§ Configuration
Risk-Free Rate
Default: 4% (0.04) - Can be adjusted in Sharpe ratio calculations
Available Sectors
Technology
Healthcare
Financial Services
Energy
Consumer Cyclical
Consumer Defensive
Utilities
Industrials
Real Estate
Materials
Communication Services
Alert Types
Price Alerts:
above
orbelow
target priceRSI Alerts:
above
orbelow
RSI threshold
π Dependencies
yfinance (>=0.2.40): Real-time and historical market data
pandas (>=2.0.0): Data manipulation and analysis
numpy (>=1.24.0): Numerical computations for risk metrics
fastmcp (>=0.1.0): MCP server framework
π Best Practices
Portfolio Management
Diversify across 10-20 different stocks
Keep largest position below 20% of portfolio
Regular rebalancing (quarterly or annually)
Track cost basis for tax purposes
Risk Management
Target Sharpe ratio > 1.0 for good risk-adjusted returns
Keep portfolio beta between 0.8-1.2 for moderate risk
Monitor maximum drawdown - be prepared for historical volatility
Use VaR to understand daily loss potential
Sector Allocation
Diversify across at least 5 different sectors
Avoid concentration > 35% in any single sector
Consider sector rotation based on economic cycles
Balance growth and defensive sectors
Dividend Investing
Look for payout ratios < 80% for sustainability
Prefer dividend growth over just high yield
Reinvest dividends for compound growth
Track ex-dividend dates for planning
β οΈ Disclaimer
This tool is for educational and informational purposes only. It is NOT financial advice.
Market data may be delayed
Past performance doesn't guarantee future results
Always do your own research before investing
Consider consulting a financial advisor
Be aware of tax implications
π Future Enhancements
Potential additions:
Options analysis and Greeks calculation
Fibonacci retracement levels
Support/resistance identification
News sentiment analysis
Backtesting capabilities
Tax lot tracking for capital gains
Portfolio rebalancing suggestions
Correlation analysis between holdings
Monte Carlo simulations
Real-time streaming quotes
π License
MIT License - Feel free to use and modify as needed.
π€ Contributing
Contributions are welcome! Please ensure:
Code follows the modular architecture
New features are in appropriate modules
Documentation is updated
Error handling is comprehensive
π Support
For issues or questions:
Check the documentation above
Review the module-specific code
Ensure all dependencies are installed
Verify API data is accessible
Version: 0.3.0
Last Updated: 2025
Author: Stock Market Analysis MCP Server
This server cannot be installed
local-only server
The server can only run on the client's local machine because it depends on local resources.
Enables comprehensive stock market analysis with portfolio management, technical indicators, dividend tracking, sector analysis, risk metrics, and price alerts. Provides real-time stock data, trend analysis, and investment insights through natural language interactions.
- π Table of Contents
- π Features
- π¦ Installation
- π― Usage Examples
- π Technical Indicators Explained
- ποΈ Architecture
- π Data Storage & Privacy
- π What's New in v0.3.0
- π§ Configuration
- π Dependencies
- π Best Practices
- β οΈ Disclaimer
- π Future Enhancements
- π License
- π€ Contributing
- π Support