yfinance_get_ticker_info
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
| Name | Required | Description | Default |
|---|---|---|---|
| symbol | Yes | Stock ticker symbol (e.g., 'AAPL', 'GOOGL', 'MSFT') |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- src/yfmcp/server.py:128-179 (handler)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) - src/yfmcp/server.py:119-127 (registration)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, ), ) - src/yfmcp/utils.py:6-24 (helper)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) - src/yfmcp/server.py:30-52 (helper)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)})