콘텐츠로 건너뛰기
Home » [Python] 파이썬으로 실시간 주가 얻어오기

[Python] 파이썬으로 실시간 주가 얻어오기

파이썬 실생활 활용시리즈로 이번 포스트에서는 파이썬으로 실시간 종목 주가 정보를 얻어오는 코드에 대하여 알아보도록 하겠습니다. 

개념

다음 금융정보의 주식시세를 파이썬으로 Read하여 일정주기로 출력해주는 코드입니다. 종목은 여러개를 지정할수 있으며, 최소 주기는 1(Second,초) 입니다. 만약 본인이 평일 회사에있고 스마트폰으로 주가 정보를 확인하기 어려울때, 특히 회사에서 HTS가 방화벽에 의해 막혀있거나 접속 불가인 상태일때 유용하게 사용할수 있을것으로 생각됩니다.

(전제는 파이썬을 조금이라도 알고 있다거나, 프로그래머라는 점입니다.^^ 이 참에 파이썬을 시작하셔도 됩니다.)

소스는 공유받은 소스를 제 환경에 맞게 약간 수정하였습니다. 공유해주신 분께 감사드립니다.

개발환경

Windows 10 64bit, Python 3.5 기반에서 테스트를 하였습니다. Anaconda 2.4.0 (32bit)을 사용함.

Source Code

import urllib.request, time, os, re, csv, sys
 
def fetch(daumticker):
    #print("daumticker",daumticker)
    url="http://finance.daum.net/item/main.daum?code="
    txt=urllib.request.urlopen(url+daumticker).read().decode()
    k=re.search('class="curPrice(.*?)">(.*?)<',txt)
    r=re.search('class="rate (.*?)?>(.*?)<',txt)
    if k:
        price=k.group(2)
        #q=tmp.replace(',','')
    else:
        price = "Nothing found for: " + daumticker + " price"
    if r:
        rate = r.group(2)
    else:
        rate = "Nothing found for: " + daumticker + " rate"
    return price, rate
 
 
# display time corresponding to your location
print(time.ctime())
 
# Set local time zone to Seoul
os.environ['TZ']='Asia/Seoul'
#time.tzset()
t=time.localtime() # string
print(time.ctime())
 
 
def combine(ticker):
    price, rate = fetch(ticker)
    t=time.localtime()   
    output=[t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour, 
            t.tm_min,t.tm_sec,ticker,price,rate]
    return output
 
 
 
# 종목코드를 넣어주세요. (아래 코드는 우리은행)
#tickers = ['000030', '023590'] ( 2개이상은 이런식으로 추가해서 쓰면 됩니다.)
tickers = ['000030']
 
for i in range(1,len(sys.argv)):
    tickers.append(sys.argv[i])
 
print("Stock List(s) : ",tickers)
# define the name of an output file
 
 
fname="portfolio.csv"
# remove a file, if exist
os.path.exists(fname) and os.remove(fname)
# freq에 주기를 입력하세요. 여기서는 1 sec 마다 주가정보를 갱신합니다.
freq=1
 
 
 
with open(fname,'a') as f:
    writer=csv.writer(f,dialect="excel") #,delimiter=" ")
    while(t.tm_hour<=15):
        if(t.tm_hour==15):
            while(t.tm_min<30):
                for ticker in tickers:
                    data=combine(ticker)
                    print(data)
                    writer.writerow(data)
                time.sleep(freq)
            else:
                break
        else:
            for ticker in tickers:
                data=combine(ticker)
                print(data)
                writer.writerow(data)
            time.sleep(freq)
 
f.close()

실행결과

1초마다 Stock List에 저장된 종목코드의 시간, 종목코드, 현재가, 등락율이 표시가 됩니다.

'정원딸린집'에는 쿠팡파트너스 등의 제휴링크가 포함되어 있으며 수수료를 제공받을 수 있습니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

error: Content is protected !!