initial commit
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on 2025-06-20
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
|
||||
import pandas as pd
|
||||
|
||||
sys.path.extend(['../..', '.']) # kis_auth 파일 경로 추가
|
||||
import kis_auth as ka
|
||||
from inquire_daily_ccld import inquire_daily_ccld
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
##############################################################################################
|
||||
# [장내채권] 주문/계좌 > 장내채권 일별체결조회 [국내주식-127]
|
||||
##############################################################################################
|
||||
|
||||
# 통합 컬럼 매핑 (모든 output에서 공통 사용)
|
||||
COLUMN_MAPPING = {
|
||||
'tot_ord_qty': '총주문수량',
|
||||
'tot_ccld_qty_smtl': '총체결수량합계',
|
||||
'tot_bond_ccld_avg_unpr': '총채권체결평균단가',
|
||||
'tot_ccld_amt_smtl': '총체결금액합계',
|
||||
'ord_dt': '주문일자',
|
||||
'odno': '주문번호',
|
||||
'orgn_odno': '원주문번호',
|
||||
'ord_dvsn_name': '주문구분명',
|
||||
'sll_buy_dvsn_cd_name': '매도매수구분코드명',
|
||||
'shtn_pdno': '단축상품번호',
|
||||
'prdt_abrv_name': '상품약어명',
|
||||
'ord_qty': '주문수량',
|
||||
'bond_ord_unpr': '채권주문단가',
|
||||
'ord_tmd': '주문시각',
|
||||
'tot_ccld_qty': '총체결수량',
|
||||
'bond_avg_unpr': '채권평균단가',
|
||||
'tot_ccld_amt': '총체결금액',
|
||||
'loan_dt': '대출일자',
|
||||
'buy_dt': '매수일자',
|
||||
'samt_mket_ptci_yn_name': '소액시장참여여부명',
|
||||
'sprx_psbl_yn_ifom': '분리과세가능여부알림',
|
||||
'ord_mdia_dvsn_name': '주문매체구분묭',
|
||||
'sll_buy_dvsn_cd': '매도매수구분코드',
|
||||
'nccs_qty': '미체결수량',
|
||||
'ord_gno_brno': '주문채번지점번호'
|
||||
}
|
||||
|
||||
NUMERIC_COLUMNS = []
|
||||
|
||||
def main():
|
||||
"""
|
||||
[장내채권] 주문/계좌
|
||||
장내채권 주문체결내역[국내주식-127]
|
||||
|
||||
장내채권 주문체결내역 테스트 함수
|
||||
|
||||
Parameters:
|
||||
- cano (str): 종합계좌번호 (종합계좌번호)
|
||||
- acnt_prdt_cd (str): 계좌상품코드 (계좌상품코드)
|
||||
- inqr_strt_dt (str): 조회시작일자 (일자 ~ (1주일 이내))
|
||||
- inqr_end_dt (str): 조회종료일자 (~ 일자 (조회 당일))
|
||||
- sll_buy_dvsn_cd (str): 매도매수구분코드 (%(전체), 01(매도), 02(매수))
|
||||
- sort_sqn_dvsn (str): 정렬순서구분 (01(주문순서), 02(주문역순))
|
||||
- pdno (str): 상품번호 ()
|
||||
- nccs_yn (str): 미체결여부 (N(전체), C(체결), Y(미체결))
|
||||
|
||||
Returns:
|
||||
- Tuple[DataFrame, ...]: 장내채권 주문체결내역 결과
|
||||
|
||||
Example:
|
||||
>>> df1, df2 = inquire_daily_ccld(cano=trenv.my_acct, acnt_prdt_cd=trenv.my_prod, inqr_strt_dt="20250601", inqr_end_dt="20250630", sll_buy_dvsn_cd="%", sort_sqn_dvsn="01", pdno="", nccs_yn="N", ctx_area_nk200="", ctx_area_fk200="")
|
||||
"""
|
||||
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("토큰 발급 완료")
|
||||
|
||||
# kis_auth 모듈에서 계좌 정보 가져오기
|
||||
trenv = ka.getTREnv()
|
||||
|
||||
# API 호출
|
||||
logger.info("API 호출 시작: 장내채권 주문체결내역")
|
||||
result1, result2 = inquire_daily_ccld(
|
||||
cano=trenv.my_acct, # 종합계좌번호
|
||||
acnt_prdt_cd=trenv.my_prod, # 계좌상품코드
|
||||
inqr_strt_dt="20250601", # 조회시작일자
|
||||
inqr_end_dt="20250630", # 조회종료일자
|
||||
sll_buy_dvsn_cd="%", # 매도매수구분코드
|
||||
sort_sqn_dvsn="01", # 정렬순서구분
|
||||
pdno="", # 상품번호
|
||||
nccs_yn="N", # 미체결여부
|
||||
ctx_area_nk200="", # 연속조회키200
|
||||
ctx_area_fk200="", # 연속조회검색조건200
|
||||
)
|
||||
|
||||
# 결과 확인
|
||||
results = [result1, result2]
|
||||
if all(result is None or result.empty for result in results):
|
||||
logger.warning("조회된 데이터가 없습니다.")
|
||||
return
|
||||
|
||||
# output1 결과 처리
|
||||
logger.info("=== output1 조회 ===")
|
||||
if not result1.empty:
|
||||
logger.info("사용 가능한 컬럼: %s", result1.columns.tolist())
|
||||
|
||||
# 통합 컬럼명 한글 변환 (필요한 컬럼만 자동 매핑됨)
|
||||
result1 = result1.rename(columns=COLUMN_MAPPING)
|
||||
|
||||
# 숫자형 컬럼 변환s
|
||||
for col in NUMERIC_COLUMNS:
|
||||
if col in result1.columns:
|
||||
result1[col] = pd.to_numeric(result1[col], errors='coerce')
|
||||
|
||||
logger.info("output1 결과:")
|
||||
print(result1)
|
||||
else:
|
||||
logger.info("output1 데이터가 없습니다.")
|
||||
|
||||
# output2 결과 처리
|
||||
logger.info("=== output2 조회 ===")
|
||||
if not result2.empty:
|
||||
logger.info("사용 가능한 컬럼: %s", result2.columns.tolist())
|
||||
|
||||
# 통합 컬럼명 한글 변환 (필요한 컬럼만 자동 매핑됨)
|
||||
result2 = result2.rename(columns=COLUMN_MAPPING)
|
||||
|
||||
# 숫자형 컬럼 변환s
|
||||
for col in NUMERIC_COLUMNS:
|
||||
if col in result2.columns:
|
||||
result2[col] = pd.to_numeric(result2[col], errors='coerce')
|
||||
|
||||
logger.info("output2 결과:")
|
||||
print(result2)
|
||||
else:
|
||||
logger.info("output2 데이터가 없습니다.")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error("에러 발생: %s", str(e))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,202 @@
|
||||
# [장내채권] 주문/계좌 - 장내채권 주문체결내역
|
||||
# Generated by KIS API Generator (Single API Mode)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on 2025-06-20
|
||||
|
||||
"""
|
||||
|
||||
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__)
|
||||
|
||||
##############################################################################################
|
||||
# [장내채권] 주문/계좌 > 장내채권 일별체결조회 [국내주식-127]
|
||||
##############################################################################################
|
||||
|
||||
# 상수 정의
|
||||
API_URL = "/uapi/domestic-bond/v1/trading/inquire-daily-ccld"
|
||||
|
||||
def inquire_daily_ccld(
|
||||
cano: str, # 종합계좌번호
|
||||
acnt_prdt_cd: str, # 계좌상품코드
|
||||
inqr_strt_dt: str, # 조회시작일자
|
||||
inqr_end_dt: str, # 조회종료일자
|
||||
sll_buy_dvsn_cd: str, # 매도매수구분코드
|
||||
sort_sqn_dvsn: str, # 정렬순서구분
|
||||
pdno: str, # 상품번호
|
||||
nccs_yn: str, # 미체결여부
|
||||
ctx_area_nk200: str, # 연속조회키200
|
||||
ctx_area_fk200: str, # 연속조회검색조건200
|
||||
dataframe1: Optional[pd.DataFrame] = None, # 누적 데이터프레임 (output1)
|
||||
dataframe2: Optional[pd.DataFrame] = None, # 누적 데이터프레임 (output2)
|
||||
tr_cont: str = "",
|
||||
depth: int = 0,
|
||||
max_depth: int = 10
|
||||
) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""
|
||||
[장내채권] 주문/계좌
|
||||
장내채권 주문체결내역[국내주식-127]
|
||||
장내채권 주문체결내역 API를 호출하여 DataFrame으로 반환합니다.
|
||||
|
||||
Args:
|
||||
cano (str): 종합계좌번호
|
||||
acnt_prdt_cd (str): 계좌상품코드
|
||||
inqr_strt_dt (str): 조회시작일자 (1주일 이내)
|
||||
inqr_end_dt (str): 조회종료일자 (조회 당일)
|
||||
sll_buy_dvsn_cd (str): 매도매수구분코드 (%(전체), 01(매도), 02(매수))
|
||||
sort_sqn_dvsn (str): 정렬순서구분 (01(주문순서), 02(주문역순))
|
||||
pdno (str): 상품번호
|
||||
nccs_yn (str): 미체결여부 (N(전체), C(체결), Y(미체결))
|
||||
ctx_area_nk200 (str): 연속조회키200
|
||||
ctx_area_fk200 (str): 연속조회검색조건200
|
||||
dataframe1 (Optional[pd.DataFrame]): 누적 데이터프레임 (output1)
|
||||
dataframe2 (Optional[pd.DataFrame]): 누적 데이터프레임 (output2)
|
||||
tr_cont (str): 연속 거래 여부
|
||||
depth (int): 현재 재귀 깊이
|
||||
max_depth (int): 최대 재귀 깊이 (기본값: 10)
|
||||
|
||||
Returns:
|
||||
Tuple[pd.DataFrame, pd.DataFrame]: 장내채권 주문체결내역 데이터
|
||||
|
||||
Example:
|
||||
>>> df1, df2 = inquire_daily_ccld(
|
||||
... cano=trenv.my_acct,
|
||||
... acnt_prdt_cd=trenv.my_prod,
|
||||
... inqr_strt_dt='20230101',
|
||||
... inqr_end_dt='20230107',
|
||||
... sll_buy_dvsn_cd='01',
|
||||
... sort_sqn_dvsn='01',
|
||||
... pdno='000000000001',
|
||||
... nccs_yn='N',
|
||||
... ctx_area_nk200='',
|
||||
... ctx_area_fk200=''
|
||||
... )
|
||||
>>> print(df1)
|
||||
>>> print(df2)
|
||||
"""
|
||||
# 필수 파라미터 검증
|
||||
if not cano:
|
||||
logger.error("cano is required. (e.g. '12345678')")
|
||||
raise ValueError("cano is required. (e.g. '12345678')")
|
||||
if not acnt_prdt_cd:
|
||||
logger.error("acnt_prdt_cd is required. (e.g. '01')")
|
||||
raise ValueError("acnt_prdt_cd is required. (e.g. '01')")
|
||||
if not inqr_strt_dt:
|
||||
logger.error("inqr_strt_dt is required. (e.g. '20230101')")
|
||||
raise ValueError("inqr_strt_dt is required. (e.g. '20230101')")
|
||||
if not inqr_end_dt:
|
||||
logger.error("inqr_end_dt is required. (e.g. '20230107')")
|
||||
raise ValueError("inqr_end_dt is required. (e.g. '20230107')")
|
||||
if not sll_buy_dvsn_cd in ["%", "01", "02"]:
|
||||
logger.error("sll_buy_dvsn_cd is required. (e.g. '01')")
|
||||
raise ValueError("sll_buy_dvsn_cd is required. (e.g. '01')")
|
||||
if not sort_sqn_dvsn in ["01", "02"]:
|
||||
logger.error("sort_sqn_dvsn is required. (e.g. '01')")
|
||||
raise ValueError("sort_sqn_dvsn is required. (e.g. '01')")
|
||||
if not nccs_yn in ["N", "C", "Y"]:
|
||||
logger.error("nccs_yn is required. (e.g. 'N')")
|
||||
raise ValueError("nccs_yn is required. (e.g. 'N')")
|
||||
|
||||
# 최대 재귀 깊이 체크
|
||||
if depth >= max_depth:
|
||||
logger.warning("Maximum recursion depth (%d) reached. Stopping further requests.", max_depth)
|
||||
return dataframe1 if dataframe1 is not None else pd.DataFrame(), dataframe2 if dataframe2 is not None else pd.DataFrame()
|
||||
|
||||
tr_id = "CTSC8013R"
|
||||
|
||||
params = {
|
||||
"CANO": cano,
|
||||
"ACNT_PRDT_CD": acnt_prdt_cd,
|
||||
"INQR_STRT_DT": inqr_strt_dt,
|
||||
"INQR_END_DT": inqr_end_dt,
|
||||
"SLL_BUY_DVSN_CD": sll_buy_dvsn_cd,
|
||||
"SORT_SQN_DVSN": sort_sqn_dvsn,
|
||||
"PDNO": pdno,
|
||||
"NCCS_YN": nccs_yn,
|
||||
"CTX_AREA_NK200": ctx_area_nk200,
|
||||
"CTX_AREA_FK200": ctx_area_fk200,
|
||||
}
|
||||
|
||||
res = ka._url_fetch(API_URL, tr_id, tr_cont, params)
|
||||
|
||||
if res.isOK():
|
||||
# output1 처리
|
||||
if hasattr(res.getBody(), 'output1'):
|
||||
output_data = res.getBody().output1
|
||||
if output_data:
|
||||
# output1은 단일 객체, output2는 배열일 수 있음
|
||||
if isinstance(output_data, list):
|
||||
current_data1 = pd.DataFrame(output_data)
|
||||
else:
|
||||
# 단일 객체인 경우 리스트로 감싸서 DataFrame 생성
|
||||
current_data1 = pd.DataFrame([output_data])
|
||||
|
||||
if dataframe1 is not None:
|
||||
dataframe1 = pd.concat([dataframe1, current_data1], ignore_index=True)
|
||||
else:
|
||||
dataframe1 = current_data1
|
||||
else:
|
||||
if dataframe1 is None:
|
||||
dataframe1 = pd.DataFrame()
|
||||
else:
|
||||
if dataframe1 is None:
|
||||
dataframe1 = pd.DataFrame()
|
||||
# output2 처리
|
||||
if hasattr(res.getBody(), 'output2'):
|
||||
output_data = res.getBody().output2
|
||||
if output_data:
|
||||
# output1은 단일 객체, output2는 배열일 수 있음
|
||||
if isinstance(output_data, list):
|
||||
current_data2 = pd.DataFrame(output_data)
|
||||
else:
|
||||
# 단일 객체인 경우 리스트로 감싸서 DataFrame 생성
|
||||
current_data2 = pd.DataFrame([output_data])
|
||||
|
||||
if dataframe2 is not None:
|
||||
dataframe2 = pd.concat([dataframe2, current_data2], ignore_index=True)
|
||||
else:
|
||||
dataframe2 = current_data2
|
||||
else:
|
||||
if dataframe2 is None:
|
||||
dataframe2 = pd.DataFrame()
|
||||
else:
|
||||
if dataframe2 is None:
|
||||
dataframe2 = pd.DataFrame()
|
||||
tr_cont = res.getHeader().tr_cont
|
||||
ctx_area_nk200 = res.getBody().ctx_area_nk200
|
||||
ctx_area_fk200 = res.getBody().ctx_area_fk200
|
||||
|
||||
if tr_cont in ["M", "F"]:
|
||||
logger.info("Calling next page...")
|
||||
ka.smart_sleep()
|
||||
return inquire_daily_ccld(
|
||||
cano,
|
||||
acnt_prdt_cd,
|
||||
inqr_strt_dt,
|
||||
inqr_end_dt,
|
||||
sll_buy_dvsn_cd,
|
||||
sort_sqn_dvsn,
|
||||
pdno,
|
||||
nccs_yn,
|
||||
ctx_area_nk200,
|
||||
ctx_area_fk200,
|
||||
"N", dataframe1, dataframe2, depth + 1, max_depth
|
||||
)
|
||||
else:
|
||||
logger.info("Data fetch complete.")
|
||||
return dataframe1, dataframe2
|
||||
else:
|
||||
logger.error("API call failed: %s - %s", res.getErrorCode(), res.getErrorMessage())
|
||||
res.printError(API_URL)
|
||||
return pd.DataFrame(), pd.DataFrame()
|
||||
Reference in New Issue
Block a user