Skip to main content
Glama
narumiruna

Yahoo Finance MCP Server

yfinance_get_ticker_info

Read-onlyIdempotent

Fetch comprehensive stock data including company details, financials, trading metrics, and governance for any ticker symbol.

Instructions

Retrieve comprehensive stock data including company information, financials, trading metrics and governance.

Returns JSON object with fields including:
- Company: symbol, longName, sector, industry, longBusinessSummary, website, city, country
- Price: currentPrice, previousClose, open, dayHigh, dayLow, fiftyTwoWeekHigh, fiftyTwoWeekLow
- Valuation: marketCap, enterpriseValue, trailingPE, forwardPE, priceToBook, pegRatio
- Trading: volume, averageVolume, averageVolume10days, bid, ask, bidSize, askSize
- Dividends: dividendRate, dividendYield, exDividendDate, payoutRatio
- Financials: totalRevenue, revenueGrowth, earningsGrowth, profitMargins, operatingMargins
- Performance: beta, fiftyDayAverage, twoHundredDayAverage, trailingEps, forwardEps

Note: Available fields vary by security type. Timestamps are converted to readable dates.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesStock ticker symbol (e.g., 'AAPL', 'GOOGL', 'MSFT')

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for 'yfinance_get_ticker_info' tool. Fetches comprehensive stock data from yfinance Ticker.info, converts timestamps to dates, and returns the result as a JSON string.
    async def get_ticker_info(
        symbol: Annotated[str, Field(description="Stock ticker symbol (e.g., 'AAPL', 'GOOGL', 'MSFT')")],
    ) -> str:
        """Retrieve comprehensive stock data including company information, financials, trading metrics and governance.
    
        Returns JSON object with fields including:
        - Company: symbol, longName, sector, industry, longBusinessSummary, website, city, country
        - Price: currentPrice, previousClose, open, dayHigh, dayLow, fiftyTwoWeekHigh, fiftyTwoWeekLow
        - Valuation: marketCap, enterpriseValue, trailingPE, forwardPE, priceToBook, pegRatio
        - Trading: volume, averageVolume, averageVolume10days, bid, ask, bidSize, askSize
        - Dividends: dividendRate, dividendYield, exDividendDate, payoutRatio
        - Financials: totalRevenue, revenueGrowth, earningsGrowth, profitMargins, operatingMargins
        - Performance: beta, fiftyDayAverage, twoHundredDayAverage, trailingEps, forwardEps
    
        Note: Available fields vary by security type. Timestamps are converted to readable dates.
        """
        try:
            ticker = await asyncio.to_thread(yf.Ticker, symbol)
            info = await asyncio.to_thread(lambda: ticker.info)
        except _RETRYABLE_YFINANCE_EXCEPTIONS as exc:
            return _create_retryable_error_response(f"fetching ticker info for '{symbol}'", exc, {"symbol": symbol})
        except Exception as exc:
            return create_error_response(
                f"Failed to fetch ticker info for '{symbol}'. Verify the symbol is correct and try again.",
                error_code="API_ERROR",
                details={"symbol": symbol, "exception": str(exc)},
            )
    
        if not info:
            return create_error_response(
                f"No information available for symbol '{symbol}'. "
                "The symbol may be invalid or delisted. Try searching for the company "
                "name using the 'yfinance_search' tool to find the correct symbol.",
                error_code="INVALID_SYMBOL",
                details={"symbol": symbol},
            )
    
        # Convert timestamps to human-readable format when they look numeric.
        for key, value in list(info.items()):
            if not isinstance(key, str):
                continue
    
            if not isinstance(value, int | float):
                continue
    
            if key.lower().endswith(("date", "start", "end", "timestamp", "time", "quarter")):
                try:
                    info[key] = datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M:%S")
                except Exception as exc:
                    logger.error("Unable to convert {}: {} to datetime: {}", key, value, exc)
    
        return dump_json(info)
  • Registration of the tool via @mcp.tool() decorator with the name 'yfinance_get_ticker_info' and annotations.
    @mcp.tool(
        name="yfinance_get_ticker_info",
        annotations=ToolAnnotations(
            readOnlyHint=True,
            destructiveHint=False,
            idempotentHint=True,
            openWorldHint=True,
        ),
    )
  • The dump_json helper used by the handler to serialize the ticker info dict to a JSON string.
    def dump_json(payload: object) -> str:
        return json.dumps(payload, ensure_ascii=False, default=str)
    
    
    def create_error_response(message: str, error_code: ErrorCode = "UNKNOWN_ERROR", details: dict | None = None) -> str:
        """Create a structured error response.
    
        Args:
            message: Human-readable error message
            error_code: Machine-readable error code for client handling
            details: Optional additional error details
    
        Returns:
            JSON string with error information
        """
        error_obj: dict[str, object] = {"error": message, "error_code": error_code}
        if details:
            error_obj["details"] = details
        return dump_json(error_obj)
  • Definition of retryable exceptions and the helper function _create_retryable_error_response used by the handler.
    _RETRYABLE_YFINANCE_EXCEPTIONS: tuple[type[Exception], ...] = (
        ConnectionError,
        TimeoutError,
        OSError,
        YFRateLimitError,
    )
    
    
    def _is_retryable_yfinance_error(exc: BaseException) -> bool:
        return isinstance(exc, _RETRYABLE_YFINANCE_EXCEPTIONS)
    
    
    def _is_rate_limit_error(exc: BaseException) -> bool:
        return isinstance(exc, YFRateLimitError)
    
    
    def _create_retryable_error_response(action: str, exc: BaseException, details: dict[str, Any]) -> str:
        if _is_rate_limit_error(exc):
            message = f"Rate limit reached while {action}. Try again later."
        else:
            message = f"Temporary network issue while {action}. Try again later."
    
        return create_error_response(message, error_code="NETWORK_ERROR", details={**details, "exception": str(exc)})
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already provide readOnlyHint, idempotentHint, etc. The description adds behavioral nuances: fields vary by security type, timestamps converted. This goes beyond annotations without contradiction.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-organized with bulleted categories, but slightly verbose with overlapping categories (e.g., Price/Valuation/Trading). Front-loaded purpose is clear.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity, annotations richness, and output schema implied via field listing, the description is complete. It provides sufficient detail on return fields and behavior for agent decision-making.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The sole parameter 'symbol' is well-described in the input schema with examples, achieving 100% coverage. The description adds no extra parameter meaning beyond what schema provides.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it retrieves comprehensive stock data including specific categories like company info, financials, trading metrics, and governance. It distinguishes from sibling tools by emphasizing comprehensiveness vs. specialized tools like yfinance_get_financials.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies use when full stock details are needed, but lacks explicit guidance on when to choose this over siblings like yfinance_get_financials or yfinance_get_price_history. No 'when not' or alternative recommendations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/narumiruna/yfinance-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server