如何直接从Python使用Alpha Vantage API

时间:2018-01-03 05:57:54

标签: python api python-requests alphavantage

我一直在使用Romel Torres' alpha_vantage包,但也希望直接从python使用Alpha Vantage API(提供更多功能),包括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]

但是在返回的dict中收到以下错误消息:

  

{'错误消息':' API调用无效。请重试或访问TIME_SERIES_DAILY的文档(https://www.alphavantage.co/documentation/)。'}

使用requests.post()结果是:

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

我已经重新检查了文档并遵循了所有必需的API参数。感谢我在这里可能缺少的一些帮助以及正确的呼叫和/或任何其他替代方法。谢谢

7 个答案:

答案 0 :(得分:3)

提示是错误的。将您的请求方法从post更改为get

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

并使用作为Alpha Vantage数据存在的股票代码。 NIFTY不是股票 - 它是一个指数。如果您使用MSFT尝试使用代码,则可以使用。

答案 1 :(得分:1)

第一

您正在使用' csv'数据类型。

  

"数据类型":" csv"

但您正尝试以JSON格式打印

print(response.json())

第二

尝试按建议使用get方法

答案 2 :(得分:1)

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'])

答案 3 :(得分:1)

在数据中的最后一个元素之后,似乎还有一个逗号(,

答案 4 :(得分:0)

这是我无需使用任何包装程序即可从Alpha Vantage获取每日股票时间序列的方式。接收后,我将数据转换为熊猫数据帧以进行进一步处理。

    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

答案 5 :(得分: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())

答案 6 :(得分:0)

这是我没有任何包装的方法。您可以使用此代码轻松地从Alpha Vantage中提取历史股价。您要做的就是插入您的符号和令牌。有关提取Alpha Vantage数据的更多功能,请随时查看以下链接: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

使用上述功能的方式如下:

df = request_stock_price_hist('IBM', 'REPLACE_YOUR_TOKEN')
df.to_csv('output.csv')