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:

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