File: D:/bin/scripts/python/prev/get_currency_exchange_rates.py
# (SS,7/4/14) Python script to lookup EUR and USD exchanges rates from Yahoo and save to HyperFlight currency tables
import urllib2
import datetime
from BeautifulSoup import BeautifulSoup
import MySQLdb
import sys
import smtplib
from email.mime.text import MIMEText
import email.utils
def fetch_page(AURL):
print AURL
req = urllib2.Request(AURL, '', {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64)'})
response = urllib2.urlopen(req)
the_page = response.read()
return the_page
def get_currency_yahoo(AFromCurrency, AToCurrency):
LToken = AFromCurrency.lower() + AToCurrency.lower() # e.g. gbpusd
LURL = 'http://uk.finance.yahoo.com/q?s=' + LToken + '=x'
html = fetch_page(LURL)
soup = BeautifulSoup(html)
# find the exchange rate which is in a span e.g. <span id="yfs_l10_gbpusd=x">1.6592</span>
spans = soup.findAll('span', {"id" : "yfs_l10_" + LToken + "=x"})
LExchangeRate = 0
if len(spans) > 0:
try:
LExchangeRate = float(spans[0].text.strip())
except ValueError, e:
print 'ValueError: %s' % (e)
else:
print 'Exchange rate not found'
return LExchangeRate
def get_currency(AFromCurrency, AToCurrency):
print
LExchangeRate = get_currency_yahoo(AFromCurrency, AToCurrency);
print 'Exchange rate %s to %s: %s' % (AFromCurrency, AToCurrency, LExchangeRate)
# save in history table
LSQL = 'INSERT INTO currency_history SET \
ExchangeRateDateTime = NOW(), Currency = "%s", \
ExchangeRate = %0.4f' % (AToCurrency, LExchangeRate)
cur.execute(LSQL)
# update currencies table if <> 0
if LExchangeRate != 0:
LSQL = 'UPDATE currencies SET \
ExchangeRate = %0.4f \
WHERE Currency = "%s"' % (LExchangeRate, AToCurrency)
cur.execute(LSQL)
else:
set_alert(True) # signal alert if exchange is 0
def set_alert(AAlert):
global FAlert # required to modify a global
FAlert = AAlert
def get_alert():
return FAlert
def send_email_file(AFileName, ASubject, AFrom, ATo, ABcc):
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open(AFileName, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# header
if get_alert():
msg['Subject'] = 'ALERT!!! ' + ASubject
else:
msg['Subject'] = ASubject
msg['From'] = AFrom
msg['To'] = ATo
msg['Date'] = email.utils.formatdate(localtime=True)
if get_alert():
msg['X-Priority'] = '2'
# send the messsage using localhost
s = smtplib.SMTP('localhost')
s.sendmail(AFrom, [ATo, ABcc], msg.as_string())
s.quit()
LOG_FILE = 'get_currency_exchange_rates.log'
FAlert = False # global used to set alert
# output all prints to file
f = open(LOG_FILE, 'w')
sys.stdout = f
start = datetime.datetime.now()
print('Started: ' + start.strftime('%Y-%m-%d %H:%M:%S'))
filename_date_suffix = start.strftime('%Y-%m-%d')
con = MySQLdb.connect(host='localhost', user='hyperflight', passwd='b747', db='hyperflight')
cur = con.cursor()
# fetch all (non GBP) currencies from currencies table
cur.execute("SELECT Currency FROM currencies WHERE Currency <> 'GBP' ORDER BY Currency")
rows = cur.fetchall()
for row in rows:
get_currency('GBP', row[0]) # e.g. get_currency('GBP', 'EUR')
cur.close()
con.close()
finish = datetime.datetime.now()
time_taken = finish - start
print
print('Finished: ' + finish.strftime('%Y-%m-%d %H:%M:%S'))
print('Time taken: %0.3f seconds' % (time_taken.seconds + time_taken.microseconds / 1E6))
# set back to default out and close the opened log file
sys.stdout = sys.__stdout__
f.close()
# send the file as an email
send_email_file(LOG_FILE, 'HyperFlight Exchange Rate Result', 'exchange_rate@hyperflight.co.uk', 'sales@hyperflight.co.uk', 'contactforms@itpartnership.com')