-
Notifications
You must be signed in to change notification settings - Fork 684
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ENH: Add support for AlphaVantage API #490
Changes from 4 commits
03fb53f
3286fff
72ee5ad
bed2ffb
1188ddb
7ef54a4
680ca16
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
AlphaVantage | ||
------------ | ||
|
||
.. py:module:: pandas_datareader.av.forex | ||
|
||
.. autoclass:: AVForexReader | ||
:members: | ||
:inherited-members: | ||
|
||
|
||
.. py:module:: pandas_datareader.av.time_series | ||
|
||
.. autoclass:: AVTimeSeriesReader | ||
:members: | ||
:inherited-members: | ||
|
||
|
||
.. py:module:: pandas_datareader.av.sector | ||
|
||
.. autoclass:: AVSectorPerformanceReader | ||
:members: | ||
:inherited-members: | ||
|
||
|
||
.. py:module:: pandas_datareader.av.quotes | ||
|
||
.. autoclass:: AVQuotesReader | ||
:members: | ||
:inherited-members: |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
import os | ||
|
||
from pandas_datareader.base import _BaseReader | ||
from pandas_datareader._utils import RemoteDataError | ||
|
||
import pandas as pd | ||
|
||
AV_BASE_URL = 'https://www.alphavantage.co/query' | ||
|
||
|
||
class AlphaVantage(_BaseReader): | ||
""" | ||
Base class for all AlphaVantage queries | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think there should be docstring here. Maybe we should use a doc string inheriter to simplify this? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nevermind - this is a base class. |
||
""" | ||
_format = 'json' | ||
|
||
def __init__(self, symbols=None, start=None, end=None, retry_count=3, | ||
pause=0.001, session=None, api_key=None): | ||
super(AlphaVantage, self).__init__(symbols=symbols, start=start, | ||
end=end, retry_count=retry_count, | ||
pause=pause, session=session) | ||
if api_key is None: | ||
api_key = os.getenv('ALPHAVANTAGE_API_KEY') | ||
if not api_key or not isinstance(api_key, str): | ||
raise ValueError('The AlphaVantage API key must be provided ' | ||
'either through the api_key variable or ' | ||
'through the environment varaible ' | ||
'ALPHAVANTAGE_API_KEY') | ||
self.api_key = api_key | ||
|
||
@property | ||
def url(self): | ||
""" API URL """ | ||
return AV_BASE_URL | ||
|
||
@property | ||
def params(self): | ||
return { | ||
'function': self.function, | ||
'apikey': self.api_key | ||
} | ||
|
||
@property | ||
def function(self): | ||
""" AlphaVantage endpoint function""" | ||
raise NotImplementedError | ||
|
||
@property | ||
def data_key(self): | ||
""" Key of data returned from AlphaVantage """ | ||
raise NotImplementedError | ||
|
||
def _read_lines(self, out): | ||
try: | ||
df = pd.DataFrame.from_dict(out[self.data_key], orient='index') | ||
except KeyError: | ||
if "Error Message" in out: | ||
raise ValueError("The requested symbol {} could not be " | ||
"retrived. Check valid ticker" | ||
".".format(self.symbols)) | ||
else: | ||
raise RemoteDataError() | ||
df = df[sorted(df.columns)] | ||
# df.sort_index(ascending=True, inplace=True) | ||
df.columns = [id[3:] for id in df.columns] | ||
return df |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
from pandas_datareader.av import AlphaVantage | ||
|
||
from pandas_datareader._utils import RemoteDataError | ||
|
||
import pandas as pd | ||
|
||
|
||
class AVForexReader(AlphaVantage): | ||
""" | ||
Returns DataFrame of the AlphaVantage Foreign Exchange (FX) Exchange Rates | ||
data. | ||
|
||
.. versionadded:: 0.7.0 | ||
|
||
Parameters | ||
---------- | ||
pairs : string, array-like object (list, tuple, Series) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not just keep the standard symbols? |
||
Single currency pair (formatted 'FROM/TO') or list of the same. | ||
retry_count : int, default 3 | ||
Number of times to retry query request. | ||
pause : int, default 0.5 | ||
Time, in seconds, to pause between consecutive queries of chunks. If | ||
single value given for symbol, represents the pause between retries. | ||
session : Session, default None | ||
requests.sessions.Session instance to be used | ||
api_key : str, optional | ||
AlphaVantage API key . If not provided the environmental variable | ||
ALPHAVANTAGE_API_KEY is read. The API key is *required*. | ||
""" | ||
def __init__(self, pairs=None, retry_count=3, pause=0.5, session=None, | ||
api_key=None): | ||
|
||
super(AVForexReader, self).__init__(symbols=pairs, | ||
start=None, end=None, | ||
retry_count=retry_count, | ||
pause=pause, | ||
session=session, | ||
api_key=api_key) | ||
self.from_curr = {} | ||
self.to_curr = {} | ||
self.optional_params = {} | ||
if isinstance(pairs, str): | ||
self.pairs = [pairs] | ||
else: | ||
self.pairs = pairs | ||
try: | ||
for pair in self.pairs: | ||
self.from_curr[pair] = pair.split('/')[0] | ||
self.to_curr[pair] = pair.split('/')[1] | ||
except Exception as e: | ||
print(e) | ||
raise ValueError("Please input a currency pair " | ||
"formatted 'FROM/TO' or a list of " | ||
"currency pairs") | ||
|
||
@property | ||
def function(self): | ||
return 'CURRENCY_EXCHANGE_RATE' | ||
|
||
@property | ||
def data_key(self): | ||
return 'Realtime Currency Exchange Rate' | ||
|
||
@property | ||
def params(self): | ||
params = { | ||
'apikey': self.api_key, | ||
'function': self.function | ||
} | ||
params.update(self.optional_params) | ||
return params | ||
|
||
def read(self): | ||
result = [] | ||
for pair in self.pairs: | ||
self.optional_params = { | ||
'from_currency': self.from_curr[pair], | ||
'to_currency': self.to_curr[pair], | ||
} | ||
data = super(AVForexReader, self).read() | ||
result.append(data) | ||
df = pd.concat(result, axis=1) | ||
df.columns = self.pairs | ||
return df | ||
|
||
def _read_lines(self, out): | ||
try: | ||
df = pd.DataFrame.from_dict(out[self.data_key], orient='index') | ||
except KeyError: | ||
raise RemoteDataError() | ||
df.sort_index(ascending=True, inplace=True) | ||
df.index = [id[3:] for id in df.index] | ||
return df |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't really like get_data_av -- how could a new user know what av is? Maybe just the long get_data_alphavantage? Autocomplete is pretty good.