136 lines
6.3 KiB
Python
136 lines
6.3 KiB
Python
# DOMSTK_RANK - 거래량순위
|
|
# Generated by KIS API Generator (Single API Mode)
|
|
import sys
|
|
import time
|
|
from typing import Optional
|
|
import logging
|
|
|
|
import pandas as pd
|
|
|
|
sys.path.extend(['../..', '.'])
|
|
import kis_auth as ka
|
|
|
|
# 로깅 설정
|
|
|
|
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
|
|
logger = logging.getLogger(__name__)
|
|
|
|
##############################################################################################
|
|
# [국내주식] 순위분석 > 거래량순위[v1_국내주식-047]
|
|
##############################################################################################
|
|
|
|
# 상수 정의
|
|
API_URL = "/uapi/domestic-stock/v1/quotations/volume-rank"
|
|
|
|
def volume_rank(
|
|
fid_cond_mrkt_div_code: str, # 필수, 조건 시장 분류 코드
|
|
fid_cond_scr_div_code: str, # 필수, 조건 화면 분류 코드
|
|
fid_input_iscd: str, # 필수, 입력 종목코드
|
|
fid_div_cls_code: str, # 필수, 분류 구분 코드
|
|
fid_blng_cls_code: str, # 필수, 소속 구분 코드
|
|
fid_trgt_cls_code: str, # 필수, 대상 구분 코드
|
|
fid_trgt_exls_cls_code: str, # 필수, 대상 제외 구분 코드
|
|
fid_input_price_1: str, # 필수, 입력 가격1
|
|
fid_input_price_2: str, # 필수, 입력 가격2
|
|
fid_vol_cnt: str, # 필수, 거래량 수
|
|
fid_input_date_1: str, # 필수, 입력 날짜1
|
|
tr_cont: str = "", # 선택, 연속 거래 여부
|
|
dataframe: Optional[pd.DataFrame] = None # 선택, 누적 데이터프레임
|
|
) -> Optional[pd.DataFrame]:
|
|
"""
|
|
[국내주식] 순위분석
|
|
순위분석[v1_국내주식-047]
|
|
순위분석 API를 호출하여 DataFrame으로 반환합니다.
|
|
|
|
Args:
|
|
fid_cond_mrkt_div_code (str): 조건 시장 분류 코드 ("J": KRX, "NX": NXT, "UN": 통합, "W": ELW)
|
|
fid_cond_scr_div_code (str): 조건 화면 분류 코드 ("20171")
|
|
fid_input_iscd (str): 입력 종목코드 ("0000": 전체, 기타: 업종코드)
|
|
fid_div_cls_code (str): 분류 구분 코드 ("0": 전체, "1": 보통주, "2": 우선주)
|
|
fid_blng_cls_code (str): 소속 구분 코드 ("0": 평균거래량, "1": 거래증가율, "2": 평균거래회전율, "3": 거래금액순, "4": 평균거래금액회전율)
|
|
fid_trgt_cls_code (str): 대상 구분 코드 (9자리, "1" or "0", 차례대로 증거금 30% 40% 50% 60% 100% 신용보증금 30% 40% 50% 60%)
|
|
fid_trgt_exls_cls_code (str): 대상 제외 구분 코드 (10자리, "1" or "0", 차례대로 투자위험/경고/주의 관리종목 정리매매 불성실공시 우선주 거래정지 ETF ETN 신용주문불가 SPAC)
|
|
fid_input_price_1 (str): 입력 가격1 (가격 ~, 전체 가격 대상 조회 시 공란)
|
|
fid_input_price_2 (str): 입력 가격2 (~ 가격, 전체 가격 대상 조회 시 공란)
|
|
fid_vol_cnt (str): 거래량 수 (거래량 ~, 전체 거래량 대상 조회 시 공란)
|
|
fid_input_date_1 (str): 입력 날짜1 (공란)
|
|
tr_cont (str): 연속 거래 여부
|
|
dataframe (Optional[pd.DataFrame]): 누적 데이터프레임
|
|
|
|
Returns:
|
|
pd.DataFrame: 순위분석 데이터
|
|
|
|
Example:
|
|
>>> df = volume_rank(fid_cond_mrkt_div_code="J", fid_cond_scr_div_code="20171", fid_input_iscd="0000", fid_div_cls_code="0", fid_blng_cls_code="0", fid_trgt_cls_code="111111111", fid_trgt_exls_cls_code="0000000000", fid_input_price_1="0", fid_input_price_2="1000000", fid_vol_cnt="100000", fid_input_date_1="")
|
|
>>> print(df)
|
|
"""
|
|
if fid_cond_mrkt_div_code not in ["J", "NX", "UN", "W"]:
|
|
raise ValueError("조건 시장 분류 코드 확인요망!!!")
|
|
|
|
if fid_cond_scr_div_code != "20171":
|
|
raise ValueError("조건 화면 분류 코드 확인요망!!!")
|
|
|
|
if fid_input_iscd == "": # "0000"은 전체를 의미하므로 유효한 값
|
|
raise ValueError("입력 종목코드 확인요망!!!")
|
|
|
|
if fid_div_cls_code not in ["0", "1", "2"]:
|
|
raise ValueError("분류 구분 코드 확인요망!!!")
|
|
|
|
if fid_blng_cls_code not in ["0", "1", "2", "3", "4"]:
|
|
raise ValueError("소속 구분 코드 확인요망!!!")
|
|
|
|
# To fix: description에 나와있는 자릿수와 다름(0 6개 입력해야 나옴)
|
|
# if len(fid_trgt_cls_code) != 9 or not (all(c == '0' for c in fid_trgt_cls_code) or all(c == '1' for c in fid_trgt_cls_code)):
|
|
# raise ValueError("대상 구분 코드 확인요망!!!")
|
|
|
|
# if len(fid_trgt_exls_cls_code) != 10 or not (all(c == '0' for c in fid_trgt_exls_cls_code) or all(c == '1' for c in fid_trgt_exls_cls_code)):
|
|
# raise ValueError("대상 제외 구분 코드 확인요망!!!")
|
|
|
|
|
|
tr_id = "FHPST01710000" # 거래량순위
|
|
|
|
params = {
|
|
"FID_COND_MRKT_DIV_CODE": fid_cond_mrkt_div_code,
|
|
"FID_COND_SCR_DIV_CODE": fid_cond_scr_div_code,
|
|
"FID_INPUT_ISCD": fid_input_iscd,
|
|
"FID_DIV_CLS_CODE": fid_div_cls_code,
|
|
"FID_BLNG_CLS_CODE": fid_blng_cls_code,
|
|
"FID_TRGT_CLS_CODE": fid_trgt_cls_code,
|
|
"FID_TRGT_EXLS_CLS_CODE": fid_trgt_exls_cls_code,
|
|
"FID_INPUT_PRICE_1": fid_input_price_1,
|
|
"FID_INPUT_PRICE_2": fid_input_price_2,
|
|
"FID_VOL_CNT": fid_vol_cnt,
|
|
"FID_INPUT_DATE_1": fid_input_date_1
|
|
}
|
|
|
|
res = ka._url_fetch(API_URL, tr_id, tr_cont, params)
|
|
|
|
if res.isOK():
|
|
if hasattr(res.getBody(), 'output'):
|
|
current_data = pd.DataFrame(res.getBody().output)
|
|
else:
|
|
current_data = pd.DataFrame()
|
|
|
|
if dataframe is not None:
|
|
dataframe = pd.concat([dataframe, current_data], ignore_index=True)
|
|
else:
|
|
dataframe = current_data
|
|
|
|
tr_cont = res.getHeader().tr_cont
|
|
|
|
if tr_cont == "M": # 다음 페이지 존재
|
|
print("Call Next")
|
|
ka.smart_sleep() # 시스템 안정적 운영을 위한 지연
|
|
return volume_rank(
|
|
fid_cond_mrkt_div_code, fid_cond_scr_div_code, fid_input_iscd,
|
|
fid_div_cls_code, fid_blng_cls_code, fid_trgt_cls_code,
|
|
fid_trgt_exls_cls_code, fid_input_price_1, fid_input_price_2,
|
|
fid_vol_cnt, fid_input_date_1, "N", dataframe
|
|
)
|
|
else:
|
|
print("The End")
|
|
return dataframe
|
|
else:
|
|
res.printError(API_URL)
|
|
return pd.DataFrame()
|