Skip to content

Commit

Permalink
Merge pull request #11 from tarioch/feature/alphavantage_fx_rates
Browse files Browse the repository at this point in the history
Also support fetching fx rates (including crypto) from alphavantage
  • Loading branch information
tarioch authored Feb 26, 2020
2 parents d86163e + 7cb71b7 commit f0fc2ed
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ Requires the environment variable ``ALPHAVANTAGE_API_KEY`` to be set with your p
2019-01-01 commodity VWRL
price: "CHF:tariochbctools.plugins.prices.alphavantage/VWRL.SW"

**alphavantagefx**

Fetches fx rates from `Alphavantage <https://www.alphavantage.co/>`_
Requires the environment variable ``ALPHAVANTAGE_API_KEY`` to be set with your personal api key.

::

2019-01-01 commodity BTC
price: "CHF:tariochbctools.plugins.prices.alphavantagefx/BTC"


**bitstamp**

Fetches prices from `Bitstamp <https://www.bitstamp.com/>`_
Expand Down
36 changes: 36 additions & 0 deletions src/tariochbctools/plugins/prices/alphavantagefx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from beancount.prices import source
from dateutil import tz
from dateutil.parser import parse
from beancount.core.number import D
import requests
from os import environ
from time import sleep


class Source(source.Source):
def get_latest_price(self, ticker):
params = {
'function': 'CURRENCY_EXCHANGE_RATE',
'from_currency': ticker,
'to_currency': 'CHF',
'apikey': environ['ALPHAVANTAGE_API_KEY'],
}

resp = requests.get(url='https://www.alphavantage.co/query', params=params)
data = resp.json()
if 'Note' in data:
sleep(60)
resp = requests.get(url='https://www.alphavantage.co/query', params=params)
data = resp.json()

priceData = data['Realtime Currency Exchange Rate']

price = D(priceData['5. Exchange Rate'])
date = parse(priceData['6. Last Refreshed'])

us_timezone = tz.gettz("Europe/Zurich")
time = date.astimezone(us_timezone)
return source.SourcePrice(price, time, 'CHF')

def get_historical_price(self, ticker, time):
return None

0 comments on commit f0fc2ed

Please sign in to comment.