Skip to main content
Glama
berlinbra

AlphaVantage-MCP

get-earnings-calendar

Retrieve upcoming earnings calendar data for companies with customizable sorting and filtering options to track corporate earnings announcements.

Instructions

Get upcoming earnings calendar data for companies with sorting capabilities

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolNoOptional: Stock symbol to filter earnings for a specific company (e.g., AAPL, MSFT, IBM)
horizonNoOptional: Time horizon for earnings data (3month, 6month, or 12month)12month
limitNoOptional: Number of earnings entries to return (default: 100)
sort_byNoOptional: Field to sort byreportDate
sort_orderNoOptional: Sort orderdesc

Implementation Reference

  • Main execution logic for the get-earnings-calendar tool. Extracts arguments, calls make_alpha_request with EARNINGS_CALENDAR function, formats using format_earnings_calendar, and returns formatted text content.
    elif name == "get-earnings-calendar":
        symbol = arguments.get("symbol")
        horizon = arguments.get("horizon", "12month")
        limit = arguments.get("limit", 100)
        sort_by = arguments.get("sort_by", "reportDate")
        sort_order = arguments.get("sort_order", "desc")
        
        async with httpx.AsyncClient() as client:
            params = {"horizon": horizon}
            if symbol:
                params["symbol"] = symbol.upper()
                
            earnings_data = await make_alpha_request(
                client,
                "EARNINGS_CALENDAR",
                None,
                params
            )
    
            if isinstance(earnings_data, str):
                return [types.TextContent(type="text", text=f"Error: {earnings_data}")]
    
            formatted_earnings = format_earnings_calendar(earnings_data, limit, sort_by, sort_order)
            earnings_text = f"Earnings calendar"
            if symbol:
                earnings_text += f" for {symbol.upper()}"
            if horizon:
                earnings_text += f" ({horizon})"
            earnings_text += f":\n\n{formatted_earnings}"
    
            return [types.TextContent(type="text", text=earnings_text)]
  • Tool registration in list_tools() handler, defining name, description, and JSON schema for input validation including optional symbol, horizon, limit, sort_by, and sort_order.
    types.Tool(
        name="get-earnings-calendar",
        description="Get upcoming earnings calendar data for companies with sorting capabilities",
        inputSchema={
            "type": "object",
            "properties": {
                "symbol": {
                    "type": "string",
                    "description": "Optional: Stock symbol to filter earnings for a specific company (e.g., AAPL, MSFT, IBM)"
                },
                "horizon": {
                    "type": "string",
                    "description": "Optional: Time horizon for earnings data (3month, 6month, or 12month)",
                    "enum": ["3month", "6month", "12month"],
                    "default": "12month"
                },
                "limit": {
                    "type": "integer",
                    "description": "Optional: Number of earnings entries to return (default: 100)",
                    "default": 100,
                    "minimum": 1
                },
                "sort_by": {
                    "type": "string",
                    "description": "Optional: Field to sort by",
                    "enum": ["reportDate", "symbol", "name", "fiscalDateEnding", "estimate"],
                    "default": "reportDate"
                },
                "sort_order": {
                    "type": "string",
                    "description": "Optional: Sort order",
                    "enum": ["asc", "desc"],
                    "default": "desc"
                }
            },
            "required": [],
        },
    ),
  • Utility function to make HTTP requests to Alpha Vantage API. Specially handles EARNINGS_CALENDAR by parsing CSV response into list of dicts.
    async def make_alpha_request(client: httpx.AsyncClient, function: str, symbol: Optional[str], additional_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any] | str:
        """Make a request to the Alpha Vantage API with proper error handling.
        
        Args:
            client: An httpx AsyncClient instance
            function: The Alpha Vantage API function to call
            symbol: The stock/crypto symbol (can be None for some endpoints)
            additional_params: Additional parameters to include in the request
            
        Returns:
            Either a dictionary containing the API response, or a string with an error message
        """
        params = {
            "function": function,
            "apikey": API_KEY
        }
        
        if symbol:
            params["symbol"] = symbol
            
        if additional_params:
            params.update(additional_params)
    
        try:
            response = await client.get(
                ALPHA_VANTAGE_BASE,
                params=params,
                timeout=30.0
            )
    
            # Check for specific error responses
            if response.status_code == 429:
                return f"Rate limit exceeded. Error details: {response.text}"
            elif response.status_code == 403:
                return f"API key invalid or expired. Error details: {response.text}"
    
            response.raise_for_status()
    
            # Check if response is empty
            if not response.text.strip():
                return "Empty response received from Alpha Vantage API"
            
            # Special handling for EARNINGS_CALENDAR which returns CSV by default
            if function == "EARNINGS_CALENDAR":
                try:
                    # Parse CSV response
                    csv_reader = csv.DictReader(io.StringIO(response.text))
                    earnings_list = list(csv_reader)
                    return earnings_list
                except Exception as e:
                    return f"Error parsing CSV response: {str(e)}"
            
            # For other functions, expect JSON
            try:
                data = response.json()
            except ValueError as e:
                return f"Invalid JSON response from Alpha Vantage API: {response.text[:200]}"
    
            # Check for Alpha Vantage specific error messages
            if "Error Message" in data:
                return f"Alpha Vantage API error: {data['Error Message']}"
            if "Note" in data and "API call frequency" in data["Note"]:
                return f"Rate limit warning: {data['Note']}"
    
            return data
        except httpx.TimeoutException:
            return "Request timed out after 30 seconds. The Alpha Vantage API may be experiencing delays."
        except httpx.ConnectError:
            return "Failed to connect to Alpha Vantage API. Please check your internet connection."
        except httpx.HTTPStatusError as e:
            return f"HTTP error occurred: {str(e)} - Response: {e.response.text}"
        except Exception as e:
            return f"Unexpected error occurred: {str(e)}"
  • Helper function that takes the raw earnings data (list of dicts from CSV), applies sorting by specified field/date/numeric handling, limits output, formats into readable multi-line string with company details, dates, and estimates.
    def format_earnings_calendar(earnings_data: List[Dict[str, str]], limit: int = 100, sort_by: str = "reportDate", sort_order: str = "desc") -> str:
        """Format earnings calendar data into a concise string with sorting.
        
        Args:
            earnings_data: List of earnings records from the Alpha Vantage EARNINGS_CALENDAR endpoint (CSV format)
            limit: Number of earnings entries to display (default: 100)
            sort_by: Field to sort by (default: reportDate)
            sort_order: Sort order asc or desc (default: desc)
            
        Returns:
            A formatted string containing the sorted earnings calendar information
        """
        try:
            if not isinstance(earnings_data, list):
                return f"Unexpected data format: {type(earnings_data)}"
                
            if not earnings_data:
                return "No earnings calendar data available"
    
            # Sort the earnings data
            def get_sort_key(earning):
                value = earning.get(sort_by, "")
                
                # Special handling for dates to ensure proper chronological sorting
                if sort_by in ["reportDate", "fiscalDateEnding"]:
                    try:
                        # Convert date string to datetime for proper sorting
                        if value:
                            return datetime.strptime(value, "%Y-%m-%d")
                        else:
                            return datetime.min  # Put empty dates at the beginning
                    except ValueError:
                        return datetime.min
                
                # Special handling for numeric fields like estimate
                elif sort_by == "estimate":
                    try:
                        if value and value.strip():
                            return float(value)
                        else:
                            return 0.0
                    except ValueError:
                        return 0.0
                
                # For text fields (symbol, name), return as-is for alphabetical sorting
                else:
                    return str(value).upper()
    
            sorted_earnings = sorted(
                earnings_data,
                key=get_sort_key,
                reverse=(sort_order == "desc")
            )
    
            formatted = [f"Upcoming Earnings Calendar (Sorted by {sort_by} {sort_order}):\n\n"]
            
            # Display limited number of entries
            display_earnings = sorted_earnings[:limit] if limit > 0 else sorted_earnings
            
            for earning in display_earnings:
                symbol = earning.get('symbol', 'N/A')
                name = earning.get('name', 'N/A')
                report_date = earning.get('reportDate', 'N/A')
                fiscal_date = earning.get('fiscalDateEnding', 'N/A')
                estimate = earning.get('estimate', 'N/A')
                currency = earning.get('currency', 'N/A')
                
                formatted.append(f"Company: {symbol} - {name}\n")
                formatted.append(f"Report Date: {report_date}\n")
                formatted.append(f"Fiscal Date End: {fiscal_date}\n")
                
                # Format estimate nicely
                if estimate and estimate != 'N/A' and estimate.strip():
                    try:
                        est_float = float(estimate)
                        formatted.append(f"Estimate: ${est_float:.2f} {currency}\n")
                    except ValueError:
                        formatted.append(f"Estimate: {estimate} {currency}\n")
                else:
                    formatted.append(f"Estimate: Not available\n")
                
                formatted.append("---\n")
            
            if limit > 0 and len(earnings_data) > limit:
                formatted.append(f"\n... and {len(earnings_data) - limit} more earnings reports")
                
            return "".join(formatted)
        except Exception as e:
            return f"Error formatting earnings calendar data: {str(e)}"
Behavior2/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 of behavioral disclosure. It mentions 'sorting capabilities' but doesn't cover other critical aspects: whether this is a read-only operation, rate limits, authentication needs, pagination behavior (beyond the 'limit' parameter), error handling, or data freshness. For a data-fetching tool with zero annotation coverage, this leaves significant gaps in understanding its behavior.

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. It directly states what the tool does ('Get upcoming earnings calendar data for companies with sorting capabilities'), earning its place with zero waste. This is appropriately sized for the tool's complexity.

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

Completeness2/5

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

Given the tool's complexity (5 parameters, no output schema, no annotations), the description is incomplete. It lacks details on behavioral traits (e.g., read-only nature, rate limits), output format, error conditions, and differentiation from siblings like 'get-historical-earnings'. Without annotations or an output schema, the description should provide more context to fully inform an agent, but it falls short.

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 schema description coverage is 100%, with all parameters well-documented in the input schema. The description adds minimal value beyond the schema, mentioning 'sorting capabilities' which aligns with 'sort_by' and 'sort_order' parameters but doesn't provide additional context like default behaviors or usage examples. With high schema coverage, the baseline score of 3 is appropriate as the description doesn't significantly enhance 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: 'Get upcoming earnings calendar data for companies with sorting capabilities'. It specifies the verb ('Get'), resource ('earnings calendar data'), and scope ('upcoming', 'for companies'), but doesn't explicitly differentiate from sibling tools like 'get-historical-earnings', which might handle different timeframes. The description is specific but lacks sibling distinction.

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. It doesn't mention sibling tools like 'get-historical-earnings' for past data or 'get-stock-quote' for real-time quotes, nor does it specify prerequisites or exclusions. Usage is implied through the description but not explicitly stated.

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

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