Skip to main content
Glama

get_stock_trading_volume

Retrieve trading volume and value data by investor type for KOSPI/KOSDAQ stocks to analyze market participation patterns and investment flows.

Instructions

Retrieves trading volume by investor type 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 with columns:
    - Volume (Sell/Buy/Net Buy)
    - Trading Value (Sell/Buy/Net Buy)
    Broken down by investor types (Financial Investment, Insurance, Trust, etc.)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fromdateYes
todateYes
tickerYes

Implementation Reference

  • The handler function for the 'get_stock_trading_volume' tool. It validates input dates and ticker, fetches trading volume data by investor type using pykrx.get_market_trading_volume_by_date, converts the DataFrame to a dictionary with dates as keys sorted in descending order, and handles errors.
    @mcp.tool()
    def get_stock_trading_volume(fromdate: Union[str, int], todate: Union[str, int], ticker: Union[str, int]) -> Dict[str, Any]:
        """Retrieves trading volume by investor type 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 with columns:
            - Volume (Sell/Buy/Net Buy)
            - Trading Value (Sell/Buy/Net Buy)
            Broken down by investor types (Financial Investment, Insurance, Trust, etc.)
        """
        # 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 trading volume by investor type: {ticker}, {fromdate}-{todate}")
    
            # Call get_market_trading_volume_by_date
            df = get_market_trading_volume_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}
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 of behavioral disclosure. It describes the retrieval action and output format (DataFrame with specific columns), but omits details like rate limits, authentication needs, error handling, or data freshness. It adds some context (e.g., breakdown by investor types) but lacks comprehensive behavioral traits.

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 and appropriately sized, with a clear purpose statement followed by parameter and return details. Every sentence adds value, though it could be slightly more front-loaded by emphasizing the investor type breakdown earlier. No wasted text, but minor room for optimization in flow.

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 tool's moderate complexity (3 parameters, no output schema, no annotations), the description is largely complete. It covers purpose, parameters, and return format in detail. However, it lacks information on behavioral aspects like error cases or data limitations, which would enhance completeness for a tool with no 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?

The description adds significant meaning beyond the input schema, which has 0% description coverage. It explicitly defines each parameter (fromdate, todate, ticker) with formats (YYYYMMDD for dates, ticker symbol) and clarifies their roles in date range and stock selection, fully compensating for the schema's lack of documentation.

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's purpose with a specific verb ('Retrieves') and resource ('trading volume by investor type for a specific stock'), distinguishing it from siblings like get_stock_ohlcv (price data) or get_stock_fundamental (financial metrics). It precisely identifies what data is fetched and how it's categorized.

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 obtaining trading volume breakdowns by investor type, but lacks explicit guidance on when to use this tool versus alternatives like get_stock_ohlcv (which might include volume without investor breakdown) or other siblings. No exclusions or prerequisites are mentioned, leaving context somewhat open-ended.

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