Skip to main content
Glama

get_stock_fundamental

Retrieve fundamental stock data including PER, PBR, and dividend yield for specific KOSPI/KOSDAQ stocks within defined date ranges to analyze financial metrics.

Instructions

Retrieves fundamental data (PER/PBR/Dividend Yield) for a specific stock.

Args:
    fromdate (str): Start date for retrieval (YYYYMMDD)
    todate   (str): End date for retrieval (YYYYMMDD)
    ticker   (str): Stock ticker symbol

Returns:
    DataFrame:
        >> get_stock_fundamental("20210104", "20210108", "005930")
                          BPS        PER       PBR   EPS       DIV   DPS
            Date
            2021-01-08  37528  28.046875  2.369141  3166  1.589844  1416
            2021-01-07  37528  26.187500  2.210938  3166  1.709961  1416
            2021-01-06  37528  25.953125  2.189453  3166  1.719727  1416
            2021-01-05  37528  26.500000  2.240234  3166  1.690430  1416
            2021-01-04  37528  26.218750  2.210938  3166  1.709961  1416

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fromdateYes
todateYes
tickerYes

Implementation Reference

  • The @mcp.tool() decorated handler function implementing the get_stock_fundamental tool. Validates input dates and ticker, fetches data using pykrx's get_market_fundamental_by_date, converts Pandas DataFrame to sorted dictionary with date keys in YYYY-MM-DD format (descending), and handles exceptions.
    @mcp.tool()
    def get_stock_fundamental(fromdate: Union[str, int], todate: Union[str, int], ticker: Union[str, int]) -> Dict[str, Any]:
        """Retrieves fundamental data (PER/PBR/Dividend Yield) for a specific stock.
    
        Args:
            fromdate (str): Start date for retrieval (YYYYMMDD)
            todate   (str): End date for retrieval (YYYYMMDD)
            ticker   (str): Stock ticker symbol
    
        Returns:
            DataFrame:
                >> get_stock_fundamental("20210104", "20210108", "005930")
                                  BPS        PER       PBR   EPS       DIV   DPS
                    Date
                    2021-01-08  37528  28.046875  2.369141  3166  1.589844  1416
                    2021-01-07  37528  26.187500  2.210938  3166  1.709961  1416
                    2021-01-06  37528  25.953125  2.189453  3166  1.719727  1416
                    2021-01-05  37528  26.500000  2.240234  3166  1.690430  1416
                    2021-01-04  37528  26.218750  2.210938  3166  1.709961  1416
        """
        # Validate and convert date format
        def validate_date(date_str: Union[str, int]) -> str:
            try:
                if isinstance(date_str, int):
                    date_str = str(date_str)
                if '-' in date_str:
                    parsed_date = datetime.strptime(date_str, '%Y-%m-%d')
                    return parsed_date.strftime('%Y%m%d')
                datetime.strptime(date_str, '%Y%m%d')
                return date_str
            except ValueError:
                raise ValueError(f"Date must be in YYYYMMDD format. Input value: {date_str}")
    
        def validate_ticker(ticker_str: Union[str, int]) -> str:
            if isinstance(ticker_str, int):
                return str(ticker_str)
            return ticker_str
    
        try:
            fromdate = validate_date(fromdate)
            todate = validate_date(todate)
            ticker = validate_ticker(ticker)
    
            logging.debug(f"Retrieving stock fundamental data: {ticker}, {fromdate}-{todate}")
    
            # Call get_market_fundamental_by_date
            df = get_market_fundamental_by_date(fromdate, todate, ticker)
    
            # Convert DataFrame to dictionary
            result = df.to_dict(orient='index')
    
            # Convert datetime index to string and sort in reverse
            sorted_items = sorted(
                ((k.strftime('%Y-%m-%d'), v) for k, v in result.items()),
                reverse=True
            )
            result = dict(sorted_items)
    
            return result
    
        except Exception as e:
            error_message = f"Data retrieval failed: {str(e)}"
            logging.error(error_message)
            return {"error": error_message}
  • The @mcp.tool() decorator registers the get_stock_fundamental function as an MCP tool, using the function name as the tool name.
    @mcp.tool()
  • Function signature with type annotations defining the input schema (fromdate, todate, ticker as str or int) and output as Dict[str, Any]. The docstring provides further description and examples.
    def get_stock_fundamental(fromdate: Union[str, int], todate: Union[str, int], ticker: Union[str, int]) -> Dict[str, Any]:
  • Import of get_market_fundamental_by_date from pykrx library, which is the core data retrieval function called by the tool handler.
    from pykrx.stock.stock_api import get_market_ohlcv, get_nearest_business_day_in_a_week, get_market_cap, \
        get_market_fundamental_by_date, get_market_trading_volume_by_date, get_index_ohlcv_by_date
Behavior3/5

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

With no annotations provided, the description carries the full burden. It clearly indicates this is a read operation ('retrieves'), shows the return format with a detailed example, and implies date-range functionality. However, it doesn't disclose potential limitations like rate limits, authentication requirements, data freshness, or error conditions that would be important for an agent.

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

Conciseness4/5

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

The description is well-structured with clear sections (purpose, Args, Returns, example). Every sentence earns its place, though the detailed example DataFrame takes significant space. The core information is front-loaded with the purpose statement first, making it easy to understand quickly.

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?

For a read-only tool with 3 parameters and no output schema, the description provides substantial context. It clearly explains what data is returned (fundamental metrics), shows the exact return format with a realistic example, and documents all parameters. The main gap is lack of behavioral constraints that would normally come from annotations.

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?

With 0% schema description coverage, the description fully compensates by providing clear parameter documentation in the Args section. It explains what each parameter represents (start date, end date, ticker symbol), shows the expected format (YYYYMMDD), and provides a concrete usage example that demonstrates all three parameters in action.

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 retrieves fundamental data (PER/PBR/Dividend Yield) for a specific stock, providing a specific verb ('retrieves') and resource ('fundamental data'). It distinguishes from siblings like get_stock_market_cap or get_stock_ohlcv by specifying the type of financial data, though it doesn't explicitly contrast with them.

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_stock_market_cap or get_stock_ohlcv. It states what the tool does but offers no context about when it's appropriate or what problems it solves compared 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

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/dragon1086/kospi-kosdaq-stock-server'

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