2017-05-31 97 views
-1

我正在尝试获取股票的当前价格,然后将其放入一个变量以运行if/else语句。我已经使用Google API检索当前的股票价格,但我无法弄清楚如何将其放入一个变量。谢谢!Python如何从字典中检索股票的当前股价并将其放入变量?

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") 
+0

数据已经由'json.dumps(getQuotes(symbols),indent = 2)'作为字典列表返回。你可以把它分配给一个像'list_of_quote = json.dumps(getQuotes(symbols))'这样的变量。但当然这不完全是你想要的。你的问题太模糊了。 –

+0

@AnthonyKong我如何从字典中获取最新的当前股票价格并将其存入变量?还有什么我可以添加,使问题更具体?对不起,我是Python新手! – Jacksoncw

+0

你应该澄清你的问题,把'从字典中获得最新的当前股票价格并将其放入一个变量'到你的问题 –

回答

0

你可以得到一个当前的股票价格从字典中,并把它变成一个变量,说price

的代码的最后一部分改为

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

但是非常不可靠的,因为如果价格顺序发生变化,您将得到一个不同股票的价格。

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

+0

如果我只输入一个股票代码,这是否始终有效? – Jacksoncw

+0

当然。当然,这意味着如果您需要多个价格,您需要更频繁地访问雅虎服务器。效率不高。这就是为什么更聪明的数据结构是更好的解决方案 –

+0

这工作!非常感谢! – Jacksoncw