Skip to main content
Glama
Indian Stock Analysis MCP Server

Indian Stock Analysis MCP Server

by tynorn1

Indian Stock Analysis MCP Server

A comprehensive Model Context Protocol (MCP) server for analyzing Indian stocks listed on BSE and NSE exchanges. Built with FastMCP and powered by Yahoo Finance API.

Features

  • Real-time Stock Data: Current prices, daily changes, volume, and market cap

  • Fundamental Analysis: P/E ratios, ROE, debt-to-equity, and other key metrics

  • Historical Data: OHLC data for technical analysis across multiple timeframes

  • Stock Discovery: Search Indian stocks by company name or ticker symbol

  • Market Overview: NIFTY 50, SENSEX, and other major Indian indices

  • News Integration: Recent news articles for sentiment analysis (handled by LLM)

  • Market Status: Real-time market hours and trading status

  • Indian Market Optimized: Specialized for NSE (.NS) and BSE (.BO) exchanges

Related MCP server: IndiaQuant MCP Server

Prerequisites

  • Python 3.13 or higher

  • uv (recommended package manager)

  • Claude Desktop (for MCP integration)

Installation

1. Clone the Repository

git clone <repository-url>
cd stock-analysis-mcp

2. Install Dependencies

# Using uv (recommended)
uv sync

# Or using pip
pip install -e .

3. Verify Installation

uv run python -c "import server; print('MCP server installed successfully')"

Claude Desktop Configuration

1. Locate Configuration File

Find your Claude Desktop configuration file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

2. Add MCP Server Configuration

{
  "mcpServers": {
    "indian-stock-analysis": {
      "command": "uv",
      "args": [
        "--directory",
        "/ABSOLUTE/PATH/TO/stock-analysis-mcp",
        "run",
        "server.py"
      ]
    }
  }
}

Important: Replace /ABSOLUTE/PATH/TO/stock-analysis-mcp with the actual absolute path to your project directory.

3. Restart Claude Desktop

Completely quit and restart Claude Desktop to load the new MCP server.

4. Verify Connection

Look for the tools icon in Claude Desktop. You should see the Indian stock analysis tools available.

Available Tools

1. stock_quote

Get current stock price and basic trading information.

Parameters:

  • ticker (required): Indian stock ticker symbol (e.g., "RELIANCE", "TCS", "INFY")

Example Usage:

What's the current price of Reliance Industries?
Show me the stock quote for TCS

Sample Output:

Current Stock Quote for RELIANCE (NSE):

Price Information:
* Current Price: ₹2,845.50
* Daily Change: +1.2% (₹33.80)
* Day's Range: ₹2,812.00 - ₹2,855.90
* Opening Price: ₹2,815.00
* Previous Close: ₹2,811.70

Trading Data:
* Volume: 15,234,567
* Market Cap: ₹19,82,123 Cr
* Currency: INR

2. company_fundamentals

Get comprehensive fundamental analysis data for a company.

Parameters:

  • ticker (required): Indian stock ticker symbol

Example Usage:

Show me the fundamentals for Infosys
What are the financial metrics for HDFC Bank?

Sample Output:

Fundamental Analysis for INFOSYS LTD (INFY):

Company Information:
* Name: Infosys Limited
* Sector: Technology
* Industry: IT Services
* Exchange: NSE
* Website: https://www.infosys.com

Valuation Metrics:
* P/E Ratio: 28.5
* P/B Ratio: 8.2
* Market Cap: ₹6,45,789 Cr

Financial Metrics:
* EPS: ₹68.5
* ROE: 29.8%
* Dividend Yield: 2.1%

3. stock_news

Get recent news articles for a specific stock.

Parameters:

  • ticker (required): Indian stock ticker symbol

  • limit (optional): Maximum number of articles (default: 5)

Example Usage:

Show me recent news about Tata Motors
What are the latest news articles for ICICI Bank?

4. search_indian_stocks

Search for Indian stocks by company name or ticker symbol.

Parameters:

  • query (required): Search query - company name or partial ticker

  • limit (optional): Maximum number of results (default: 10)

Example Usage:

Search for banking stocks
Find companies with "tata" in the name

5. market_overview

Get current Indian market indices and sector performance.

Example Usage:

What's the current market overview?
Show me NIFTY and SENSEX performance

Sample Output:

Indian Market Overview:

Market Indices:
* NIFTY 50: ₹21,834.25 (+0.8%)
* SENSEX: ₹72,156.85 (+0.6%)
* NIFTY BANK: ₹46,789.30 (+1.2%)
* NIFTY IT: ₹29,456.20 (-0.3%)

Market Status: Open
Market is currently open for trading
Current Time: 2024-01-15 14:30:25 IST

Available Resources

1. indian-stock://market-status

Current Indian market status and trading hours.

Access through: MCP client resource interface

2. indian-stock://popular-stocks

List of frequently analyzed Indian stocks with basic information.

Access through: MCP client resource interface

Usage Examples

Portfolio Analysis Workflow

User: "Show me fundamentals of Reliance Industries"
[Uses company_fundamentals tool]

User: "What's current market status?"
[Uses market_overview tool]

User: "Get recent news about Reliance"
[Uses stock_news tool]

User: "How has Reliance performed technically over the past 6 months?"
[Uses technical_analysis tool]

Stock Discovery Workflow

User: "Search for technology companies"
[Uses search_indian_stocks tool]

User: "Show me the current price of TCS"
[Uses stock_quote tool]

User: "What are TCS's financial metrics?"
[Uses company_fundamentals tool]

Market Research Workflow

User: "What's today's market overview?"
[Uses market_overview tool]

User: "Find banking stocks with good fundamentals"
[Uses search_indian_stocks tool + company_fundamentals tool]

User: "Show me technical analysis for top performers"
[Uses technical_analysis tool]

Development

Project Structure

stock-analysis-mcp/
├── server.py              # Main MCP server with FastMCP tools
├── stock_analyzer.py      # Core data fetching and processing
├── pyproject.toml         # Project configuration and dependencies
├── main.py               # Entry point
└── README.md             # This file

Code Quality

  • Uses ruff for linting and code formatting

  • Follows Python type hints and async/await patterns

  • Comprehensive error handling

  • Structured logging to stderr (MCP-safe)

Running the Server Locally

# Start the MCP server
uv run python server.py

# The server will listen for JSON-RPC messages on stdin/stdout

Adding New Tools

  1. Add the data fetching function to stock_analyzer.py

  2. Create the tool function in server.py with @mcp.tool() decorator

  3. Follow the existing patterns for error handling and return formatting

Troubleshooting

Common Issues

Server not showing up in Claude Desktop

  • Verify the absolute path in claude_desktop_config.json

  • Completely quit and restart Claude Desktop

  • Check that dependencies are installed: uv sync

No data found for a ticker

  • Ensure the ticker is valid (try with .NS or .BO suffix)

  • Check if the market is open

  • Verify the stock is listed on NSE or BSE

Error fetching data

  • Check network connection

  • Yahoo Finance API may have rate limits

  • Try again after a few minutes

Market Timing Considerations

  • Market Hours: 9:15 AM - 3:30 PM IST, Monday to Friday

  • Pre-market: Data may be limited before 9:15 AM

  • Weekends: No real-time data available

  • Holidays: Indian market holidays affect data availability

Data Limitations

  • Real-time data is subject to Yahoo Finance API limitations

  • Some fundamental data may not be available for all stocks

  • Historical data accuracy depends on Yahoo Finance data quality

  • News article availability varies by stock and source

Contributing

  1. Fork the repository

  2. Create a feature branch: git checkout -b feature-name

  3. Make your changes and ensure they pass linting: uv run ruff check .

  4. Commit your changes: git commit -m "feat: add new feature"

  5. Push to the branch: git push origin feature-name

  6. Open a pull request

Support

For issues and questions:

  • Check the troubleshooting section above

  • Open an issue on the repository

  • Review the MCP documentation for Claude Desktop integration


Disclaimer: This tool provides financial information for educational purposes only. Not financial advice. Always consult with qualified financial professionals before making investment decisions.

Available Tools

13 tools
analyst_recommendationsA

Get analyst recommendations and price targets for an Indian stock.

Provides professional market sentiment including:

  • Current analyst consensus (Buy/Sell/Hold)

  • Price targets and upside potential

  • Number of analysts covering the stock

  • Recent recommendation changes

Args: ticker: Indian stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY')

Inputs: ticker (required). Returns: result

arima_model_diagnosticsA

Perform comprehensive diagnostics on trained ARIMA model.

Provides:

  • Residual analysis with ACF/PACF plots

  • Normality tests and QQ plots

  • Ljung-Box test for autocorrelation

  • Model adequacy checks and recommendations

  • Visual diagnostic charts

Args: ticker: Stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY') period: Time period for analysis ('1mo', '3mo', '6mo', '1y', '2y', '5y') transform: Data transformation type ("log", "boxcox", or None for no transformation)

Returns: List containing text analysis and ImageContent with diagnostic plots

Inputs: ticker (required), period, transform.

company_fundamentalsB

Get fundamental analysis data for an Indian company.

Args: ticker: Indian stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY')

Inputs: ticker (required). Returns: result

forecast_arima_modelA

Generate ARIMA model forecasts with confidence intervals and validation.

Provides:

  • Multi-period forecasting with confidence bands

  • Model validation and quality checks

  • Visual forecast charts with historical data

  • Performance metrics and accuracy indicators

  • Error handling with fallback strategies

Args: ticker: Stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY') periods: Number of periods to forecast (default: 20 trading days) confidence: Confidence interval level (0.8-0.99, default: 0.95) p: AR order (None for auto-selection) d: Differencing order (default 1 for stock prices) q: MA order (None for auto-selection) auto_select: Use pmdarima auto_arima for parameter selection (True) or manual (False) lags: Number of lags for analysis (default 40, used for fallback ACF/PACF) period: Time period for training data ('1mo', '3mo', '6mo', '1y', '2y', '5y') transform: Data transformation type ("log", "boxcox", or None for no transformation)

Returns: List containing text analysis and ImageContent with forecast plot

Inputs: ticker (required), d, p, q, +6 more.

forecast_prophet_modelA

Train Prophet model and generate forecasts with confidence intervals.

Provides:

  • Automatic seasonality detection (yearly, weekly patterns)

  • Trend changepoint identification

  • Holiday effects support (Indian market holidays)

  • Component decomposition (trend + seasonality)

  • Multi-period forecasting with confidence bands

  • Model validation and quality checks

  • Visual forecast charts with historical data

Args: ticker: Stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY') periods: Number of periods to forecast (default: 20 trading days) confidence: Confidence interval level (0.8-0.99, default: 0.95) period: Time period for training data ('1mo', '3mo', '6mo', '1y', '2y', '5y') yearly_seasonality: Enable yearly seasonality (default True) weekly_seasonality: Enable weekly seasonality (default True) seasonality_mode: 'additive' or 'multiplicative' (default 'additive') changepoint_prior_scale: Flexibility of trend changes (default 0.05) seasonality_prior_scale: Flexibility of seasonality (default 10.0) holidays_prior_scale: Flexibility of holiday effects (default 10.0) validation_split: Train-validation split ratio (default 0.2) include_holidays: Include Indian market holidays (default False)

Returns: List containing text analysis and ImageContent with forecast plot

Inputs: ticker (required), period, periods, confidence, +8 more.

market_overviewA

Get current Indian market indices and sector performance.

Inputs: no named parameters. Returns: result

search_indian_stocksA

Search for Indian stocks by company name or ticker symbol.

Args: query: Search query - company name or partial ticker symbol limit: Maximum number of results to return (default: 10)

Inputs: query (required), limit. Returns: result

stock_actionsA

Get corporate actions (dividends, stock splits) for an Indian stock.

Provides information about:

  • Recent dividend payments and yields

  • Dividend history and frequency

  • Stock split history and ratios

  • Dividend stability analysis

Args: ticker: Indian stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY')

Inputs: ticker (required). Returns: result

stock_holdersA

Get major holders and institutional ownership information for an Indian stock.

Provides insights into:

  • Major shareholder categories and percentages

  • Top institutional holders and their positions

  • Insider ownership and trading activity

  • Ownership concentration analysis

Args: ticker: Indian stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY')

Inputs: ticker (required). Returns: result

stock_newsA

Get recent news articles for a specific Indian stock.

Args: ticker: Indian stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY') limit: Maximum number of news articles to return (default: 5)

Inputs: ticker (required), limit. Returns: result

stock_quoteC

Get current stock price and basic trading information for Indian stocks.

Args: ticker: Indian stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY')

Inputs: ticker (required). Returns: result

technical_analysisA

Get comprehensive technical analysis indicators for an Indian stock.

Provides key technical indicators including:

  • RSI (Relative Strength Index) for momentum

  • MACD (Moving Average Convergence Divergence) for trend signals

  • SMA/EMA (Simple/Exponential Moving Averages) for trend direction

  • Rate of Change for momentum analysis

  • Bollinger Bands for volatility and price position

Args: ticker: Indian stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY') period: Time period for analysis (1mo, 3mo, 6mo, 1y, 2y)

Inputs: ticker (required), period. Returns: result

train_arima_modelA

Train ARIMA model with intelligent parameter selection using pmdarima auto_arima.

Provides:

  • Model training with automated ARIMA order selection via pmdarima

  • Data transformation support (log, Box-Cox) for improved normality

  • Performance metrics and validation on holdout set

  • Model persistence with caching capability

  • Error handling and graceful fallbacks

Args: ticker: Stock ticker symbol (e.g., 'RELIANCE', 'TCS', 'INFY') p: AR order (None for auto-selection) d: Differencing order (default 1 for stock prices) q: MA order (None for auto-selection) validation_split: Train-validation split ratio (default 0.2) auto_select: Use pmdarima auto_arima for parameter selection (True) or manual (False) lags: Number of lags for analysis (default 40, used for fallback ACF/PACF) period: Time period for training data ('1mo', '3mo', '6mo', '1y', '2y', '5y') transform: Data transformation type ("log", "boxcox", or None for no transformation)

Returns: List containing text analysis and ImageContent with training plot

Inputs: ticker (required), d, p, q, +5 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 13 tools

    Disambiguation4/5

    Tools are largely distinct, but forecast_arima_model and forecast_prophet_model overlap in purpose and output style, potentially confusing agents. Other tools like stock_quote vs market_overview and technical_analysis vs arima_model_diagnostics have clear boundaries.

    Naming Consistency3/5

    Naming conventions are mixed: some tools use stock_* prefixes, some use model-related prefixes like train_arima_model, and others are bare nouns like market_overview. While all are readable snake_case, the lack of a consistent prefix/verb pattern reduces predictability.

    Tool Count5/5

    With 13 tools, the count is within the ideal range and each tool serves a distinct analytical function, from market overview and fundamentals to ARIMA/Prophet forecasting and diagnostics. No tool feels redundant.

    Completeness4/5

    The toolkit covers a broad range of Indian stock analysis needs, but there is no direct tool for retrieving raw historical price data, which is a common prerequisite for custom analysis or model building. Otherwise, the surface is fairly comprehensive.

    Maintenance

    ActivityStale
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      C
      quality
      D
      maintenance
      Enables access to comprehensive Indian stock market data from the NSE and BSE, including historical statistics, corporate actions, and IPO information. It also provides tools for mutual fund searches, analyst recommendations, and tracking market-active or trending stocks.
      16
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      Provides real-time Indian stock market analysis, including live price tracking, technical indicators, and options Greeks calculations for NSE/BSE securities. It also enables news-based sentiment analysis, market scanning for NIFTY 50 stocks, and virtual portfolio management.
      -
    • F
      license
      A
      quality
      D
      maintenance
      Enables real-time and historical Indian stock market data retrieval, including prices, news, recommendations, and top gainers/losers.
      11
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables NSE stock market research with screening, quotes, peer comparison, watchlists, alerts, and strategies using natural language.
      MIT