home / mcp / stock market analysis mcp server

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.

Installation
Add the following to your MCP client configuration file.

Configuration

View docs
{
  "mcpServers": {
    "calvinliuu-stock_mcp_server": {
      "command": "/absolute/path/to/stock_mcp_server/.venv/bin/python",
      "args": [
        "-m",
        "mcp.server.fastmcp",
        "run",
        "/absolute/path/to/stock_mcp_server/stock.server.py"
      ],
      "env": {
        "STAKE_API_URL": "https://global-prd-api.stake.com",
        "STAKE_ACCOUNT_ID": "acct_12345",
        "STAKE_GRAPHQL_PATH": "/graphql"
      }
    }
  }
}

You have a practical, Python-based MCP server for stock market analysis that provides real-time pricing, historical data, portfolio management, technical indicators, risk metrics, sector and sentiment analysis, and even optional integration with Stake trading. It is designed to run locally, keep your data private, and expose a rich set of tools that you can access through an MCP-compatible client to analyze markets, manage portfolios, set alerts, and test strategies.

How to use

Launch the MCP server within a compatible client and begin by loading the stock analyzer MCP endpoint. Use the client’s command palette or chat-based interface to request data or run analyses. Typical tasks you can perform include getting the latest price for a ticker, retrieving historical OHLC data, viewing your portfolio with real-time valuations, and running technical indicators like RSI and MACD. You can also set price or RSI alerts, track dividend income, analyze sector allocations, evaluate risk metrics such as Sharpe ratio and VaR, and monitor market sentiment signals. If you enable Stake integration, you can submit trades or manage orders through the same interface using the dedicated tooling. Start by querying simple data, then progressively combine tools to build dashboards, alerts, and automated signals.

How to install

Prerequisites you need before installing are Python 3.8 or higher and a MCP-compatible client. You should also have internet access to fetch market data.

Step 1: Prepare your environment. Create and activate a virtual environment to isolate dependencies.

Step 2: Install dependencies from the requirements file to ensure all needed packages are present.

Step 3: Run the MCP server using one of the provided configurations to enable a local stdio-based server that your MCP client can connect to.

Configuration and startup options

Two stdio configurations are shown for running the MCP server locally. The first uses the Python module runner to start the server, and the second uses the FastMCP CLI. Each configuration uses an absolute path to the Python interpreter or the fastmcp launcher and passes the script that runs the stock server. Use one of these configurations in your MCP client setup.

You can also provide environment variables for the server, but the examples show an empty env block. You can fill in values as needed for your setup.

Usage notes

After the server starts, you can verify operation by querying common data points such as the latest price for a ticker or by requesting a portfolio view. The server exposes tools across data retrieval, portfolio management, technical analysis, alerts, dividends, sector analysis, risk metrics, and sentiment tracking. If you enable Stake integration, you can execute GraphQL-based trades with appropriate session tokens and API configuration.

Troubleshooting

If the MCP server does not start, ensure the paths in your configuration are absolute, confirm you are using the Python interpreter from your virtual environment, and verify all dependencies are installed (the environment should show yfinance, pandas, numpy, and fastmcp). If you encounter module not found errors, reactivate the virtual environment and reinstall dependencies. For data access issues, check your internet connection and ensure the ticker symbols are valid.

Notes on Stake trading integration

If you plan to forward trades to Stake, you must provide valid session tokens obtained from a manual login. Collect the access token and account ID from Stake’s GraphQL requests, and supply optional extra headers as needed. Tokens expire, so you can provide a token_expiry timestamp to receive reminders for refreshing the session. The integration supports submitting market and limit orders, listing and canceling orders, and executing custom GraphQL operations.

Technical indicators and examples

RSI, MACD, and SMA crossover strategies are used to identify momentum and trend signals. For RSI, readings above 70 indicate overbought conditions, below 30 indicate oversold conditions. The SMA crossover strategy signals a potential buy when the short-term SMA crosses above the long-term SMA (e.g., 20-day vs 50-day). The MACD is used to detect momentum changes, with bullish crossovers suggesting upward momentum and bearish crossovers suggesting downward momentum.

Architecture overview

The server follows a modular design with separate components for price data, portfolio management, analysis, alerts, dividends, sector analysis, risk metrics, and sentiment tracking. Each module is self-contained and can be updated independently, while a shared utility layer handles data persistence.

Data storage and privacy

All data is stored locally on your machine to keep your information private. Portfolio holdings, transactions, alerts, and sentiment history reside in data/ files within your project directory. Market data requests may fetch data from external sources, but personal data remains local.

Best practices and notes

Follow a disciplined approach: diversify holdings, monitor risk metrics, and regularly rebalance. Use alerts to stay informed of price moves or RSI conditions. Maintain a clean data directory and back up the data/ folder periodically.

Dependencies and compatibility

Core dependencies include yfinance for data, pandas for analysis, numpy for numerical computations, and fastmcp for the MCP server framework. Ensure your environment has compatible versions as specified in the installation flow.

Common commands to run the server (recap)

Use one of the two stdio configurations to start the server from your MCP client. The first uses a Python interpreter path and the second uses the FastMCP launcher. Both options require absolute paths to your installation.

Available tools

get_latest_price

Fetches the most recent market price for a given ticker symbol.

get_historical_data

Retrieves historical OHLCV data for a ticker over a specified period.

get_stock_info

Returns comprehensive stock fundamentals and key metrics.

add_holding

Adds a stock to the portfolio with automatic cost basis tracking.

remove_holding

Sells shares from the portfolio and computes realized P/L.

view_portfolio

Displays current holdings with real-time valuations and P/L.

view_transactions

Shows the transaction history with optional limits.

analyze_buy_opportunity

Simple SMA crossover based buy signal detector.

calculate_rsi

Calculates RSI for a ticker with optional period and timeframe.

calculate_macd

Calculates MACD for momentum analysis.

analyze_trends

Performs multi-indicator trend analysis for a ticker.

compare_stocks

Compares multiple tickers side-by-side on key metrics.

set_price_alert

Configures price-based alerts for a ticker.

set_rsi_alert

Configures RSI-based alerts for a ticker.

check_alerts

Evaluates active alerts and returns triggered ones.

list_alerts

Lists all configured alerts.

clear_triggered_alerts

Removes alerts that have been triggered.

delete_all_alerts

Deletes all configured alerts.

get_dividend_history

Fetches dividend history for a ticker over a period.

get_dividend_yield

Retrieves current dividend yield and related metrics.

calculate_portfolio_dividend_income

Estimates expected annual dividend income from the portfolio.

find_high_dividend_stocks

Finds high-yield stocks by minimum yield and sector.

analyze_sector

Provides comprehensive sector analysis for a given sector.

compare_sectors

Compares performance across major sectors.

get_sector_leaders

Gets top performing stocks within a sector by a metric.

analyze_portfolio_sector_allocation

Analyzes your portfolio’s sector diversification.

calculate_sharpe_ratio

Calculates risk-adjusted return with an optional risk-free rate.

calculate_beta

Calculates a ticker’s beta against a benchmark.

calculate_portfolio_risk

Performs a comprehensive risk analysis for the portfolio.

calculate_var

Computes Value at Risk for a ticker with confidence and size.

calculate_drawdown

Analyzes maximum drawdown and peak-to-trough changes.

get_stock_info

Retrieves fundamental data and key metrics for a ticker.

track_sentiment_history

Tracks historical sentiment scores over a period.