initial commit
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on 2025-07-01
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
|
||||
import pandas as pd
|
||||
|
||||
sys.path.extend(['../..', '.']) # kis_auth 파일 경로 추가
|
||||
import kis_auth as ka
|
||||
from investor_unpd_trend import investor_unpd_trend
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
##############################################################################################
|
||||
# [해외선물옵션] 기본시세 > 해외선물 미결제추이 [v1_해외선물-029]
|
||||
##############################################################################################
|
||||
|
||||
# 상수 정의
|
||||
COLUMN_MAPPING = {
|
||||
'row_cnt': '응답레코드카운트',
|
||||
'prod_iscd': '상품',
|
||||
'cftc_iscd': 'CFTC코드',
|
||||
'bsop_date': '일자',
|
||||
'bidp_spec': '매수투기',
|
||||
'askp_spec': '매도투기',
|
||||
'spread_spec': '스프레드투기',
|
||||
'bidp_hedge': '매수헤지',
|
||||
'askp_hedge': '매도헤지',
|
||||
'hts_otst_smtn': '미결제합계',
|
||||
'bidp_missing': '매수누락',
|
||||
'askp_missing': '매도누락',
|
||||
'bidp_spec_cust': '매수투기고객',
|
||||
'askp_spec_cust': '매도투기고객',
|
||||
'spread_spec_cust': '스프레드투기고객',
|
||||
'bidp_hedge_cust': '매수헤지고객',
|
||||
'askp_hedge_cust': '매도헤지고객',
|
||||
'cust_smtn': '고객합계'
|
||||
}
|
||||
|
||||
NUMERIC_COLUMNS = ['응답레코드카운트', '매수투기', '매도투기', '스프레드투기', '매수헤지', '매도헤지', '미결제합계',
|
||||
'매수누락', '매도누락', '매수투기고객', '매도투기고객', '스프레드투기고객', '매수헤지고객',
|
||||
'매도헤지고객', '고객합계']
|
||||
|
||||
def main():
|
||||
"""
|
||||
[해외선물옵션] 기본시세
|
||||
해외선물 미결제추이[해외선물-029]
|
||||
|
||||
해외선물 미결제추이 테스트 함수
|
||||
|
||||
Parameters:
|
||||
- prod_iscd (str): 상품 (금리 (GE, ZB, ZF,ZN,ZT), 금속(GC, PA, PL,SI, HG), 농산물(CC, CT,KC, OJ, SB, ZC,ZL, ZM, ZO, ZR, ZS, ZW), 에너지(CL, HO, NG, WBS), 지수(ES, NQ, TF, YM, VX), 축산물(GF, HE, LE), 통화(6A, 6B, 6C, 6E, 6J, 6N, 6S, DX))
|
||||
- bsop_date (str): 일자 (기준일(ex)20240513))
|
||||
- upmu_gubun (str): 구분 (0(수량), 1(증감))
|
||||
- cts_key (str): CTS_KEY (공백)
|
||||
|
||||
Returns:
|
||||
- DataFrame: 해외선물 미결제추이 결과
|
||||
|
||||
Example:
|
||||
>>> df1, df2 = investor_unpd_trend(prod_iscd="GE", bsop_date="20240513", upmu_gubun="0", cts_key="")
|
||||
"""
|
||||
try:
|
||||
# pandas 출력 옵션 설정
|
||||
pd.set_option('display.max_columns', None) # 모든 컬럼 표시
|
||||
pd.set_option('display.width', None) # 출력 너비 제한 해제
|
||||
pd.set_option('display.max_rows', None) # 모든 행 표시
|
||||
|
||||
# 토큰 발급
|
||||
ka.auth()
|
||||
|
||||
# API 호출
|
||||
logger.info("API 호출")
|
||||
result1, result2 = investor_unpd_trend(
|
||||
prod_iscd="CL",
|
||||
bsop_date="20250630",
|
||||
upmu_gubun="0",
|
||||
cts_key=""
|
||||
)
|
||||
|
||||
# 결과 확인
|
||||
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)
|
||||
|
||||
# 숫자형 컬럼 처리
|
||||
for col in NUMERIC_COLUMNS:
|
||||
if col in result1.columns:
|
||||
result1[col] = pd.to_numeric(result1[col], errors='coerce').round(2)
|
||||
|
||||
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)
|
||||
|
||||
# 숫자형 컬럼 처리
|
||||
for col in NUMERIC_COLUMNS:
|
||||
if col in result2.columns:
|
||||
result2[col] = pd.to_numeric(result2[col], errors='coerce').round(2)
|
||||
|
||||
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,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on 2025-07-01
|
||||
|
||||
"""
|
||||
|
||||
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__)
|
||||
|
||||
##############################################################################################
|
||||
# [해외선물옵션] 기본시세 > 해외선물 미결제추이 [해외선물-029]
|
||||
##############################################################################################
|
||||
|
||||
# API 정보
|
||||
API_URL = "/uapi/overseas-futureoption/v1/quotations/investor-unpd-trend"
|
||||
|
||||
def investor_unpd_trend(
|
||||
prod_iscd: str, # 상품
|
||||
bsop_date: str, # 일자
|
||||
upmu_gubun: str, # 구분
|
||||
cts_key: str, # CTS_KEY
|
||||
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]:
|
||||
"""
|
||||
[해외선물옵션] 기본시세
|
||||
해외선물 미결제추이[해외선물-029]
|
||||
해외선물 미결제추이 API를 호출하여 DataFrame으로 반환합니다.
|
||||
|
||||
Args:
|
||||
prod_iscd (str): 금리 (GE, ZB, ZF,ZN,ZT), 금속(GC, PA, PL,SI, HG), 농산물(CC, CT,KC, OJ, SB, ZC,ZL, ZM, ZO, ZR, ZS, ZW), 에너지(CL, HO, NG, WBS), 지수(ES, NQ, TF, YM, VX), 축산물(GF, HE, LE), 통화(6A, 6B, 6C, 6E, 6J, 6N, 6S, DX)
|
||||
bsop_date (str): 기준일(ex)20240513)
|
||||
upmu_gubun (str): 0(수량), 1(증감)
|
||||
cts_key (str): 공백
|
||||
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 = investor_unpd_trend(
|
||||
... prod_iscd="ES",
|
||||
... bsop_date="20240624",
|
||||
... upmu_gubun="0",
|
||||
... cts_key=""
|
||||
... )
|
||||
>>> print(df1)
|
||||
>>> print(df2)
|
||||
"""
|
||||
# [필수 파라미터 검증]
|
||||
if not prod_iscd:
|
||||
logger.error("prod_iscd is required. (e.g. 'ES')")
|
||||
raise ValueError("prod_iscd is required. (e.g. 'ES')")
|
||||
if not bsop_date:
|
||||
logger.error("bsop_date is required. (e.g. '20240624')")
|
||||
raise ValueError("bsop_date is required. (e.g. '20240624')")
|
||||
if not upmu_gubun:
|
||||
logger.error("upmu_gubun is required. (e.g. '0')")
|
||||
raise ValueError("upmu_gubun is required. (e.g. '0')")
|
||||
|
||||
# 최대 재귀 깊이 체크
|
||||
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 = "HHDDB95030000"
|
||||
|
||||
params = {
|
||||
"PROD_ISCD": prod_iscd,
|
||||
"BSOP_DATE": bsop_date,
|
||||
"UPMU_GUBUN": upmu_gubun,
|
||||
"CTS_KEY": cts_key,
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
if tr_cont in ["M", "F"]:
|
||||
logger.info("Calling next page...")
|
||||
ka.smart_sleep()
|
||||
return investor_unpd_trend(
|
||||
prod_iscd,
|
||||
bsop_date,
|
||||
upmu_gubun,
|
||||
cts_key,
|
||||
dataframe1, dataframe2, "N", 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