DEV Community

Cover image for Creating a Candlestick Chart with JS to Analyze Stocks
Awan Shrestha
Awan Shrestha

Posted on

Creating a Candlestick Chart with JS to Analyze Stocks

Candlestick charts are a fantastic data visualization tool for tracking the price movements of stocks over a period of time. In this tutorial, I'll show you how to create your own candlestick chart using JavaScript.

We’ll be using TSMC (Taiwan Semiconductor Manufacturing Company) as an example, as they're the largest contract chip maker in the world and have been making waves in the stock market recently.

By the end of this tutorial, you'll be able to create your own JS candlestick charts and analyze stock trends like a pro. So, let's get started and dive into the exciting world of data visualization with JavaScript!

What is a Candlestick Chart?

You may already be familiar with candlestick charts, but just in case you need a quick refresher, here's the gist: A candlestick chart, or a Japanese candlestick chart, is a type of chart used to visualize the price movement of a stock over time. Each point on the graph represents a specific time period, and the "candle" shape is made up of a rectangular body and two wicks that extend from either end.

The body of the candle represents the difference between the opening and closing prices, while the wicks represent the highest and lowest prices that occurred during that time period. The color of the candle can indicate whether the stock price went up or down during that period, with green or blue usually indicating a rise and red indicating a decline.

Candlestick charts are a popular tool used by traders and analysts to identify trends and patterns in stock prices. And now, with the power of JavaScript, you can create your very own candlesticks and impress all your finance friends with your data visualization skills!

Candlestick Chart Being Built

Are you ready to create your very own candlestick chart with JavaScript? I sure am! By the end of this tutorial, you'll have a beautiful graph that looks something like the one below:

Final interactive stock candlestick chart on a web page, built with JavaScript (HTML5)

Exciting, right? So let's not waste any time, and get right into the fun part: building our candlestick chart!

Steps to Build a Basic JS Candlestick Chart

Okay, let's get started with building our very own candlestick chart using JavaScript! Don't worry if you're new to this — I'll walk you through each step, and before you know it, you'll be a pro at it!

Here's a quick list of what we'll be doing:

  1. Create a basic HTML page.
  2. Insert the required JS files.
  3. Set the data.
  4. Write some JS charting code.

Let's get started!

1. Create a Basic HTML Page

To start things off, let's create a basic HTML page and give it the snazzy title "JavaScript Candlestick Chart." We'll add an HTML block element called <div> to contain our masterpiece, and give it a special ID attribute of "container" so we can refer to it later in the code.

To make our chart look extra slick, we'll throw in some CSS rules in the <style> block. We can set the width and height properties to 100% and the margin and padding to 0. Of course, you can always change these to suit your personal style.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Candlestick Chart</title>
    <style type="text/css">
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

2. Insert the Required JS files

Using JavaScript charting libraries is an absolute game-changer when it comes to creating stunning interactive visualizations. Luckily, you don't need to be a technical wizard to use them. For this tutorial, we'll be working with AnyChart, which has detailed documentation (e.g., candlestick here and stock candlestick here), and does not require a fee for non-commercial use.

Next up, we need to insert the required JS files. This is where the beauty of CDNs (Content Delivery Networks) comes in handy. We can simply add the links to the Core, Stock, and Data Adapter modules in the <head> section of our HTML page. We'll also need to add the CSS links for UI and fonts to ensure our candlestick chart looks top-notch.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Candlestick Chart</title>
    <link href="https://cdn.anychart.com/releases/8.11.0/css/anychart-ui.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.anychart.com/releases/8.11.0/fonts/css/anychart-font.min.css" rel="stylesheet" type="text/css">  
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-stock.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-data-adapter.min.js"></script>
    <style type="text/css">
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      // All the code for the JS Candlestick chart will come here
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Later on, we might need several other modules for customization.

3. Set the Data

To set up the data for the candlestick chart, we will use the stock data of TSMC, which I have compiled into a CSV file available at this link. Loading the data is easy with the anychart.data.loadCsvFile() function, which we can use to load the data from the CSV file into our chart. This function will parse the CSV file and create a data table, which will be used to plot the chart.

anychart.data.loadCsvFile('https://gist.githubusercontent.com/awanshrestha/6481638c175e82dc6a91a499a8730057/raw/1791ef1f55f0be268479286284a0452129371003/TSMC.csv', function (data) {});
Enter fullscreen mode Exit fullscreen mode

4. Write Some JS Charting Code

Alright, it's time to put all the pieces together and create our awesome candlestick chart for TSMC! Let's start by writing some JS code to make our chart functional.

First off, we need to wrap our code in the anychart.onDocumentReady() function. This ensures that the code is executed only after the document has finished loading.

anychart.onDocumentReady(function () {
  anychart.data.loadCsvFile(
'https://gist.githubusercontent.com/awanshrestha/6481638c175e82dc6a91a499a8730057/raw/1791ef1f55f0be268479286284a0452129371003/TSMC.csv',
    function (data) {});
});
Enter fullscreen mode Exit fullscreen mode

Since candlestick charts can process table-formatted data, we create a table using the table() method and add our data to it with the addData() method.

var dataTable = anychart.data.table();
dataTable.addData(data);
Enter fullscreen mode Exit fullscreen mode

But hold up, we're not done yet! We need to map our data properly to make it visually appealing. So, we use the mapAs() function to create a new mapping object responsible for mapping the data.

var mapping = dataTable.mapAs({
  open: 1,
  high: 2,
  low: 3,
  close: 4
});
Enter fullscreen mode Exit fullscreen mode

Next, we create a stock chart and a plot to represent our data.

// create a stock chart
var chart = anychart.stock();
// create the plot
var plot = chart.plot(0);
Enter fullscreen mode Exit fullscreen mode

Moving on, we work on the grid settings and create a series for our data. Using the addSeries() method, we configure our series name to be TSMC using the name() function. And to add a playful touch, we use the iconType() function to show the rise and fall of the stock markets with arrowheads pointing up and down, respectively.

// set the grid
plot.yGrid(true).xGrid(true).yMinorGrid(true).xMinorGrid(true);
// create the candlestick series
var series = plot.candlestick(mapping);
series.name('TSMC');
series.legendItem().iconType('rising-falling');
Enter fullscreen mode Exit fullscreen mode

To give our chart a title, we use the title() function. And finally, we specify the container of our chart as the HTML div with the id "container". And voila! Our JavaScript-based candlestick chart for TSMC is ready to be rendered with the draw() function.

// set the title of the chart
chart.title('TSMC Stock Chart');
// set the container id for the chart
chart.container('container');
// initiate the chart drawing
chart.draw();
Enter fullscreen mode Exit fullscreen mode

And here it is. Our (first) candlestick chart for the TSMC:

Basic interactive stock candlestick chart on a web page, built with JavaScript (HTML5)

But wait, there's more! In the next section, we'll learn how to customize our chart to make it even more visually appealing and informative. So keep reading!

The Playground Link is also available for you to play with the interactive version of this visualization. And the entire code for the basic JS candlestick chart has been placed below for your convenience.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Candlestick Chart</title>
    <link href="https://cdn.anychart.com/releases/8.11.0/css/anychart-ui.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.anychart.com/releases/8.11.0/fonts/css/anychart-font.min.css" rel="stylesheet" type="text/css">  
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-stock.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-data-adapter.min.js"></script>
    <style type="text/css">
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
anychart.onDocumentReady(function () {
  // load data
  anychart.data.loadCsvFile(
'https://gist.githubusercontent.com/awanshrestha/6481638c175e82dc6a91a499a8730057/raw/1791ef1f55f0be268479286284a0452129371003/TSMC.csv',
    function (data) {
      // create a data table with the loaded data
      var dataTable = anychart.data.table();
      dataTable.addData(data);
      // map the loaded data for the candlestick series
      var mapping = dataTable.mapAs({
        open: 1,
        high: 2,
        low: 3,
        close: 4
      });
      // create a stock chart
      var chart = anychart.stock();
      // create the chart plot
      var plot = chart.plot(0);
      // set the grid settings
      plot
        .yGrid(true)
        .xGrid(true)
        .yMinorGrid(true)
        .xMinorGrid(true);
      // create the candlestick series
      var series = plot.candlestick(mapping);
      series.name('TSMC');
      series.legendItem().iconType('rising-falling');
      // set the title of the chart
      chart.title('TSMC Stock Chart');
      // set the container id for the chart
      chart.container('container');
      // initiate the chart drawing
      chart.draw();
    }
  );
});
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Options to Customize a JS Candlestick Chart

Alright, now that we've got our basic JavaScript-based candlestick chart up and running, it's time to put our creative hats on and add some customizations to make it even more awesome! Let's explore some fun ways to jazz up our chart and make it stand out from the rest.

A. Get a Custom Date Range Picker and Selector

Buckle up, it's time to play with some dates! Let's add some customization to our candlestick chart by setting up a custom date range picker and selector. With this feature, users can easily navigate date/time-based charts and select specific periods for further analysis.

To get started, we need to add the Common UI module by including the following CDN link in the head section of our HTML page.

<script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-ui.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Once added, we can use the range picker to facilitate the use of the scroller by providing two input fields that allow users to customize the start and end dates on the display.

var rangePicker = anychart.ui.rangePicker();
rangePicker.render(chart);
Enter fullscreen mode Exit fullscreen mode

Additionally, we can use the range selector, which provides a set of buttons for selecting certain time periods.

var rangeSelector = anychart.ui.rangeSelector();
rangeSelector.render(chart);
Enter fullscreen mode Exit fullscreen mode

For our chart, we've chosen a custom date range of 2020 to 2022 to represent the post-COVID scenario.

chart.selectRange('2020-01-01', '2022-12-31');
Enter fullscreen mode Exit fullscreen mode

With a Custom Date Range Picker and Selector

B. Configure the Visual Appearance

Who said charts have to be boring? Let's make our JS candlestick chart stand out with some visual enhancements! In this section, we will explore how to configure the theme of the chart.

The theme changes the face, feel, and layout of the candlestick chart. I want to go with something glamorous. To get started, we need to add the following CDN link in the head section of our HTML page.

<script src="https://cdn.anychart.com/releases/8.11.0/themes/dark_glamour.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Once added, we can use the function theme() to change the theme or background color of the chart.

anychart.theme('darkGlamour');
Enter fullscreen mode Exit fullscreen mode

With the code provided below, we can change different parts of the candlesticks to create a unique look and feel. And don't forget the conditional coloring of the chart: green for positive growth and red for negative.

series.fallingFill("#FF0D0D");
series.fallingStroke("#FF0D0D");
series.risingFill("#43FF43");
series.risingStroke("#43FF43");
Enter fullscreen mode Exit fullscreen mode

Ta-da! Feast your eyes on the beautiful transformation of our candlestick chart!

Configured the Visual Appearance

C. Add Event Markers

Let's make our candlestick chart even more informative by adding event markers. This will provide a better understanding of key developments and dividends that occurred during the selected time period.

To begin with, we need to establish the settings for the event markers in our graph.

var eventMarkers = plot.eventMarkers();
Enter fullscreen mode Exit fullscreen mode

We can also customize the appearance of our event markers.
set the symbol of event markers

plot.eventMarkers().format(function() {
  return this.getData("symbol");
});
Enter fullscreen mode Exit fullscreen mode

Next, we add the data for the event markers. I have added some significant events that occurred between 2020 and 2022 based on information from the TSMC Wikipedia page and various news portals.

eventMarkers.data([
  { "symbol": 1, date: '2020-03-11', description: 'WHO declares COVID-19 a global pandemic' },
  { "symbol": 2, date: '2020-11-20', description: 'TSMC wins approval from Arizona for $12 billion chip plant' },
  { "symbol": 3, date: '2021-07-12', description: 'TSMC and Foxconn reach deals to buy COVID-19 vaccines for Taiwan' },
  { "symbol": 4, date: '2021-11-09', description: 'TSMC announces to build a specialty technology fab in Japan with Sony' },
  { "symbol": 5, date: '2022-02-24', description: 'Russia-Ukraine war begins' },
  { "symbol": 6, date: '2022-11-15', description: 'Berkshire Hathaway discloses a $4.1 billion stake in TSMC' },
]);
Enter fullscreen mode Exit fullscreen mode

The result of implementing all of the above code will be a candlestick chart that includes event markers, making it easier to understand the key events that took place during the selected time period.

Added Event Markers

D. Add Annotations

Let's add some helpful fun to the JS candlestick chart by including annotations!

First, we need to add the Annotations module by including the following script in the HTML code:

<script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-annotations.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

To add an annotation to the candlestick chart, we'll use the annotations() object and one of its methods, such as ellipse(), rectangle(), or more. Let's start by creating the annotation object:

var annotation = plot.annotations();
Enter fullscreen mode Exit fullscreen mode

For this article, we'll use the rectangle() method, which requires four points to define its location. You'll need to insert these four points in YYYY-MM-DD format. Since the exact start and end dates of the "work from home" period may vary, we'll use the day the pandemic was declared as the first date, and the day the first vaccine was approved by the WHO as the second date.

annotation.rectangle({
  // X - part of the first anchor
  xAnchor: '2020-03-11',
  // Y - part of the first anchor
  valueAnchor: 45,
  // X - part of the second anchor
  secondXAnchor: '2020-12-31',
  // Y - part of the second anchor
  secondValueAnchor: 125,
  // set the stroke settings
  stroke: '3 #098209',
  // set the fill settings
  fill: '#43FF43 0.25'
});
Enter fullscreen mode Exit fullscreen mode

We can also add a text label annotation:

annotation
  .label()
  .xAnchor('2020-03-11')
  .valueAnchor(75)
  .anchor('left-top')
  .offsetY(5)
  .padding(6)
  .text('Global Lockdowns — Rise in demand for semiconductor chips')
  .fontColor('#fff')
  .background({
    fill: '#098209 0.75',
    stroke: '0.5 #098209',
    corners: 2
  });
Enter fullscreen mode Exit fullscreen mode

Added Annotations

E. Add the MACD Indicator for Technical Analysis

MACD (Moving Average Convergence / Divergence) is like a superhero of technical analysis indicators! It shows the difference between a fast and slow exponential moving average (EMA) of closing prices. To add this indicator to the candlestick chart, we'll create a separate plot using the macd() method, which requires a mapping with the value field in it:

// add a second plot to show macd values
var indicatorPlot = chart.plot(1);
// map the macd values
var macdIndicator = indicatorPlot.macd(mapping);
Enter fullscreen mode Exit fullscreen mode

Don't forget to set the series type for the histogram series and adjust the plot height if needed:

// set the histogram series type
macdIndicator.histogramSeries('area');
macdIndicator
  .histogramSeries().normal().fill('green .3').stroke('green');
macdIndicator
  .histogramSeries().normal().negativeFill('red .3').negativeStroke('red');
// set the second plot's height
indicatorPlot.height('30%');
Enter fullscreen mode Exit fullscreen mode

Note that the MACD indicator must be placed before the date range configuration:

// add a second plot to show macd values
var indicatorPlot = chart.plot(1);
// map the macd values
var macdIndicator = indicatorPlot.macd(mapping);
// set the histogram series
macdIndicator.histogramSeries('area');
macdIndicator
  .histogramSeries().normal().fill('green .3').stroke('green');
macdIndicator
  .histogramSeries().normal().negativeFill('red .3').negativeStroke('red');
// set the second plot's height
indicatorPlot.height('30%');
// set the pre-selected range
chart.selectRange('2020-01-01', '2022-12-31');
Enter fullscreen mode Exit fullscreen mode

Great job! You're now ready to view the final version of the JavaScript candlestick chart on the Playground and make any additional customizations you desire. The entire code, with all the additions made, is listed below. So feel free to experiment and make any further changes you see fit!

Final interactive stock candlestick chart on a web page, built with JavaScript (HTML5)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Candlestick Chart</title>
    <link href="https://cdn.anychart.com/releases/v8/css/anychart-ui.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.anychart.com/releases/v8/fonts/css/anychart-font.min.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-stock.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/themes/dark_glamour.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-ui.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-data-adapter.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-annotations.min.js
"></script>
    <style type="text/css">
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      anychart.onDocumentReady(function () {
  // load data
  anychart.data.loadCsvFile(
'https://gist.githubusercontent.com/awanshrestha/6481638c175e82dc6a91a499a8730057/raw/1791ef1f55f0be268479286284a0452129371003/TSMC.csv',
    function (data) {
      // create a data table on the loaded data
      var dataTable = anychart.data.table();
      dataTable.addData(data);
      // map the loaded data for the candlestick series
      var mapping = dataTable.mapAs({
        open: 1,
        high: 2,
        low: 3,
        close: 4
      });
      // create a stock chart
      var chart = anychart.stock();
      // change the color theme
      anychart.theme('darkGlamour');
      // create the chart plot
      var plot = chart.plot(0);
      // set the grid settings
      plot
        .yGrid(true)
        .xGrid(true)
        .yMinorGrid(true)
        .xMinorGrid(true);
      // create the candlestick series
      var series = plot.candlestick(mapping);
      series.name('TSMC');
      series.legendItem().iconType('rising-falling');
      // create a range picker
      var rangePicker = anychart.ui.rangePicker();
      rangePicker.render(chart);
      // create a range selector
      var rangeSelector = anychart.ui.rangeSelector();
      rangeSelector.render(chart);
      // modify the color of the candlesticks 
      series.fallingFill("#FF0D0D");
      series.fallingStroke("#FF0D0D");
      series.risingFill("#43FF43");
      series.risingStroke("#43FF43");
      // set the event markers
      var eventMarkers = plot.eventMarkers();
      // set the symbol of the event markers
      plot.eventMarkers().format(function() {
        return this.getData("symbol");
      });
      // set the event markers data
      eventMarkers.data([
        { "symbol": 1, date: '2020-03-11', description: 'WHO declares COVID-19 a global pandemic' },
        { "symbol": 2, date: '2020-11-20', description: 'TSMC wins approval from Arizona for $12 billion chip plant' },
        { "symbol": 3, date: '2021-07-12', description: 'TSMC and Foxconn reach deals to buy COVID-19 vaccines for Taiwan' },
        { "symbol": 4, date: '2021-11-09', description: 'TSMC announces to build a specialty technology fab in Japan with Sony' },
        { "symbol": 5, date: '2022-02-24', description: 'Russia-Ukraine war begins' },
        { "symbol": 6, date: '2022-11-15', description: 'Berkshire Hathaway discloses a $4.1 billion stake in TSMC' },
      ]);
      // create an annotation
      var annotation = plot.annotations();
      // create a rectangle
      annotation.rectangle({
        // X - part of the first anchor
        xAnchor: '2020-03-11',
        // Y - part of the first anchor
        valueAnchor: 45,
        // X - part of the second anchor
        secondXAnchor: '2020-12-31',
        // Y - part of the second anchor
        secondValueAnchor: 125,
        // set the stroke settings
        stroke: '3 #098209',
        // set the fill settings
        fill: '#43FF43 0.25'
      });
      // create a text label
      annotation
        .label()
        .xAnchor('2020-03-11')
        .valueAnchor(75)
        .anchor('left-top')
        .offsetY(5)
        .padding(6)
        .text('Global Lockdowns — Rise in demand for semiconductor chips')
        .fontColor('#fff')
        .background({
          fill: '#098209 0.75',
          stroke: '0.5 #098209',
          corners: 2
        });
      // add a second plot to show macd values
      var indicatorPlot = chart.plot(1);
      // map the macd values
      var macdIndicator = indicatorPlot.macd(mapping);
      // set the histogram series
      macdIndicator.histogramSeries('area');
      macdIndicator
        .histogramSeries().normal().fill('green .3').stroke('green');
      macdIndicator
        .histogramSeries().normal().negativeFill('red .3').negativeStroke('red');
      // set the second plot's height
      indicatorPlot.height('30%');
      // set the chart display for the selected date/time range
      chart.selectRange('2020-01-01', '2022-12-31');
      // set the title of the chart
      chart.title('TSMC Stock Chart');
      // set the container id for the chart
      chart.container('container');
      // initiate the chart drawing
      chart.draw();
    }
  );
});
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You've made it to the end of our candlestick charting journey with JavaScript! It might have been a bit overwhelming at first, but now you're a pro at visualizing stock data like a boss. If you have any questions or need any help, don't hesitate to reach out. Happy charting!

Top comments (0)