Thursday, November 9, 2017

Graphing data in Rails 5 with Highcharts / Highstocks

On a recent project I've been working on, Markolio (market portfolio), we wanted to chart historical pricing data. After a quick Google search, Highcharts / Highstocks became the obvious option. I came across a few roadblocks while getting my graph functioning properly, so I figured I would share my solution to hopefully help others.
To begin, you will need an array of arrays, which is the data that you want graphed. I have my dates along the X axis, and prices along the Y axis. My first hiccup was that Javascript expects a date to be in milliseconds. Rails will convert a date to an integer by simply doing .to_i but you will need to multiple this by 1000 to make Javascript happy. My resulting code is as follows:

Easy enough, right? Graphing the data is pretty straightforward, you just set a javascript variable to your Rails object, then feed Highstocks the Javascript variable in the series configuration. My next struggle came with calculating the percentage change between the first value and the last value. Highstocks has the min and max values as part of their API, but no obvious way to get the first Y value on the X-axis and the last Y value on the X-axis. I posed the question on the Highstocks forums, and the response works great:

My full Highstocks configuration is as follows:

The above code will calculate the difference between the first and last points when the graph is loaded, as well as when the user zooms in on any point of the graph. The calculation happens if the user clicks one of the pre-defined ranges via the range selector, or if they manually zoom in on a portion of the graph.
The last little feature here is the year to date value in the range selector. I didn't come across this in the documentation, but rather on the Highcharts Github page. This is pretty straight forward as well.

That's it!