-
Notifications
You must be signed in to change notification settings - Fork 684
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ENH: Add support for AlphaVantage API (#490)
* Added AlphaVantage readeres * DOCS: Cleanup AlphaVantage docs * Added AlphaVantage Quotes Reader * Updated AV tests * Updated AV docstrings, repaired names * DOCS: Added Alphavantage to readers index
- Loading branch information
1 parent
8a9ca74
commit 1763dbd
Showing
15 changed files
with
855 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ Data Readers | |
.. toctree:: | ||
:maxdepth: 2 | ||
|
||
alphavantage | ||
fred | ||
famafrench | ||
bank-of-canada | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
""" | ||
_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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
---------- | ||
symbols : string, array-like object (list, tuple, Series) | ||
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, symbols=None, retry_count=3, pause=0.5, session=None, | ||
api_key=None): | ||
|
||
super(AVForexReader, self).__init__(symbols=symbols, | ||
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(symbols, str): | ||
self.symbols = [symbols] | ||
else: | ||
self.symbols = symbols | ||
try: | ||
for pair in self.symbols: | ||
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 symbols") | ||
|
||
@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.symbols: | ||
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.symbols | ||
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 |
Oops, something went wrong.