How to use the Alpha Vantage API directly from Python

shanlodh picture shanlodh · Jan 3, 2018 · Viewed 24.5k times · Source

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

Answer

I_got_a_guy picture I_got_a_guy · May 3, 2018

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.