Skip to main content
Glama
maxscheijen

MCP Yahoo Finance

by maxscheijen

get_stock_price_by_date

Retrieve the stock price for a specific symbol on a chosen date using Yahoo Finance data. Input the stock symbol and date in YYYY-MM-DD format for accurate results.

Instructions

Get the stock price for a given stock symbol on a specific date.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dateYesThe date in YYYY-MM-DD format.
symbolYesStock symbol in Yahoo Finance format.

Implementation Reference

  • Core handler function that implements the logic to fetch the closing stock price for a given symbol and date using yfinance library.
    def get_stock_price_by_date(self, symbol: str, date: str) -> str:
        """Get the stock price for a given stock symbol on a specific date.
    
        Args:
            symbol (str): Stock symbol in Yahoo Finance format.
            date (str): The date in YYYY-MM-DD format.
        """
        stock = Ticker(ticker=symbol, session=self.session)
        price = stock.history(start=date, period="1d")
        return f"{price.iloc[0]['Close']:.4f}"
  • Registration of all tools including get_stock_price_by_date via generate_tool in the MCP list_tools handler.
    @server.list_tools()
    async def list_tools() -> list[Tool]:
        return [
            generate_tool(yf.get_current_stock_price),
            generate_tool(yf.get_stock_price_by_date),
            generate_tool(yf.get_stock_price_date_range),
            generate_tool(yf.get_historical_stock_prices),
            generate_tool(yf.get_dividends),
            generate_tool(yf.get_income_statement),
            generate_tool(yf.get_cashflow),
            generate_tool(yf.get_earning_dates),
            generate_tool(yf.get_news),
            generate_tool(yf.get_recommendations),
            generate_tool(yf.get_option_expiration_dates),
            generate_tool(yf.get_option_chain),
        ]
  • Dispatch handler in MCP call_tool that invokes the get_stock_price_by_date method with arguments and returns the result as TextContent.
    case "get_stock_price_by_date":
        price = yf.get_stock_price_by_date(**args)
        return [TextContent(type="text", text=price)]
  • Helper function generate_tool that dynamically generates the JSON schema for the tool based on function signature, type annotations, and docstring.
    def generate_tool(func: Any) -> Tool:
        """Generates a tool schema from a Python function."""
        signature = inspect.signature(func)
        docstring = inspect.getdoc(func) or ""
        param_descriptions = parse_docstring(docstring)
    
        schema = {
            "name": func.__name__,
            "description": docstring.split("Args:")[0].strip(),
            "inputSchema": {
                "type": "object",
                "properties": {},
            },
        }
    
        for param_name, param in signature.parameters.items():
            param_type = (
                "number"
                if param.annotation is float
                else "string"
                if param.annotation is str
                else "string"
            )
            schema["inputSchema"]["properties"][param_name] = {
                "type": param_type,
                "description": param_descriptions.get(param_name, ""),
            }
    
            if "required" not in schema["inputSchema"]:
                schema["inputSchema"]["required"] = [param_name]
            else:
                if "=" not in str(param):
                    schema["inputSchema"]["required"].append(param_name)
    
        return Tool(**schema)
  • Supporting utility to parse Google-style docstrings for parameter descriptions used in schema generation.
    def parse_docstring(docstring: str) -> dict[str, str]:
        """Parses a Google-style docstring to extract parameter descriptions."""
        descriptions = {}
        if not docstring:
            return descriptions
    
        lines = docstring.split("\n")
        current_param = None
    
        for line in lines:
            line = line.strip()
            if line.startswith("Args:"):
                continue
            elif line and "(" in line and ")" in line and ":" in line:
                param = line.split("(")[0].strip()
                desc = line.split("):")[1].strip()
                descriptions[param] = desc
                current_param = param
            elif current_param and line:
                descriptions[current_param] += " " + line.strip()
    
        return descriptions

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/maxscheijen/mcp-yahoo-finance'

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