pykrx

repository·master·Indexed 21 days ago

https://github.com/sharebook-kr/pykrx

A Python library for scraping stock and bond data from the Korean stock market, including KRX and Naver. It provides functionality to retrieve ticker lists, OHLCV data, market fundamentals, trading values and volumes by investor, market capitalization, foreign investment exhaustion rates, index portfolios, and short selling status.

Tokens
7.1K
Snippets
32
Records
34
Agent score
27%

What's inside pykrx

  1. Set up a development environment for pykrx

    master

    For local development and testing, follow these steps in the project root to set up a virtual environment, install development dependencies (including pytest, ruff, and pre-commit), and run tests.

    # Create and activate virtual environment
    python3 -m venv .venv
    source .venv/bin/activate  # macOS / Linux
    # .venv\Scripts\activate   # Windows (PowerShell)
    
    # Install with development dependencies
    pip install -e .[dev]
    
    # Install pre-commit hooks
    pre-commit install
    
    # (Optional) Auto-fix code with Ruff
    ruff check --fix .
    ruff format .
    
    # Run all tests
    pytest -v
  2. Configure required environment variables for KRX login

    master

    To use APIs that require KRX login, you must set the following environment variables. Without these, KRX login will fail and authenticated data cannot be retrieved.

    VariableRequiredDescription
    KRX_IDYesKRX (Korea Exchange) member login ID
    KRX_PWYesKRX (Korea Exchange) member login password

    Note: If using a .env file, use a library like python-dotenv to load it. Never commit your .env file to version control (git).

    # macOS / Linux
    export KRX_ID="your_krx_id"
    export KRX_PW="your_krx_password"
    
    # Windows (PowerShell)
    $env:KRX_ID="your_krx_id"
    $env:KRX_PW="your_krx_password"
    
    # Windows (Command Prompt)
    set KRX_ID=your_krx_id
    set KRX_PW=your_krx_password
  3. Automatic font configuration for Matplotlib

    master

    When you import pykrx, the library automatically configures matplotlib to support Korean characters to prevent broken text in plots:

    • macOS (Darwin): Sets the font family to AppleGothic.
    • Other Platforms (Windows/Linux): Automatically loads and registers the NanumBarunGothic.ttf font bundled with the package.
    • Unicode Support: Disables the unicode minus sign (axes.unicode_minus = False) to ensure negative signs are rendered correctly in plots.

    This configuration happens immediately upon importing the package.

  4. Get stock major changes with get_stock_major_changes()

    master

    Use the get_stock_major_changes function to retrieve historical major changes for a specific company. This includes changes to the company name (상호), business type (업종), par value (액면), and CEO/Representative Director (대표이사).

    Returns a pandas DataFrame where the index is the date of the change.

    import stock
    
    # Retrieve major changes for a specific stock code (e.g., Samsung Electronics '005930')
    df = stock.get_stock_major_changes("005930")
    print(df.head())
  5. Retrieve fundamental data with `get_market_fundamental`

    master

    Use stock.get_market_fundamental to retrieve financial ratios like DIV, BPS, PER, EPS, and PBR.

    Market-wide Fundamentals

    Returns a DataFrame of all stocks in a market for a specific date.

    • market: KOSPI, KOSDAQ, KONEX, or ALL.

    Ticker-specific Fundamentals

    Returns a time-series of fundamentals for a specific ticker.

    • frequency: 'd' (daily), 'm' (monthly), or 'y' (yearly).
    # Fundamentals for all KOSDAQ stocks on a specific date
    df = stock.get_market_fundamental("20210104", market="KOSDAQ")
    
    # Monthly fundamentals for a specific ticker
    df = stock.get_market_fundamental("20200101", "20200430", "005930", freq="m")
  6. Get foreign investment exhaustion rates

    master

    Use get_exhaustion_rates_of_foreign_investment to retrieve information regarding outstanding shares, foreign limit quantity, foreign holding quantity, and the foreign investment exhaustion rate.

    • Market Filter: Specify KOSPI, KOSDAQ, or KONEX.
    • Limit Filter: Set balance_limit=True to search only for stocks that have reached their foreign ownership limit.
    • Data Timing: Foreign holding quantities and exhaustion rates are based on the previous day's confirmed figures from the FSS (Financial Supervisory Service) as of the market opening.
    # Get exhaustion rates for all stocks on a date
    df = stock.get_exhaustion_rates_of_foreign_investment('20200703')
    
    # Get exhaustion rates for KOSPI stocks only
    df = stock.get_exhaustion_rates_of_foreign_investment('20200703', "KOSPI")
    
    # Get only stocks that have reached their foreign ownership limit
    df = stock.get_exhaustion_rates_of_foreign_investment('20200703', "KOSPI", balance_limit=True)
    
    # Get historical exhaustion rates for a specific ticker
    df = stock.get_exhaustion_rates_of_foreign_investment("20210108", "20210115", "005930")
  7. Get Index Listing Information and Price Changes

    master

    Use these functions to analyze index metadata and performance:

    • get_index_listing_date(market): Returns the listing date and base index information. Supported markets: KRX, KOSPI, KOSDAQ, or specific themes.
    • get_index_price_change(start_date, end_date, market): Returns the price change rate, volume, and trading value for indices. Supports KRX, KOSPI, and KOSDAQ markets.
    # Get listing info for KOSPI
    df = stock.get_index_listing_date("KOSPI")
    
    # Get price change statistics for KOSDAQ
    df = stock.get_index_price_change("20200520", "20200527", "KOSDAQ")
  8. Retrieve ticker lists with `get_market_ticker_list`

    master

    Use stock.get_market_ticker_list to get a list of stock tickers for a specific date.

    • Date format: YYYYMMDD. If omitted, the function calculates the most recent business day.
    • Market selection: Use the market parameter to filter by KOSPI, KOSDAQ, KONEX, or ALL (all markets). If omitted, it defaults to KOSPI.
    # Get KOSDAQ tickers for a specific date
    tickers = stock.get_market_ticker_list("20190225", market="KOSDAQ")
    
    # Get all tickers for the most recent business day
    tickers = stock.get_market_ticker_list()
  9. Get shorting volume or value by ticker

    master

    Retrieve short selling transaction information for all tickers on a specific date.

    • get_shorting_volume_by_ticker(date, market="KOSPI", include=None): Returns short selling volume, buy volume, and the ratio.
    • get_shorting_value_by_ticker(date, market="KOSPI", include=None): Returns short selling transaction value.

    Parameters:

    • date: The target date (string).
    • market: The market to query. Options are KOSPI, KOSDAQ, or KONEX. Defaults to KOSPI.
    • include: A list of specific security types to include. Supported values are: 주식 (Stock), ETF, ETN, ELW, 신주인수권증서및증권 (Warrants), 수익증권 (Beneficiary Certificates).
    # Get volume for KOSDAQ including Stocks and ELWs
    df = stock.get_shorting_volume_by_ticker("20210125", "KOSDAQ", include=["주식", "ELW"])
    print(df.head())
  10. Get shorting status by investor type

    master

    Retrieve short selling transaction data categorized by investor type (e.g., Institutional, Individual, Foreigner) for a specific market over a date range.

    • get_shorting_investor_volume_by_date(start_date, end_date, market="KOSPI"): Returns transaction volume.
    • get_shorting_investor_value_by_date(start_date, end_date, market="KOSPI"): Returns transaction value.
    # Get volume by investor for KOSDAQ
    df = stock.get_shorting_investor_volume_by_date("20190401", "20190405", "KOSDAQ")
    print(df.head())