### Install pykrx Source: https://context7.com/sharebook-kr/pykrx/llms.txt Install the pykrx library using pip. Ensure you are using Python 3.10 or higher. ```bash pip install pykrx ``` -------------------------------- ### Get ETF Ticker List Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Fetches a list of ETF tickers available on a specific date. The first example shows the first 10 tickers, while the second demonstrates retrieving all tickers for a past date. ```python tickers = stock.get_etf_ticker_list("20200717") print(tickers[:10]) ``` ```python get_etf_ticker_list("20021014") print(tickers) ``` -------------------------------- ### Get Index Portfolio Deposit File Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the list of tickers that constitute a specific index. The example shows that the '1005' index (Textiles and Apparel) is composed of 37 stocks. ```python pdf = stock.get_index_portfolio_deposit_file("1005") print(len(pdf), pdf) ``` -------------------------------- ### Set Up Local Development Environment Source: https://github.com/sharebook-kr/pykrx/blob/master/CONTRIBUTING.md Commands to create a virtual environment, activate it, install development dependencies, and set up pre-commit hooks. ```bash python3.10 -m venv .venv source .venv/bin/activate # macOS / Linux # Windows (PowerShell): .venv\Scripts\Activate.ps1 pip install -e .[dev] pre-commit install ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Commands to set up a local development environment, including creating a virtual environment, installing dependencies, and setting up pre-commit hooks. ```bash # 가상환경 생성 및 활성화 python3 -m venv .venv source .venv/bin/activate # macOS / Linux .venv\Scripts\activate # Windows (PowerShell) # 개발 의존성 포함 설치 pip install -e .[dev] # pre-commit 훅 설치 pre-commit install # Ruff로 코드 자동수정(포맷/정리) - 선택사항 ruff check --fix . ruff format . # 전체 테스트 실행 pytest -v ``` -------------------------------- ### Get market ticker list Source: https://context7.com/sharebook-kr/pykrx/llms.txt Fetch a list of stock tickers for a specific market (KOSPI, KOSDAQ, KONEX, ALL) on a given date. If no date is provided, it defaults to the most recent business day. Also includes a function to get the name of a ticker. ```python from pykrx import stock # 코스피 전체 티커 조회 tickers = stock.get_market_ticker_list("20210104") print(tickers[:5]) # ['095570', '006840', '027410', '282330', '138930'] # 코스닥 티커 조회 kosdaq_tickers = stock.get_market_ticker_list("20210104", market="KOSDAQ") print(kosdaq_tickers[:5]) # ['060310', '054620', '265520', '211270', '035760'] # 종목명 조회 name = stock.get_market_ticker_name("005930") print(name) # '삼성전자' ``` -------------------------------- ### Get Short Selling Balance for All Stocks on a Date Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves short selling balance information for all stocks on a specific date. ```python from pykrx import stock # 전종목 공매도 잔고 (티커별) df_all = stock.get_shorting_balance("20210127") print(df_all.head(3)) ``` -------------------------------- ### Get Tickers by Market Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Specify the market (KOSPI, KOSDAQ, KONEX, or ALL) when retrieving the ticker list for a given date. ```python tickers = stock.get_market_ticker_list("20190225", market="KOSDAQ") print(tickers) ``` -------------------------------- ### Get Index Ticker List and OHLCV Data Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves ticker lists for various index markets (KOSPI, KOSDAQ, KRX, Theme) and their OHLCV data. Includes functions to get ticker names and portfolio composition. ```python from pykrx import stock # 코스피 인덱스 티커 목록 tickers = stock.get_index_ticker_list(market="KOSPI") for t in tickers[:3]: print(t, stock.get_index_ticker_name(t)) # 1001 코스피 # 1028 코스피 200 # 1034 코스피 100 # 코스피 200 인덱스 OHLCV (기간별) df = stock.get_index_ohlcv("20210101", "20210130", "1028") print(df.head(3)) # 시가 고가 저가 종가 거래량 # 날짜 # 2021-01-04 389.29 397.32 386.03 395.98 808484044 ``` -------------------------------- ### Get Daily Short Selling Volume by Date Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves daily short selling volume for a specific stock over a period. ```python from pykrx import stock # 공매도 거래량 (일별) df_vol = stock.get_shorting_volume_by_date("20210104", "20210108", "005930") print(df_vol) ``` -------------------------------- ### Get List of KOSDAQ Index Tickers Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves a list of KOSDAQ index tickers using the 'market' option. ```python tickers = stock.get_index_ticker_list(market='KOSDAQ') ``` -------------------------------- ### Get ETF Portfolio Deposit File Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the constituent stock and weight information for a given ETF. ```APIDOC ## get_etf_portfolio_deposit_file ### Description Retrieves the portfolio composition of an ETF, including the number of contracts, amount, and weight of each constituent stock. A specific date can also be provided to get the portfolio status on that day. ### Method `stock.get_etf_portfolio_deposit_file(ticker, date=None)` ### Parameters #### Path Parameters - **ticker** (str) - Required - The ETF ticker symbol. - **date** (str) - Optional - The date in 'YYYYMMDD' format to retrieve the portfolio composition for. If not provided, the latest available data is returned. ### Request Example ```python df = stock.get_etf_portfolio_deposit_file("152100") print(df.head()) ``` ```python df = stock.get_etf_portfolio_deposit_file("152100", "20161206") print(df.head()) ``` ### Response #### Success Response (DataFrame) Returns a pandas DataFrame containing the ETF's portfolio composition. Columns include '계약수', '금액', '비중'. The index is the ticker symbol of the constituent stocks. ``` -------------------------------- ### Get ETF Price Change by Ticker Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Fetches the price change and related metrics for all ETFs within a specified date range. ```python df = get_etf_price_change_by_ticker("20210325", "20210402") print(df.head()) ``` -------------------------------- ### Get Daily Short Selling Value by Date Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves daily short selling trading value for a specific stock over a period. ```python from pykrx import stock # 공매도 거래대금 (일별) df_val = stock.get_shorting_value_by_date("20210104", "20210108", "005930") print(df_val) ``` -------------------------------- ### Get ETF Price Deviation Source: https://context7.com/sharebook-kr/pykrx/llms.txt Fetches the daily closing price, NAV, and price deviation for a specific ETF within a given date range. ```python from pykrx import stock # ARIRANG 200 괴리율 df_dev = stock.get_etf_price_deviation("20210104", "20210108", "152100") print(df_dev) ``` -------------------------------- ### Get ELW Ticker Name Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Fetches the name of an ELW using its ticker symbol and a specified date. The example iterates through a list of tickers to get their corresponding names. ```python tickers = stock.get_elw_ticker_list("20200306") for ticker in tickers: print(stock.get_elw_ticker_name(ticker)) ``` -------------------------------- ### Run Tests Source: https://github.com/sharebook-kr/pykrx/blob/master/CONTRIBUTING.md Commands to execute integration and live tests. Integration tests use VCR cassettes for replay, while live tests perform actual network calls. ```bash pytest -v # integration 테스트 실행 pytest tests/integration/ -v # 명시적으로 integration만 실행 pytest tests/live/ -v # live 테스트 (실제 네트워크 호출) ``` -------------------------------- ### 기본 Integration 테스트 실행 Source: https://github.com/sharebook-kr/pykrx/blob/master/tests/README.md PyKrx에서 기본적으로 제공되는 녹화된 Cassette을 사용하여 전체 또는 특정 Integration 테스트 파일을 실행하는 방법입니다. ```bash # 전체 Integration 테스트 실행 pytest tests/integration/ -v # 특정 테스트 파일 실행 pytest tests/integration/test_etf_api.py -v ``` -------------------------------- ### Get OTC Treasury Yields by Period and Bond Type Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves the yield trend for a specific type of treasury bond over a given date range. Requires start date, end date, and bond type. ```python from pykrx import bond # 국고채 2년 기간별 수익률 추이 df_period = bond.get_otc_treasury_yields("20220104", "20220204", "국고채2년") print(df_period.head(3)) ``` -------------------------------- ### 새 Cassette 녹화 및 최적화 절차 Source: https://github.com/sharebook-kr/pykrx/blob/master/tests/README.md 새로운 기능을 개발하거나 기존 Cassette을 갱신할 때 필요한 테스트 실행 및 용량 최적화 절차를 안내합니다. 최초 실행 시 녹화 후 스크립트를 통해 중복 응답을 공통 DB로 추출합니다. ```bash # 예: test_new_feature.py 실행 pytest tests/integration/test_new_feature.py ``` ```bash python tests/extract_common_cassettes.py ``` -------------------------------- ### Get List of KOSPI Index Tickers Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves a list of KOSPI index tickers. An optional date can be provided to get tickers existing on that specific date. ```python tickers = stock.get_index_ticker_list() print(tickers) ``` ```python tickers = stock.get_index_ticker_list("19800104") ``` -------------------------------- ### Get ETN Ticker Name Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the name of an ETN given its ticker symbol and a specific date. This function is used within a loop to get names for multiple tickers. ```python tickers = stock.get_etn_ticker_list("20141215") for ticker in tickers: print(stock.get_etn_ticker_name(ticker)) ``` -------------------------------- ### 투자자별 공매도 거래 현황 (거래량) 조회 Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md get_shorting_investor_volume_by_date 함수를 사용하여 코스피 또는 코스닥 시장의 특정 기간 동안 투자자별 공매도 거래량을 조회합니다. market 파라미터에 'KOSPI' 또는 'KOSDAQ'을 지정할 수 있습니다. ```python df = stock.get_shorting_investor_volume_by_date("20190401", "20190405", "KOSPI") print(df.head()) print(df) ``` ```python df = stock.get_shorting_investor_volume_by_date("20190401", "20190405", "KOSDAQ") print(df.head()) ``` -------------------------------- ### 투자자별 공매도 거래 현황 (거래대금) 조회 Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md get_shorting_investor_value_by_date 함수를 사용하여 코스피 또는 코스닥 시장의 특정 기간 동안 투자자별 공매도 거래대금을 조회합니다. market 파라미터에 'KOSPI' 또는 'KOSDAQ'을 지정할 수 있습니다. ```python df = stock.get_shorting_investor_value_by_date("20190401", "20190405", "KOSPI") print(df.head()) ``` ```python df = stock.get_shorting_investor_value_by_date("20190401", "20190405", "KOSDAQ") print(df.head()) ``` -------------------------------- ### Get ETF Trading Volume and Value Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves trading volume and value for ETFs within a specified date range. Use the ticker argument to get data for a specific ETF. ```python df = stock.get_etf_trading_volumne_and_value("20220415", "20220422") print(df.head()) ``` ```python df = get_etf_trading_volume_and_value("20220908", "20220916", "580011") print(df.head()) ``` -------------------------------- ### 종목별 공매도 잔고 현황 조회 Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md get_shorting_balance_by_date 메서드를 사용하여 특정 종목의 주어진 기간 동안의 공매도 잔고 정보를 조회합니다. 조회 속도는 조회 기간에 비례하여 증가할 수 있습니다. ```python df = stock.get_shorting_balance_by_date("20190401", "20190405", "005930") print(df.head()) ``` -------------------------------- ### Get ETF Portfolio Deposit File (PDF) Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves the composition of an ETF, including constituent tickers, quantities, values, and weights. Can fetch for a specific date. ```python from pykrx import stock # ARIRANG 200 PDF (구성종목 및 비중) df_pdf = stock.get_etf_portfolio_deposit_file("152100") print(df_pdf.head(3)) ``` ```python # 특정 일자 PDF df_pdf_date = stock.get_etf_portfolio_deposit_file("152100", "20210104") ``` -------------------------------- ### Get Index OHLCV Data Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the Open, High, Low, Close, and Volume data for a given index within a specified date range. The frequency parameter can be used to get daily ('d'), monthly ('m'), or yearly ('y') data. ```python df = stock.get_index_ohlcv("20190101", "20190228", "1028") print(df.head(2)) ``` ```python df = stock.get_index_ohlcv("20190101", "20190228", "1028", "m") print(df.head(2)) ``` -------------------------------- ### 일자별 공매도 거래 현황 조회 Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md get_shorting_volume_by_date 함수를 사용하여 특정 종목의 주어진 기간 동안의 공매도 거래 정보를 조회합니다. 조회된 데이터는 DataFrame 형태로 반환됩니다. ```python df = df = stock.get_shorting_volume_by_date("20210104", "20210108", "005930") print(df.head(3)) ``` -------------------------------- ### Get Index Components Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves the list of stocks that constitute a specific index. ```python from pykrx import stock components = stock.get_index_portfolio_deposit_file("1005") print(len(components), components[:3]) ``` -------------------------------- ### PyKrx 테스트 디렉터리 구조 Source: https://github.com/sharebook-kr/pykrx/blob/master/tests/README.md PyKrx 프로젝트의 테스트 관련 디렉터리 구조를 보여줍니다. 공통 Cassette과 개별 테스트 파일, 그리고 Cassette 최적화 스크립트의 위치를 확인할 수 있습니다. ```tree tests/ ├── cassettes/ │ ├── common/ │ │ ├── etx_ticker_init.yaml │ │ ├── stock_ticker_init.yaml │ │ └── ... │ ├── TestEtfPdf.test_with_business_day.yaml │ ├── TestShortBalanceByDate.test_with_default_param.yaml │ └── ... ├── integration/ │ ├── test_bond_api.py │ ├── test_etf_api.py │ ├── ... ├── extract_common_cassettes.py └── conftest.py ``` -------------------------------- ### Get OHLCV for All ETFs by Ticker Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the OHLCV data for all ETFs on a specific date. ```APIDOC ## get_etf_ohlcv_by_ticker ### Description Retrieves the OHLCV data for all ETFs on a specified date. If the date is a holiday, an empty DataFrame is returned. ### Method `stock.get_etf_ohlcv_by_ticker(date)` ### Parameters #### Path Parameters - **date** (str) - Required - The date in 'YYYYMMDD' format. ### Request Example ```python df = stock.get_etf_ohlcv_by_ticker("20210325") print(df.head()) ``` ### Response #### Success Response (DataFrame) Returns a pandas DataFrame containing the OHLCV data for all ETFs on the given date. Columns include 'NAV', '시가', '고가', '저가', '종가', '거래량', '거래대금', '기초지수'. The index is the ticker symbol. ``` -------------------------------- ### Get Top 50 Short Selling Balance Ratio Stocks for Kosdaq Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves the top 50 stocks by short selling balance ratio for the Kosdaq market on a specific date. ```python from pykrx import stock # 코스닥 공매도 잔고비중 TOP50 df_bal = stock.get_shorting_balance_top50("20210127", market="KOSDAQ") print(df_bal.head(3)) ``` -------------------------------- ### Get Index Ticker Names Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Iterates through index tickers and prints their corresponding names using `get_index_ticker_name`. ```python for ticker in stock.get_index_ticker_list(): print(ticker, stock.get_index_ticker_name(ticker)) ``` -------------------------------- ### Get Index Listing Date Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the listing date and base date information for a specified index. Accepts parameters like 'KRX', 'KOSPI', 'KOSDAQ', or theme names. ```python df = stock.get_index_listing_date("KOSPI") print(df.head()) ``` -------------------------------- ### Get Market Ticker Name Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Converts a given stock ticker symbol into its corresponding company name. ```APIDOC ## Get Market Ticker Name ### Description Converts a given stock ticker symbol into its corresponding company name. ### Method `stock.get_market_ticker_name(ticker)` ### Parameters #### Path Parameters - **ticker** (str) - Required - The stock ticker symbol. ### Request Example ```python for ticker in stock.get_market_ticker_list(): 종목 = stock.get_market_ticker_name(ticker) print(종목) ``` ### Response Example ```text SK하이닉스 .... ``` ``` -------------------------------- ### Import pykrx modules Source: https://context7.com/sharebook-kr/pykrx/llms.txt Import the necessary modules from the pykrx library for accessing stock and bond data. ```python from pykrx import stock from pykrx import bond ``` -------------------------------- ### Get ETF Ticker List Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves a list of ETF tickers, names, and ISINs for a specific date. ```python from pykrx import stock # ETF 티커 목록 etf_tickers = stock.get_etf_ticker_list("20210325") print(etf_tickers[:3]) ``` -------------------------------- ### Get Index Fundamental Data for a Specific Date Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves fundamental data for all indices on a particular date. ```python from pykrx import stock # 특정 일자 전 인덱스 펀더멘털 df_all = stock.get_index_fundamental("20210122") print(df_all.head(3)) ``` -------------------------------- ### Get Daily Market Trading Volume Including ETFs, ETNs, and ELWs Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves daily market trading volume, optionally including data for ETFs, ETNs, and ELWs by setting `etf=True`, `etn=True`, and `elw=True`. This option is only valid when querying KOSPI, KOSDAQ, or KONEX. If not specified, these are excluded. ```python df = stock.get_market_trading_volume_by_date("20210115", "20210122", "KOSPI", etf=True, etn=True, elw=True) print(df.head()) ``` -------------------------------- ### Get Market Price Change Source: https://context7.com/sharebook-kr/pykrx/llms.txt Fetches price change data for all stocks in a market over a specified period. ```APIDOC ## get_market_price_change ### Description Retrieves price change data (Open, Close, Change, Rate of Change, Volume, Transaction Amount) for all stocks in a market over a specified period. Delisted stocks are shown with a closing price of 0 and a -100% rate of change. ### Method `stock.get_market_price_change(from_date, to_date, market='ALL')` ### Parameters - **from_date** (str or datetime) - The start date of the period (format: YYYYMMDD). - **to_date** (str or datetime) - The end date of the period (format: YYYYMMDD). - **market** (str) - Optional. The market to query. Options: 'KOSPI', 'KOSDAQ', 'KONEX', 'ALL'. Defaults to 'ALL'. ### Example ```python from pykrx import stock # Price change for all KOSPI stocks between two dates df = stock.get_market_price_change("20210101", "20210108") print(df.head(3)) # 종목명 시가 종가 변동폭 등락률 거래량 거래대금 # 티커 # 095570 AJ네트웍스 4615 4540 -75 -1.63 3004291 14398725745 ``` ``` -------------------------------- ### get_shorting_balance Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves daily short selling balance, balance value, market capitalization, and ratio for a specific stock or all stocks. ```APIDOC ## get_shorting_balance ### Description Retrieves daily short selling balance, balance value, market capitalization, and ratio for a specific stock or all stocks. ### Method `get_shorting_balance(start_date, end_date, ticker)` or `get_shorting_balance(date)` ### Parameters #### Path Parameters - `start_date` (str) - Optional - The start date for the period (YYYYMMDD). - `end_date` (str) - Optional - The end date for the period (YYYYMMDD). - `ticker` (str) - Optional - The stock ticker symbol (e.g., "005930"). If omitted, data for all stocks is returned. - `date` (str) - Optional - The specific date for which to retrieve data (YYYYMMDD). Used when `ticker` is omitted. ### Request Example ```python from pykrx import stock # Daily short selling balance for a specific stock df = stock.get_shorting_balance("20200106", "20200110", "005930") # All stocks short selling balance for a specific date df_all = stock.get_shorting_balance("20210127") ``` ### Response #### Success Response (200) - `공매도잔고` (int) - Short selling balance. - `상장주식수` (int) - Number of listed shares. - `공매도금액` (int) - Short selling value. - `시가총액` (int) - Market capitalization. - `비중` (float) - Ratio of short selling balance to market capitalization. #### Response Example ```json { "example": " 공매도잔고 상장주식수 공매도금액 시가총액 비중\n날짜\n2020-01-06 5630893 5969782550 312514561500 3.313229e+14 0.090027" } ``` ``` -------------------------------- ### Get Market Cap Source: https://context7.com/sharebook-kr/pykrx/llms.txt Fetches market capitalization data for a specific stock or all stocks on a given date. ```APIDOC ## get_market_cap ### Description Retrieves market capitalization data. If two dates are provided, it fetches daily market cap for a specific stock. If one date is provided, it fetches market cap for all stocks on that date. Can also fetch monthly data using `freq='m'`. ### Method `stock.get_market_cap(from_date, to_date=None, ticker=None, freq='d')` ### Parameters - **from_date** (str or datetime) - The start date or the single date for fetching data (format: YYYYMMDD). - **to_date** (str or datetime) - Optional. The end date for fetching daily data. - **ticker** (str) - Optional. The stock ticker symbol. If omitted and `to_date` is provided, fetches data for all stocks. - **freq** (str) - Optional. Frequency of the data. 'd' for daily (default), 'm' for monthly. ### Example ```python from pykrx import stock # Daily market cap for Samsung Electronics (005930) df = stock.get_market_cap("20210104", "20210108", "005930") print(df) # 시가총액 거래량 거래대금 상장주식수 # 날짜 # 2021-01-04 495491951650000 38655276 3185356823460 5969782550 # 2021-01-05 474956843150000 35335669 2915618322800 5969782550 # Market cap for all stocks on a specific date df_all = stock.get_market_cap("20210104") print(df_all.head(3)) # 종가 시가총액 거래량 거래대금 상장주식수 # 티커 # 005930 83000 495491951650000 38655276 3185356823460 5969782550 # Monthly market cap for Samsung Electronics df_month = stock.get_market_cap("20200101", "20200430", "005930", freq="m") print(df_month) ``` ``` -------------------------------- ### Get Market OHLCV by Ticker Source: https://context7.com/sharebook-kr/pykrx/llms.txt Fetches OHLCV data for all stocks in a specific market on a given date. ```APIDOC ## get_market_ohlcv_by_ticker ### Description Retrieves OHLCV (Open, High, Low, Close, Volume) data for all stocks in a specified market on a given date. If the date is a holiday, it returns an empty DataFrame or data from the previous business day if `alternative=True`. ### Method `stock.get_market_ohlcv_by_ticker(date, market='ALL', alternative=False)` ### Parameters - **date** (str or datetime) - The date for which to retrieve the data (format: YYYYMMDD). - **market** (str) - Optional. The market to query. Options: 'KOSPI', 'KOSDAQ', 'KONEX', 'ALL'. Defaults to 'ALL'. - **alternative** (bool) - Optional. If True, returns data from the previous business day if the specified date is a holiday. Defaults to False. ### Example ```python from pykrx import stock # OHLCV for all KOSPI stocks on a specific date df = stock.get_market_ohlcv_by_ticker("20210122") print(df.head(3)) # 시가 고가 저가 종가 거래량 거래대금 등락률 # 티커 # 095570 4190 4245 4160 4210 216835 910274405 0.839844 # 006840 25750 29550 25600 29100 727088 20462325950 12.570312 # 027410 5020 5250 4955 5220 1547629 7990770515 4.191406 # OHLCV for KOSDAQ stocks, with alternative=True for holidays df_kosdaq = stock.get_market_ohlcv_by_ticker("20210122", market="KOSDAQ", alternative=True) print(df_kosdaq.head(3)) ``` ``` -------------------------------- ### Get Short Selling Balance by Date for a Stock Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves daily short selling balance, value, market cap, and ratio for a specific stock over a period. ```python from pykrx import stock # 삼성전자 기간별 공매도 잔고 df = stock.get_shorting_balance("20200106", "20200110", "005930") print(df) ``` -------------------------------- ### Get Price Change for All ETFs by Ticker Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the price change information for all ETFs within a specified period. ```APIDOC ## get_etf_price_change_by_ticker ### Description Retrieves the price change information (open, close, change amount, rate of change, volume, trading value) for all ETFs within a specified date range. ### Method `get_etf_price_change_by_ticker(start_date, end_date)` ### Parameters #### Path Parameters - **start_date** (str) - Required - The start date in 'YYYYMMDD' format. - **end_date** (str) - Required - The end date in 'YYYYMMDD' format. ### Request Example ```python df = get_etf_price_change_by_ticker("20210325", "20210402") print(df.head()) ``` ### Response #### Success Response (DataFrame) Returns a pandas DataFrame with price change details for all ETFs. Columns include '시가', '종가', '변동폭', '등락률', '거래량', '거래대금'. The index is the ticker symbol. ``` -------------------------------- ### Linting and Formatting with Ruff Source: https://github.com/sharebook-kr/pykrx/blob/master/CONTRIBUTING.md Commands to check for linting errors and apply code formatting using the ruff tool. The configuration is specified in pyproject.toml. ```bash ruff check --config pyproject.toml . ruff check --fix --config pyproject.toml . ruff format --config pyproject.toml . ``` -------------------------------- ### Get Top 50 Short Selling Volume Ratio Stocks Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves the top 50 stocks by short selling trading ratio for a specific date. ```python from pykrx import stock # 코스피 공매도 거래비중 TOP50 df = stock.get_shorting_volume_top50("20210127") print(df.head(3)) ``` -------------------------------- ### Get Future Ticker List Source: https://context7.com/sharebook-kr/pykrx/llms.txt Fetches a list of available future contract tickers. The output is a list of strings. ```python from pykrx.stock import get_future_ticker_list, get_future_ohlcv # 선물 티커 목록 tickers = get_future_ticker_list() print(tickers[:3]) ``` -------------------------------- ### Get OTC Treasury Yields (All Instruments) Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the over-the-counter (OTC) treasury yields for 11 types of bonds on a specific date. The output includes yield and change from the previous day. ```python df = bond.get_otc_treasury_yields("20190208") print(df) ``` -------------------------------- ### Get Daily Market Trading Value by Date Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves daily sorted trading volume (net purchase) for a specified period. Final trading details for the day are available after 6 PM. This function can also fetch trading value for specific markets (KOSPI, KOSDAQ, KONEX) or combined markets, with options to include or exclude ETFs, ETNs, and ELWs, and to get detailed breakdowns. ```APIDOC ## GET Daily Market Trading Value by Date ### Description Retrieves daily sorted trading volume (net purchase) for a specified period. Final trading details for the day are available after 6 PM. This function can also fetch trading value for specific markets (KOSPI, KOSDAQ, KONEX) or combined markets, with options to include or exclude ETFs, ETNs, and ELWs, and to get detailed breakdowns. ### Method `stock.get_market_trading_value_by_date` ### Parameters #### Path Parameters None #### Query Parameters - **start_date** (str) - Required - The start date for the data retrieval (YYYYMMDD format). - **end_date** (str) - Required - The end date for the data retrieval (YYYYMMDD format). - **ticker** (str) - Required - The stock ticker symbol or market identifier (e.g., "005930", "KOSPI", "ALL"). - **on** (str) - Optional - Specifies the type of transaction to retrieve ('매수' for purchase, '매도' for sale). Defaults to '순매수' (net purchase) if not provided. - **etf** (bool) - Optional - Include ETF trading data. Only valid when querying KOSPI, KOSDAQ, or KONEX. - **etn** (bool) - Optional - Include ETN trading data. Only valid when querying KOSPI, KOSDAQ, or KONEX. - **elw** (bool) - Optional - Include ELW trading data. Only valid when querying KOSPI, KOSDAQ, or KONEX. - **detail** (bool) - Optional - Include detailed trading information. Only valid when querying KOSPI, KOSDAQ, or KONEX. ### Request Example ```python df = stock.get_market_trading_value_by_date("20210115", "20210122", "005930") print(df.head()) ``` ### Response #### Success Response (200) Returns a pandas DataFrame containing the daily trading value data, with columns like '기관합계', '기타법인', '개인', '외국인합계', and '전체'. The index is the date. #### Response Example ```text 기관합계 기타법인 개인 외국인합계 전체 날짜 2021-01-15 -440769209300 25442287800 661609085600 -246282164100 0 2021-01-18 42323535000 22682344800 14829121700 -79835001500 0 2021-01-19 95523053500 -3250422500 -173484213300 81211582300 0 2021-01-20 -364476214000 22980632900 430115581000 -88619999900 0 2021-01-21 -60637506300 -27880854000 250285510000 -161767149700 0 ``` ### Additional Examples **Fetching '매도' (Sale) trading value:** ```python df = stock.get_market_trading_value_by_date("20210115", "20210122", "005930", on='매도') print(df.head()) ``` **Fetching KOSPI market trading value:** ```python df = stock.get_market_trading_value_by_date("20210115", "20210122", "KOSPI") print(df.head()) ``` **Fetching KOSPI market trading value including ETF, ETN, ELW:** ```python df = stock.get_market_trading_value_by_date("20210115", "20210122", "KOSPI", etf=True, etn=True, elw=True) print(df.head()) ``` **Fetching KOSPI market trading value with detailed breakdown:** ```python df = stock.get_market_trading_value_by_date("20210115", "20210122", "KOSPI", etf=True, etn=True, elw=True, detail=True) print(df.head()) ``` ``` -------------------------------- ### Get Foreign Investment Rates for a Specific Date and Market Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves foreign investment rates for a specific date, filtering by market (e.g., 'KOSPI', 'KOSDAQ', 'KONEX'). ```python df = stock.get_exhaustion_rates_of_foreign_investment('20200703', "KOSPI") print(df.head()) ``` -------------------------------- ### Get ELW Ticker List Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves a list of ELW tickers for a specified date. Ensure the date is in 'YYYYMMDD' format. ```python from pykrx import stock elw_tickers = stock.get_elw_ticker_list("20200306") print(elw_tickers) ``` -------------------------------- ### Get ETN Ticker List Source: https://context7.com/sharebook-kr/pykrx/llms.txt Retrieves a list of ETN tickers for a specified date. Ensure the date is in 'YYYYMMDD' format. ```python from pykrx import stock etn_tickers = stock.get_etn_ticker_list("20141215") print(etn_tickers) ``` -------------------------------- ### Get ETF Portfolio Deposit File Source: https://github.com/sharebook-kr/pykrx/blob/master/README.md Retrieves the constituent stocks and their weights for a given ETF. An optional date parameter can be provided to check the portfolio composition on a specific day. ```python df = stock.get_etf_portfolio_deposit_file("152100") print(df.head()) ``` ```python df = stock.get_etf_portfolio_deposit_file("152100", "20161206") print(df.head()) ```