# yahoochart.py

import string, copy, urllib

from reportlab.lib import colors
from reportlab.graphics import shapes
from reportlab.graphics import renderPDF, renderPM
from reportlab.graphics.charts import linecharts
from reportlab.graphics.widgets import markers

mm = markers.makeMarker


def makeChart(titles, data, cats):
   x, y, w, h = 50, 50, 300, 125

   # make chart
   lc = linecharts.HorizontalLineChart()
   lc.x, lc.y = x, y
   lc.width, lc.height = w, h
   lc.data = data
   lc.lines.strokeWidth = 1.5
   lc.lines[0].strokeColor = colors.blue
   lc.lines[0].symbol = mm('Circle')
   lc.lines[1].strokeColor = colors.aqua
   lc.lines[1].symbol = mm('Diamond')
   lc.valueAxis.valueMin = 0
   lc.valueAxis.valueStep = 25
   lc.valueAxis.valueMax = 1.2*max(map(max, data))
   lc.valueAxis.visibleGrid = 1
   lc.valueAxis.gridStrokeColor = colors.black
   lc.valueAxis.gridEnd = w
   lc.categoryAxis.tickDown = 0
   lc.categoryAxis.categoryNames = cats
   lc.categoryAxis.labels.boxAnchor = 'e'
   lc.categoryAxis.labels.dy = -2
   lc.categoryAxis.labels.angle = 90
   lc.categoryAxis.labels.fontSize = 8

   drawing = shapes.Drawing(400, 200)
   drawing.add(lc)

   # make titles
   tdata = [(70, 160, titles[0], colors.blue),
            (70, 80, titles[1], colors.aqua)]
   for x, y, str, col in tdata:
       t = apply(shapes.String, [x, y, str])
       t.fontName = "Helvetica-Bold"
       t.fontSize = 10
       t.fillColor = col
       drawing.add(t)

   return drawing


close = lambda l: float(l[:-1].split(',')[-2])
date = lambda l: l[:-1].split(',')[0]

base = "http://table.finance.yahoo.com/"
format = "table.csv?a=1&b=1&c=2002&d=7&e=31&f=2002"
format = format + "&s=%s&y=0&g=w&ignore=.csv"

values = []
for val in ['ibm', 'aapl']:
   url = base + format % val
   lines = urllib.urlopen(url).readlines()
   cats = map(date, lines[1:])
   cats.reverse()
   closeVals = map(close, lines[1:])
   closeVals.reverse()
   values.append(closeVals)

d = makeChart(['IBM', 'Apple'], values, cats)
renderPM.drawToFile(d, "yahoo.png", "PNG")