Skip to main content
Glama

get_stock_ohlcv

Retrieve historical OHLCV stock data for KOSPI/KOSDAQ markets by specifying ticker symbol and date range to analyze price movements and trading volume.

Instructions

Retrieves OHLCV (Open/High/Low/Close/Volume) data for a specific stock.

Args:
    fromdate (str): Start date for retrieval (YYYYMMDD)
    todate   (str): End date for retrieval (YYYYMMDD)
    ticker   (str): Stock ticker symbol
    adjusted (bool, optional): Whether to use adjusted prices (True: adjusted, False: unadjusted). Defaults to True.

Returns:
    DataFrame:
        >> get_stock_ohlcv("20210118", "20210126", "005930")
                        Open     High     Low    Close   Volume
        Date
        2021-01-26  89500  94800  89500  93800  46415214
        2021-01-25  87300  89400  86800  88700  25577517
        2021-01-22  89000  89700  86800  86800  30861661
        2021-01-21  87500  88600  86500  88100  25318011
        2021-01-20  89000  89000  86500  87200  25211127
        2021-01-19  84500  88000  83600  87000  39895044
        2021-01-18  86600  87300  84100  85000  43227951

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fromdateYes
todateYes
tickerYes
adjustedNo

Implementation Reference

  • The core handler function decorated with @mcp.tool(), implementing the get_stock_ohlcv tool logic. It validates inputs, fetches OHLCV data from pykrx.get_market_ohlcv, converts to dict, sorts dates descending, and handles errors.
    @mcp.tool()
    def get_stock_ohlcv(fromdate: Union[str, int], todate: Union[str, int], ticker: Union[str, int], adjusted: bool = True) -> Dict[str, Any]:
        """Retrieves OHLCV (Open/High/Low/Close/Volume) data for a specific stock.
    
        Args:
            fromdate (str): Start date for retrieval (YYYYMMDD)
            todate   (str): End date for retrieval (YYYYMMDD)
            ticker   (str): Stock ticker symbol
            adjusted (bool, optional): Whether to use adjusted prices (True: adjusted, False: unadjusted). Defaults to True.
    
        Returns:
            DataFrame:
                >> get_stock_ohlcv("20210118", "20210126", "005930")
                                Open     High     Low    Close   Volume
                Date
                2021-01-26  89500  94800  89500  93800  46415214
                2021-01-25  87300  89400  86800  88700  25577517
                2021-01-22  89000  89700  86800  86800  30861661
                2021-01-21  87500  88600  86500  88100  25318011
                2021-01-20  89000  89000  86500  87200  25211127
                2021-01-19  84500  88000  83600  87000  39895044
                2021-01-18  86600  87300  84100  85000  43227951
        """
        # 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)
                # Convert if in YYYY-MM-DD format
                if '-' in date_str:
                    parsed_date = datetime.strptime(date_str, '%Y-%m-%d')
                    return parsed_date.strftime('%Y%m%d')
                # Validate if in YYYYMMDD format
                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 OHLCV data: {ticker}, {fromdate}-{todate}, adjusted={adjusted}")
    
            # Call get_market_ohlcv (changed adj -> adjusted)
            df = get_market_ohlcv(fromdate, todate, ticker, adjusted=adjusted)
    
            # 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/output schema defined via type hints (Union[str, int] for dates/ticker, bool for adjusted) and detailed docstring describing parameters and return format as dict of OHLCV data.
    Args:
        fromdate (str): Start date for retrieval (YYYYMMDD)
        todate   (str): End date for retrieval (YYYYMMDD)
        ticker   (str): Stock ticker symbol
        adjusted (bool, optional): Whether to use adjusted prices (True: adjusted, False: unadjusted). Defaults to True.
    
    Returns:
        DataFrame:
            >> get_stock_ohlcv("20210118", "20210126", "005930")
                            Open     High     Low    Close   Volume
            Date
            2021-01-26  89500  94800  89500  93800  46415214
            2021-01-25  87300  89400  86800  88700  25577517
            2021-01-22  89000  89700  86800  86800  30861661
            2021-01-21  87500  88600  86500  88100  25318011
            2021-01-20  89000  89000  86500  87200  25211127
            2021-01-19  84500  88000  83600  87000  39895044
            2021-01-18  86600  87300  84100  85000  43227951
    """
  • The @mcp.tool() decorator registers the get_stock_ohlcv function as an MCP tool.
    @mcp.tool()
  • Helper function for validating and normalizing date inputs to YYYYMMDD format.
    def validate_date(date_str: Union[str, int]) -> str:
        try:
            if isinstance(date_str, int):
                date_str = str(date_str)
            # Convert if in YYYY-MM-DD format
            if '-' in date_str:
                parsed_date = datetime.strptime(date_str, '%Y-%m-%d')
                return parsed_date.strftime('%Y%m%d')
            # Validate if in YYYYMMDD format
            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}")
Behavior3/5

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

With no annotations provided, the description carries full burden. It clearly indicates this is a read operation ('Retrieves'), implies data retrieval from a source, and shows the return format with an example. However, it lacks details on rate limits, authentication needs, 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?

Well-structured with clear sections (purpose, args, returns, example). The example is detailed but necessary to show the return format. Slightly verbose due to the full example table, but each section adds value. Could be more front-loaded by moving the example after a brief return description.

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 4-parameter tool with no annotations and no output schema, the description does an excellent job explaining parameters and showing the return format through example. It covers the core functionality well but lacks context about data sources, limitations, or error handling that would make it fully complete.

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 provides comprehensive parameter documentation beyond the schema's 0% coverage. It explains each parameter's purpose, format requirements (YYYYMMDD for dates), and the adjusted parameter's meaning and default value. The example demonstrates proper usage with concrete values.

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 specific action ('Retrieves OHLCV data') and resource ('for a specific stock'), distinguishing it from siblings like get_stock_fundamental or get_stock_trading_volume. It precisely identifies the data type (Open/High/Low/Close/Volume) and target resource (stock).

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?

No guidance is provided on when to use this tool versus alternatives like get_index_ohlcv or get_stock_trading_volume. The description mentions only what the tool does, not when it's appropriate relative to sibling tools or any prerequisites for use.

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