Skip to content

Commit

Permalink
Merge branch 'release/1.3.1'
Browse files Browse the repository at this point in the history
  • Loading branch information
RomelTorres committed Oct 15, 2017
2 parents c28db8d + 1dcd05f commit ba54d7a
Show file tree
Hide file tree
Showing 8 changed files with 345 additions and 150 deletions.
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/RomelTorres/alpha_vantage.svg)](http://isitmaintained.com/project/RomelTorres/alpha_vantage "Average time to resolve an issue")
[![Percentage of issues still open](http://isitmaintained.com/badge/open/RomelTorres/alpha_vantage.svg)](http://isitmaintained.com/project/RomelTorres/alpha_vantage "Percentage of issues still open")

*Python module to get stock data from the Alpha Vantage API*
*Python module to get stock data/cryptocurrencies from the Alpha Vantage API*

Alpha Vantage delivers a free API for real time financial data and most used finance indicators in a simple json or pandas format. This module implements a python interface to the free API provided by Alpha
Vantage (http://www.alphavantage.co/). It requires a free API, that can be requested on http://www.alphavantage.co/support/#api-key. You can have a look at all the api calls available in their documentation http://www.alphavantage.co/documentation
Expand Down Expand Up @@ -87,9 +87,29 @@ plt.tight_layout()
plt.grid()
plt.show()
```

Giving us as output:
![alt text](images/docs_sp_rt_example.png?raw=True "Real Time Sector Performance")

Finally, we can also plot crypto currencies prices like BTC:

```python
from alpha_vantage.cryptocurrencies import CryptoCurrencies
import matplotlib.pyplot as plt

cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas')
data, meta_data = cc.get_digital_currency_intraday(symbol='BTC', market='CNY')
data['. price (USD)'].plot()
plt.tight_layout()
plt.title('Intraday value for bitcoin (BTC)')
plt.grid()
plt.show()
```

Giving us as output:
![alt text](images/docs_cripto_btc.png?raw=True "Crypto Currenci daily (BTC)")


## Tests

In order to run the tests you have to first export your API key so that the test can use it to run.
Expand Down
60 changes: 14 additions & 46 deletions alpha_vantage/alphavantage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# Python 2.* import
from urllib2 import urlopen

from simplejson import loads
from json import loads
from functools import wraps
import inspect
import pandas
Expand All @@ -19,30 +19,7 @@ class AlphaVantage:
_ALPHA_VANTAGE_API_URL = "http://www.alphavantage.co/query?"
_ALPHA_VANTAGE_MATH_MAP = ['SMA', 'EMA', 'WMA', 'DEMA', 'TEMA', 'TRIMA', 'T3',
'KAMA', 'MAMA']
_EXCHANGE_SUPPORTED = { 'ASX': 'Australian Securities Exchange',
'BOM': 'Bombay Stock Exchange',
'BIT': 'Borsa Italiana Milan Stock Exchange',
'TSE': 'Canadian/Toronto Securities Exchange',
'FRA': 'Deutsche Boerse Frankfurt Stock Exchange',
'ETR': 'Deutsche Boerse Frankfurt Stock Exchange',
'AMS': 'Euronext Amsterdam',
'EBR': 'Euronext Brussels',
'ELI': 'Euronext Lisbon',
'EPA': 'Euronext Paris',
'LON': 'London Stock Exchange',
'MCX': 'Moscow Exchange',
'NASDAQ': 'NASDAQ Exchange',
'CPH': 'NASDAQ OMX Copenhagen',
'HEL': 'NASDAQ OMX Helsinki',
'ICE': 'NASDAQ OMX Iceland',
'STO': 'NASDAQ OMX Stockholm',
'NSE': 'National Stock Exchange of India',
'NYSE': 'New York Stock Exchange',
'SGX': 'Singapore Exchange',
'SHA': 'Shanghai Stock Exchange',
'SHE': 'Shenzhen Stock Exchange',
'TPE': 'Taiwan Stock Exchange',
'TYO': 'Tokyo Stock Exchange'}
_ALPHA_VANTAGE_DIGITAL_CURRENCY_LIST = "https://www.alphavantage.co/digital_currency_list/"

def __init__(self, key=None, retries=5, output_format='json', treat_info_as_error=True):
""" Initialize the class
Expand All @@ -54,7 +31,8 @@ def __init__(self, key=None, retries=5, output_format='json', treat_info_as_erro
output_format: Either 'json' or 'pandas'
"""
if key is None:
raise ValueError('Get a free key from the alphavantage website: https://www.alphavantage.co/support/#api-key')
raise ValueError(
'Get a free key from the alphavantage website: https://www.alphavantage.co/support/#api-key')
self.key = key
self.retries = retries
self.output_format = output_format
Expand Down Expand Up @@ -94,7 +72,8 @@ def _call_api_on_func(cls, func):
# Asumme most of the cases have a mixed between args and named
# args
positional_count = len(argspec.args) - len(argspec.defaults)
defaults = dict(zip(argspec.args[positional_count:], argspec.defaults))
defaults = dict(
zip(argspec.args[positional_count:], argspec.defaults))
except TypeError:
if argspec.args:
# No defaults
Expand All @@ -119,7 +98,8 @@ def _call_wrapper(self, *args, **kwargs):
# Form the base url, the original function called must return
# the function name defined in the alpha vantage api and the data
# key for it and for its meta data.
function_name, data_key, meta_data_key = func(self, *args, **kwargs)
function_name, data_key, meta_data_key = func(
self, *args, **kwargs)
url = "{}function={}".format(AlphaVantage._ALPHA_VANTAGE_API_URL,
function_name)
for idx, arg_name in enumerate(argspec.args[1:]):
Expand Down Expand Up @@ -151,7 +131,8 @@ def _output_format(cls, func, override=None):
"""
@wraps(func)
def _format_wrapper(self, *args, **kwargs):
json_response, data_key, meta_data_key = func(self, *args, **kwargs)
json_response, data_key, meta_data_key = func(
self, *args, **kwargs)
data = json_response[data_key]
if meta_data_key is not None:
meta_data = json_response[meta_data_key]
Expand Down Expand Up @@ -221,26 +202,13 @@ def _handle_api_call(self, url):
response = urlopen(url)
url_response = response.read()
json_response = loads(url_response)

if not json_response:
raise ValueError('Error getting data from the api, no return was given.')
raise ValueError(
'Error getting data from the api, no return was given.')
elif "Error Message" in json_response:
raise ValueError(json_response["Error Message"])
elif "Information" in json_response and self.treat_info_as_error:
raise ValueError(json_response["Information"])

return json_response

def is_exchange_supported(self, exchange_name):
"""
Get if a specific global exchange type is supported by this library

Keyword Arguments:
exchange_name: The exchange type to check for
Returns:
The description of the given key or None
"""
try:
return AlphaVantage._EXCHANGE_SUPPORTED[exchange_name]
except KeyError:
return None
return json_response
95 changes: 95 additions & 0 deletions alpha_vantage/cryptocurrencies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from .alphavantage import AlphaVantage as av


class CryptoCurrencies(av):
"""This class implements all the crypto currencies api calls
"""

@av._output_format
@av._call_api_on_func
def get_currency_exchange_rate(self, from_currency, to_currency):
""" Returns the realtime exchange rate for any pair of digital
currency (e.g., Bitcoin) or physical currency (e.g., USD).
Keyword Arguments:
from_currency: The currency you would like to get the exchange rate
for. It can either be a physical currency or digital/crypto currency.
For example: from_currency=USD or from_currency=BTC.
to_currency: The destination currency for the exchange rate.
It can either be a physical currency or digital/crypto currency.
For example: to_currency=USD or to_currency=BTC.
"""
_FUNCTION_KEY = 'CURRENCY_EXCHANGE_RATE'
return _FUNCTION_KEY, 'Realtime Currency Exchange Rate', None

@av._output_format
@av._call_api_on_func
def get_digital_currency_intraday(self, symbol, market):
""" Returns the intraday (with 5-minute intervals) time series for a
digital currency (e.g., BTC) traded on a specific market
(e.g., CNY/Chinese Yuan), updated realtime. Prices and volumes are
quoted in both the market-specific currency and USD.
Keyword Arguments:
symbol: The digital/crypto currency of your choice. It can be any
of the currencies in the digital currency list. For example:
symbol=BTC.
market: The exchange market of your choice. It can be any of the
market in the market list. For example: market=CNY.
"""
_FUNCTION_KEY = 'DIGITAL_CURRENCY_INTRADAY'
return _FUNCTION_KEY, 'Time Series (Digital Currency Intraday)', 'Meta Data'

@av._output_format
@av._call_api_on_func
def get_digital_currency_daily(self, symbol, market):
""" Returns the daily historical time series for a digital currency
(e.g., BTC) traded on a specific market (e.g., CNY/Chinese Yuan),
refreshed daily at midnight (UTC). Prices and volumes are quoted in
both the market-specific currency and USD..
Keyword Arguments:
symbol: The digital/crypto currency of your choice. It can be any
of the currencies in the digital currency list. For example:
symbol=BTC.
market: The exchange market of your choice. It can be any of the
market in the market list. For example: market=CNY.
"""
_FUNCTION_KEY = 'DIGITAL_CURRENCY_DAILY'
return _FUNCTION_KEY, 'Time Series (Digital Currency Daily)', 'Meta Data'

@av._output_format
@av._call_api_on_func
def get_digital_currency_weekly(self, symbol, market):
""" Returns the weekly historical time series for a digital currency
(e.g., BTC) traded on a specific market (e.g., CNY/Chinese Yuan),
refreshed daily at midnight (UTC). Prices and volumes are quoted in
both the market-specific currency and USD..
Keyword Arguments:
symbol: The digital/crypto currency of your choice. It can be any
of the currencies in the digital currency list. For example:
symbol=BTC.
market: The exchange market of your choice. It can be any of the
market in the market list. For example: market=CNY.
"""
_FUNCTION_KEY = 'DIGITAL_CURRENCY_WEEKLY'
return _FUNCTION_KEY, 'Time Series (Digital Currency Weekly)', 'Meta Data'

@av._output_format
@av._call_api_on_func
def get_digital_currency_monthly(self, symbol, market):
""" Returns the monthly historical time series for a digital currency
(e.g., BTC) traded on a specific market (e.g., CNY/Chinese Yuan),
refreshed daily at midnight (UTC). Prices and volumes are quoted in
both the market-specific currency and USD..
Keyword Arguments:
symbol: The digital/crypto currency of your choice. It can be any
of the currencies in the digital currency list. For example:
symbol=BTC.
market: The exchange market of your choice. It can be any of the
market in the market list. For example: market=CNY.
"""
_FUNCTION_KEY = 'DIGITAL_CURRENCY_MONTHLY'
return _FUNCTION_KEY, 'Time Series (Digital Currency Monthly)', 'Meta Data'
33 changes: 16 additions & 17 deletions alpha_vantage/sectorperformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pandas
import re


class SectorPerformances(av):
"""This class implements all the sector performance api calls
"""
Expand All @@ -14,8 +15,7 @@ def percentage_to_float(self, val):
Keyword Arguments:
val: The string to convert
"""
return float(val.strip('%'))/100

return float(val.strip('%')) / 100

def _output_format_sector(func, override=None):
""" Decorator in charge of giving the output its right format, either
Expand All @@ -29,14 +29,15 @@ def _output_format_sector(func, override=None):
"""
@wraps(func)
def _format_wrapper(self, *args, **kwargs):
json_response, data_key, meta_data_key = func(self, *args, **kwargs)
json_response, data_key, meta_data_key = func(
self, *args, **kwargs)
if isinstance(data_key, list):
# Replace the strings into percentage
data = {key: {k:self.percentage_to_float(v)
for k,v in json_response[key].items()} for key in data_key}
data = {key: {k: self.percentage_to_float(v)
for k, v in json_response[key].items()} for key in data_key}
else:
data = json_response[data_key]
#TODO: Fix orientation in a better way
# TODO: Fix orientation in a better way
meta_data = json_response[meta_data_key]
# Allow to override the output parameter in the call
if override is None:
Expand All @@ -59,8 +60,6 @@ def _format_wrapper(self, *args, **kwargs):
self.output_format))
return _format_wrapper



@_output_format_sector
@av._call_api_on_func
def get_sector(self):
Expand All @@ -73,13 +72,13 @@ def get_sector(self):
_FUNCTION_KEY = "SECTOR"
# The keys for the json output
_DATA_KEYS = ["Rank A: Real-Time Performance",
"Rank B: 1 Day Performance",
"Rank C: 5 Day Performance",
"Rank D: 1 Month Performance",
"Rank E: 3 Month Performance",
"Rank F: Year-to-Date (YTD) Performance",
"Rank G: 1 Year Performance",
"Rank H: 3 Year Performance",
"Rank I: 5 Year Performance",
"Rank J: 10 Year Performance"]
"Rank B: 1 Day Performance",
"Rank C: 5 Day Performance",
"Rank D: 1 Month Performance",
"Rank E: 3 Month Performance",
"Rank F: Year-to-Date (YTD) Performance",
"Rank G: 1 Year Performance",
"Rank H: 3 Year Performance",
"Rank I: 5 Year Performance",
"Rank J: 10 Year Performance"]
return _FUNCTION_KEY, _DATA_KEYS, 'Meta Data'
2 changes: 1 addition & 1 deletion helpers/pipy_rst_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
parent = path.abspath(path.dirname(path.dirname(__file__)))
readmemd_path = path.join(parent, 'README.md')
readmerst_path = path.join(parent, 'README.rst')
output = pypandoc.convert_file(readmemd_path,'rst')
output = pypandoc.convert_file(readmemd_path, 'rst')
with codecs.open(readmerst_path, 'w+', encoding='utf8') as f:
f.write(output)
Binary file added images/docs_cripto_btc.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

setup(
name='alpha_vantage',
version='1.2.1',
version='1.3.1',
author='Romel J. Torres',
author_email='[email protected]',
license='MIT',
Expand All @@ -35,7 +35,8 @@
],
keywords=['stocks', 'market', 'finance', 'alpha_vantage', 'quotes',
'shares'],
packages=find_packages(exclude=['helpers', 'test_alpha_vantage', 'images']),
packages=find_packages(
exclude=['helpers', 'test_alpha_vantage', 'images']),
package_data={
'alpha_vantage': [],
}
Expand Down
Loading

0 comments on commit ba54d7a

Please sign in to comment.