Skip to main content
Glama
berlinbra

AlphaVantage-MCP

get-time-series

Retrieve daily stock price history with date filtering to analyze market trends and performance over time.

Instructions

Get daily time series data for a stock with optional date filtering

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesStock symbol (e.g., AAPL, MSFT)
outputsizeNocompact (latest 100 data points) or full (up to 20 years of data). When start_date or end_date is specified, defaults to 'full'compact
start_dateNoOptional: Start date in YYYY-MM-DD format for filtering results
end_dateNoOptional: End date in YYYY-MM-DD format for filtering results
limitNoOptional: Number of data points to return when no date filtering is applied (default: 5)

Implementation Reference

  • The main handler logic for executing the 'get-time-series' tool. Extracts parameters, determines outputsize, fetches data from Alpha Vantage TIME_SERIES_DAILY endpoint, formats using format_time_series helper, and returns formatted text content.
    elif name == "get-time-series":
        symbol = arguments.get("symbol")
        if not symbol:
            return [types.TextContent(type="text", text="Missing symbol parameter")]
    
        symbol = symbol.upper()
        start_date = arguments.get("start_date")
        end_date = arguments.get("end_date")
        limit = arguments.get("limit", 5)
        
        # Auto-select outputsize: use 'full' when date filtering is requested
        outputsize = arguments.get("outputsize")
        if not outputsize:
            outputsize = "full" if (start_date or end_date) else "compact"
    
        async with httpx.AsyncClient() as client:
            time_series_data = await make_alpha_request(
                client,
                "TIME_SERIES_DAILY",
                symbol,
                {"outputsize": outputsize}
            )
    
            if isinstance(time_series_data, str):
                return [types.TextContent(type="text", text=f"Error: {time_series_data}")]
    
            formatted_series = format_time_series(time_series_data, start_date, end_date, limit)
            series_text = f"Time series data for {symbol}:\n\n{formatted_series}"
    
            return [types.TextContent(type="text", text=series_text)]
  • Tool registration in the list_tools handler, defining the name, description, and JSON schema for input validation including symbol, outputsize, date filters, and limit.
    types.Tool(
        name="get-time-series",
        description="Get daily time series data for a stock with optional date filtering",
        inputSchema={
            "type": "object",
            "properties": {
                "symbol": {
                    "type": "string",
                    "description": "Stock symbol (e.g., AAPL, MSFT)",
                },
                "outputsize": {
                    "type": "string",
                    "description": "compact (latest 100 data points) or full (up to 20 years of data). When start_date or end_date is specified, defaults to 'full'",
                    "enum": ["compact", "full"],
                    "default": "compact"
                },
                "start_date": {
                    "type": "string",
                    "description": "Optional: Start date in YYYY-MM-DD format for filtering results",
                    "pattern": "^20[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$"
                },
                "end_date": {
                    "type": "string",
                    "description": "Optional: End date in YYYY-MM-DD format for filtering results",
                    "pattern": "^20[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$"
                },
                "limit": {
                    "type": "integer",
                    "description": "Optional: Number of data points to return when no date filtering is applied (default: 5)",
                    "default": 5,
                    "minimum": 1
                }
            },
            "required": ["symbol"],
        },
    ),
  • Supporting helper function that processes and formats the raw time series API response, applying date range filtering, limiting results, and generating a readable text output.
    def format_time_series(time_series_data: Dict[str, Any], start_date: Optional[str] = None, end_date: Optional[str] = None, limit: int = 5) -> str:
        """Format time series data into a concise string with optional date filtering.
        
        Args:
            time_series_data: The response data from the Alpha Vantage TIME_SERIES_DAILY endpoint
            start_date: Optional start date in YYYY-MM-DD format for filtering
            end_date: Optional end date in YYYY-MM-DD format for filtering  
            limit: Number of data points to return when no date filtering is applied
            
        Returns:
            A formatted string containing the time series information
        """
        try:
            # Get the daily time series data
            time_series = time_series_data.get("Time Series (Daily)", {})
            if not time_series:
                return "No time series data available in the response"
    
            # Get metadata
            metadata = time_series_data.get("Meta Data", {})
            symbol = metadata.get("2. Symbol", "Unknown")
            last_refreshed = metadata.get("3. Last Refreshed", "Unknown")
    
            # Filter by date range if specified
            filtered_data = {}
            if start_date or end_date:
                for date_str, values in time_series.items():
                    try:
                        date_obj = datetime.strptime(date_str, "%Y-%m-%d")
                        
                        # Check start date filter
                        if start_date:
                            start_obj = datetime.strptime(start_date, "%Y-%m-%d")
                            if date_obj < start_obj:
                                continue
                        
                        # Check end date filter
                        if end_date:
                            end_obj = datetime.strptime(end_date, "%Y-%m-%d")
                            if date_obj > end_obj:
                                continue
                        
                        filtered_data[date_str] = values
                    except ValueError:
                        # Skip invalid date formats
                        continue
                
                # Sort filtered data by date (most recent first)
                sorted_items = sorted(filtered_data.items(), key=lambda x: x[0], reverse=True)
            else:
                # Use original data with limit
                sorted_items = list(time_series.items())[:limit]
    
            if not sorted_items:
                return f"No time series data found for the specified date range"
    
            # Build header
            formatted_data = [
                f"Time Series Data for {symbol} (Last Refreshed: {last_refreshed})\n"
            ]
            
            # Add date range info if filtering was applied
            if start_date or end_date:
                date_range = ""
                if start_date and end_date:
                    date_range = f"Date Range: {start_date} to {end_date}"
                elif start_date:
                    date_range = f"From: {start_date}"
                elif end_date:
                    date_range = f"Until: {end_date}"
                formatted_data.append(f"{date_range} ({len(sorted_items)} data points)\n\n")
            else:
                formatted_data.append(f"(Showing {len(sorted_items)} most recent data points)\n\n")
    
            # Format the data points
            for date, values in sorted_items:
                formatted_data.append(
                    f"Date: {date}\n"
                    f"Open: ${values.get('1. open', 'N/A')}\n"
                    f"High: ${values.get('2. high', 'N/A')}\n"
                    f"Low: ${values.get('3. low', 'N/A')}\n"
                    f"Close: ${values.get('4. close', 'N/A')}\n"
                    f"Volume: {values.get('5. volume', 'N/A')}\n"
                    "---\n"
                )
    
            return "\n".join(formatted_data)
        except Exception as e:
            return f"Error formatting time series data: {str(e)}"

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/berlinbra/alpha-vantage-mcp'

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