Alpha Vantage - Isolate Stock Price

1.4k Views Asked by At

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', '}})
4

There are 4 best solutions below

0
On BEST ANSWER

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.

0
On

Thanks - I hadn't considered that as a possibility, i.e., a dict within a tuple. I am new to both Linux and Python so I guess that's kind of an amateur error. Nevertheless, I really appreciate the time taken to respond. I hope to pay that back in the near future.

Just BTW, I notice w/Python if I code something wrong I sometimes don't get an error - exactly. For example, if I issue a print statement to debug and do not reference the above item correctly, the print command doesn't execute but I do not get an error code. In fact, code following the offensive print statement might also not execute; I might simply go to EOJ. Does that make sense? NB - I haven't compiled yet; still running in interpretive mode.

0
On

Hey below is a function I wrote to easily extract historical stock prices from Alpha Vantage. All you have to do is plug in your symbol and token. If you want the stock price for a specific day, then you will need to filter for that day in the result dataframe. For more functions on extracting Alpha Vantage data, feel free to check out my link: https://github.com/hklchung/StockPricePredictor/blob/master/2020/alphavantage_funcs.py.

def request_stock_price_hist(symbol, token, sample = False):
    if sample == False:
        q_string = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={}&outputsize=full&apikey={}'
    else:
        q_string = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={}&apikey={}'

    print("Retrieving stock price data from Alpha Vantage (This may take a while)...")
    r = requests.get(q_string.format(symbol, token))
    print("Data has been successfully downloaded...")
    date = []
    colnames = list(range(0, 7))
    df = pd.DataFrame(columns = colnames)
    print("Sorting the retrieved data into a dataframe...")
    for i in tqdm(r.json()['Time Series (Daily)'].keys()):
        date.append(i)
        row = pd.DataFrame.from_dict(r.json()['Time Series (Daily)'][i], orient='index').reset_index().T[1:]
        df = pd.concat([df, row], ignore_index=True)
    df.columns = ["open", "high", "low", "close", "adjusted close", "volume", "dividend amount", "split cf"]
    df['date'] = date
    return df
0
On

The best way I found to get the price data is this

from alpha_vantage.timeseries import TimeSeries
import pandas as pd
import time
import random
import numpy as np
import math
import datetime as dt
import requests
import os
import json

stock_ticker="TSLA"
apikey=""
ts = TimeSeries (key=apikey, output_format = "pandas")



    ### STOCK TIME SERIES > DAILY ADJUSTED ###
        # Date / Open / High / Low / Close / Adjusted Close / Volume / Dividend / Split
data_daily, meta_data = ts.get_daily_adjusted(symbol=stock_ticker, outputsize ='full')
        # data_daily['column name'][row number]
data_daily_lastOpenPrice = data_daily['1. open'][0]
data_daily_lastHighPrice = data_daily['2. high'][0]
data_daily_lastLowPrice = data_daily['3. low'][0]
data_daily_lastAdjustedClosingPrice = data_daily['5. adjusted close'][0]
data_daily_lastTradingVolume = data_daily['6. volume'][0]
data_daily_lastDividendAmount = data_daily['7. dividend amount'][0]