initial commit
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on 2025-06-17
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
|
||||
import pandas as pd
|
||||
|
||||
sys.path.extend(['../..', '.']) # kis_auth 파일 경로 추가
|
||||
import kis_auth as ka
|
||||
|
||||
from ksdinfo_cap_dcrs import ksdinfo_cap_dcrs
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
##############################################################################################
|
||||
# [국내주식] 종목정보 > 예탁원정보(자본감소일정) [국내주식-149]
|
||||
##############################################################################################
|
||||
|
||||
COLUMN_MAPPING = {
|
||||
'record_date': '기준일',
|
||||
'sht_cd': '종목코드',
|
||||
'stk_kind': '주식종류',
|
||||
'reduce_cap_type': '감자구분',
|
||||
'reduce_cap_rate': '감자배정율',
|
||||
'comp_way': '계산방법',
|
||||
'td_stop_dt': '매매거래정지기간',
|
||||
'list_dt': '상장/등록일'
|
||||
}
|
||||
|
||||
NUMERIC_COLUMNS = []
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
[국내주식] 종목정보
|
||||
예탁원정보(자본감소일정)[국내주식-149]
|
||||
|
||||
예탁원정보(자본감소일정) 테스트 함수
|
||||
|
||||
Parameters:
|
||||
- cts (str): CTS (공백)
|
||||
- f_dt (str): 조회일자From (일자 ~)
|
||||
- t_dt (str): 조회일자To (~ 일자)
|
||||
- sht_cd (str): 종목코드 (공백: 전체, 특정종목 조회시 : 종목코드)
|
||||
Returns:
|
||||
- DataFrame: 예탁원정보(자본감소일정) 결과
|
||||
|
||||
Example:
|
||||
>>> df = ksdinfo_cap_dcrs(cts="", f_dt="20250101", t_dt="20250131", sht_cd="")
|
||||
"""
|
||||
try:
|
||||
# pandas 출력 옵션 설정
|
||||
pd.set_option('display.max_columns', None) # 모든 컬럼 표시
|
||||
pd.set_option('display.width', None) # 출력 너비 제한 해제
|
||||
pd.set_option('display.max_rows', None) # 모든 행 표시
|
||||
|
||||
# 토큰 발급
|
||||
logger.info("토큰 발급 중...")
|
||||
ka.auth()
|
||||
logger.info("토큰 발급 완료")
|
||||
|
||||
# API 호출
|
||||
result = ksdinfo_cap_dcrs(
|
||||
cts="", # CTS
|
||||
f_dt="20250101", # 조회일자From
|
||||
t_dt="20250131", # 조회일자To
|
||||
sht_cd="", # 종목코드
|
||||
)
|
||||
|
||||
if result is None or result.empty:
|
||||
logger.warning("조회된 데이터가 없습니다.")
|
||||
return
|
||||
|
||||
# 컬럼명 출력
|
||||
logger.info("사용 가능한 컬럼 목록:")
|
||||
logger.info(result.columns.tolist())
|
||||
|
||||
# 한글 컬럼명으로 변환
|
||||
result = result.rename(columns=COLUMN_MAPPING)
|
||||
|
||||
for col in NUMERIC_COLUMNS:
|
||||
if col in result.columns:
|
||||
result[col] = pd.to_numeric(result[col], errors='coerce').round(2)
|
||||
|
||||
# 결과 출력
|
||||
logger.info("=== 예탁원정보(자본감소일정) 결과 ===")
|
||||
logger.info("조회된 데이터 건수: %d", len(result))
|
||||
print(result)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("에러 발생: %s", str(e))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
Created on 2025-06-17
|
||||
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
import sys
|
||||
|
||||
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__)
|
||||
|
||||
##############################################################################################
|
||||
# [국내주식] 종목정보 > 예탁원정보(자본감소일정) [국내주식-149]
|
||||
##############################################################################################
|
||||
|
||||
# 상수 정의
|
||||
API_URL = "/uapi/domestic-stock/v1/ksdinfo/cap-dcrs"
|
||||
|
||||
def ksdinfo_cap_dcrs(
|
||||
cts: str, # CTS
|
||||
f_dt: str, # 조회일자From
|
||||
t_dt: str, # 조회일자To
|
||||
sht_cd: str, # 종목코드
|
||||
tr_cont: str = "",
|
||||
dataframe: Optional[pd.DataFrame] = None,
|
||||
depth: int = 0,
|
||||
max_depth: int = 10
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
[국내주식] 종목정보
|
||||
예탁원정보(자본감소일정)[국내주식-149]
|
||||
예탁원정보(자본감소일정) API를 호출하여 DataFrame으로 반환합니다.
|
||||
|
||||
Args:
|
||||
cts (str): 공백
|
||||
f_dt (str): 일자 ~
|
||||
t_dt (str): ~ 일자
|
||||
sht_cd (str): 공백: 전체, 특정종목 조회시 : 종목코드
|
||||
tr_cont (str): 연속 거래 여부
|
||||
dataframe (Optional[pd.DataFrame]): 누적 데이터프레임
|
||||
depth (int): 현재 재귀 깊이
|
||||
max_depth (int): 최대 재귀 깊이 (기본값: 10)
|
||||
|
||||
Returns:
|
||||
Optional[pd.DataFrame]: 예탁원정보(자본감소일정) 데이터
|
||||
|
||||
Example:
|
||||
>>> df = ksdinfo_cap_dcrs(" ", "20230101", "20231231", "005930")
|
||||
>>> print(df)
|
||||
"""
|
||||
# 로깅 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 필수 파라미터 검증
|
||||
if not f_dt:
|
||||
logger.error("f_dt is required. (e.g. '20230101')")
|
||||
raise ValueError("f_dt is required. (e.g. '20230101')")
|
||||
|
||||
if not t_dt:
|
||||
logger.error("t_dt is required. (e.g. '20231231')")
|
||||
raise ValueError("t_dt is required. (e.g. '20231231')")
|
||||
|
||||
# 최대 재귀 깊이 체크
|
||||
if depth >= max_depth:
|
||||
logger.warning("Maximum recursion depth (%d) reached. Stopping further requests.", max_depth)
|
||||
return dataframe if dataframe is not None else pd.DataFrame()
|
||||
|
||||
tr_id = "HHKDB669106C0"
|
||||
|
||||
params = {
|
||||
"CTS": cts,
|
||||
"F_DT": f_dt,
|
||||
"T_DT": t_dt,
|
||||
"SHT_CD": sht_cd,
|
||||
}
|
||||
|
||||
# API 호출
|
||||
res = ka._url_fetch(API_URL, tr_id, tr_cont, params)
|
||||
|
||||
if res.isOK():
|
||||
if hasattr(res.getBody(), 'output1'):
|
||||
output_data = res.getBody().output1
|
||||
if not isinstance(output_data, list):
|
||||
output_data = [output_data]
|
||||
current_data = pd.DataFrame(output_data)
|
||||
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":
|
||||
logger.info("Calling next page...")
|
||||
ka.smart_sleep()
|
||||
return ksdinfo_cap_dcrs(
|
||||
cts,
|
||||
f_dt,
|
||||
t_dt,
|
||||
sht_cd,
|
||||
"N", dataframe, depth + 1, max_depth
|
||||
)
|
||||
else:
|
||||
logger.info("Data fetch complete.")
|
||||
return dataframe
|
||||
else:
|
||||
logger.error("API call failed: %s - %s", res.getErrorCode(), res.getErrorMessage())
|
||||
res.printError(API_URL)
|
||||
return pd.DataFrame()
|
||||
Reference in New Issue
Block a user