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

发布于 2024-10-18 20:05:36 字数 293 浏览 1 评论 0原文

我对 Python 编程还很陌生。

我想要制作一个从 google Finance获取股票价格的应用程序。 CSCO(思科系统)就是一个例子。然后,我将使用该数据在股票达到特定值时警告用户。它还需要每 30 秒刷新

问题是我不知道如何获取数据!

有人有什么想法吗?

I'm quite new to programming in Python.

I want to make an application which will fetch stock prices from google finance. One example is CSCO (Cisco Sytems). I would then use that data to warn the user when the stock reaches a certain value. It also needs to refresh every 30 seconds.

The problem is I dont have a clue how to fetch the data!

Anyone have any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

浅听莫相离 2024-10-25 20:05:36

该模块由 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 日)。这说明了依赖屏幕抓取时的主要问题。

This module comes courtesy of Corey Goldberg.

Program:

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

Sample Usage:

import stockquote
print stockquote.get_quote('goog')

Update: Changed the regular expression to match Google Finance's latest format (as of 23-Feb-2011). This demonstrates the main issue when relying upon screen scraping.

几味少女 2024-10-25 20:05:36

截至目前(2015 年),Google 财经 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 Finance是提供实时股票数据的来源。还有其他来自yahoo的API,例如yahoo-finance,但延迟15分钟适用于纽约证券交易所和纳斯达克股票。

As for now (2015), the google finance api is deprecated. But you may use the pypi module googlefinance.

Install googlefinance

$pip install googlefinance

It is easy to get current stock price:

>>> 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 finance is a source that provides real-time stock data. There are also other APIs from yahoo, such as yahoo-finance, but they are delayed by 15min for NYSE and NASDAQ stocks.

会傲 2024-10-25 20:05:36
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 会随着股票的变化而变化。

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

I find that if you use ref_(.*?) and use m.group(2) you will get a better result as the reference id changes from stock to stock.

写给空气的情书 2024-10-25 20:05:36

我建议使用 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

I suggest using the HTMLParser to get the value of the meta tags google places in it's 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" />

With code like this:

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
旧时浪漫 2024-10-25 20:05:36

以防万一您想从雅虎提取数据...这是一个简单的函数。这不会从普通页面上刮掉数据。我以为我有一个链接到评论中描述这一点的页面,但我现在看不到它 - 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

Just in case you want to pull data from Yahoo... Here is a simple function. This does not scrape data off a normal page. I thought I had a link to the page describing this in the comments, but I do not see it now - there is a magic string appended to the URL to request specific fields.

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

Here, I found the link that describes the magic string:
http://cliffngan.net/a/13

毁虫ゝ 2024-10-25 20:05:36

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

除此之外,您应该更好地查看一些提供 JSON 格式数据的 Web 服务。

否则你必须自己实现解析等。

通过抓取 yahoo.com 的屏幕来获取股票不太可能是成功的正确途径。

http://docs.python.org/library/urllib.html
for fetching arbitrary URLs.

Apart from that you should better look a some web service providing the data in JSON format.

Otherwise you have to implement parsing etc. on your own.

Screenscrapping yahoo.com for getting the stocks is unlikely the right road to success.

时光清浅 2024-10-25 20:05:36

您可以首先查看 Google Finance API,尽管我没有看到 Python API或包装纸。看起来直接访问数据的唯一选择是 Java 和 JavaScript。如果您熟悉 cURL 并且可用,您还可以使用 cURL在您的系统上。

You can start by looking at the Google Finance APIs, although I don't see a Python API or wrapper. It looks like the only options for accessing the data directly are Java and JavaScript. You can also use cURL if you're familiar with it and it's available on your system.

甜妞爱困 2024-10-25 20:05:36

另一个不错的起点是 Google 财经自己的 API:http://code.google.com/apis/finance / 您可以查看他们的金融小工具一些示例代码。

Another good place to start is Google Finance's own API: http://code.google.com/apis/finance/ You can look at their finance gadgets for some example code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文