Skip to main content
Glama
narumiruna

Yahoo Finance MCP Server

get_price_history

Retrieve historical stock price data for a specified symbol, period, and interval to analyze market trends and performance over time.

Instructions

Fetch historical price data for a given stock symbol over a specified period and interval.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
intervalNoData interval frequency (e.g. '1d', '1h', '1m')1d
periodNoTime period to retrieve data for (e.g. '1d', '1mo', '1y')1mo
symbolYesThe stock symbol

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'get_price_history' tool, decorated with @mcp.tool() for automatic registration in FastMCP. It fetches historical price data using yfinance, handles empty data, returns markdown table or delegates to chart generation.
    @mcp.tool()
    def get_price_history(
        symbol: Annotated[str, Field(description="The stock symbol")],
        period: Annotated[Period, Field(description="Time period to retrieve data for (e.g. '1d', '1mo', '1y').")] = "1mo",
        interval: Annotated[Interval, Field(description="Data interval frequency (e.g. '1d', '1h', '1m')")] = "1d",
        chart_type: Annotated[
            ChartType | None,
            Field(
                description=(
                    "Type of chart: 'price_volume' for candlestick with volume bars, "
                    "'vwap' for Volume Weighted Average Price, or 'volume_profile' "
                    "for volume distribution by price level"
                )
            ),
        ] = None,
    ) -> str | ImageContent:
        """Fetch historical price data for a given stock symbol over a specified period and interval."""
        ticker = yf.Ticker(symbol)
    
        df = ticker.history(
            period=period,
            interval=interval,
            rounding=True,
        )
    
        if df.empty:
            return f"No data available for symbol {symbol} with period {period} and interval {interval}"
    
        if chart_type is None:
            return df.to_markdown()
    
        return generate_chart(symbol=symbol, df=df, chart_type=chart_type)
  • Pydantic-compatible Literal type defining valid periods for historical data retrieval in get_price_history.
    Period = Literal[
        "1d",
        "5d",
        "1mo",
        "3mo",
        "6mo",
        "1y",
        "2y",
        "5y",
        "10y",
        "ytd",
        "max",
    ]
  • Pydantic-compatible Literal type defining valid intervals for data frequency in get_price_history.
    Interval = Literal[
        "1m",
        "2m",
        "5m",
        "15m",
        "30m",
        "60m",
        "90m",
        "1h",
        "1d",
        "5d",
        "1wk",
        "1mo",
        "3mo",
    ]
  • Pydantic-compatible Literal type for chart_type parameter, enabling different chart visualizations.
    ChartType = Literal[
        "price_volume",
        "vwap",
        "volume_profile",
    ]
  • Helper function that generates and returns image content for price/volume charts, VWAP overlay, or volume profile, invoked conditionally in get_price_history.
    def generate_chart(symbol: str, df: pd.DataFrame, chart_type: ChartType) -> ImageContent | str:
        """Generate a financial chart using mplfinance.
    
        Shows candlestick price data with volume, optionally with VWAP or volume profile.
        Returns base64-encoded WebP image for efficient token usage.
        """
    
        import matplotlib
    
        matplotlib.use("Agg")  # Use non-interactive backend
    
        import matplotlib.cm as cm
        import matplotlib.pyplot as plt
        import mplfinance as mpf
    
        # Prepare data for mplfinance (needs OHLCV columns)
        # Ensure column names match what mplfinance expects
        df = df[["Open", "High", "Low", "Close", "Volume"]]
    
        # Handle volume profile separately as it needs custom layout
        if chart_type == "volume_profile":
            # Calculate volume profile
            volume_profile = _calculate_volume_profile(df)
    
            # Create a custom figure with proper layout for side-by-side charts
            fig = plt.figure(figsize=(18, 10))
    
            # Create gridspec for layout: left side for candlestick+volume, right side for volume profile
            gs = fig.add_gridspec(
                2,
                2,
                width_ratios=[3.5, 1],
                height_ratios=[3, 1],
                hspace=0.3,
                wspace=0.15,
                left=0.08,
                right=0.95,
                top=0.95,
                bottom=0.1,
            )
    
            # Left side: candlestick chart (top) and volume bars (bottom)
            ax_price = fig.add_subplot(gs[0, 0])
            ax_volume = fig.add_subplot(gs[1, 0], sharex=ax_price)
    
            # Right side: volume profile (aligned with price chart)
            ax_profile = fig.add_subplot(gs[0, 1], sharey=ax_price)
    
            # Plot candlestick and volume using mplfinance on our custom axes
            style = mpf.make_mpf_style(base_mpf_style="yahoo", rc={"figure.facecolor": "white"})
            mpf.plot(
                df,
                type="candle",
                volume=ax_volume,
                style=style,
                ax=ax_price,
                show_nontrading=False,
                returnfig=False,
            )
    
            # Plot volume profile as horizontal bars on the right
            viridis = cm.get_cmap("viridis")
            colors = viridis(np.linspace(0, 1, len(volume_profile)))
            ax_profile.barh(volume_profile.index, volume_profile.values, color=colors, alpha=0.7)
            ax_profile.set_xlabel("Volume", fontsize=10)
            ax_profile.set_title("Volume Profile", fontsize=12, fontweight="bold", pad=10)
            ax_profile.grid(True, alpha=0.3, axis="x")
            ax_profile.set_ylabel("")  # Share y-axis label with main chart
    
            # Set overall title
            fig.suptitle(f"{symbol} - Volume Profile", fontsize=16, fontweight="bold", y=0.98)
    
            # Save directly to WebP format
            buf = io.BytesIO()
            fig.savefig(buf, format="webp", dpi=150, bbox_inches="tight")
            buf.seek(0)
            plt.close(fig)
    
        else:
            # Standard mplfinance chart (price_volume or vwap)
            addplots = []
            if chart_type == "vwap":
                # VWAP = Sum(Price * Volume) / Sum(Volume)
                typical_price = (df["High"] + df["Low"] + df["Close"]) / 3
                vwap = (typical_price * df["Volume"]).cumsum() / df["Volume"].cumsum()
                addplots.append(mpf.make_addplot(vwap, color="orange", width=2, linestyle="--", label="VWAP"))
    
            # Create style
            style = mpf.make_mpf_style(base_mpf_style="yahoo", rc={"figure.facecolor": "white"})
    
            # Save chart directly to WebP format
            buf = io.BytesIO()
            plot_kwargs = {
                "type": "candle",
                "volume": True,
                "style": style,
                "title": f"{symbol} - {chart_type.replace('_', ' ').title()}",
                "ylabel": "Price",
                "ylabel_lower": "Volume",
                "savefig": {"fname": buf, "format": "webp", "dpi": 150, "bbox_inches": "tight"},
                "show_nontrading": False,
                "returnfig": False,
            }
            if addplots:
                plot_kwargs["addplot"] = addplots
    
            mpf.plot(df, **plot_kwargs)
            buf.seek(0)
    
        return ImageContent(
            type="image",
            data=base64.b64encode(buf.read()).decode("utf-8"),
            mimeType="image/webp",
        )
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool fetches data (implying read-only), but doesn't mention rate limits, authentication requirements, data freshness, error handling, or response format details. This leaves significant gaps for a tool that interacts with external data sources.

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 a single, efficient sentence that front-loads the core purpose without unnecessary words. Every part of the sentence contributes directly to understanding the tool's function.

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, financial data fetching) and the presence of an output schema (which handles return values), the description is minimally adequate. However, with no annotations and incomplete behavioral context, it doesn't fully prepare an agent for real-world usage scenarios.

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

Parameters3/5

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

The description mentions parameters ('stock symbol', 'period', 'interval') but adds minimal semantic value beyond what's already in the schema, which has 100% coverage with detailed descriptions and enums. The baseline score of 3 reflects adequate but not enhanced parameter understanding.

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 with specific verbs ('fetch historical price data') and resources ('stock symbol'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'get_ticker_info' or 'get_ticker_news', which might also retrieve 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 like 'get_ticker_info' or 'search'. It mentions the scope ('over a specified period and interval') but offers no explicit when/when-not instructions or comparisons to 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

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/narumiruna/yfinance-mcp'

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