[Tutor] Can I get some feedback on my currency converter program

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Dec 9 22:33:24 CET 2005



> On Fri, 9 Dec 2005, vikas mohan wrote:
>
> > Thanks! Looks in a better shape now! I have a diffrent question now:
> > What if like in Java, i would like to have live currency quotes fed to
> > my function, from some forex dealer website? So, that my program can
> > provide uptodate info. How can I hot/live link my function?


Hi Vikas,

Ok, so I looked into this a bit more; I think you mean to grab the
currency rates that are being used at any given time.  There's a web site
on finance.yahoo.com that gives quotes:

    http://finance.yahoo.com/currency

and it seems common for people to write tools to scrap information off
that page.  We can grab such pages in Python by using the 'urllib'
library.

    http://www.python.org/doc/lib/module-urllib.html


For example, the following program:

######
import urllib
text = urllib.urlopen("http://finance.yahoo.com/d/quotes.csv" +
                      "?s=USDJPY=X&f=sl1d1t1ba&e=.csv").read()
print text
######

shows how we can download a page and get some data --- the program above
grabs data for the US-to-Japanese-Yen exchange rate.  If you take this
route, you'll probably need to do a bit more to make this work across all
the currency types you want.

If you look around the web, you should be able to find some module that
people have written to do this.



Besides Yahoo, there appears to be other places where live
currency-exchange data can be grabbed in bulk.  For example, the European
Central Bank (ECB) appears to provide this data against the Euro:

    http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html

Not only does ECB provides this information in HTML, but also in a
machine-parsable XML format:

    http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml

So one way to grab the live data would be to take the above XML document
and use an XML parser to yank out the data values.  One popular one that
we've been using recently is a third-party module called ElementTree,
which can be found here:

    http://effbot.org/zone/element-index.htm

This seems to be XML-parsing week for me, so for fun, I wrote something to
parse the content out.  If you don't want to be spoiled, don't read the
end of this message.  *grin*


** spoiler space ahead **





** spoiler space **

Here's a small program that can do this retrieval and parsing.  (I'm still
an ElementTree newbie, so there may be a more concise way of programming
the following):

######################################################################
"""A small module to grab the reference rates against the Euro, using
statistics from the European Central Bank."""

import urllib
from elementtree import ElementTree

def getLiveEuroData():
    """Returns a dictionary mapping currency codes from the Euro to
    that particular currency."""
    tree = getTree()
    euroData = {}
    for elt in tree.findall(".//*"):
        if (elt.attrib.get('currency', None) and
            elt.attrib.get('rate', None)):
            euroData[elt.attrib.get('currency')] = (
                float(elt.attrib.get('rate')))
    return euroData

def getTree():
    """Grabs the latest xml document from the European Central Bank at
    http://www.ecb.int."""
    f = urllib.urlopen("http://www.ecb.int/stats/eurofxref/" +
                       "eurofxref-daily.xml")
    tree = ElementTree.parse(f)
    f.close()
    return tree
#######################################################################


So, for example, to find the currency exchange rate from the Euro to US
dollars, we can do:

#####
>>> euroToOtherCurrencyRate = getLiveEuroData()
>>> euroToOtherCurrencyRate['USD']
1.1785000000000001
#####


If we wanted to be nice, we'd probably add something to cache the exchange
rates somewhere in memory, so that we don't hammer ECB.



Anyway, I hope this comes in handy!



More information about the Tutor mailing list