June 5, 2008

Python - Generating Sparkline Graphs For Stock Pricing

In a previous post, I introduced the new historical stock pricing function in the ystockquote.py module.

Here is an interesting use of the module to create sparklines of historical stock pricing for a given stock.

To generate the sparklines, I use Grig Gheorghiu's Sparkplot Python module (which uses Matplotlib for graphing).

This module expects a file named data.txt, which contains lines of data to be graphed. All you need to do is generate a data file with the pricing data, and the Sparkplot module will take care of the rest.

To generate the data, I use a script like this:

import ystockquote

ticker = 'GOOG'
start = '20080101'
end = '20080523'

data = ystockquote.get_historical_prices(ticker, start, end)

closing_prices = [x[4] for x in data][1:]

fh = open('data.txt', 'w')
for closing_price in closing_prices:
    fh.write(closing_price + '\n')
Now that you have the data.txt file setup, you can call the Sparkplot script via the command line to generate the sparkline image:
python sparkplot.py --label_first --label_last
*Note: The Sparkplot module needs Matplotlib installed. The sparkline output is an image (png) like this:


Gary said...

I don't know if you'd be interested, but I wrote a Python module to generate sparklines without using an imaging library using Marc's original CSS-only approach.


Matt Joyce said...


Corey Goldberg said...

thanks.. I fixed the "label_last" typo.

John said...

You need better PNG compression. I just compressed it to 1799 bytes without any loss using optipng and pngout.