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}")

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