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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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],
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 retrieves data (read-only behavior) and mentions two return formats (JSON string or base64-encoded chart), which adds useful context. However, it does not cover potential rate limits, authentication needs, data freshness, or error handling, leaving gaps in behavioral disclosure for a data retrieval tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded: the first sentence states the core purpose, followed by a well-structured 'Args' and 'Returns' section with clear bullet points. Every sentence earns its place by providing essential information without redundancy or fluff.

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

Completeness4/5

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

Given the complexity (4 parameters, no annotations, but with output schema indicated by 'Returns'), the description is mostly complete. It explains parameters thoroughly and specifies return formats, but lacks details on output schema structure (e.g., JSON fields) or potential errors. With output schema existence, it need not fully explain return values, but could benefit from more behavioral context.

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 input schema has 0% description coverage, so the description must fully compensate. It provides detailed semantics for all 4 parameters: 'symbol' as ticker symbol with examples, 'interval' and 'period' with valid value lists, and 'visualize' explaining its effect on return type. This adds significant meaning beyond the schema's basic titles and enums.

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

Purpose5/5

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

The description clearly states the tool 'retrieves historical price data (OHLCV) for a given symbol,' which is a specific verb (retrieves) and resource (historical price data) with the scope (OHLCV format). It distinguishes from siblings like 'get_crypto_price' by specifying historical data rather than current prices, and from 'get_fundamentals' by focusing on price data rather than company metrics.

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

Usage Guidelines3/5

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

The description implies usage for historical price data retrieval, but does not explicitly state when to use this tool versus alternatives like 'get_crypto_price' for current prices or 'get_technical_summary' for analyzed data. It provides context (historical data) but lacks explicit guidance on exclusions or comparisons with sibling tools.

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

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