Skip to main content
Glama
16Coffee

Yahoo Finance MCP Server

by 16Coffee

get_historical_stock_prices

Retrieve historical stock price data, including date, open, high, low, close, and volume, for a specified ticker over a defined period and interval using Yahoo Finance data.

Instructions

获取指定股票的历史价格,返回日期、开盘价、最高价、最低价、收盘价和成交量。 参数说明: ticker: str 股票代码,例如 "AAPL" period : str 支持的周期:1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max; 也可以使用开始和结束日期;默认 "1mo" interval : str 支持的间隔:1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo; 分钟级数据最多可追溯60天;默认 "1d"

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
intervalNo1d
periodNo1mo
tickerYes

Implementation Reference

  • The async handler function that implements the tool logic: fetches data from Financial Modeling Prep API based on interval, processes with pandas DataFrame, filters by period, and returns JSON.
    async def get_historical_stock_prices(
        ticker: str, period: str = "1mo", interval: str = "1d"
    ) -> str:
        """Get historical stock prices for a given ticker symbol"""
    
        api_key = os.environ.get("FMP_API_KEY")
        if not api_key:
            return "Error: FMP_API_KEY environment variable not set."
    
        base = "https://financialmodelingprep.com/api/v3"
        try:
            if interval in ["1min", "5min", "15min", "30min", "1hour", "4hour"]:
                url = f"{base}/historical-chart/{interval}/{ticker}"
                resp = requests.get(url, params={"apikey": api_key}, timeout=10)
                resp.raise_for_status()
                data = resp.json()
            else:
                url = f"{base}/historical-price-full/{ticker}"
                resp = requests.get(url, params={"apikey": api_key}, timeout=10)
                resp.raise_for_status()
                data = resp.json().get("historical", [])
        except Exception as e:
            return f"Error: getting historical stock prices for {ticker}: {e}"
    
        df = pd.DataFrame(data)
        if not df.empty:
            if "date" in df.columns:
                df.rename(columns={"date": "Date"}, inplace=True)
            df = df[["Date", "open", "high", "low", "close", "volume"]]
            df.columns = [c.title() for c in df.columns]
            # Convert the Date column to datetime for proper comparison
            df["Date"] = pd.to_datetime(df["Date"])
    
        period_map = {
            "1d": pd.Timedelta(days=1),
            "5d": pd.Timedelta(days=5),
            "1mo": pd.Timedelta(days=30),
            "3mo": pd.Timedelta(days=90),
            "6mo": pd.Timedelta(days=180),
            "1y": pd.Timedelta(days=365),
            "2y": pd.Timedelta(days=730),
            "5y": pd.Timedelta(days=1825),
            "10y": pd.Timedelta(days=3650),
        }
    
        if period == "ytd":
            start = pd.Timestamp.now().replace(month=1, day=1)
        elif period != "max" and period in period_map:
            start = pd.Timestamp.now() - period_map[period]
        else:
            start = None
    
        if start is not None and not df.empty:
            df = df[df["Date"] >= start]
    
        return df.to_json(orient="records", date_format="iso")
  • server.py:54-67 (registration)
    Tool registration decorator @fmp_server.tool with name and detailed description including input parameters.
    @fmp_server.tool(
        name="get_historical_stock_prices",
        description="""获取指定股票的历史价格,返回日期、开盘价、最高价、最低价、收盘价和成交量。
    参数说明:
        ticker: str
            股票代码,例如 "AAPL"
        period : str
            支持的周期:1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max;
            也可以使用开始和结束日期;默认 "1mo"
        interval : str
            支持的间隔:1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo;
            分钟级数据最多可追溯60天;默认 "1d"
    """,
    )
  • Function signature providing type hints for input parameters (ticker, period, interval) and return type (str).
    async def get_historical_stock_prices(
        ticker: str, period: str = "1mo", interval: str = "1d"
    ) -> str:
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses that the tool returns specific price data (date, open, high, low, close, volume) and mentions constraints like '分钟级数据最多可追溯60天' (minute-level data can trace back up to 60 days), which is useful behavioral context. However, it doesn't cover other important aspects like rate limits, authentication needs, error conditions, or data freshness, leaving gaps for a tool with no annotation support.

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 appropriately sized and well-structured. It starts with the core purpose, then lists parameters with clear explanations in a bullet-like format. Every sentence adds value, with no redundant information. It could be slightly more front-loaded by emphasizing key constraints earlier, but overall it's efficient and readable.

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

Completeness3/5

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

Given the tool's moderate complexity (3 parameters, no output schema, no annotations), the description is partially complete. It covers the purpose and parameters well, but lacks output details (beyond listing returned fields), error handling, or examples. For a data retrieval tool with sibling alternatives, more context on data format or usage scenarios would improve completeness.

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

Parameters5/5

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

The description adds significant value beyond the input schema, which has 0% description coverage. It explains all three parameters in detail: 'ticker' as stock code with an example ('AAPL'), 'period' with supported values and default, and 'interval' with supported values, constraints ('分钟级数据最多可追溯60天'), and default. This fully compensates for the lack of schema descriptions and provides clear semantics for each parameter.

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

Purpose4/5

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

The description clearly states the tool's purpose: '获取指定股票的历史价格,返回日期、开盘价、最高价、最低价、收盘价和成交量' (Get historical stock prices for a specified stock, returning date, open, high, low, close prices and volume). It specifies the verb ('获取' - get), resource ('股票的历史价格' - historical stock prices), and output format. However, it doesn't explicitly distinguish this tool from sibling tools like 'get_stock_info' or 'get_stock_actions', which might also provide stock-related data.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. With many sibling tools available (e.g., 'get_stock_info', 'get_stock_actions', 'get_financial_statement'), there's no indication of how this tool differs in context or when it should be preferred. The parameter explanations imply usage for historical price retrieval but don't address tool selection.

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

Related 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/16Coffee/finance-mcp'

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