Skip to main content
Glama

get_index_ohlcv

Retrieve OHLCV data for KOSPI/KOSDAQ market indices to analyze historical price movements and trading volumes for specific date ranges and frequencies.

Instructions

Retrieves OHLCV data for a specific index.

Args:
    fromdate (str): Start date for retrieval (YYYYMMDD)
    todate   (str): End date for retrieval (YYYYMMDD)
    ticker   (str): Index ticker symbol (e.g., 1001 for KOSPI, 2001 for KOSDAQ)
    freq     (str, optional): d - daily / m - monthly / y - yearly. Defaults to 'd'.

Returns:
    DataFrame:
        >> get_index_ohlcv("20210101", "20210130", "1001")
                       Open     High      Low    Close       Volume    Trading Value
        Date
        2021-01-04  2874.50  2946.54  2869.11  2944.45  1026510465  25011393960858
        2021-01-05  2943.67  2990.57  2921.84  2990.57  1519911750  26548380179493
        2021-01-06  2993.34  3027.16  2961.37  2968.21  1793418534  29909396443430
        2021-01-07  2980.75  3055.28  2980.75  3031.68  1524654500  27182807334912
        2021-01-08  3040.11  3161.11  3040.11  3152.18  1297903388  40909490005818

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fromdateYes
todateYes
tickerYes
freqNod

Implementation Reference

  • The primary handler for the get_index_ohlcv tool. Decorated with @mcp.tool() for registration in FastMCP. Validates input dates, ticker, and frequency; fetches OHLCV data using pykrx.get_index_ohlcv_by_date; converts to sorted dictionary by date (descending); handles exceptions.
    @mcp.tool()
    def get_index_ohlcv(fromdate: Union[str, int], todate: Union[str, int], ticker: Union[str, int], freq: str = 'd') -> \
    Dict[str, Any]:
        """Retrieves OHLCV data for a specific index.
    
        Args:
            fromdate (str): Start date for retrieval (YYYYMMDD)
            todate   (str): End date for retrieval (YYYYMMDD)
            ticker   (str): Index ticker symbol (e.g., 1001 for KOSPI, 2001 for KOSDAQ)
            freq     (str, optional): d - daily / m - monthly / y - yearly. Defaults to 'd'.
    
        Returns:
            DataFrame:
                >> get_index_ohlcv("20210101", "20210130", "1001")
                               Open     High      Low    Close       Volume    Trading Value
                Date
                2021-01-04  2874.50  2946.54  2869.11  2944.45  1026510465  25011393960858
                2021-01-05  2943.67  2990.57  2921.84  2990.57  1519911750  26548380179493
                2021-01-06  2993.34  3027.16  2961.37  2968.21  1793418534  29909396443430
                2021-01-07  2980.75  3055.28  2980.75  3031.68  1524654500  27182807334912
                2021-01-08  3040.11  3161.11  3040.11  3152.18  1297903388  40909490005818
        """
    
        # 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
    
        def validate_freq(freq_str: str) -> str:
            valid_freqs = ['d', 'm', 'y']
            if freq_str not in valid_freqs:
                raise ValueError(f"Frequency must be one of {valid_freqs}. Input value: {freq_str}")
            return freq_str
    
        try:
            fromdate = validate_date(fromdate)
            todate = validate_date(todate)
            ticker = validate_ticker(ticker)
            freq = validate_freq(freq)
    
            logging.debug(f"Retrieving index OHLCV data: {ticker}, {fromdate}-{todate}, freq={freq}")
    
            # Call get_index_ohlcv_by_date
            # Note: name_display is set to False to match the pattern of other functions
            df = get_index_ohlcv_by_date(fromdate, todate, ticker, freq=freq, name_display=False)
    
            # 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}
  • Input validation functions used within the handler for schema enforcement: validate_date (ensures YYYYMMDD format), validate_ticker (converts to str), validate_freq (checks 'd','m','y'). Also type hints on function parameters provide schema info.
    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
    
    def validate_freq(freq_str: str) -> str:
        valid_freqs = ['d', 'm', 'y']
        if freq_str not in valid_freqs:
            raise ValueError(f"Frequency must be one of {valid_freqs}. Input value: {freq_str}")
        return freq_str
  • The @mcp.tool() decorator registers the get_index_ohlcv function as an MCP tool in the FastMCP server.
    @mcp.tool()
  • Invocation of the underlying pykrx library function get_index_ohlcv_by_date, which provides the core data retrieval logic.
    df = get_index_ohlcv_by_date(fromdate, todate, ticker, freq=freq, name_display=False)
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by specifying the return format (DataFrame), showing example output structure, and explaining parameter formats. However, it doesn't mention potential limitations like rate limits, authentication needs, or data availability constraints.

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?

Well-structured with purpose statement, parameter documentation, return specification, and concrete example. Every sentence adds value - no redundant information. The example output is appropriately detailed to illustrate the DataFrame structure.

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 data retrieval tool with no annotations and no output schema, the description provides excellent context about parameters and return format. The example DataFrame shows exactly what to expect. Minor deduction because it doesn't address potential error conditions or data source limitations.

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?

Given 0% schema description coverage, the description compensates excellently by explaining all 4 parameters with clear semantics: date formats (YYYYMMDD), ticker examples (1001 for KOSPI), frequency options (d/m/y), and default values. The example call demonstrates proper parameter usage.

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 specific verb ('Retrieves') and resource ('OHLCV data for a specific index'). It distinguishes from sibling tools like get_stock_ohlcv by specifying it's for indices rather than individual stocks.

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 context through parameter explanations and example, but doesn't explicitly state when to use this tool versus alternatives like get_stock_ohlcv. No explicit guidance on when-not-to-use or comparison with sibling tools is provided.

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