주식시세 query
webservicex는 response가 간단해서 빠른편인데, data 자체는 realtime도 아니고 15-20분에 한번씩 update는것 같음.
Google finance는 response자체가 너무 복잡함. 시간이 좀 걸림. 개인적인 용도로는 상관없지만.
간단하게 빠르게 update되는 서버는 무료는 없을듯. Nasdaq에서 한달에 얼마씩 내면 준다고 함.
-------------
http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=aapl
XML response example)
<string xmlns="http://www.webserviceX.NET/">
<StockQuotes>
<Stock>
<Symbol>aapl</Symbol>
<Last>109.06</Last>
<Date>9/29/2015</Date>
<Time>4:00pm</Time>
<Change>-3.38</Change>
<Open>112.79</Open>
<High>113.51</High>
<Low>107.86</Low>
<Volume>73365384</Volume>
<MktCap>621.94B</MktCap>
<PreviousClose>112.44</PreviousClose>
<PercentageChange>-3.01%</PercentageChange>
<AnnRange>92.00 - 134.54</AnnRange>
<Earns>8.65</Earns>
<P-E>12.62</P-E>
<Name>Apple Inc.</Name>
</Stock>
</StockQuotes>
*but from urllib2 read, all tags are UTF-9 encoded(llike corrupted) like below ==> HTML parser로 escape문자를 바꿔줘야함
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.webserviceX.NET/"><StockQuotes><Stock><Symbol>AAPL</Symbol><Last>
;109.06</Last><Date>9/29/2015</Date><Time>4:00pm</Time><Change>-3.38</Change>&
lt;Open>112.79</Open><High>113.51</High><Low>107.86</Low><Volume>73365384</Vol
ume><MktCap>621.94B</MktCap><PreviousClose>112.44</PreviousClose><PercentageChange>-3.0
1%</PercentageChange><AnnRange>92.00 - 134.54</AnnRange><Earns>8.65</Earns><P-E>12.6
2</P-E><Name>Apple Inc.</Name></Stock></StockQuotes></string>
-------------
Pattern matching in XML
import urllib2, time, os, reimport HTMLParser def fetchStockPrice(ticker): url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=" txt=urllib2.urlopen(url+ticker).read() html_parser = HTMLParser.HTMLParser() parsed = html_parser.unescape(txt) #print parsed #unicode = txt.encode('utf-8') #print unicode #result=re.search('(.*?) ',parsed) result=re.search('([0-9]+\.[0-9]+) ', parsed) if result: stockprice = result.group(1) cur_date = re.search('(.*?) ',parsed) cur_time = re.search('',parsed) ret = stockprice + " " + cur_date.group(1) + " " + cur_time.group(1) else: stockprice = "Nothing found for: " + ticker ret = "Nothing found for: " + ticker return ret print ("NOW = " + time.ctime()) print "Stock Price is " + fetchStockPrice("AAPL")
-------------
import urllib2, time, os, re def fetchStockPrice(ticker): url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=" txt=urllib2.urlopen(url+ticker).read() #f=open("sample.xml") #txt = f.read() #print txt #result=re.search('(.*?) ',txt) result=re.search('([0-9]+\.[0-9]+) ',txt) #result=re.search("Last\>(\d+\.\d+)\</Last", txt) if result: stockprice = result.group(1) else: stockprice = "Nothing found for: " + ticker return stockprice print(time.ctime()) print fetchStockPrice("AAPL")
-------------
XML parsing example
import xml.dom.minidom document = """\""" def getText(nodelist): rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc) def getStockPrice(quote): print "Last Stock Price is :" % getText(quote.childNodes) def handleToc(stocks): for stock in stocks: symbol = stock.getElementsByTagName("Symbol")[0] print " aapl 109.06 9/29/2015 -3.38 112.79 113.51 107.86 73365384 621.94B 112.44 -3.01% 92.00 - 134.54 8.65 12.62 Apple Inc. %s
" % getText(symbol.childNodes) last = stock.getElementsByTagName("Last")[0] print "%s
" % getText(last.childNodes) date = stock.getElementsByTagName("Date")[0] print "%s
" % getText(date.childNodes) time = stock.getElementsByTagName("Time")[0] print "%s
" % getText(time.childNodes) dom = xml.dom.minidom.parseString(document) stocks = dom.getElementsByTagName("Stock") handleToc(stocks)
-------------
Stock Quote from Google finance
import urllib2, time, os, re, csv
def fetchGF(googleticker):
url="http://www.google.com/finance?&q="
txt=urllib2.urlopen(url+googleticker).read()
#print txt
#search phase 112.44
k=re.search('id="ref_(.*?)">(.*?)<',txt)
#print k
if k:
tmp1=k.group(0)
tmp2=k.group(1)
#print tmp1
#print tmp2
tmp=k.group(2)
#print tmp
q=tmp.replace(',','')
#print q
else:
q="Nothing found for: "+googleticker
return q
print(time.ctime())
print fetchGF("AAPL")
#print fetchGF("NASDAQ:AAPL")
-------------
Stock Portfolio를 query하려면
#file에서 읽어도 좋겠다. tickers=["NASDAQ:AAPL","NASDAQ:GOOG","NASDAQ:BIDU","NYSE:IBM", \ "NASDAQ:INTC","NASDAQ:MSFT","NYSEARCA:SPY"] for ticker in tickers: data=combine(ticker) print(data)
-------------
xmlparsing_finished.py-------------
import urllib2, time, os, re import HTMLParser def fetchStockPrice(ticker): url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=" txt=urllib2.urlopen(url+ticker).read() html_parser = HTMLParser.HTMLParser() parsed = html_parser.unescape(txt) #print parsed #unicode = txt.encode('utf-8') #print unicode #result=re.search('(.*?) ',parsed) result=re.search('([0-9]+\.[0-9]+) ', parsed) if result: stockprice = result.group(1) cur_date = re.search('(.*?) ',parsed) cur_time = re.search('',parsed) cur_percent = re.search('(.*?) ',parsed) #Text formatting ret = '{:4s}: {:7s} {:7s} - {:10s} {:7s}'.format(ticker, stockprice, cur_percent.group(1), cur_date.group(1), cur_time.group(1)) #ret = '{:4s}'.format(ticker) + ": " +stockprice + " " + cur_percent.group(1) + " " + cur_date.group(1) + " " + cur_time.group(1) else: stockprice = "Nothing found for: " + ticker ret = "Nothing found for: " + ticker return ret print(time.ctime()) #tickers=["NASDAQ:AAPL","NASDAQ:GOOG","NASDAQ:QCOM","NYSE:NUAN", \ # "NASDAQ:INTC","NYSE:DAL","NYSE:F", "NYSE:SMI", "NASDAQ:HQCL", "NYSEARCA:UCO"] tickers=["AAPL","GOOG","QCOM","NUAN", \ "INTC","DAL","F", "SMI", "HQCL", "UCO"] print ("--------------------------") #print fetchStockPrice("AAPL") for ticker in tickers: data=fetchStockPrice(ticker) print(data) print ("--------------------------")
-------------
'Programming' 카테고리의 다른 글
VM Virtualbox에 Ubuntu설치후 (0) | 2015.10.01 |
---|---|
Python - String, File, Regular Expression (0) | 2015.09.30 |
VIM resource file (0) | 2015.09.30 |
Python - Date, Time (0) | 2015.09.29 |
Python with Django (0) | 2015.09.26 |