Surfacing important news for a company with Yahoo Finance API and d3.js (part 2)21 May 2014
After a good start last week, we now know how to get a company share value's historical data with Yahoo Finance API. That's as simple as speaking YQL.
Today, we're going to have a look at how to graphically represent this data, with our good friend d3.js.
Here's a little souvenir from the last article, in which we formulated the query to Yahoo and prepared its use with jQuery:
data variable contains our JSON blob, and the
$.getJSON() bit calls a function named
foo() - we will change this name soon.
Let's dive right into it by setting up the viewport, i.e. the box in which we will place the chart:
Now, our data is still resting quietly in the
data variable, and we are going to use it right away.
Shall we? Throw a function in your code that takes our data variable as a parameter. How? Like this:
Then, let's declare our extents (from where to where our array goes), so we can declare our scales, which we need for our axis.
I know, that is very painful to go through all this, I do agree. What we just did was basically mapping our arrays (so the program is able to iterate through them), and then using d3's capabilities to create a y-axis that is linear (we want to populate it with US dollars values), and an x-axis that follows time.
We are almost ready. Let's make sure that our visualisation goes somewhere, and let's draw the axis. To do so, append a SVG element to your HTML document, and append to this SVG element your two axis:
Now. We want to draw a line chart of the price, right? Have a look at this clear example from the master himself.
We are going to call
d3.svg.line, but with a subtlety:
See what I did there?
On the y-axis, we will have the daily value, by accessing through
d.Close; and on the x-axis, the date. But wait, the name should be
Right. I forgot to mention. There is some preparation to do here.
draw(data), declare a date format so d3 knows we're doing business with dates - and how it has to deal with them. Like that:
draw(data), parse the date accordingly (we are making sure here that d3 understands what to put on the axis).
Append the SVG path to the big SVG element...
We also need labels under our axis. Luckily, that's easy.
And voilà! You're good to go!
If you want some sort of transition while the chart draws, here's an esoteric solution:
You may now take a breath.
Next week, we will look at how to use HTML inputs to make something more dynamic than what we have at the moment.