All of the interesting technological, artistic or just plain fun subjects I'd investigate if I had an infinite number of lifetimes. In other words, a dumping ground...

Friday, 6 June 2008

Python - Generating Sparkline Graphs For Stock Pricing

http://coreygoldberg.blogspot.com/2008/06/python-generating-sparkline-graphs-for.html

Thursday, 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:]
closing_prices.reverse()

fh = open('data.txt', 'w')
for closing_price in closing_prices:
fh.write(closing_price + '\n')
fh.close()

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 --lable_last
*Note: The Sparkplot module needs Matplotlib installed.


The sparkline output is an image (png) like this:


1 comment:

Corey Goldberg said...

why did you republish my blog post on your blog?

tim's shared items

Add to Google Reader or Homepage