Skip to content

Instantly share code, notes, and snippets.

@kmandov
Created September 26, 2016 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmandov/dcb94f02e71e3560eb3255f2de3120e4 to your computer and use it in GitHub Desktop.
Save kmandov/dcb94f02e71e3560eb3255f2de3120e4 to your computer and use it in GitHub Desktop.
Visualizing stock data using horizon charts

Visualizing stock data using horizon charts. This example is based on Mike Bostock's cubism example.

Example demonstrating the use of D3 Horizon Chart.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
margin: 0;
padding: 0;
}
.horizon {
border-top: solid 1px #000;
border-bottom: solid 1px #000;
overflow: hidden;
position: relative;
}
.horizon + .horizon {
border-top: none;
}
.horizon canvas {
display: block;
image-rendering: pixelated;
}
.horizon .title,
.horizon .value {
bottom: 0;
line-height: 30px;
margin: 0 6px;
position: absolute;
font-family: sans-serif;
text-shadow: 0 1px 0 rgba(255,255,255,.5);
white-space: nowrap;
}
.horizon .title {
left: 0;
}
.horizon .value {
right: 0;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://npmcdn.com/d3-horizon-chart/build/d3-horizon-chart.min.js"></script>
<script>
function loadStockData(stock, callback) {
d3.csv('https://bost.ocks.org/mike/cubism/intro/stocks/' + stock + '.csv', function(rows) {
rows = rows.map(function(d) {
return [d3.timeParse(d.Date), +d.Open];
}).filter(function(d) {
return d[1];
}).reverse();
var date = rows[0][0],
compare = rows[400][1],
value = rows[0][1],
values = [];
rows.forEach(function(d, i ) {
values.push(value = (d[1] - compare) / compare);
});
callback(null, {
'stock': stock,
'values': values
});
});
}
var q = d3.queue();
['AAPL', 'BIDU', 'SINA', 'GOOG', 'MSFT', 'YHOO', 'ADBE', 'REDF', 'INSP', 'IACI', 'AVID', 'CCUR', 'DELL', 'DGII', 'HPQ', 'SGI', 'SMCI', 'SNDK', 'SYNA'].forEach(function(stock) {
q.defer(loadStockData, stock);
});
q.awaitAll(function(error, stocks) {
if (error) throw error;
d3.select('body').selectAll('.horizon')
.data(stocks)
.enter()
.append('div')
.attr('class', 'horizon')
.each(function(d) {
d3.horizonChart()
.title(d.stock)
.call(this, d.values);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment