initial commit
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
Created on 20250601
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
|
||||
import pandas as pd
|
||||
|
||||
sys.path.extend(['../..', '.'])
|
||||
import kis_auth as ka
|
||||
from inquire_ccnl_bstime import inquire_ccnl_bstime
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
##############################################################################################
|
||||
# [국내선물옵션] 주문/계좌 > 선물옵션 기준일체결내역[v1_국내선물-016]
|
||||
##############################################################################################
|
||||
|
||||
COLUMN_MAPPING = {
|
||||
'pdno': '상품번호',
|
||||
'prdt_name': '상품명',
|
||||
'odno': '주문번호',
|
||||
'tr_type_name': '거래유형명',
|
||||
'last_sttldt': '최종결제일',
|
||||
'ccld_idx': '체결지수',
|
||||
'ccld_qty': '체결량',
|
||||
'trad_amt': '매매금액',
|
||||
'fee': '수수료',
|
||||
'ccld_btwn': '체결시간',
|
||||
'tot_ccld_qty_smtl': '총체결수량합계',
|
||||
'tot_ccld_amt_smtl': '총체결금액합계',
|
||||
'fee_adjt': '수수료조정',
|
||||
'fee_smtl': '수수료합계'
|
||||
}
|
||||
|
||||
NUMERIC_COLUMNS = []
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
선물옵션 기준일체결내역 조회 테스트 함수
|
||||
|
||||
이 함수는 선물옵션 기준일체결내역 API를 호출하여 결과를 출력합니다.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
|
||||
# pandas 출력 옵션 설정
|
||||
pd.set_option('display.max_columns', None) # 모든 컬럼 표시
|
||||
pd.set_option('display.width', None) # 출력 너비 제한 해제
|
||||
pd.set_option('display.max_rows', None) # 모든 행 표시
|
||||
|
||||
# 인증 토큰 발급
|
||||
ka.auth()
|
||||
|
||||
trenv = ka.getTREnv()
|
||||
|
||||
# case1 조회
|
||||
logging.info("=== case1 조회 ===")
|
||||
try:
|
||||
result1, result2 = inquire_ccnl_bstime(
|
||||
cano=trenv.my_acct,
|
||||
acnt_prdt_cd=trenv.my_prod,
|
||||
ord_dt="20230920",
|
||||
fuop_tr_strt_tmd="000000",
|
||||
fuop_tr_end_tmd="240000"
|
||||
)
|
||||
except ValueError as e:
|
||||
logging.error("에러 발생: %s" % str(e))
|
||||
return
|
||||
|
||||
# output1 처리
|
||||
logging.info("=== output1 결과 ===")
|
||||
logging.info("사용 가능한 컬럼: %s", result1.columns.tolist())
|
||||
|
||||
# 컬럼명 한글 변환 및 데이터 출력
|
||||
result1 = result1.rename(columns=COLUMN_MAPPING)
|
||||
|
||||
# 숫자형 컬럼 소수점 둘째자리까지 표시
|
||||
|
||||
for col in NUMERIC_COLUMNS:
|
||||
if col in result1.columns:
|
||||
result1[col] = pd.to_numeric(result1[col], errors='coerce').round(2)
|
||||
|
||||
logging.info("결과:")
|
||||
print(result1)
|
||||
|
||||
# output2 처리
|
||||
logging.info("=== output2 결과 ===")
|
||||
logging.info("사용 가능한 컬럼: %s", result2.columns.tolist())
|
||||
|
||||
# 컬럼명 한글 변환 및 데이터 출력
|
||||
result2 = result2.rename(columns=COLUMN_MAPPING)
|
||||
|
||||
# 숫자형 컬럼 소수점 둘째자리까지 표시
|
||||
for col in NUMERIC_COLUMNS:
|
||||
if col in result2.columns:
|
||||
result2[col] = pd.to_numeric(result2[col], errors='coerce').round(2)
|
||||
|
||||
logging.info("결과:")
|
||||
print(result2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Created on 20250601
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Optional, Tuple
|
||||
import logging
|
||||
|
||||
import pandas as pd
|
||||
|
||||
sys.path.extend(['../..', '.'])
|
||||
import kis_auth as ka
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
##############################################################################################
|
||||
# [국내선물옵션] 주문/계좌 > 선물옵션 기준일체결내역[v1_국내선물-016]
|
||||
##############################################################################################
|
||||
|
||||
# 상수 정의
|
||||
API_URL = "/uapi/domestic-futureoption/v1/trading/inquire-ccnl-bstime"
|
||||
|
||||
def inquire_ccnl_bstime(
|
||||
cano: str, # [필수] 종합계좌번호
|
||||
acnt_prdt_cd: str, # [필수] 계좌상품코드 (ex. 03)
|
||||
ord_dt: str, # [필수] 주문일자 (ex. 20250101)
|
||||
fuop_tr_strt_tmd: str, # [필수] 선물옵션거래시작시각 (ex. HHMMSS)
|
||||
fuop_tr_end_tmd: str, # [필수] 선물옵션거래종료시각 (ex. HHMMSS)
|
||||
FK200: str = "", # 연속조회검색조건200
|
||||
NK200: str = "", # 연속조회키200
|
||||
tr_cont: str = "", # 연속거래여부
|
||||
dataframe1: Optional[pd.DataFrame] = None, # 누적 데이터프레임1
|
||||
dataframe2: Optional[pd.DataFrame] = None, # 누적 데이터프레임2
|
||||
depth: int = 0, # 내부 재귀깊이 (자동관리)
|
||||
max_depth: int = 10 # 최대 재귀 횟수 제한
|
||||
) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""
|
||||
선물옵션 기준일체결내역 API입니다.
|
||||
|
||||
Args:
|
||||
cano (str): [필수] 종합계좌번호
|
||||
acnt_prdt_cd (str): [필수] 계좌상품코드 (ex. 03)
|
||||
ord_dt (str): [필수] 주문일자 (ex. 20250101)
|
||||
fuop_tr_strt_tmd (str): [필수] 선물옵션거래시작시각 (ex. HHMMSS)
|
||||
fuop_tr_end_tmd (str): [필수] 선물옵션거래종료시각 (ex. HHMMSS)
|
||||
FK200 (str): 연속조회검색조건200
|
||||
NK200 (str): 연속조회키200
|
||||
tr_cont (str): 연속거래여부
|
||||
dataframe1 (Optional[pd.DataFrame]): 누적 데이터프레임1
|
||||
dataframe2 (Optional[pd.DataFrame]): 누적 데이터프레임2
|
||||
depth (int): 내부 재귀깊이 (자동관리)
|
||||
max_depth (int): 최대 재귀 횟수 제한
|
||||
|
||||
Returns:
|
||||
Tuple[pd.DataFrame, pd.DataFrame]: 선물옵션 기준일체결내역 데이터 (output1, output2)
|
||||
|
||||
Example:
|
||||
>>> df1, df2 = inquire_ccnl_bstime(cano=trenv.my_acct, acnt_prdt_cd=trenv.my_prod, ord_dt="20230920", fuop_tr_strt_tmd="000000", fuop_tr_end_tmd="240000")
|
||||
>>> print(df1)
|
||||
>>> print(df2)
|
||||
"""
|
||||
|
||||
if cano == "":
|
||||
raise ValueError("cano is required")
|
||||
|
||||
if acnt_prdt_cd == "":
|
||||
raise ValueError("acnt_prdt_cd is required (e.g. '03')")
|
||||
|
||||
if ord_dt == "":
|
||||
raise ValueError("ord_dt is required (e.g. '20250101')")
|
||||
|
||||
if fuop_tr_strt_tmd == "":
|
||||
raise ValueError("fuop_tr_strt_tmd is required (e.g. 'HHMMSS')")
|
||||
|
||||
if fuop_tr_end_tmd == "":
|
||||
raise ValueError("fuop_tr_end_tmd is required (e.g. 'HHMMSS')")
|
||||
|
||||
if depth > max_depth:
|
||||
logging.warning("Max recursive depth reached.")
|
||||
if dataframe1 is None:
|
||||
dataframe1 = pd.DataFrame()
|
||||
if dataframe2 is None:
|
||||
dataframe2 = pd.DataFrame()
|
||||
return dataframe1, dataframe2
|
||||
|
||||
tr_id = "CTFO5139R"
|
||||
|
||||
params = {
|
||||
"CANO": cano, # 종합계좌번호
|
||||
"ACNT_PRDT_CD": acnt_prdt_cd, # 계좌상품코드
|
||||
"ORD_DT": ord_dt, # 주문일자
|
||||
"FUOP_TR_STRT_TMD": fuop_tr_strt_tmd, # 선물옵션거래시작시각
|
||||
"FUOP_TR_END_TMD": fuop_tr_end_tmd, # 선물옵션거래종료시각
|
||||
"CTX_AREA_FK200": FK200, # 연속조회검색조건200
|
||||
"CTX_AREA_NK200": NK200 # 연속조회키200
|
||||
}
|
||||
|
||||
res = ka._url_fetch(API_URL, tr_id, tr_cont, params)
|
||||
|
||||
if res.isOK():
|
||||
# output1 처리 (array)
|
||||
current_data1 = pd.DataFrame(res.getBody().output1)
|
||||
if dataframe1 is not None:
|
||||
dataframe1 = pd.concat([dataframe1, current_data1], ignore_index=True)
|
||||
else:
|
||||
dataframe1 = current_data1
|
||||
|
||||
# output2 처리 (object)
|
||||
current_data2 = pd.DataFrame([res.getBody().output2])
|
||||
if dataframe2 is not None:
|
||||
dataframe2 = pd.concat([dataframe2, current_data2], ignore_index=True)
|
||||
else:
|
||||
dataframe2 = current_data2
|
||||
|
||||
tr_cont = res.getHeader().tr_cont
|
||||
FK200 = res.getBody().ctx_area_fk200
|
||||
NK200 = res.getBody().ctx_area_nk200
|
||||
|
||||
if tr_cont in ["M", "F"]: # 다음 페이지 존재
|
||||
logging.info("Call Next page...")
|
||||
ka.smart_sleep() # 시스템 안정적 운영을 위한 지연
|
||||
return inquire_ccnl_bstime(
|
||||
cano, acnt_prdt_cd, ord_dt, fuop_tr_strt_tmd, fuop_tr_end_tmd,
|
||||
FK200, NK200, "N", dataframe1, dataframe2, depth + 1, max_depth
|
||||
)
|
||||
else:
|
||||
logging.info("Data fetch complete.")
|
||||
return dataframe1, dataframe2
|
||||
else:
|
||||
res.printError(url=API_URL)
|
||||
return pd.DataFrame(), pd.DataFrame()
|
||||
Reference in New Issue
Block a user