1

According to the docs for this Alpha Vantage python wrapper, https://github.com/RomelTorres/alpha_vantage, you can output the response to CSV using the following code.

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

But there are no examples of using this csv format within the documentation (he mainly writes to using Pandas as output). How would you write this csv output to a file?

billv1179
  • 323
  • 5
  • 15

2 Answers2

2

This is more of a question of how to write a csv object to a file. See here for more information.

However, how to specifically do it with that wrapper:

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

Then we just make a csv writer object and write each row to the file we want, named aapl.csv here:

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

You use the dialect='excel' because the row object is a list, and the write defaults to accept strings.

Patrick Collins
  • 5,621
  • 3
  • 26
  • 64
0

Hey instead of using that library, below is a function I wrote 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 my 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 this function is like this:

df = request_stock_price_hist('IBM', 'REPLACE_YOUR_TOKEN')
df.to_csv('output.csv')
Dharman
  • 30,962
  • 25
  • 85
  • 135
hklchung
  • 41
  • 4