Search code examples
python-3.xalphaalpha-vantage

Alpha Vantage - Isolate Stock Price


Using Python I can access most of the Alpha Vantage APIs and get the results either as a tuple or a dict. What I want is just the stock price at a point in time. With "global quote", for example, I get all the data but cannot parse or divide the tuple / dict into the individual items.

Has anyone done this? I'd be grateful to see the code.

The API returns the following data; it is type dict with len 1. What I need is the price (108.29) in a normal floating point variable.

 (' data ', {u'Global Quote': {u'05. price': u'108.2900', u'08. previous close': u'107.2800', u'10. change percent': u'0.9415%', u'03. high': u'108.8800', u'07. latest trading day': u'2018-11-16', '}})

Solution

  • The data you have given appears to have a slight problem at the end (there is a trailing comma and open quote). Assuming that the actual data does not have this problem, you could extract the price into a float variable as follows:

    data = (' data ', {u'Global Quote': {u'05. price': u'108.2900', u'08. previous close': u'107.2800', u'10. change percent': u'0.9415%', u'03. high': u'108.8800', u'07. latest trading day': u'2018-11-16'}})
    price = float(data[1]['Global Quote']['05. price'])
    print(price)
    

    This would display the price as:

    108.29
    

    The API appears to be returing a tuple which consists of the word data and then a dictionary holding all the values. So first use [1] to access the dictionary. The Global Quote entry itself is a dictionary.