What is pykrx?

pykrx is an open-source Python library that pulls data from the KRX website. It is the easiest way to get Korean stock market data without needing a paid API.

Installation

pip install pykrx

Basic Usage

Get Stock Price History

from pykrx import stock

# Get Samsung Electronics (005930) price history
df = stock.get_market_ohlcv_by_date("20240101", "20241231", "005930")
print(df.head())

Get All KOSPI Tickers

from pykrx import stock

# Get all KOSPI tickers
tickers = stock.get_market_ticker_list(market="KOSPI")
print(f"Total KOSPI stocks: {len(tickers)}")

# Get company name from ticker
name = stock.get_market_ticker_name("005930")
print(f"005930 = {name}")  # Samsung Electronics

Get Market Cap Data

# Get market cap for all KOSPI stocks
df = stock.get_market_cap_by_ticker("20241231", market="KOSPI")
print(df.sort_values("시가총액", ascending=False).head(10))

Get Fundamental Data

# Get PER, PBR, dividend yield
df = stock.get_market_fundamental_by_ticker("20241231", market="KOSPI")
print(df[["PER", "PBR", "DIV"]].head())

Building a Simple Screener

from pykrx import stock

def screen_low_per_stocks(market="KOSPI", max_per=10):
    today = "20241231"
    fundamentals = stock.get_market_fundamental_by_ticker(today, market=market)
    low_per = fundamentals[
        (fundamentals["PER"] > 0) & 
        (fundamentals["PER"] < max_per)
    ]
    low_per["name"] = [stock.get_market_ticker_name(t) for t in low_per.index]
    return low_per[["name", "PER", "PBR", "DIV"]].sort_values("PER")

results = screen_low_per_stocks()
print(results.head(20))

pykrx vs KIS API Comparison

Feature pykrx KIS API
Real-time data No Yes
Historical data Yes Yes
Order placement No Yes
Cost Free Free (with account)
Best for Research, backtesting Live trading