1

根据此 Alpha Vantage python 包装器的文档https://github.com/RomelTorres/alpha_vantage,您可以使用以下代码将响应输出到 CSV。

ts = TimeSeries(key='YOUR_API_KEY',output_format='csv')

但是文档中没有使用这种 csv 格式的示例(他主要写到使用 Pandas 作为输出)。您将如何将此 csv 输出写入文件?

4

2 回答 2

2

这更多是关于如何将 csv 对象写入文件的问题。请参阅此处了解更多信息。

但是,如何使用该包装器专门执行此操作:

from alpha_vantage.timeseries import TimeSeries
# Your key here
key = 'yourkeyhere'
ts = TimeSeries(key,  output_format='csv')

# remember it returns a tuple, the first being a _csv.reader object
aapl_csvreader, meta = ts.get_daily(symbol='AAPL')

然后我们只需创建一个 csv writer 对象并将每一行写入我们想要的文件,这里命名为 aapl.csv:

with open('aapl.csv', 'w') as write_csvfile:
    writer = csv.writer(write_csvfile, dialect='excel')
    for row in aapl_csvreader:
        writer.writerow(row)

您使用 dialect='excel' 因为row对象是一个列表,并且写入默认接受字符串。

于 2019-09-13T16:47:42.593 回答
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')
于 2020-09-07T08:30:58.303 回答