Skip to main content
Glama

get_price

Retrieve historical price data (OHLCV) for financial symbols with customizable intervals and periods, optionally generating candlestick charts for analysis.

Instructions

Retrieves historical price data (OHLCV) for a given symbol.

Args:
    symbol: The ticker symbol (e.g., 'AAPL', 'BTC-USD').
    interval: Data interval. Valid values: "1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo".
    period: Data period to download. Valid values: "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max".
    visualize: If True, returns a candlestick chart instead of raw data.
    
Returns:
    JSON string of OHLCV data or base64-encoded candlestick chart.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYes
intervalNo1d
periodNo1y
visualizeNo

Implementation Reference

  • Core handler implementation of the 'get_price' MCP tool. Fetches historical stock/crypto price data (OHLCV) from yfinance with retry logic, optional candlestick visualization, and JSON output.
    def get_price(
        symbol: str, 
        interval: Literal["1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo"] = "1d", 
        period: Literal["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"] = "1y",
        visualize: bool = False
    ) -> str:
        """
        Retrieves historical price data (OHLCV) for a given symbol.
        
        Args:
            symbol: The ticker symbol (e.g., 'AAPL', 'BTC-USD').
            interval: Data interval. Valid values: "1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo".
            period: Data period to download. Valid values: "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max".
            visualize: If True, returns a candlestick chart instead of raw data.
            
        Returns:
            JSON string of OHLCV data or base64-encoded candlestick chart.
        """
        try:
            ticker = yf.Ticker(symbol)
            history = ticker.history(period=period, interval=interval)
            
            if history.empty:
                logger.warning(f"No price data found for {symbol} (period={period}, interval={interval})")
                return json.dumps([])
            
            # Reset index to make Date a column
            history.reset_index(inplace=True)
            
            if visualize:
                try:
                    from tools.visualizer import plot_candlestick
                    # Convert to DataFrame format expected by visualizer
                    df = history[['Date', 'Open', 'High', 'Low', 'Close']].copy()
                    if 'Volume' in history.columns:
                        df['Volume'] = history['Volume']
                    
                    chart = plot_candlestick(
                        df,
                        title=f"{symbol} - {period} ({interval} interval)",
                        volume='Volume' in df.columns
                    )
                    return chart
                except Exception as e:
                    logger.error(f"Error generating candlestick chart: {e}")
                    # Fall through to return data
            
            # Convert to JSON-friendly format (list of dicts)
            # Convert timestamps to string
            history['Date'] = history['Date'].astype(str)
            
            data = history.to_dict(orient="records")
            logger.info(f"Fetched {len(data)} price records for {symbol}")
            
            return json.dumps(data, indent=2)
            
        except Exception as e:
            logger.error(f"Error fetching price data for {symbol}: {e}")
            return json.dumps([])
  • server.py:370-373 (registration)
    MCP tool registration of 'get_price' as part of the 'Market Data' category. The register_tools helper applies the @mcp.tool() decorator to enable the tool in the FastMCP server.
    register_tools(
        [get_price, get_fundamentals, get_orderbook],
        "Market Data"
    )
  • Internal helper function named get_price used within portfolio_optimizer.py for fetching price data in optimization workflows. Not the registered MCP tool.
    def get_price(ticker: str, period: str, interval: str) -> str:
        """
        Fetches historical price data for a given ticker and returns it as a JSON string.
        This is a placeholder to satisfy the new mean_variance_optimize function's dependency.
        In a real scenario, this might be an API call or a more sophisticated data fetcher.
        """
        try:
            data = yf.download(ticker, period=period, interval=interval, progress=False)
            if data.empty:
                return json.dumps([])
            # Rename columns to match expected structure if necessary, e.g., 'Date' instead of index
            data_reset = data.reset_index()
            data_reset['Date'] = data_reset['Date'].dt.strftime('%Y-%m-%d') # Format date as string
            # Select relevant columns, e.g., 'Date', 'Close'
            # The new code expects 'Date' and 'Close' to be present.
            # If other columns are needed, adjust here.
            history_list = data_reset[['Date', 'Close']].to_dict(orient='records')
            return json.dumps(history_list)
        except Exception as e:
            logger.error(f"Error fetching data for {ticker} with yfinance: {e}")
            return json.dumps([])
  • app.py:286-286 (registration)
    Inclusion of get_price in the Gradio UI toolbox under 'Market Data' category for demo interface.
    "Market Data": [get_price, get_fundamentals, get_orderbook],

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/N-lia/MonteWalk'

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