Alpha Vantage is today one of the best sources to get financial data. It's not just for cryptos. Also offers Stock prices, Forex rates and other indicators.
Alpha Vantage strong selling point is its simplicity. It has a couple of simple to use methods that give you access to prices with just a few requests. The limitation is that it doesn't offer data "per exchange". That is, you can't access Bitcoin prices in both Coinbase and Bitstamp (for example). There's only one price for Bitcoin (probably a weighted average).
import os
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
API Authentication¶
Before we begin, you MUST request a free API key from Alpha Vantage's official site: https://www.alphavantage.co/support/#api-key
After getting the API Key, you can set it as an environment variable (in the project edit page) or just replace it where it says 'YOUR-API-KEY'.
AV_API_KEY = os.environ.get('ALPHAVANTAGE_API_KEY', 'YOUR-API-KEY')
assert AV_API_KEY != 'YOUR-API-KEY'
we'll use this API Key in each request sending it as a regular parameter.
Supported cryptos and fiat currencies¶
With this project I've included 2 csv files with the cryptocurrencies supported by Alpha Vantage. Fork it to see it by yourself. Here's a quick summary:
cryptos = pd.read_csv('digital_currency_list.csv')
cryptos.head()
cryptos[cryptos['currency name'].str.contains('Bitcoin')]
cryptos[cryptos['currency name'].str.contains('Ethereum')]
fiat = pd.read_csv('physical_currency_list.csv')
fiat.head()
fiat[fiat['currency code'] == 'USD']
Realtime exchange rates¶
The simplest function exposed by Alpha Vantage API is CURRENCY_EXCHANGE_RATE
, which returns the current exchange rate (the price) for a given crypto. Here's an example with Bitcoin:
resp = requests.get('https://www.alphavantage.co/query', params={
'function': 'CURRENCY_EXCHANGE_RATE',
'from_currency': 'BTC',
'to_currency': 'USD',
'apikey': AV_API_KEY
})
resp
resp.json()
And here's one for Ethereum:
resp = requests.get('https://www.alphavantage.co/query', params={
'function': 'CURRENCY_EXCHANGE_RATE',
'from_currency': 'ETH',
'to_currency': 'USD',
'apikey': AV_API_KEY
})
resp
resp.json()
Cryptos' daily data¶
From the docs:
This API returns the daily historical time series for a digital currency (e.g., BTC) traded on a specific market (e.g., CNY/Chinese Yuan), refreshed daily at midnight (UTC).
The function
to use in this case is DIGITAL_CURRENCY_DAILY
.
resp = requests.get('https://www.alphavantage.co/query', params={
'function': 'DIGITAL_CURRENCY_DAILY',
'symbol': 'BTC',
'market': 'USD',
'apikey': AV_API_KEY
})
resp
doc = resp.json()
We can see the metadata associated with the response:
doc['Meta Data']
This endpoint returns more than 4 years of data. For example, Jan 1st:
doc['Time Series (Digital Currency Daily)']['2019-01-01']
Feb 2nd:
doc['Time Series (Digital Currency Daily)']['2019-02-01']
There are repeated values because the result will always include USD information. Now, I'll turn it into a pandas DataFrame
to visualize it:
df = pd.DataFrame.from_dict(doc['Time Series (Digital Currency Daily)'], orient='index', dtype=np.float)
df.head()
And we'll do some processing to "clean it" a little bit. First step is get rid of repeated columns:
[c for c in df.columns.values if 'b.' in c]
df.drop(columns=[c for c in df.columns.values if 'b.' in c], inplace=True)
df.head()
And now turn the index into a DateTime index:
df.reset_index(inplace=True)
df.head()
df['index'] = pd.to_datetime(df['index'])
df.set_index('index', inplace=True)
df.head()
df.info()
We can now visualize the prices:
df.plot(figsize=(14, 7))
Utility function¶
I've written a small function to simplify the process of pulling the daily data, let's use it to get Ether prices:
from utils import get_daily_data
df = get_daily_data(AV_API_KEY, 'ETH')
df.head()
df['4a. close (USD)'].plot(figsize=(14, 7))
A simple multi-currencies experiment¶
With the get_daily_data
it's now simple to pull multiple currencies and work them together, here's a quick example using Bitcoin (BTC), Bitcoin Cash (BCH) and Bitcoin Gold (BTG):
btc = get_daily_data(AV_API_KEY, 'BTC')
bch = get_daily_data(AV_API_KEY, 'BCH')
btg = get_daily_data(AV_API_KEY, 'BTG')
df = pd.DataFrame(index=btc.index)
df = pd.concat([btc['4a. close (USD)'], bch['4a. close (USD)'], btg['4a. close (USD)']], axis=1, join='inner')
df.columns = ['BTC', 'BCH', 'BTG']
df.head()
Plotting them:
df[['BTG', 'BCH']].plot(figsize=(14, 7))
df[['BTC', 'BCH']].plot(figsize=(14, 7))
(df['BTC'] / df['BCH']).plot(figsize=(14, 7))
(df['BCH'] / df['BTG']).plot(figsize=(14, 7))
Stock Prices¶
I started this notebook with Cryptos because it was included in guide about accessing crypto data from different APIs. But Alpha Vantage also includes Stocks:
resp = requests.get('https://www.alphavantage.co/query', params={
'function': 'DIGITAL_CURRENCY_DAILY',
'symbol': 'BTC',
'market': 'USD',
'apikey': AV_API_KEY
})