'finance'에 해당되는 글 2건

  1. 2015.09.30 Python - Stock Price Quote
  2. 2015.06.03 Stock APIs - Bloomberg, NASDAQ and E*TRADE
Programming2015. 9. 30. 10:28

주식시세 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/">&lt;StockQuotes&gt;&lt;Stock&gt;&lt;Symbol&gt;AAPL&lt;/Symbol&gt;&lt;Last&gt

;109.06&lt;/Last&gt;&lt;Date&gt;9/29/2015&lt;/Date&gt;&lt;Time&gt;4:00pm&lt;/Time&gt;&lt;Change&gt;-3.38&lt;/Change&gt;&

lt;Open&gt;112.79&lt;/Open&gt;&lt;High&gt;113.51&lt;/High&gt;&lt;Low&gt;107.86&lt;/Low&gt;&lt;Volume&gt;73365384&lt;/Vol

ume&gt;&lt;MktCap&gt;621.94B&lt;/MktCap&gt;&lt;PreviousClose&gt;112.44&lt;/PreviousClose&gt;&lt;PercentageChange&gt;-3.0

1%&lt;/PercentageChange&gt;&lt;AnnRange&gt;92.00 - 134.54&lt;/AnnRange&gt;&lt;Earns&gt;8.65&lt;/Earns&gt;&lt;P-E&gt;12.6

2&lt;/P-E&gt;&lt;Name&gt;Apple Inc.&lt;/Name&gt;&lt;/Stock&gt;&lt;/StockQuotes&gt;</string>

-------------

Pattern matching in XML

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

-------------

Just Pattern Matching Python code
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

https://docs.python.org/2/library/xml.dom.minidom.html?highlight=xml.dom.minidom#module-xml.dom.minidom

import xml.dom.minidom

document = """\

	
		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.
	

"""

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 "

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

-------------


stockprices.py


'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
Posted by 쁘레드
Programming2015. 6. 3. 06:17

공개된 Stock API이 많은것 같습니다. 한국에서는 대우증권에서 2000년대 초반에 API를 공개해서 자동으로 trade하고자 하는 저의 꿈에 한발짝 다가갈수 있게해줬었는데, 그 이후 막히고 점점 퇴보하는것 같았습니다. open해주면 아무래도 보안에 문제가 있을거란 걱정을 윗대가리들은 하겠지요. 오픈이 가끔 보안문제를 야기시키지만 사회를 투명하게 하고는데 도움이 됩니다. 뭘 오픈할지도 생각하지 않고 안된다고만 하는것은 안되겠지요.


시간을 내서 재밌는거 하나 만들어봐야겠네요. 매번 반복적으로 하는거 자동화하게요.

----------------

http://www.programmableweb.com/news/96-stocks-apis-bloomberg-nasdaq-and-etrade/2013/05/22

Our API directory now includes 96 stocks APIs. The newest is theEurex VALUES API. The most popular, in terms of directory page views, is the Bloomberg API. Below you'll find some more stats from the directory, including the entire list of stocks APIs.



In terms of the technical details, REST and XML lead the way. There are 55 stocks REST APIsand 42 stocks SOAP APIs. Our directory lists 64 stocks XML APIs and 18 stocks JSON APIs


  Bloomberg API: Financial markets data service

  E*TRADE API: Access to E*Trade services for applications

  NASDAQ Data-On-Demand API: NASDAQ historical stock quote data servcie


----------------------

http://www.programmableweb.com/api/bloomberg

Financial
StatisticsStocks
Unspecified
No
C, C++, .NET, Java, Perl Node.js
open-tech@bloomberg.net
Unspecified, IP authentication, Bloomberg Terminal authentication






















--------------------

ETrade

Financial
Stocks
XMLJSONREST
Yes
OAuth



















--------------------

Nasdaq

Financial
Stocks
XMLRESTSOAP
ASP, C#, Java, PHP, Perl, .NET, VB, XSLT


Posted by 쁘레드