Tuesday, October 14, 2008

Unicode Sparklines

The concept of Sparklines (http://sparkline.org for examples) has been around for a while. I was reminded of it when browsing the Unicode character map the other day, and coming across the "block shapes" characters. There is a set of 8 characters that are essentially vertical bars with heights ranging from 1/8th to full character height. That allows to create crude but image-less quick spark-lines directly in text.

I mocked up a quick script that pulls stock data from Yahoo! Finance and converts it into a bar-graph using those Unicode characters. My Debian machine's fonts display those codes, so I assume most browsers out there will, too. Here is an example: ▇█▆▄▄▃▂▁. Link: http://sigmaxis.com/misc/quote-unicode.php

By the way, it was pleasantly surprising to see Unicode support for a lot of other "pragmatic" characters, such as ASCII box-drawing, etc. Heh, reminds me of good old DOS pseudo-GUIs and spreadsheets.

Script source:


$ticker = 'JAVA';

$handle = fopen("http://ichart.finance.yahoo.com/table.csv?s=$ticker&g=m", "r");
$csvdata = fread($handle, 4000);
$lines = explode("\n", $csvdata);

$prices = array();
$max = 0;
$min = 1000000;
$skipped = 0;
foreach($lines as $line) {
if(!$skipped) { $skipped = 1; continue; }

$values = explode(",", $line);
$price = $values[4];

if($price > $max) { $max = $price; }
if($price < $min) { $min = $price; }
$prices[] = $price;
if(sizeof($prices) >= 8) { break; }

$prices = array_reverse($prices);

header("Content-Type: text/html");

echo "Monthly closing price for $ticker: ";
echo '<span style="background: #cdb">';

foreach($prices as $price) {
$adj = intval(1 + 7 * ($price - $min) / ($max - $min));
echo "&#960$adj;";

echo '</span>';


No comments: