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!
Thursday, November 9, 2017
Graphing data in Rails 5 with Highcharts / Highstocks
Wednesday, July 12, 2017
Nginx virtualhost example for Passenger / Rails
For those of us coming from the Apache world, getting a working Nginx virtualhost configured for Rails can be quite the headache. It's actually pretty simple once you know what's going on. After installing nginx and passenger-phusion for nginx, all you need is the following (Note: the location portion of the config is for setting resource expiration to 1 month. You may need to adjust this based on your needs):
Subscribe to:
Posts (Atom)