ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [python] 한국거래소 주가 데이터 수정 주가 비율 구하기
    IT/python 2022. 1. 11. 15:30

    주식 데이터를 다루다보면 수정주가 이슈 때문에 머리가 아픈 경우가 많다.

     

    수정주가에 대해 수 많은 데이터와 자료들을 찾고 직접 계산해본 결과, "정확한 수정주가라는 것은 존재하지 않다" 라는 결론을 내렸다.

     

    증권사마다 (심지어 한국거래소도) 수정주가를 계산하는 방식이 모두 각양 각색이고, 애초에 수정주가라는 것이 정답이 없기 때문이다.

     

    이번 포스트는 한국거래소의 수정주가 비율을 역산하는 방법에 대한 것이다.

     

    # 필요 라이브러리

    ##################################################################################

    python 3.7 version (32bit)

    Name: pykrx (pip install pykrx)
    Version: 1.0.19
    Summary: KRX data scraping
    Home-page: https://github.com/sharebook-kr/pykrx
    Author: Brayden Jo, Jonghun Yoo
    Author-email: brayden.jo@outlook.com, jonghun.yoo@outlook.com, pystock@outlook.com
    License: MIT
    Location: c:\programdata\anaconda3\envs\py37_32bit\lib\site-packages
    Requires: numpy, xlrd, datetime, requests, pandas, deprecated
    Required-by:

    ##################################################################################

     

    # 코드

    ###################################################################################

    import datetime
    from pykrx import stock
    import pandas as pd
    import numpy as np
    import warnings
    warnings.filterwarnings('ignore')
    
    
    start_date = '20010101'
    last_date = str(datetime.date.today() - datetime.timedelta(days=1)).split(' ')[0].replace('-', '')
    code = '101390'
    
    # krx 무수정 주가
    original_df = stock.get_market_ohlcv_by_date(start_date, last_date, code, adjusted=False).reset_index(drop=False)
    # krx 수정 주가
    modified_df = stock.get_market_ohlcv_by_date(start_date, last_date, code, adjusted=True).reset_index(drop=False)
    
    original_df = original_df[['날짜', '종가']]
    original_df.columns = ['date', 'original_close']
    modified_df = modified_df[['날짜', '종가']]
    modified_df.columns = ['date', 'modified_close']
    
    df = pd.merge(original_df, modified_df, on=['date'])
    df['rate'] = df['modified_close'] / df['original_close']
    df['calculated_close'] = df['original_close']
    df['calculated_rate'] = df['rate']
    
    print('수정비율')
    while True:
        # 소수점 둘째 자리 반올림 했을 때, krx 수정주가와 차이가 있는 경우 -> 수정 주가 이슈가 있다고 판단
        gap_date_list = df[df['calculated_rate'].apply(lambda x: np.around(x, 2)) != 1]['date'].tolist()
    
        # 더 이상 수정할 데이터가 없을 경우 break
        if len(gap_date_list) <= 0:
            break
    
        adj_date = str(gap_date_list[-1]).split(' ')[0]
        adj_rate = df[df['date'] == adj_date]['calculated_rate'].iloc[0]
        print(f'{adj_date}: {adj_rate}')
        not_change_df = df[df['date'] > adj_date]
        change_df = df[df['date'] <= adj_date]
        change_df['calculated_close'] = change_df['calculated_close'] * adj_rate
    
        df = pd.concat([change_df, not_change_df])
        df['calculated_rate'] = df['modified_close'] / df['calculated_close']
    
    df.to_csv(f'{code}.csv', index=False)
    

    ###################################################################################

     

    # 실행화면

    ###################################################################################

    ###################################################################################

     

    역산한 수정주가 비율을 이용하여 수정주가를 재계산했을 때,

    calculated_rate 가 1에 거의 근접하는 것을 볼 수 있다.

Designed by Tistory.