How to Build a Stock Chart (JS) in 4 Steps
Tags: javascript, webdev, tutorial, datascience
Published: 2022-02-27 07:46:28

[Data visualization](https://www.anychart.com/blog/2018/11/20/data-visualization-definition-history-examples/) is vastly applied in various fields. One such domain is financial trading, where [stock charts](https://www.anychart.com/chartopedia/chart-type/stock-chart/) are essential for smart market data analysis and decision making. Whether you invest in stocks or not, I am pretty sure that you have come across such graphics or even might need to build one right now. So, would you like to know how to make a stock chart? I’m ready to show you an easy path using the Tesla stock price data and JavaScript! Come along with me throughout this tutorial and you’ll learn how to quickly create elegant, interactive JS stock charts like the one you see in the picture.

## What Is a Stock Chart?

Most of you may know the basics, but to ensure that we are all on the same page, I will briefly tell you what a stock chart is.

A stock chart basically represents the price or volume movements of a stock over time by plotting the price or volume figures over the Y-axis and the time period over the X-axis.

Stock charts play a very important role in helping investors spot trends and make the right buy and sell decisions in the fast-paced financial markets.

The most common chart type used to depict stocks is the candlestick stock chart. But you can also use open-high-low-close (OHLC), line, area, column, or other forms of series visualization depending on a particular case and task.

## Stock Chart to Be Created

Tesla is a company that is always in the news. It has grown exponentially over the years and that is pretty much reflected in its stock value over time. So, I am going to build a stock chart to showcase the price movement of Tesla Inc. for this tutorial. I will also show you how to add various technical indicators and illustrate the effect of the recent hype surrounding the selling of stocks by Elon Musk.

Here is a peek at the final version of the JavaScript stock chart to get you all pumped up for the upcoming steps.

![JavaScript-based stock chart built along the tutorial.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84pvez86yhyx0lcdm7e9.png) 

## Building a Stock Chart with JavaScript

Creating an interactive stock chart from scratch can be quite a daunting task but becomes much easier and faster with an appropriate data visualization tool. For example, there are some useful [JavaScript charting libraries](https://en.wikipedia.org/wiki/Comparison_of_JavaScript_charting_libraries) that have the capability to create financial graphics, and you can work with whichever suits your needs.

In this tutorial, I am using one of the good ones — the [AnyChart](https://www.anychart.com/) JS library, which has some great options for [stock charts](https://www.anychart.com/products/anystock/overview/) along with neat [documentation](https://docs.anychart.com/Stock_Charts/Overview) for them and is free for any non-commercial and educational use.

Although it is not necessary, some skills with HTML and JavaScript can help understand the concepts faster. But everything is quite straightforward and will be vastly explained, so there is nothing to worry about even if you are a novice.

The opening bell has rung, and it’s time to create the stock chart!

### 1. Make an HTML page

The first thing I do is create an HTML page to hold the chart and add a `div` element to render the chart. This block element should be given a unique id so it can be referenced in the code later.

I also set the styling of the `div` where I define the width and height as 100% with 0 margins and padding. This will display the stock chart over the entire screen.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Stock 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>
```

### 2. Add the required scripts

Since I am using a charting library, I need to reference the appropriate JS scripts from that library for the stock chart. Remember that these scripts are included in the `head` section of the HTML page.

For a stock chart, I need to add multiple scripts. Firstly, I include AnyChart’s ‘[core](https://docs.anychart.com/Quick_Start/Modules#core)’ and ‘[stock](https://docs.anychart.com/Quick_Start/Modules#stock)’ modules. Next, I add the [Data Adapter](https://docs.anychart.com/Quick_Start/Modules#data_adapter) module that helps load the data. Finally, I include the [UI](https://docs.anychart.com/Quick_Start/Modules#common_ui) and [Exports](https://docs.anychart.com/Quick_Start/Modules#exports) modules for user interface elements and to enable export features that let you save the chart as an image or extract the underlying data to a data file.

For the stock UI features to work properly, I also need to link the appropriate stylesheets.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Stock Chart</title>
    <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>

    <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-exports.min.js"></script>

    <link href="https://cdn.anychart.com/releases/8.11.0/css/anychart-ui.min.css" type="text/css" rel="stylesheet">
    <link href="https://cdn.anychart.com/releases/8.11.0/fonts/css/anychart-font.min.css" type="text/css" rel="stylesheet">

    <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 Stock Chart will come here
    </script>
  </body>
</html>
```

### 3. Prepare the data

In this stock chart, I want to visualize daily stock price data for Tesla Inc. (TSLA), so I take it from [Yahoo Finance](https://finance.yahoo.com/quote/TSLA/history?p=TSLA) and the CSV data file [here](https://gist.githubusercontent.com/shacheeswadia/cd509e0b0c03964ca86ae7d894137043/raw/5f336c644ad61728dbac93026f3268b86b8d0680/teslaDailyData.csv).

All the preparations are done now, so let’s start the trading or in our case writing the JavaScript stock charting code!

### 4. Write the necessary JavaScript code

To start with, I enclose the code within a function called `anychart.onDocumentReady()`. This ensures that the code will not be executed till the page is fully loaded. Next, I load the data file using the `anychart.data.loadCsvFile()` function.

I then create a data table and add the loaded data to it but before I can use this data for my stock chart, I need to map it. Since I am creating a candlestick stock chart, I map the open, high, low, and close values.

```javascript
anychart.onDocumentReady(function () {
  anychart.data.loadCsvFile(
    'https://gist.githubusercontent.com/shacheeswadia/cd509e0b0c03964ca86ae7d894137043/raw/5f336c644ad61728dbac93026f3268b86b8d0680/teslaDailyData.csv',
    function (data) {
      // create data table on loaded data
      var dataTable = anychart.data.table();
      dataTable.addData(data);

      // map loaded data for the candlestick series
      var mapping = dataTable.mapAs({
        open: 1,
        high: 2,
        low: 3,
        close: 4
      });
    }
  );
});
```

Now, I define the stock chart, plot it, and set the gridlines. As numbers are important when looking at stock data values, I enable all the gridlines for better readability.

```javascript
// create stock chart
var chart = anychart.stock();

// create first plot on the chart
var plot = chart.plot(0);

// set grid settings
plot.yGrid(true).xGrid(true).yMinorGrid(true).xMinorGrid(true);
```

Now comes the main part of creating the series. This is done by using the candlestick drawing function with the mapping that I defined earlier. I give the series a name and add a legend icon.

```javascript
var series = plot.candlestick(mapping)
        .name('Tesla');

series.legendItem().iconType('rising-falling');

// create scroller series with mapped data
chart.scroller().candlestick(mapping);
```

Stock charts have values over a long period of time. So I add a scroller series under the main chart that enables the user to specify the date range and take a closer look at the values of that data. I set a one-year range for default display.

To make it easier for the user, I provide both a range picker where the user can manually enter dates and a range selector where the commonly used time periods can be selected with just a click.

```javascript
// set chart selected date/time range
chart.selectRange('2020-11-27', '2021-11-26');

// create range picker
var rangePicker = anychart.ui.rangePicker();

// init range picker
rangePicker.render(chart);

// create range selector
var rangeSelector = anychart.ui.rangeSelector();

// init range selector
rangeSelector.render(chart);
```

Finally, I give the chart a title, reference the previously defined chart container, and draw the chart.

```javascript
// sets the title of the chart
chart.title('Tesla Inc. Stock Chart');

// set container id for the chart
chart.container('container');

// initiate chart drawing
chart.draw();
```

That’s the closing bell and a beautiful, functional stock chart is created!

![Basic JS stock chart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2lq396fxfw6c8dyhclh9.png) 

You can quickly figure out the stock prices of Tesla have been fluctuating in the past year, but the overall trend is positive. Hover over the chart to see a functional tooltip showing the date along with open, high, low, and close values. This is one of the many useful features already available here.

You can see this initial JS stock chart version on [CodePen](https://codepen.io/shacheeswadia/pen/MWEWVxy) [and on [AnyChart Playground](https://playground.anychart.com/Koc2SDL3/)] with the full code.

## Customizing the JavaScript Stock chart
A. Series type and conditional coloring
B. Technical indicators: EMA and Envelope
C. MACD indicator
D. Awesome Oscillator
E. Color palette
F. Illustrating and annotating

**FOR A WALKTHROUGH OF THESE JS STOCK CHART CUSTOMIZATIONS, [CONTINUE READING HERE](https://www.anychart.com/blog/2022/02/24/stock-chart-js/).**