Created
April 25, 2011 09:08
-
-
Save yml/940298 to your computer and use it in GitHub Desktop.
This gist use the Yahoo web services to extract the currency rate for 1 USD.
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
#!/usr/bin/env python | |
from datetime import datetime | |
import json | |
from urllib import urlopen | |
YAHOO_CURRENCY_CONVERTER = 'http://finance.yahoo.com/connection/currency-converter-cache?date=' | |
class CurrencyCoverterException(Exception): | |
def __init__(self, value): | |
self.value = value | |
def __str__(self): | |
return repr(self.value) | |
def get_json_currencies(date): | |
""" | |
This method returns a json string containing a list of dict for each | |
currency:: | |
{u'resource': {u'classname': u'Quote', | |
u'fields': {u'date': u'2010-02-01', | |
u'price': u'0.71767', | |
u'symbol': u'EUR=X', | |
u'type': u'currency'}}} | |
Note: of course the string returned by yahoo web service is not a valid json | |
string so we need to do some uggly hack to transform it into one | |
""" | |
string_cur = ('[' + | |
"".join(urlopen(YAHOO_CURRENCY_CONVERTER + date).readlines()[8:-5]) | |
.replace("\n", "") | |
+']') | |
currencies = json.loads(string_cur) | |
if currencies: | |
return currencies | |
else: | |
raise CurrencyCoverterException("The json string return by Yahoo WS is empty") | |
def extract_rate(currency, list_currencies): | |
""" | |
""" | |
for cur in list_currencies: | |
if cur['resource']['fields']['symbol'] == currency +'=X': | |
return cur['resource']['fields'] | |
if __name__ == '__main__': | |
from optparse import OptionParser | |
parser = OptionParser() | |
parser.add_option("-d", | |
"--dates", | |
dest="dates", | |
help="Comma separated list of dates : yyyymmdd,yyyymmdd", | |
default=datetime.now().strftime('%Y%m%d') | |
) | |
parser.add_option("-c", | |
"--currency", | |
dest="currency", | |
help="Currency you want the rate : EUR", | |
default="EUR" | |
) | |
(options, args) = parser.parse_args() | |
for date in options.dates.split(","): | |
try: | |
currencies = get_json_currencies(date) | |
rate = extract_rate(options.currency, currencies) | |
print rate['date'], 'theorique : ',rate['price'], 'banque : ', float(rate['price'])-0.03 | |
except CurrencyCoverterException as e: | |
print "date %s : rate not available" %date |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment