-
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
03fb53f
Added AlphaVantage readeres
addisonlynch 3286fff
DOCS: Cleanup AlphaVantage docs
addisonlynch 72ee5ad
Added AlphaVantage Quotes Reader
addisonlynch bed2ffb
Updated AV tests
addisonlynch 1188ddb
Updated AV docstrings, repaired names
addisonlynch 7ef54a4
DOCS: Added Alphavantage to readers index
addisonlynch 680ca16
Merge branch 'master' into alphavantage
addisonlynch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 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 comment
The reason will be displayed to describe this comment to others. Learn more.
Nevermind - this is a base class.