initial commit

This commit is contained in:
2026-02-04 00:16:34 +09:00
commit ae11528dd9
867 changed files with 209640 additions and 0 deletions

View File

@@ -0,0 +1,111 @@
# -*- 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_balance import inquire_balance
# 로깅 설정
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
##############################################################################################
# [장내채권] 주문/계좌 > 장내채권 잔고조회 [국내주식-198]
##############################################################################################
COLUMN_MAPPING = {
'pdno': '상품번호',
'buy_dt': '매수일자',
'buy_sqno': '매수일련번호',
'cblc_qty': '잔고수량',
'agrx_qty': '종합과세수량',
'sprx_qty': '분리과세수량',
'exdt': '만기일',
'buy_erng_rt': '매수수익율',
'buy_unpr': '매수단가',
'buy_amt': '매수금액',
'ord_psbl_qty': '주문가능수량'
}
NUMERIC_COLUMNS = []
def main():
"""
[장내채권] 주문/계좌
장내채권 잔고조회[국내주식-198]
장내채권 잔고조회 테스트 함수
Parameters:
- cano (str): 종합계좌번호 ()
- acnt_prdt_cd (str): 계좌상품코드 ()
- inqr_cndt (str): 조회조건 (00: 전체, 01: 상품번호단위)
- pdno (str): 상품번호 (공백)
- buy_dt (str): 매수일자 (공백)
Returns:
- DataFrame: 장내채권 잔고조회 결과
Example:
>>> df = inquire_balance(cano=trenv.my_acct, acnt_prdt_cd=trenv.my_prod, inqr_cndt="00", pdno="", buy_dt="")
"""
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 호출 시작: 장내채권 잔고조회")
result = inquire_balance(
cano=trenv.my_acct, # 종합계좌번호
acnt_prdt_cd=trenv.my_prod, # 계좌상품코드
inqr_cndt="00", # 조회조건
pdno="", # 상품번호
buy_dt="", # 매수일자
)
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')
# 결과 출력
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,147 @@
# [장내채권] 주문/계좌 - 장내채권 잔고조회
# Generated by KIS API Generator (Single API Mode)
# -*- coding: utf-8 -*-
"""
Created on 2025-06-20
"""
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__)
##############################################################################################
# [장내채권] 주문/계좌 > 장내채권 잔고조회 [국내주식-198]
##############################################################################################
# 상수 정의
API_URL = "/uapi/domestic-bond/v1/trading/inquire-balance"
def inquire_balance(
cano: str, # 종합계좌번호
acnt_prdt_cd: str, # 계좌상품코드
inqr_cndt: str, # 조회조건
pdno: str, # 상품번호
buy_dt: str, # 매수일자
FK200: str = "", # 연속조회검색조건200
NK200: str = "", # 연속조회키200
tr_cont: str = "", # 연속 거래 여부
dataframe: Optional[pd.DataFrame] = None, # 누적 데이터프레임
depth: int = 0, # 현재 재귀 깊이
max_depth: int = 10 # 최대 재귀 깊이
) -> Optional[pd.DataFrame]:
"""
[장내채권] 주문/계좌
장내채권 잔고조회[국내주식-198]
장내채권 잔고조회 API를 호출하여 DataFrame으로 반환합니다.
Args:
cano (str): 종합계좌번호
acnt_prdt_cd (str): 계좌상품코드
inqr_cndt (str): 조회조건 (00: 전체, 01: 상품번호단위)
pdno (str): 상품번호 (공백 허용)
buy_dt (str): 매수일자 (공백 허용)
FK200 (str): 연속조회검색조건200
NK200 (str): 연속조회키200
tr_cont (str): 연속 거래 여부 (기본값: "")
dataframe (Optional[pd.DataFrame]): 누적 데이터프레임
depth (int): 현재 재귀 깊이
max_depth (int): 최대 재귀 깊이 (기본값: 10)
Returns:
Optional[pd.DataFrame]: 장내채권 잔고조회 데이터
Example:
>>> df = inquire_balance(
... cano=trenv.my_acct,
... acnt_prdt_cd=trenv.my_prod,
... inqr_cndt='00',
... pdno='',
... buy_dt='',
... )
>>> print(df)
"""
# 로깅 설정
logger = logging.getLogger(__name__)
# 필수 파라미터 검증
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_cndt:
logger.error("inqr_cndt is required. (e.g. '00')")
raise ValueError("inqr_cndt is required. (e.g. '00')")
# 최대 재귀 깊이 체크
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 = "CTSC8407R"
params = {
"CANO": cano,
"ACNT_PRDT_CD": acnt_prdt_cd,
"INQR_CNDT": inqr_cndt,
"PDNO": pdno,
"BUY_DT": buy_dt,
"CTX_AREA_FK200": FK200,
"CTX_AREA_NK200": NK200,
}
# API 호출
res = ka._url_fetch(API_URL, tr_id, tr_cont, params)
if res.isOK():
if hasattr(res.getBody(), 'output'):
output_data = res.getBody().output
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
NK200 = res.getBody().ctx_area_nk200
FK200 = res.getBody().ctx_area_fk200
if tr_cont == "M":
logger.info("Calling next page...")
ka.smart_sleep()
return inquire_balance(
cano,
acnt_prdt_cd,
inqr_cndt,
pdno,
buy_dt,
FK200,
NK200,
"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()