Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly call data from Alpha Vantage using Python pandas-datareader 0.8

noobs on python here.

I am currently using python pandas-datareader 0.7 for some stock analysis.

With the update of pandas-datareader 0.8. It should be able to grab historical data from Alpha Vantage.

But I don't really understand how to use the api key (currently using yahoo and no key is needed)

From the documentation of pandas-datareader, I tried the same code (with my api key say ABC123 registered in alpha vantage) by replacing the ALPHAVANTAGE_API_KEY with ABC123

    import os

    from datetime import datetime

    import pandas_datareader.data as web

    df = web.DataReader("AAPL", "av-daily", start=datetime(2017, 2, 9),end=datetime(2017, 5, 24),api_key=os.getenv('ABC123')) 

    print(df)

I expected it outputs the historical data.
But it said "DataReader() got an unexpected keyword argument 'api_key'"

How do I correctly use the api key so that I can grab the data?

like image 617
Max Cheung Avatar asked Sep 06 '25 03:09

Max Cheung


1 Answers

Hey do you have to use pandas datareader? 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. 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

The way you would use the above function is as follows:

df = request_stock_price_hist('IBM', 'REPLACE_YOUR_TOKEN')
df.to_csv('output.csv')
like image 146
hklchung Avatar answered Sep 07 '25 21:09

hklchung