Python 如何从字典中检索股票的最后当前股票价格并将其放入变量中?



我正在尝试获取股票的当前价格,然后将其放入以上的变量,如果/else语句上的语句。我已经使用Google API检索了当前的股票价格,但是我无法弄清楚如何将其放入变量中。谢谢!

import json
import sys
try:
    from urllib.request import Request, urlopen
except ImportError:  #python 2
    from urllib2 import Request, urlopen
googleFinanceKeyToFullName = {
    u'id'     : u'ID',
    u't'      : u'StockSymbol',
    u'e'      : u'Index',
    u'l'      : u'LastTradePrice',
    u'l_cur'  : u'LastTradeWithCurrency',
    u'ltt'    : u'LastTradeTime',
    u'lt_dts' : u'LastTradeDateTime',
    u'lt'     : u'LastTradeDateTimeLong',
    u'div'    : u'Dividend',
    u'yld'    : u'Yield'
}
def buildUrl(symbols):
    symbol_list = ','.join([symbol for symbol in symbols])
    #a deprecated but still active & correct api
    return 'http://finance.google.com/finance/info?client=ig&q=' 
        + symbol_list
def request(symbols):
    url = buildUrl(symbols)
    req = Request(url)
    resp = urlopen(req)
    #remove special symbols such as the pound symbol
    content = resp.read().decode('ascii', 'ignore').strip()
    content = content[3:]
    return content
def replaceKeys(quotes):
    global googleFinanceKeyToFullName
    quotesWithReadableKey = []
    for q in quotes:
        qReadableKey = {}
        for k in googleFinanceKeyToFullName:
            if k in q:
                qReadableKey[googleFinanceKeyToFullName[k]] = q[k]
        quotesWithReadableKey.append(qReadableKey)
    return quotesWithReadableKey
def getQuotes(symbols):
    if type(symbols) == type('str'):
        symbols = [symbols]
    content = json.loads(request(symbols))
    return replaceKeys(content);
if __name__ == '__main__':
    try:
        symbols = sys.argv[1]
    except:
        symbols = "GOOG,AAPL,MSFT,AMZN,SBUX"
    symbols = symbols.split(',')
    try:
        print(json.dumps(getQuotes(symbols), indent=2))
    except:
        print("Fail")

您可以从字典中获取最后的当前股票价格,然后将其放入变量中,例如 price

通过将代码的最后一部分更改为

 try:
      quotes = getQuotes(symbols)
      price = quotes[-1]['LastTradePrice']  # -1 means last in a  list
      print(price)
  except Exception as e:
      print(e)

但这是非常不可靠的,因为如果价格更改,您将获得其他股票的价格。

您应该做的是学习如何定义合适的RO解决您的问题的数据结构。

最新更新