Skip to content

Instantly share code, notes, and snippets.

@markcapece
Created June 18, 2019 02:27
Show Gist options
  • Save markcapece/240d8f183253f98eac3e26d9bf1defdd to your computer and use it in GitHub Desktop.
Save markcapece/240d8f183253f98eac3e26d9bf1defdd to your computer and use it in GitHub Desktop.
Script for accessing equity data on AlphaVantage API. Includes endpoint quote, time series, and technical indicator requests. Returns pandas dataframes.
import pandas as pd
import requests
class AlphaQuery(object):
'''Base class to access the AlphaVantage API
Tries to access the AlphaVantage API key in ./API/AlphaVantage.txt
If this file does not exist, key must be provided manually when creating instance
'''
try:
with open('./API/AlphaVantage.txt', 'r') as f:
KEY = f.read()
except FileNotFoundError:
KEY=None
URL = 'https://www.alphavantage.co/query?'
def __init__(self, apikey=KEY):
'''Initialize AlphaQuery class
Keyword arguments:
apikey: AlphaVantage API key (default tries to find key in ./API/AlphaVantage.txt)
'''
self.key = apikey
self.indicator_list = ['sma', 'ema', 'wma', 'dema', 'tema', 'trima', 't3', 'kama', 'mama',
'vwap', 'macd', 'macdext', 'stoch', 'stochf', 'rsi', 'stochrsi',
'willr', 'adx', 'adxr', 'apo', 'ppo', 'mom', 'bop', 'cci', 'cmo',
'roc', 'rocr', 'aroon', 'aroonosc', 'mfi', 'trix', 'ultosc', 'dx',
'minus_di', 'plus_di', 'minus_dm', 'plus_dm', 'brands', 'midpoint',
'midprice', 'sar', 'trange', 'atr', 'natr', 'ad', 'adosc', 'obv',
'ht_trendline', 'htsine', 'ht_trendmode', 'ht_dcperiod', 'ht_dcphase',
'ht_phasor']
def _get_key(self):
return self.key
def _indicator_list(self):
return self.indicator_list
def get_quote(self, *args, symbol=None, **kwargs):
'''Return GLOBAL_QUOTE request as pandas dataframe
Keyword arguments:
symbol: stock ticker
'''
parameters = {
'function': 'GLOBAL_QUOTE',
'symbol': symbol,
'apikey': self._get_key()
}
parameters.update(kwargs)
response = requests.get(AlphaQuery.URL, params=parameters)
table = pd.read_json(response.content)
# Remove numbers in front of row labels and change first row to header
row_series = pd.Series([row.split(' ')[1] for row in table.index])
table.set_index(row_series, inplace=True)
table.columns = table.iloc[0]
return table
def get_timeseries(self, *args, symbol=None, barsize=None, adjusted=False, **kwargs):
'''Return TIME_SERIES request as pandas dataframe
Keyword arguments:
symbol: stock ticker
barsize: interval (1min, 5min, 15min, 30min, 60min, day, week, month)
adjusted: bool for including the adjusted close (defaul False)
'''
parameters = {
'function': 'TIME_SERIES',
'symbol': symbol,
'apikey': self._get_key()
}
if barsize == 'day':
bar = '_DAILY'
elif barsize == 'week':
bar = '_WEEKLY'
elif barsize == 'month':
bar = '_MONTHLY'
else:
bar = '_INTRADAY'
parameters['interval'] = barsize
parameters.update(kwargs)
adj = '_ADJUSTED' if adjusted else ''
parameters['function'] += (bar + adj)
response = requests.get(AlphaQuery.URL, params=parameters)
table = pd.read_json(response.content)
table = table[table.columns[1]]
# Unpack dictionary of open, high, low, close, etc values into separate columns
table = table.apply(pd.Series)
# Remove columns and rows composed entirely of NaN
table.dropna(axis=1, how='all', inplace=True)
table.dropna(axis=0, how='all', inplace=True)
# Remove numbers in front of column headers
table.columns = [col.split(' ')[1] for col in table.columns]
return table
def get_indicator(self, *args, indicator=None, symbol=None, barsize=None, price='close', period=10, **kwargs):
'''Return technical indicator request as pandas dataframe
Keyword arguments:
indicator: technical indicator abbreviation
symbol: stock ticker
barsize: interval (1min, 5min, 15min, 30min, 60min, daily, weekly, monthly)
price: price type for calculating indicator (open, high, low, default close)
period: rolling data window for calculating indicator (default 10 bars)
**NB some indicators use additional arguments
'''
parameters = {
'function': indicator,
'symbol': symbol,
'interval': barsize,
'series_type': price,
'time_period': period,
'apikey': self._get_key()
}
parameters.update(kwargs)
if indicator.lower() not in self._indicator_list():
raise ValueError('indicator cannot be {}. Call {} for a list of available indicators'.format(
indicator,
self._indicator_list.__name__
))
response = requests.get(AlphaQuery.URL, params=parameters)
# Unpack dictionary of technical indicator values
table = pd.read_json(response.content)
table = table[table.columns[1]]
table = table.apply(pd.Series)
# Remove columns and rows composed entirely of NaN
table.dropna(axis=1, how='all', inplace=True)
table.dropna(axis=0, how='all', inplace=True)
return table
def __str__(self):
return self.__class__.__name__
def __repr__(self):
return str(self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment