How to use the Alpha Vantage API directly from Python
Asked Answered
C

7

5

I've been using Romel Torres' alpha_vantage package but would also like to use the Alpha Vantage API directly from python (gives greater functionality) with package requests as described here CALL with CURL an API through Python:

import requests
import alpha_vantage

API_URL = "https://www.alphavantage.co/query"

data = {
    "function": "TIME_SERIES_DAILY",
    "symbol": "NIFTY",
    "outputsize": "compact",
    "datatype": "csv"
    "apikey": "XXX",
    }
response = requests.get(API_URL, data)
print(response.json())[/code]

But am getting the following error message in the dict returned:

{'Error Message': 'Invalid API call. Please retry or visit the documentation (https://www.alphavantage.co/documentation/) for TIME_SERIES_DAILY.'}

And with requests.post() the outcome is:

response = requests.post(API_URL, data)
{'detail': 'Method "POST" not allowed.'}

I've re-checked the documentation and am following all the required API parameters. Appreciate some help re what I might be missing here and what the correct call would be and/or any other alternative approach. Thanks

Coxa answered 3/1, 2018 at 5:57 Comment(4)
page which convert curl to python requestsEquestrienne
you have to get unique API key to work with API - so you have to register on this portal.Equestrienne
see in doc which parameters you have to use - function, symbol, interval, apikey. You forgot interval.Equestrienne
@furas: there's no 'interval' field for TIME_SERIES_DAILY (the interval is clear in the name of the function) and I have a API key that's just hidden with the 'XXX' in my OP. As mentioned above, I'm already using alpha_vantage package and so am registered on the portalCoxa
A
8

The hint is in the error. Change the method of your request from post to get:

response = requests.get(API_URL, params=data)

And use a ticker symbol that exists as data for Alpha Vantage. NIFTY is not a stock - it's an index. If you try your code with MSFT, it will work.

Apocrine answered 3/5, 2018 at 21:0 Comment(0)
B
5

This is how I obtain daily stocks time series from Alpha Vantage without using any wrapper. After receiving, I convert the data into a pandas data frame for further processing.

    import requests
    import pandas as pd

    API_URL = "https://www.alphavantage.co/query" 
    symbol = 'SMBL'

    data = { "function": "TIME_SERIES_DAILY", 
    "symbol": symbol,
    "outputsize" : "full",
    "datatype": "json", 
    "apikey": "your_api_key" } 

    response = requests.get(API_URL, data) 
    response_json = response.json() # maybe redundant

    data = pd.DataFrame.from_dict(response_json['Time Series (Daily)'], orient= 'index').sort_index(axis=1)
    data = data.rename(columns={ '1. open': 'Open', '2. high': 'High', '3. low': 'Low', '4. close': 'Close', '5. adjusted close': 'AdjClose', '6. volume': 'Volume'})
    data = data[[ 'Open', 'High', 'Low', 'Close', 'AdjClose', 'Volume']]
    data.tail() # check OK or not
Burdelle answered 3/12, 2019 at 16:5 Comment(2)
When I try running this I get: Traceback (most recent call last): File "after.py", line 16, in <module> data = pd.DataFrame.from_dict(response_json['Time Series (Daily)'], orient= 'index').sort_index(axis=1) KeyError: 'Time Series (Daily)' Carothers
See the official documentation - alphavantage.co/documentation - very usefulBurdelle
S
2
import requests
import alpha_vantage
import json


API_URL = "https://www.alphavantage.co/query" 
symbols = ['QCOM',"INTC","PDD"]

for symbol in symbols:
        data = { "function": "TIME_SERIES_INTRADAY", 
        "symbol": symbol,
        "interval" : "60min",       
        "datatype": "json", 
        "apikey": "XXX" } 
        response = requests.get(API_URL, data) 
        data = response.json()
        print(symbol)
        a = (data['Time Series (60min)'])
        keys = (a.keys())
        for key in keys:
                print(a[key]['2. high'] + " " + a[key]['5. volume'])
Scurf answered 27/7, 2018 at 16:13 Comment(0)
B
1

First

You are using 'csv' datatype.

"datatype": "csv"

But you are trying to print in JSON format

print(response.json())

Second

try using get method as suggested

Bothwell answered 20/5, 2018 at 1:18 Comment(0)
C
0

It looks like you have an extra comma (,) after your last element in data.

Czarism answered 14/6, 2019 at 12:22 Comment(1)
That's allowed in Python though, there is no issue with it.Iconoclasm
C
0
import requests
import alpha_vantage

API_URL = "https://www.alphavantage.co/query"
data = {
    "function": "TIME_SERIES_DAILY",
    "symbol": "AAPL",
 "outputsize": "compact",
    "apikey": "your key"
    }

response = requests.get(API_URL, params=data)
print(response.json())
Cropeared answered 14/6, 2020 at 10:56 Comment(2)
Providing some context would help to understand how your answer works. Please consider How to AnswerSquirm
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Transsonic
M
0

This is how I do it without any wrapper. You can use this code 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 this 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')
Muscadine answered 7/9, 2020 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.