▶ [국내주식]기본시세>주식현재가 일자별
1. API 정보 및 요청 파라메터 분석
2. 일자별 조회 함수
def get_ohlcv(code="005930"):
"""국내주식기간별 시세"""
while True:
PATH = "/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice"
URL = f"{URL_BASE}/{PATH}"
headers = {"Content-Type":"application/json",
"authorization": f"Bearer {ACCESS_TOKEN}",
"appkey":APP_KEY,
"appsecret":APP_SECRET,
"tr_id":"FHKST03010100"}
params = {
"fid_cond_mrkt_div_code":"J",
"fid_input_iscd":code,
"fid_input_date_1": "00000101",
"fid_input_date_2": "99991231",
"fid_period_div_code": "D",
"fid_org_adj_prc": "0"
}
time.sleep(1)
res = requests.get(URL, headers=headers, params=params)
result = res.json()
if not result:
print("[get_ohlcv:일별시세조회] 에러")
time.sleep(0.3)
continue
else:
print('[get_ohlcv:일별시세조회]가 정상적으로 완료되었습니다.')
#print(result)
temp = result['output2'][::-1]
temp = pd.DataFrame(temp)
temp = temp.rename(columns={'stck_bsop_date':'timestamp','stck_clpr':'close','stck_oprc':'open','stck_hgpr':'high','stck_lwpr':'low','acml_vol':'volume'})
temp[['close','open','high','low','volume']] = temp[['close','open','high','low','volume']].astype(float)
break
return temp
3. 확인 코드
print("# 1. 시작")
import requests
import json
import time
import pandas as pd
import ki_config # 개인정보에 대한 별도화일 링크용
##################################################################################################################################
'''
한국투자증권에 접속하기 위한 보안승인 코드 (공통)
'''
##################################################################################################################################
def get_access_token():
"""토큰 발급"""
while True:
headers = {"content-type":"application/json"}
body = {"grant_type":"client_credentials",
"appkey":APP_KEY,
"appsecret":APP_SECRET}
PATH = "oauth2/tokenP"
URL = f"{URL_BASE}/{PATH}"
res = requests.post(URL, headers=headers, data=json.dumps(body))
'''
print(res.json())
{
'access_token':'....' # 발급토큰
'access_token_token_expired': '2024-00-00 00:00:00', # 유효기간
'token_type': 'Bearer', # API 호출 시, 접근토큰유형 "Bearer" 입력. ex) "Bearer eyJ...."
'expires_in': 86400 # 유효기간(초)
}
'''
time.sleep(0.2)
try:
ACCESS_TOKEN = res.json()["access_token"]
ACCESS_TOKEN_EXPIRED = res.json()["access_token_token_expired"]
print('# 2. 접근토큰 발급 완료')
return ACCESS_TOKEN, ACCESS_TOKEN_EXPIRED
except:
print("접근 토큰 발급이 불가능합니다")
print(res.json())
time.sleep(1)
##################################################################################################################################
def get_ohlcv(code="005930"):
"""국내주식기간별 시세"""
while True:
PATH = "/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice"
URL = f"{URL_BASE}/{PATH}"
headers = {"Content-Type":"application/json",
"authorization": f"Bearer {ACCESS_TOKEN}",
"appkey":APP_KEY,
"appsecret":APP_SECRET,
"tr_id":"FHKST03010100"}
params = {
"fid_cond_mrkt_div_code":"J",
"fid_input_iscd":code,
"fid_input_date_1": "00000101",
"fid_input_date_2": "99991231",
"fid_period_div_code": "D",
"fid_org_adj_prc": "0"
}
time.sleep(1)
res = requests.get(URL, headers=headers, params=params)
result = res.json()
if not result:
print("[get_ohlcv:일별시세조회] 에러")
time.sleep(0.3)
continue
else:
print('[get_ohlcv:일별시세조회]가 정상적으로 완료되었습니다.')
print(result)
temp = result['output2'][::-1]
temp = pd.DataFrame(temp)
temp = temp.rename(columns={'stck_bsop_date':'timestamp','stck_clpr':'close','stck_oprc':'open','stck_hgpr':'high','stck_lwpr':'low','acml_vol':'volume'})
temp[['close','open','high','low','volume']] = temp[['close','open','high','low','volume']].astype(float)
break
return temp
##################################################################################################################################
'''
한국투자증권 주식투자 자동매매 프로그램 시작
'''
APP_KEY = ki_config.APP_KEY
APP_SECRET = ki_config.APP_SECRET
URL_BASE = ki_config.URL_BASE
# CANO = ki_config.CANO
# ACNT_PRDT_CD = ki_config.ACNT_PRDT_CD
ACCESS_TOKEN, ACCESS_TOKEN_EXPIRED = get_access_token()
ohlcv = get_ohlcv()
print(ohlcv)
#화면 출력(라인 수정)
(tensor37) F:\python>C:/Users/webti/anaconda3/envs/tensor37/python.exe f:/python/STOCKS/Korea_Investment/koreainvest_test2.py
# 1. 시작
# 2. 접근토큰 발급 완료
[get_ohlcv:일별시세조회]가 정상적으로 완료되었습니다.
timestamp close open high low volume acml_tr_pbmn flng_cls_code prtt_rate mod_yn prdy_vrss_sign prdy_vrss revl_issu_reas
0 20241120 55300.0 56100.0 56500.0 54800.0 20864667.0 1156033483400 00 0.00 N 5 -1000
1 20241121 56400.0 54900.0 56900.0 54700.0 19096850.0 1068199169900 00 0.00 N 2 1100
2 20241122 56000.0 56000.0 56700.0 55900.0 15281543.0 860560563100 00 0.00 N 5 -400
3 20241125 57900.0 57400.0 57900.0 56700.0 36237325.0 2086462735928 00 0.00 N 2 1900
4 20241126 58300.0 57900.0 58900.0 57500.0 23209405.0 1350434011510 00 0.00 N 2 400
.. ... ... ... ... ... ... ... ... ... ... ... ... ...
95 20250414 56200.0 56300.0 56700.0 55800.0 12852613.0 722365102751 00 0.00 N 2 1000
96 20250415 56600.0 56300.0 57100.0 56200.0 8998640.0 510390643850 00 0.00 N 2 400
97 20250416 54700.0 56000.0 56200.0 54500.0 14437025.0 795695286400 00 0.00 N 5 -1900
98 20250417 55100.0 54700.0 55300.0 54500.0 10867069.0 597524532250 00 0.00 N 2 400
99 20250418 55300.0 55300.0 55600.0 54900.0 5848342.0 323289923300 00 0.00 N 2 200
[100 rows x 13 columns]