Skip to content

Instantly share code, notes, and snippets.

@sgs00
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgs00/63fd28ab62d7c8d965ff to your computer and use it in GitHub Desktop.
Save sgs00/63fd28ab62d7c8d965ff to your computer and use it in GitHub Desktop.
Currency converter using Yahoo API
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