Last active
August 29, 2015 14:14
-
-
Save sgs00/63fd28ab62d7c8d965ff to your computer and use it in GitHub Desktop.
Currency converter using Yahoo API
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
from decimal import Decimal | |
import json | |
import urllib | |
def convert(from_val, from_cur, to_cur): | |
""" | |
currency codes: http://en.wikipedia.org/wiki/ISO_4217 | |
""" | |
url = "https://query.yahooapis.com/v1/public/yql" | |
q_tmpl = 'select * from yahoo.finance.xchange where pair in ("%s%s")' | |
p = {'q': q_tmpl % (from_cur, to_cur), | |
'env': 'store://datatables.org/alltableswithkeys', | |
'format': 'json', } | |
qry_str = urllib.urlencode(p) | |
resp = urllib.urlopen("?".join([url, qry_str])) | |
j = json.loads(resp.read()) | |
rate = j['query']['results']['rate']['Rate'] | |
to_val = Decimal(str(from_val)) * Decimal(rate) | |
return to_val.quantize(Decimal('0.00')) | |
if __name__ == '__main__': | |
print convert(1, 'EUR', 'USD') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment