-1

I am trying to obtain a stock's current price, and then put it into a variable to run if / else statements on. I have used the Google API to retrieve current stock prices, but I am unable to figure out how to put it into a variable. Thanks!

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")
Jacksoncw
  • 23
  • 4
  • The data is already returned by `json.dumps(getQuotes(symbols), indent=2)` as a list of dictionary. You can assign it to a variable like `list_of_quote = json.dumps(getQuotes(symbols))`. But of course it is not exactly what you want. Your question is too vague. – Anthony Kong May 31 '17 at 00:43
  • @AnthonyKong How would I get the last current stock price from the dictionary and put it into a variable? Also is there anything I can add to make the question more specific? Sorry I'm new to Python! – Jacksoncw May 31 '17 at 00:51
  • You should clarify your question by putting in the requirement `get the last current stock price from the dictionary and put it into a variable` into your question – Anthony Kong May 31 '17 at 01:03
  • It is better. It is always a good idea to follow this SO guideline: https://stackoverflow.com/help/how-to-ask The more specific your question is, the less likely you get downvoted. – Anthony Kong May 31 '17 at 04:42

1 Answers1

0

You can get the last current stock price from the dictionary and put it into a variable, say price,

by changing the last part of the code to

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

but it is very unreliable because if the order of prices is changed, you will get a price for a different stock.

What you should do is to learn how to define a data structure that's suitable ro solve your problem.

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • If I only inputted one stock symbol, would this always work? – Jacksoncw May 31 '17 at 04:13
  • Surely. Of course it means you will need to hit the yahoo server more often if you need multiple prices. Not very efficient. That's why a smarter data structure is a better solution – Anthony Kong May 31 '17 at 04:15