从雅虎财经中读取股票市值

时间:2015-09-22 20:09:41

标签: python arrays loops yahoo-finance ticker

import urllib.request, urllib.error

m = 0 
web ='x'  # This reads the stock value for "United States Steel Corp."
t =str(web)
try: f = urllib.request.urlopen('http://finance.yahoo.com/q?s='+ t +'')
except ValueError:
    print(str('Error'))
    m = 1
    pass

if m == 0:
    urlText = f.read().decode('utf-8')

    if urlText.find('<span id="yfs_l84_'+ t +'">'):
        cat = urlText[urlText.find('<span id="yfs_l84_'+ t +'">'):urlText.find('<span id="yfs_l84_'+ t +'">')+30]
        dog = cat.strip('</span></span>')
        dog = cat.strip('<span id="yfs_l84_'+ t +'">')
        print('United States Steel Corp. = ', dog)
    else:print("---> Couldn't read URL text")

此程序正在读取特定公司缩写的库存值。在我的第3行中,它显示web ='x'

我想要实现的是,如果我在分配的web变量中输入更多缩写,那么我应该能够显示所有输入缩写的库存值。我的意思是:web = 'x', 'y', 'z'

我不确定如何在我的程序中实现它。我相信我需要创建一个数组,然后使用for循环进行循环。但是,我不确定。

谢谢!

2 个答案:

答案 0 :(得分:1)

Python中的数组称为列表!你可以这样做:

web = ['x','y','z']

并循环浏览它们,你可以这样:

for i in web:
    #do stuff

此链接也可以帮助您学习Python:Python Track in CodeAcademy

编辑:OP正在寻找字典。

companies = {
        'Company A' : 15,
        'Company B' : 6 
        }

在字典中,您可以按索引访问元素:companies['Company A']将返回其值6

答案 1 :(得分:0)

您可以通过将符号与+(例如AAPL + GOOG + MSFT)相关联来通过YFinance API请求报价。要加入像这样的符号列表,'+'.join(symbols)。然后,您需要附加&f=...。我使用&f=a来获得卖价。

import urllib

symbols = ['MSFT', 'AAPL', 'GOOG']

# To request ask (delayed) for all symbols.
url_req = ("http://finance.yahoo.com/d/quotes.csv?s={symbols}&f=a"
           .format(symbols="+".join(symbols)))

prices = urllib.request.urlopen(url_req).read().decode().split('\n')

# Use dictionary comprehension together with zip to get dict of values.
ask_quotes = {symbol: quote for symbol, quote in zip(symbols, prices)}

>>> url_req
'http://finance.yahoo.com/d/quotes.csv?s=MSFT+AAPL+GOOG&f=a'

>>> ask_quotes
{'AAPL': '114.60', 'GOOG': '614.920', 'MSFT': '43.93'}