initial commit
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Created on 2025-06-30
|
||||
|
||||
"""
|
||||
|
||||
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__)
|
||||
|
||||
##############################################################################################
|
||||
# [해외주식] 주문/계좌 > 해외주식 잔고 [v1_해외주식-006]
|
||||
##############################################################################################
|
||||
|
||||
COLUMN_MAPPING = {
|
||||
'cano': '종합계좌번호',
|
||||
'acnt_prdt_cd': '계좌상품코드',
|
||||
'prdt_type_cd': '상품유형코드',
|
||||
'ovrs_pdno': '해외상품번호',
|
||||
'frcr_evlu_pfls_amt': '외화평가손익금액',
|
||||
'evlu_pfls_rt': '평가손익율',
|
||||
'pchs_avg_pric': '매입평균가격',
|
||||
'ovrs_cblc_qty': '해외잔고수량',
|
||||
'ord_psbl_qty': '주문가능수량',
|
||||
'frcr_pchs_amt1': '외화매입금액1',
|
||||
'ovrs_stck_evlu_amt': '해외주식평가금액',
|
||||
'now_pric2': '현재가격2',
|
||||
'tr_crcy_cd': '거래통화코드',
|
||||
'ovrs_excg_cd': '해외거래소코드',
|
||||
'loan_type_cd': '대출유형코드',
|
||||
'loan_dt': '대출일자',
|
||||
'expd_dt': '만기일자',
|
||||
'frcr_pchs_amt1': '외화매입금액1',
|
||||
'ovrs_rlzt_pfls_amt': '해외실현손익금액',
|
||||
'ovrs_tot_pfls': '해외총손익',
|
||||
'rlzt_erng_rt': '실현수익율',
|
||||
'tot_evlu_pfls_amt': '총평가손익금액',
|
||||
'tot_pftrt': '총수익률',
|
||||
'frcr_buy_amt_smtl1': '외화매수금액합계1',
|
||||
'ovrs_rlzt_pfls_amt2': '해외실현손익금액2',
|
||||
'frcr_buy_amt_smtl2': '외화매수금액합계2'
|
||||
}
|
||||
|
||||
# 숫자형 컬럼 정의
|
||||
NUMERIC_COLUMNS = []
|
||||
|
||||
def main():
|
||||
"""
|
||||
[해외주식] 주문/계좌
|
||||
해외주식 잔고[해외주식-006]
|
||||
|
||||
해외주식 잔고 테스트 함수
|
||||
|
||||
Parameters:
|
||||
- cano (str): 종합계좌번호 ()
|
||||
- acnt_prdt_cd (str): 계좌상품코드 ()
|
||||
- ovrs_excg_cd (str): 해외거래소코드 ()
|
||||
- tr_crcy_cd (str): 거래통화코드 ()
|
||||
- FK200 (str): 연속조회검색조건200 ()
|
||||
- NK200 (str): 연속조회키200 ()
|
||||
|
||||
Returns:
|
||||
- DataFrame: 해외주식 잔고 결과
|
||||
|
||||
Example:
|
||||
>>> df = inquire_balance(cano=trenv.my_acct, acnt_prdt_cd=trenv.my_prod, ovrs_excg_cd="NASD", tr_crcy_cd="USD")
|
||||
"""
|
||||
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("토큰 발급 완료")
|
||||
trenv = ka.getTREnv()
|
||||
|
||||
# API 호출
|
||||
logger.info("API 호출")
|
||||
result1, result2 = inquire_balance(
|
||||
cano=trenv.my_acct, # 종합계좌번호
|
||||
acnt_prdt_cd=trenv.my_prod, # 계좌상품코드
|
||||
ovrs_excg_cd="NASD", # 해외거래소코드
|
||||
tr_crcy_cd="USD", # 거래통화코드
|
||||
FK200="", # 연속조회검색조건200
|
||||
NK200="", # 연속조회키200
|
||||
)
|
||||
|
||||
# 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)
|
||||
|
||||
# output3 결과 처리
|
||||
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("결과(output2):")
|
||||
print(result2)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("에러 발생: %s", str(e))
|
||||
raise
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
Created on 2025-06-30
|
||||
|
||||
"""
|
||||
|
||||
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__)
|
||||
|
||||
##############################################################################################
|
||||
# [해외주식] 주문/계좌 > 해외주식 잔고 [v1_해외주식-006]
|
||||
##############################################################################################
|
||||
|
||||
# 상수 정의
|
||||
API_URL = "/uapi/overseas-stock/v1/trading/inquire-balance"
|
||||
|
||||
def inquire_balance(
|
||||
cano: str, # 종합계좌번호
|
||||
acnt_prdt_cd: str, # 계좌상품코드
|
||||
ovrs_excg_cd: str, # 해외거래소코드
|
||||
tr_crcy_cd: str, # 거래통화코드
|
||||
FK200: str = "", # 연속조회검색조건200
|
||||
NK200: str = "", # 연속조회키200
|
||||
env_dv: str = "real", # 실전모의구분
|
||||
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]:
|
||||
"""
|
||||
[해외주식] 주문/계좌
|
||||
해외주식 잔고[v1_해외주식-006]
|
||||
해외주식 잔고 API를 호출하여 DataFrame으로 반환합니다.
|
||||
|
||||
Args:
|
||||
cano (str): 계좌번호 체계(8-2)의 앞 8자리
|
||||
acnt_prdt_cd (str): 계좌번호 체계(8-2)의 뒤 2자리
|
||||
ovrs_excg_cd (str): [모의] NASD : 나스닥 NYSE : 뉴욕 AMEX : 아멕스 [실전] NASD : 미국전체 NAS : 나스닥 NYSE : 뉴욕 AMEX : 아멕스 [모의/실전 공통] SEHK : 홍콩 SHAA : 중국상해 SZAA : 중국심천 TKSE : 일본 HASE : 베트남 하노이 VNSE : 베트남 호치민
|
||||
tr_crcy_cd (str): USD : 미국달러 HKD : 홍콩달러 CNY : 중국위안화 JPY : 일본엔화 VND : 베트남동
|
||||
FK200 (str): 공란 : 최초 조회시 이전 조회 Output CTX_AREA_FK200값 : 다음페이지 조회시(2번째부터)
|
||||
NK200 (str): 공란 : 최초 조회시 이전 조회 Output CTX_AREA_NK200값 : 다음페이지 조회시(2번째부터)
|
||||
env_dv (str): 실전모의구분 (real:실전, demo:모의)
|
||||
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_balance(
|
||||
... cano=trenv.my_acct,
|
||||
... acnt_prdt_cd=trenv.my_prod,
|
||||
... ovrs_excg_cd="NASD",
|
||||
... tr_crcy_cd="USD",
|
||||
... FK200="",
|
||||
... NK200=""
|
||||
... )
|
||||
>>> print(df1)
|
||||
>>> print(df2)
|
||||
"""
|
||||
# [필수 파라미터 검증]
|
||||
if not cano:
|
||||
logger.error("cano is required. (e.g. '810XXXXX')")
|
||||
raise ValueError("cano is required. (e.g. '810XXXXX')")
|
||||
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 ovrs_excg_cd:
|
||||
logger.error("ovrs_excg_cd is required. (e.g. 'NASD')")
|
||||
raise ValueError("ovrs_excg_cd is required. (e.g. 'NASD')")
|
||||
if not tr_crcy_cd:
|
||||
logger.error("tr_crcy_cd is required. (e.g. 'USD')")
|
||||
raise ValueError("tr_crcy_cd is required. (e.g. 'USD')")
|
||||
|
||||
# 최대 재귀 깊이 체크
|
||||
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 설정 (모의투자 지원 로직)
|
||||
if env_dv == "real":
|
||||
tr_id = "TTTS3012R" # 실전투자용 TR ID
|
||||
elif env_dv == "demo":
|
||||
tr_id = "VTTS3012R" # 모의투자용 TR ID
|
||||
else:
|
||||
raise ValueError("env_dv can only be 'real' or 'demo'")
|
||||
|
||||
params = {
|
||||
"CANO": cano,
|
||||
"ACNT_PRDT_CD": acnt_prdt_cd,
|
||||
"OVRS_EXCG_CD": ovrs_excg_cd,
|
||||
"TR_CRCY_CD": tr_crcy_cd,
|
||||
"CTX_AREA_FK200": FK200,
|
||||
"CTX_AREA_NK200": NK200,
|
||||
}
|
||||
|
||||
res = ka._url_fetch(api_url=API_URL, ptr_id=tr_id, tr_cont=tr_cont, params=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, FK200, NK200 = res.getHeader().tr_cont, res.getBody().ctx_area_fk200, res.getBody().ctx_area_nk200
|
||||
|
||||
if tr_cont in ["M", "F"]:
|
||||
logger.info("Calling next page...")
|
||||
ka.smart_sleep()
|
||||
return inquire_balance(
|
||||
cano,
|
||||
acnt_prdt_cd,
|
||||
ovrs_excg_cd,
|
||||
tr_crcy_cd,
|
||||
FK200,
|
||||
NK200,
|
||||
env_dv,
|
||||
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