ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [파이썬] 30 거래일 내 종가의 5% 이상 하락 여부를 체크
    Python/파이썬과 주식 2025. 1. 25. 08:40
    반응형

    FinanceDataReader 가 좋긴 한데, 조금 무겁습니다.
    먼저 만들었던 미국지수체커를 배포하려니 140MB 정도 되더군요.
    가볍게 만들기 위해 파이썬 기본 라이브러리만 사용해
    네이버 데이터를 직접 크롤링했습니다.
    20MB 내로 배포할 수 있습니다. 

    import urllib.request
    import xml.etree.ElementTree as ET
    from datetime import datetime
    
    
    def load_data(code, count):
        url = f'https://fchart.stock.naver.com/sise.nhn?symbol={code}&timeframe=day&count={count}&requestType=0'
        r = urllib.request.urlopen(url)
        xml_data = r.read().decode('EUC-KR')
        return ET.fromstring(xml_data)
    
    
    def find_data(root):
        first_date = max_date = min_date = last_date = ''
        max_val, min_val, last_val = 0, float('inf'), 0
        name = root.find('chartdata').attrib['name']
        for each in root.findall('.//item'):
            temp = each.attrib['data'].split('|')
            # print(temp)  # 0: 날짜, 1: 시가, 2: 고가, 3: 저가, 4: 종가, 5: 거래량
            date = datetime.strptime(temp[0], '%Y%m%d').strftime('%Y-%m-%d')
            price = int(temp[4])
            if max_val <= price:
                max_val = price
                max_date = date
            if min_val >= price:
                min_val = price
                min_date = date
            if first_date == '':
                first_date = date
            last_date, last_val = date, price
        return name, first_date, max_date, max_val, min_date, min_val, last_date, last_val
    
    
    def main():
        count = '30'
        codes = [
            '102110',
        ]
    
        for code in codes:
            root = load_data(code, count)
            name, first_date, max_date, max_val, min_date, min_val, last_date, last_val = find_data(root)
            min_ratio = (min_val - max_val) / max_val * 100
            last_ratio = (last_val - max_val) / last_val * 100
    
            print(f'\n{name} [{first_date}~]')
            print(f'Max: {max_date}, {max_val}')
            print(f'Min: {min_date}, {min_val}, {min_ratio:0.2f}%')
            if last_ratio <= -5:
                print('* ', end='')
            print(f'Last: {last_date}, {last_val}, {last_ratio:0.2f}%')
    
        input('\nGood Luck!')
    
    
    if __name__ == '__main__':
        main()

     

    반응형
Designed by Tistory.