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

jww
  • 97,681
  • 90
  • 411
  • 885
shanlodh
  • 1,015
  • 2
  • 11
  • 30
  • page which [convert curl to python requests](https://curl.trillworks.com/) – furas Jan 03 '18 at 10:21
  • you have to get unique `API key` to work with API - so you have to register on this portal. – furas Jan 03 '18 at 10:22
  • see in doc which parameters you **have to** use - `function`, `symbol`, `interval`, `apikey`. You forgot `interval`. – furas Jan 03 '18 at 10:29
  • @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 portal – shanlodh Jan 03 '18 at 11:42

7 Answers7

7

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.

I_got_a_guy
  • 86
  • 1
  • 4
4

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
  • When I try running this I get: ```Traceback (most recent call last): File "after.py", line 16, in data = pd.DataFrame.from_dict(response_json['Time Series (Daily)'], orient= 'index').sort_index(axis=1) KeyError: 'Time Series (Daily)' ``` – HMLDude Mar 26 '20 at 05:33
  • See the official documentation - https://www.alphavantage.co/documentation/ - very useful – Serhii Kushchenko Jul 15 '21 at 08:22
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'])
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

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

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

double-beep
  • 5,031
  • 17
  • 33
  • 41
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())
4b0
  • 21,981
  • 30
  • 95
  • 142
  • Providing some context would help to understand how your answer works. Please consider [answer] – dboy Jun 14 '20 at 11:02
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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. – double-beep Jun 14 '20 at 11:26
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')
hklchung
  • 41
  • 4