2007-08-23

 

Python Cookbook 3.16 查看外汇兑换汇率

需求:

你想定期的查看两种货币间的兑换汇率(用linux的crontab或window的计划任务),从网上获得,并获得邮件通知.

讨论:

本节的代码和其它类似需求很相似,都是从网上获得数据,比如汇率,股票价格,甚至天气情况.让我们在这里看看如果获得美元和加元的汇率 ,从加拿大银行的网页获得.
import httplib
import smtplib
# configure script's parameters here
thresholdRate = 1.30
smtpServer = ' smtp.freebie.com'
fromaddr = 'foo@bar.com'
toaddrs = 'your@corp.com'
# end of configuration
url = '/en/financial_markets/csv/exchange_eng.csv'
conn = httplib.HTTPConnection(' www.bankofcanada.ca')
conn.request('GET', url)
response = conn.getresponse( )
data = response.read( )
start = data.index('United States Dollar')
line = data[start:data.index('\n', start)] # get the relevant line
rate = line.split(',')[-1] # last field on the line
if float(rate) < thresholdRate:
# send email
msg = 'Subject: Bank of Canada exchange rate alert %s' % rate
server = smtplib.SMTP(smtpServer)
server.sendmail(fromaddr, toaddrs, msg)
server.quit( )
conn.close( )
当需要知道外汇汇率时,最好能自动进行货币转换.本节的代码很直白,访问网页,获得CSV,它里面描述了汇率信息:
 Date (m/d/year),11/12/2004,11/15/2004, ... ,11/19/2004,11/22/2004
$Can/US closing rate,1.1927,1.2005,1.1956,1.1934,1.2058,1.1930,
United States Dollar,1.1925,1.2031,1.1934,1.1924,1.2074,1.1916,1.1844
...
这个脚本首先查找需要的币种(United States Dollar),然后找到最后, 获得今天的数据.如果你不太明天它是如何工作的,可以分开来看:
US = data.find('United States Dollar')  # find the index of the currency
endofUSline = data.index('\n', US) # find index for that line end
USline = data[US:endofUSline] # slice to make one string
rate = USline.split(',')[-1] # split on ',' and return last field
最后用email发送感兴趣的信息,你自己可以配置自己喜欢的信息.

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?