[Python] 실시간 지수 가져오기

2024. 2. 16. 07:07카테고리 없음

주식의 실시간 지수를 30분 단위로 사이트에 접속 후 데이터를 파싱하여 가져오도록 설정하였다. 

나스닥지수와 코스피지수의 내용을 예제로 하였다. 

나의 경우는 30분 단위로 이전의 데이터(1일전) 최종가와 금일의 최종가를 비교하여 거래 유무를 판단하도록 처리하였다. 

 

1. 나스닥 지수 가져오기

def getRealTimeZISU(self):
	try:
		strURL = 'https://www.google.com/finance/quote/.IXIC:INDEXNASDAQ?hl=ko'
		headers = {
        	"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
		}
        
        response = requests.get(strURL, headers=headers)
		html = response.text
		soup = BeautifulSoup(html, "html.parser")
		span = soup.find("div", {"class":"YMlKec fxKbKc"})
		span = str(span)
		value = span.split(">")
		print(f"0 : " + value[0])
        print(f"1 : " + value[1])
        NASValue = str(value[1])
        NASValue = NASValue.replace("</div","")
        NASValue = NASValue.replace(",", "")
        print(NASValue)
	except Exception as e:
		print(f" ____________ getRealTimeZISU ______________ {e}")
        
        

0 : <div class="YMlKec fxKbKc"
1 : 15,904.87</div
15904.87

 

2. 코스피 지수 가져오기

def getRealTimeZISU(self):
	try:    	
        strURL = 'https://finance.naver.com/sise/sise_index.nhn?code=KOSPI'
        headers = {
        	"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
        }
        
        response = requests.get(strURL, headers=headers)        
        html = response.text        
        soup = BeautifulSoup(html, "html.parser")        
        # print(soup)        
        span = soup.find("em", {"id":"now_value"})        
        span = str(span)        
        value = span.split(">")        
        print(f"0 : " + value[0])
        print(f"1 : " + value[1])        
        NASValue = str(value[1])
        NASValue = NASValue.replace("</em","")
        NASValue = NASValue.replace(",", "")
	except Exception as e:
		print(f" ____________ getRealTimeZISU ______________ {e}")


0 : <em id="now_value"
1 : 2,613.80</em
2613.80

 

해당 지수의 항목을 기준으로 거래 유무를 판단한다. 

일단 시도만 해보는 것인데 효과는 나름 괜찮은듯...

반응형