import urllib from datetime import date timedelta from xml dom minidom

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import urllib
from datetime import date, timedelta
from xml.dom.minidom import parse
from PIL import Image, ImageDraw
import random
currency = {'USD' : 'R01235',
'GBP' : 'R01035',
'Euro' : 'R01239'}
def getData(currency,months):
today = date.today()
months = timedelta(days=30*months)
date_req1 = today - months
today = str(today).split('-')
date_req1 = str(date_req1).split('-')
try:
doc = parse(urllib.urlopen(r'http://www.cbr.ru/scripts/XML_dynamic.asp?date_req1='+date_req1[2]+'/'+date_req1[1]+'/'+date_req1[0]+'&date_req2='+today[2]+'/'+today[1]+'/'+today[0]+'&VAL_NM_RQ='+currency))
except:
print "Wrong parameters of function or the Center Bank's server inaccessible"
return None
data = []
for node in doc.getElementsByTagName("Record"):
value = node.getElementsByTagName("Value")[0].firstChild.data.replace(',','.')
value = value.replace(u'\xa0','')
data.append(float(value))
maxValue = max(data)
minValue = min(data)
return {'data':data,'minValue':minValue,'maxValue':maxValue}
def drawCurrency(currency,months,width,height):
img = Image.new('RGB',(width,height),(255,255,255))
shiftY = 30
shiftX = 100
draw = ImageDraw.Draw(img)
draw.line((shiftX,height - shiftY,width,height - shiftY),fill = (0,0,0))
draw.line((shiftX,height - shiftY,shiftX,0),fill = (0,0,0))
today = date.today()
lastday = today - timedelta(days=30*months)
draw.text((width-50,height-shiftY),str(today.month)+', '+str(today.year),(0,0,0))
draw.text((shiftX,height-shiftY),str(lastday.month)+', '+str(lastday.year),(0,0,0))
width -= shiftX
height -= shiftY
dataSpis = []
absMax = 0
absMin = 9999999
level = 50
for j,key in enumerate(currency.keys()):
data = getData(currency[key],months)
if data != None:
for i in range(1,4):
data.update({'color'+str(i):random.randint(0,255)})
dataSpis.append(data)
if absMax < dataSpis[-1]['maxValue']: absMax = dataSpis[-1]['maxValue']
if absMin > dataSpis[-1]['minValue']: absMin = dataSpis[-1]['minValue']
draw.line((20,(j+1)*level,40,(j+1)*level),fill=(data['color1'],data['color2'],data['color3']))
draw.text((45,(j+1)*level-7),key,(0,0,0))
else: break
if dataSpis != []:
draw.text((shiftX-shiftX*0.5,height-height*0.02),str(absMin),(0,0,0))
draw.text((shiftX-shiftX*0.5,5),str(absMax),(0,0,0))
for elem in dataSpis:
step = float(width)/len(elem['data'])
x = shiftX
It = iter(elem['data'])
y = height - (It.next() - absMin)/(absMax - absMin) * height
for i in range(len(elem['data'])-1):
it = {'next':It.next()}
draw.line((x,y,x+step,height - (it['next'] - absMin)/(absMax - absMin) * height),fill=(elem['color1'],elem['color2'],elem['color3']))
y = height - (it['next'] - absMin)/(absMax - absMin) * height
x += step
img.save('dinamic.jpg','JPEG')
drawCurrency(currency,120,800,300)