Install pykrx via pip
masterYou can install pykrx using pip. The library is used to scrape stock and bond data from the Korean stock market (KRX, Naver).
pip install pykrxrepository·master·Indexed 21 days ago
https://github.com/sharebook-kr/pykrxA 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.
You can install pykrx using pip. The library is used to scrape stock and bond data from the Korean stock market (KRX, Naver).
pip install pykrxTo use the library, import the specific modules for the type of data you want to scrape. The primary modules are stock and bond.
from pykrx import stock
from pykrx import bondFor 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 -vTo 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.
| Variable | Required | Description |
|---|---|---|
KRX_ID | Yes | KRX (Korea Exchange) member login ID |
KRX_PW | Yes | KRX (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_passwordWhen you import pykrx, the library automatically configures matplotlib to support Korean characters to prevent broken text in plots:
AppleGothic.NanumBarunGothic.ttf font bundled with the package.axes.unicode_minus = False) to ensure negative signs are rendered correctly in plots.This configuration happens immediately upon importing the package.
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())Use stock.get_market_fundamental to retrieve financial ratios like DIV, BPS, PER, EPS, and PBR.
Returns a DataFrame of all stocks in a market for a specific date.
market: KOSPI, KOSDAQ, KONEX, or ALL.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")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.
KOSPI, KOSDAQ, or KONEX.balance_limit=True to search only for stocks that have reached their foreign ownership limit.# 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")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")Use stock.get_market_ticker_list to get a list of stock tickers for a specific date.
YYYYMMDD. If omitted, the function calculates the most recent business day.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()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())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())