How to use the Alpha Vantage API directly from Python
Solution 1
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.
Solution 2
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
Solution 3
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'])
Solution 4
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
shanlodh
Updated on July 20, 2022Comments
-
shanlodh almost 2 years
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