2011-02-22 51 views
12

我很新編程Python如何在python中創建股票報價提取應用程序

我想提出申請google finance獲取股票價格。一個例子是CSCO (思科系統)。然後,我會使用該數據當股票達到某個值時警告用​​戶。它還需要每30秒更新一次

問題是我沒有線索如何獲取數據!

任何人有任何想法?

回答

15

該模塊來自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') 

更新:改變了正則表達式匹配谷歌財經的最新格式(如23 - 2月 - 2011年)。這表明依靠屏幕抓取時的主要問題。

+0

只需複製粘貼此代碼。但輸出說`沒有報價可用於:goog`。 – Dharmit 2011-02-23 06:21:57

+0

謝謝達爾米特。我暫時沒有使用過這段代碼,但你說得對 - Google財經有一個新的輸出格式。我更新了代碼,現在它應該可以工作。 – 2011-02-23 15:57:51

+0

工程像魅力。感謝代碼。 :) – Dharmit 2011-02-24 05:04:21

0

http://docs.python.org/library/urllib.html 用於獲取任意URL。

除此之外,您應該更好地看看一些提供JSON格式數據的Web服務。

否則你必須自己實現解析等。

抓拍yahoo.com獲取股票不太可能成功的正確道路。

0

您可以先看Google Finance APIs,儘管我沒有看到Python API或包裝。它看起來像直接訪問數據的唯一選擇是Java和JavaScript。如果您熟悉它並且它可在您的系統上使用,您也可以使用use cURL

1

以防萬一你想從雅虎拉數據...這是一個簡單的功能。這不會從常規頁面中刪除數據。我以爲我有一個鏈接到描述這個在評論中的頁面,但我現在沒有看到它 - 有一個魔術字符串附加到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

2
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 

我發現,如果你使用的參考_和使用m.group(2)你會(*?)當參考ID從庫存變爲庫存時獲得更好的結果。

2

我建議使用的HTMLParser得到meta標籤的價值谷歌的地方,在它的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 
13

至於現在(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" 
    } 
] 

谷歌財經是提供實時股票數據的來源。雅虎還有其他API,例如yahoo-finance,但是對於紐約證券交易所和納斯達克股票,它們延遲了15分鐘。