본문 바로가기

Programming/Python Program

실시간 내 주가를 알려주는 Python Code

이번에는 실시간 주식 데이터를 가져와서 시시각각 동향을 출력하게 하려고 한다. 그 후에는 내가 보유한 종목의 주가 흐름을 계속 추적하고, 더 나아가 컴퓨터가 보유종목의 주가를 계속 오디오로 알려주게 하는데까지 알아보려고 한다.


포털사이트 다음의 증권에 올라오는 종목 시세를 참고하였다. 옛날 같으면 포털사이트에서 제공하는 주가는 20분 지연 시세를 제공하여 효용성이 많이 떨어졌던게 사실이다. 그러나 이제는 실시간 시세를 제공하고 있으므로, 증권사에서 제공하는 데이터 못지않게 빠르고 정확하다. 그래서 다음 사이트의 데이터를 가지고 와서 뚝딱뚝딱 기름칠해서 내가 필요로 하는 정보만을 추출하였다.

아래는 그 코드이다.

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 = []

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=10 




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()

위 코드를 실행하면 아래와 같은 결과를 볼 수 있다.

2017년 5월 26일 오전 장 시작 시점의 데이터 값 들이다. 뭐, 시가나 종가, 거래량 등등도 추가할 수 있을것이나 별로 도움이 되지 않을 것 같아 그만두었다.

2초 단위로 새로운 데이터를 가지고 오게 하였는데, 너무 서버에 부담이 된다 싶으면 10초쯤 해도 무방할 것이다.


원래 이 코드를 만들려고 한 계기는, 사람들이 많은 곳에서 HTS를 볼 수 없는데, 내가 가진 종목의 주가가 궁금할 때가 있었었다. 그래서 이렇게 만들어 둔 코드에서 현재 주가 부분만 컴퓨터가 text to audio 모듈처럼 알려주면 좋겠다 싶어 만들어 보았다. 혼자 있을 때는 스피커로 그냥 떠들게 하면 되지만, 사람이 많을 시에는 블루투스로 동기화 시켜두고, 주가의 흐름을 오디오로 들으면서 다른 일을 하면 될 것 같았다. 이놈의 성미가 궁금한건 못 참아서 나온 코드라고 할 수 있겠다.

오디오로 읽어주는 코드는 뒤에 추가하면서 코드가 일부 변경되었는데, 그 부분은 이 글을 읽는 분들이 고민해 보시라고 숙제를 던져두는 것으로 마무리 하려고 한다.