Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Created March 15, 2018 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranaroussi/2a49c827c7b742bdd38e3547f7c71261 to your computer and use it in GitHub Desktop.
Save ranaroussi/2a49c827c7b742bdd38e3547f7c71261 to your computer and use it in GitHub Desktop.
API client for AlphaVantage (stocks only atm) - https://www.alphavantage.co
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
from urllib.parse import urlencode
class AlphaVantage(object):
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://www.alphavantage.co/query"
def __get_csv(self, function, **kwargs):
return pd.read_csv("%s?apikey=%s&function=%s&datatype=csv&%s" % (
self.base_url, self.api_key, function, urlencode(kwargs)
))
def __get_ohlc(self, interval, symbols, full, group_by, auto_adjust):
if isinstance(symbols, str):
symbols = [symbols]
api_call = "TIME_SERIES_DAILY_ADJUSTED"
if isinstance(interval, int):
auto_adjust = False
interval = str(interval)+"min"
api_call = "TIME_SERIES_INTRADAY"
elif isinstance(interval, str) and interval.upper() == "D":
api_call = "TIME_SERIES_DAILY_ADJUSTED"
elif isinstance(interval, str) and interval.upper() == "W":
api_call = "TIME_SERIES_WEEKLY_ADJUSTED"
elif isinstance(interval, str) and interval.upper() == "M":
api_call = "TIME_SERIES_MONTHLY_ADJUSTED"
dfs = {}
for symbol in symbols:
df = self.__get_csv(function=api_call, symbol=symbol, interval=interval,
outputsize=("full" if full else "compact"))
df["timestamp"] = pd.to_datetime(df["timestamp"])
df.set_index(["timestamp"], inplace=True)
df.sort_index(inplace=True)
df["volume"] = df["volume"].astype(int)
if str(interval).upper() not in ["W", "M"]:
df.rename(columns={
"dividend_amount": "dividend",
"split_coefficient": "split"
}, inplace=True)
if auto_adjust:
if "adjusted close" in df.columns:
df["adjusted_close"] = df["adjusted close"]
ratio = df["close"] / df["adjusted_close"]
df["adjusted_open"] = df["open"] / ratio
df["adjusted_high"] = df["high"] / ratio
df["adjusted_low"] = df["low"] / ratio
df.drop(
["open", "high", "low", "close"],
axis=1, inplace=True)
df.rename(columns={
"adjusted_open": "open",
"adjusted_high": "high",
"adjusted_low": "low",
"adjusted_close": "close"
}, inplace=True)
if str(interval).upper() == "D":
dfs[symbol] = df[["open","high","low","close","volume","dividend","split"]]
else:
dfs[symbol] = df[["open","high","low","close","volume"]]
if len(symbols) == 1:
return dfs[symbol]
# combine data
data = pd.concat(dfs.values(), axis=1, keys=dfs.keys())
if group_by == "column":
data.columns = data.columns.swaplevel(0, 1)
return data
def get_quotes(self, symbols):
if isinstance(symbols, list):
symbols = ",".join(symbols)
return self.__get_csv(function="BATCH_STOCK_QUOTES", symbols=symbols)
def get_intraday(self, symbols, interval=1, full=False, group_by="column", auto_adjust=True):
return self.__get_ohlc(interval, symbols, full, group_by, auto_adjust)
def get_daily(self, symbols, full=False, group_by="column", auto_adjust=True):
return self.__get_ohlc("D", symbols, full, group_by, auto_adjust)
def get_weekly(self, symbols, full=False, group_by="column", auto_adjust=True):
return self.__get_ohlc("W", symbols, full, group_by, auto_adjust)
def get_monthly(self, symbols, full=False, group_by="column", auto_adjust=True):
return self.__get_ohlc("M", symbols, full, group_by, auto_adjust)
@ranaroussi
Copy link
Author

Example usage:

av = AlphaVantage(API_KEY)

# get quotes
data = av.get_quotes(symbols=["AAPL", "GOOG"])

# get full, intraday, auto-adjusted prices, groupped by colums
data = av.get_intraday(symbols=["AAPL", "GOOG"], interval=1, full=True, group_by="column", auto_adjust=True)

# get full daily, auto-adjusted prices, groupped by colums
data = av.get_daily(symbols=["AAPL", "GOOG"], full=True, group_by="column", auto_adjust=True)

# get full daily, auto-adjusted prices, groupped by colums
data = av.get_weekly(symbols=["AAPL", "GOOG"], full=True, group_by="column", auto_adjust=True)

# get full daily, auto-adjusted prices, groupped by colums
data = av.get_monthly(symbols=["AAPL", "GOOG"], full=True, group_by="column", auto_adjust=True)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment