initial commit

This commit is contained in:
2026-01-31 22:34:57 +09:00
commit f1301de543
875 changed files with 196598 additions and 0 deletions

View File

@@ -0,0 +1,105 @@
# -*- 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_pub_offer import ksdinfo_pub_offer
# 로깅 설정
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
##############################################################################################
# [국내주식] 종목정보 > 예탁원정보(공모주청약일정)[국내주식-151]
##############################################################################################
# 통합 컬럼 매핑
COLUMN_MAPPING = {
'record_date': '기준일',
'sht_cd': '종목코드',
'fix_subscr_pri': '공모가',
'face_value': '액면가',
'subscr_dt': '청약기간',
'pay_dt': '납입일',
'refund_dt': '환불일',
'list_dt': '상장/등록일',
'lead_mgr': '주간사',
'pub_bf_cap': '공모전자본금',
'pub_af_cap': '공모후자본금',
'assign_stk_qty': '당사배정물량'
}
NUMERIC_COLUMNS = []
def main():
"""
[국내주식] 종목정보
예탁원정보(공모주청약일정)[국내주식-151]
예탁원정보(공모주청약일정) 테스트 함수
Parameters:
- sht_cd (str): 종목코드 (공백: 전체, 특정종목 조회시 : 종목코드)
- cts (str): CTS (공백)
- f_dt (str): 조회일자From (일자 ~)
- t_dt (str): 조회일자To (~ 일자)
Returns:
- DataFrame: 예탁원정보(공모주청약일정) 결과
Example:
>>> df = ksdinfo_pub_offer(sht_cd="", cts="", f_dt="20250101", t_dt="20250131")
"""
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_pub_offer(
sht_cd="", # 종목코드
cts="", # CTS
f_dt="20250101", # 조회일자From
t_dt="20250131", # 조회일자To
)
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()

View File

@@ -0,0 +1,121 @@
# [국내주식] 종목정보 - 예탁원정보(공모주청약일정)
# Generated by KIS API Generator (Single API Mode)
# -*- coding: utf-8 -*-
"""
Created on 2025-06-17
"""
import logging
import time
from typing import Optional, Tuple
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__)
##############################################################################################
# [국내주식] 종목정보 > 예탁원정보(공모주청약일정)[국내주식-151]
##############################################################################################
# 상수 정의
API_URL = "/uapi/domestic-stock/v1/ksdinfo/pub-offer"
def ksdinfo_pub_offer(
sht_cd: str, # 종목코드
cts: str, # CTS
f_dt: str, # 조회일자From
t_dt: str, # 조회일자To
tr_cont: str = "", # 연속 거래 여부
dataframe: Optional[pd.DataFrame] = None, # 누적 데이터프레임
depth: int = 0, # 현재 재귀 깊이
max_depth: int = 10 # 최대 재귀 깊이
) -> Optional[pd.DataFrame]:
"""
[국내주식] 종목정보
예탁원정보(공모주청약일정)[국내주식-151]
예탁원정보(공모주청약일정) API를 호출하여 DataFrame으로 반환합니다.
Args:
sht_cd (str): 공백: 전체, 특정종목 조회시 : 종목코드
cts (str): 공백
f_dt (str): 일자 ~
t_dt (str): ~ 일자
tr_cont (str): 연속 거래 여부
dataframe (Optional[pd.DataFrame]): 누적 데이터프레임
depth (int): 현재 재귀 깊이
max_depth (int): 최대 재귀 깊이 (기본값: 10)
Returns:
Optional[pd.DataFrame]: 예탁원정보(공모주청약일정) 데이터
Example:
>>> df = ksdinfo_pub_offer("000000", "", "20230101", "20231231")
>>> print(df)
"""
# 필수 파라미터 검증
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 = "HHKDB669108C0"
params = {
"SHT_CD": sht_cd,
"CTS": cts,
"F_DT": f_dt,
"T_DT": t_dt,
}
# 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_pub_offer(
sht_cd,
cts,
f_dt,
t_dt,
"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()