我对Python编程很陌生。
我想做一个从谷歌金融获取股票价格的应用程序。一个例子是 CSCO (思科系统)。然后,当库存达到某个值时,我会使用该数据警告用户。它还需要每 30 秒刷新一次。
问题是我不知道如何获取数据!
有人有想法么?
我对Python编程很陌生。
我想做一个从谷歌金融获取股票价格的应用程序。一个例子是 CSCO (思科系统)。然后,当库存达到某个值时,我会使用该数据警告用户。它还需要每 30 秒刷新一次。
问题是我不知道如何获取数据!
有人有想法么?
该模块由Corey Goldberg提供。
程序:
import urllib
import re
def get_quote(symbol):
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('id="ref_694653_l".*?>(.*?)<', content)
if m:
quote = m.group(1)
else:
quote = 'no quote available for: ' + symbol
return quote
样品用法:
import stockquote
print stockquote.get_quote('goog')
更新:更改了正则表达式以匹配 Google 财经的最新格式(截至 2011 年 2 月 23 日)。这说明了依赖屏幕抓取时的主要问题。
至于现在(2015 年),谷歌金融 api 已被弃用。但是您可以使用 pypi 模块googlefinance。
安装 googlefinance
$pip install googlefinance
很容易得到当前的股票价格:
>>> from googlefinance import getQuotes
>>> import json
>>> print json.dumps(getQuotes('AAPL'), indent=2)
[
{
"Index": "NASDAQ",
"LastTradeWithCurrency": "129.09",
"LastTradeDateTime": "2015-03-02T16:04:29Z",
"LastTradePrice": "129.09",
"Yield": "1.46",
"LastTradeTime": "4:04PM EST",
"LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
"Dividend": "0.47",
"StockSymbol": "AAPL",
"ID": "22144"
}
]
谷歌财经是提供实时股票数据的来源。还有来自 yahoo 的其他 API,例如yahoo-finance,但它们对 NYSE 和 NASDAQ 股票延迟了 15 分钟。
import urllib
import re
def get_quote(symbol):
base_url = 'http://finance.google.com/finance?q='
content = urllib.urlopen(base_url + symbol).read()
m = re.search('id="ref_(.*?)">(.*?)<', content)
if m:
quote = m.group(2)
else:
quote = 'no quote available for: ' + symbol
return quote
我发现如果您使用 ref_(.*?) 并使用 m.group(2) 您将获得更好的结果,因为参考 id 从库存变为库存。
我建议使用 HTMLParser 来获取谷歌在它的 html 中放置的元标记的值
<meta itemprop="name"
content="Cerner Corporation" />
<meta itemprop="url"
content="https://www.google.com/finance?cid=92421" />
<meta itemprop="imageUrl"
content="https://www.google.com/finance/chart?cht=g&q=NASDAQ:CERN&tkr=1&p=1d&enddatetime=2014-04-09T12:47:31Z" />
<meta itemprop="tickerSymbol"
content="CERN" />
<meta itemprop="exchange"
content="NASDAQ" />
<meta itemprop="exchangeTimezone"
content="America/New_York" />
<meta itemprop="price"
content="54.66" />
<meta itemprop="priceChange"
content="+0.36" />
<meta itemprop="priceChangePercent"
content="0.66" />
<meta itemprop="quoteTime"
content="2014-04-09T12:47:31Z" />
<meta itemprop="dataSource"
content="NASDAQ real-time data" />
<meta itemprop="dataSourceDisclaimerUrl"
content="//www.google.com/help/stock_disclaimer.html#realtime" />
<meta itemprop="priceCurrency"
content="USD" />
使用这样的代码:
import urllib
try:
from html.parser import HTMLParser
except:
from HTMLParser import HTMLParser
class QuoteData:
pass
class GoogleFinanceParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.quote = QuoteData()
self.quote.price = -1
def handle_starttag(self, tag, attrs):
if tag == "meta":
last_itemprop = ""
for attr, value in attrs:
if attr == "itemprop":
last_itemprop = value
if attr == "content" and last_itemprop == "name":
self.quote.name = value
if attr == "content" and last_itemprop == "price":
self.quote.price = value
if attr == "content" and last_itemprop == "priceCurrency":
self.quote.priceCurrency = value
if attr == "content" and last_itemprop == "priceChange":
self.quote.priceChange = value
if attr == "content" and last_itemprop == "priceChangePercent":
self.quote.priceChangePercent = value
if attr == "content" and last_itemprop == "quoteTime":
self.quote.quoteTime = value
if attr == "content" and last_itemprop == "exchange":
self.quote.exchange = value
if attr == "content" and last_itemprop == "exchangeTimezone":
self.quote.exchangeTimezone = value
def getquote(symbol):
url = "http://finance.google.com/finance?q=%s" % symbol
content = urllib.urlopen(url).read()
gfp = GoogleFinanceParser()
gfp.feed(content)
return gfp.quote;
quote = getquote('CSCO')
print quote.name, quote.price
以防万一你想从雅虎拉数据......这是一个简单的功能。这不会从普通页面上刮取数据。我以为我在评论中有一个指向描述此页面的链接,但我现在看不到它 - 有一个魔术字符串附加到 URL 以请求特定字段。
import urllib as u
import string
symbols = 'amd ibm gm kft'.split()
def get_data():
data = []
url = 'http://finance.yahoo.com/d/quotes.csv?s='
for s in symbols:
url += s+"+"
url = url[0:-1]
url += "&f=sb3b2l1l"
f = u.urlopen(url,proxies = {})
rows = f.readlines()
for r in rows:
values = [x for x in r.split(',')]
symbol = values[0][1:-1]
bid = string.atof(values[1])
ask = string.atof(values[2])
last = string.atof(values[3])
data.append([symbol,bid,ask,last,values[4]])
return data
在这里,我找到了描述魔术字符串的链接: http: //cliffngan.net/a/13
http://docs.python.org/library/urllib.html 用于获取任意 URL。
除此之外,您最好查看一些以 JSON 格式提供数据的 Web 服务。
否则你必须自己实现解析等。
截屏 yahoo.com 以获取股票不太可能是通往成功的正确道路。
您可以从查看Google Finance APIs开始,尽管我没有看到 Python API 或包装器。看起来直接访问数据的唯一选项是 Java 和 JavaScript。如果您熟悉cURL并且它在您的系统上可用,您也可以使用它。