Quick update - the code in this article was used as the starting point for components in the d3fc project. It’s a bit more advanced than this article, but you might find it interesting to see what this code evolved into!
The component I’m going to create is going to look like this:
What are Bollinger Bands?
Glad you asked. In a nutshell, Bollinger Bands are used on financial charts to indicate price volatility. As you can see from the chart above, they consist of three components:
- A moving average
- An upper band
- A lower band
The upper and lower bands are some number of standard deviations away from the moving average - and note that here we’re talking about a moving standard deviation. From this definition we can see that we need two parameters for our calculations - the moving average period, for which a value of 20 is typically used, and the number of standard deviations, which is typically 2.
Bollinger Bands Component
Here’s the complete code for the Bollinger Bands component - I’ll go through it below and explain what’s going on.
That’s a decent amount of code, so let’s start at the top by looking at the properties I’ve defined on this component - you’ll see that I’ve broken them down into sections so we don’t have a monolithic block of declarations at the top of the file.
- First we have the X and Y scales, which the component needs when it’s working out where to draw things.
- Next we have the fields we need to perform our calculations - the field to use on the data model, the moving average period, and the number of standard deviations to use. Note that we’re defaulting the moving average period to 20 and the number of standard deviations to 2, the typical values for these fields.
- Finally we have a number of properties which define CSS classes for the various parts of the component. This provides the user with a lot of customisability when it comes to styling, but we set default values so that the user doesn’t have to specify these properties.
In the component function we create a
d3.svg.area to represent the area between the upper and lower bands, and three
d3.svg.line objects to represent the upper band, lower band, and moving average line, setting their X-values appropriately. I’m using the area element because that’s a really nice, built-in way to show the area between two lines. The best part is, it’s really simple to use - where a line element requires you to set its Y-value, an area element has two Y-values - and I’m very much in favour of making life easy for myself.
In the next section we define two functions to calculate the moving average and the moving standard deviation. Note that Bollinger Bands use the population version of the standard deviation formula.
selection.each block is where we do our heavy lifting - setting the Y-values of our various SVG elements. We declare an empty variable,
bollingerData, then we populate it with data - it’s a map of date to
avg (moving average) and
sd (standard deviation) for each data item. We do this once, which is massively more efficient than it would be if we did all these calculations on the fly! On the other hand, this means we’re doing these calculations every time the component is redrawn; if we wanted to be maximally efficient we’d cache this information, but that would also require us to check that the data hadn’t changed every time we needed to redraw, which brings its own problems. The remainder of the
selection.each block is lengthy but pretty simple - we’re just setting the Y-values for our area and line elements based on the data in the
Finally we add the
lineAverage SVG elements to the path. Note that we don’t set the whole of the
data array on these elements - Bollinger Bands typically aren’t shown when there’s not enough data to calculate the full moving average, so we start at index
movingAverage, which has the desired effect.
I’ve not shown the various get/set accessors because they’re not especially interesting, as they’re pretty much all the same:
Adding the component to the chart
OK, that’s the tricky bit out of the way, so now let’s use this new Bollinger Bands component.
First we create and configure our component:
Here we’re just telling the component about the X and Y scales, and telling it to use the ‘close’ property on the data model. The
standardDeviations properties are optional (especially since we’re just setting them to their default values here, but you’d need to include them if you wanted anything non-standard). We could also set any of the four CSS properties that the component exposes, but I’ve chosen to omit them here and just leave them with their default values.
With that done, we add the component to the chart:
Pro tip: I’m putting this code just in front of the code to display the chart data itself, so that the Bollinger Bands will be in the background and the chart data will be in the foreground.
Obviously, the last step is to style the various sections of the component.
I’ve chosen to display the Bollinger Bands in grey, so I’m using a light grey for the area between the upper and lower bands and a darker grey for the bands themselves (you could instead use transparency to make the area lighter).
As an aside, note that I’ve set
stroke-width: 0 on the area so that it doesn’t show any borders. I’ve done this for two reasons. firstly, we’re drawing over the top and bottom borders anyway, and secondly we don’t want a left or right border to be shown - try removing this line and you’ll see what I mean.
Putting it all together, this is the result:
I’m pretty happy with this component - it works really well and it’s reasonably efficient, programmatically. There are still a few enhancements we could do though. If you read through the Wikipedia entry on Bollinger Bands you’ll see that we’re using a simple moving average calculation, but that other types of calculation are sometimes used; we could extend our component to allow the user to choose by providing an additional property like
In this article I’ve taken the moving average component I developed in my previous article and used it as the basis for a Bollinger Bands component. The new component is very easy to configure and style.