-
-
Notifications
You must be signed in to change notification settings - Fork 286
/
usd.py
51 lines (42 loc) · 1.44 KB
/
usd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'''Provide USD(s) function to convert string like '£300' or '205 AUD' to equivalent US$ as float.
Uses data from fixer.io
'''
from visidata import option, options, urlcache, vd
import functools
import json
option('fixer_key', '', 'API Key for fixer.io')
currency_symbols = {
'$': 'USD',
'£': 'GBP',
'₩': 'KRW',
'€': 'EUR',
'₪': 'ILS',
'zł': 'PLN',
'₽': 'RUB',
'₫': 'VND',
}
def currency_rates_json(date='latest'):
url = 'http://data.fixer.io/api/%s?access_key=%s' % (date, options.fixer_key)
return urlcache(url).read_text()
@functools.lru_cache()
def currency_rates():
return json.loads(currency_rates_json())['rates']
@functools.lru_cache()
def currency_multiplier(src_currency, dest_currency):
'returns equivalent value in USD for an amt of currency_code'
if src_currency == 'USD':
return 1.0
eur_usd_mult = currency_rates()['USD']
eur_src_mult = currency_rates()[src_currency]
usd_mult = eur_usd_mult/eur_src_mult
if dest_currency == 'USD':
return usd_mult
return usd_mult/currency_rates()[dest_currency]
def USD(s):
for currency_symbol, currency_code in currency_symbols.items():
if currency_symbol in s:
amt = float(s.replace(currency_symbol, ''))
return amt*currency_multiplier(currency_code, 'USD')
amtstr, currcode = s.split(' ')
return float(amtstr) * currency_multiplier(currcode, 'USD')
vd.addGlobals(globals())