如何在python中创建股票报价获取应用程序

我是Python新手编程的新手。 我想创建一个从谷歌财务中获取股票价格的应用程序。一个例子是CSCO(Cisco Sytems)。然后我会使用该数据在库存达到某个值时警告用户。它还需要每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"
  }
]
Google财经是提供实时股票数据的来源。还有来自雅虎的其他API,如雅虎金融,但纽约证券交易所和纳斯达克股票的延迟时间为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获取元标记google在其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 API开始,但我没有看到Python API或包装器。看起来直接访问数据的唯一选择是Java和JavaScript。如果您熟悉cURL并且系统上可以使用cURL,也可以使用它。     
另一个好的起点是Google财经自己的API:http://code.google.com/apis/finance/您可以查看他们的财务小工具以获取一些示例代码。     

要回复问题请先登录注册