How to Build a Stock Chart (JS) in 4 Steps
andreykh
Posted on February 27, 2022
Data visualization is vastly applied in various fields. One such domain is financial trading, where stock charts 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.
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 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 JS library, which has some great options for stock charts along with neat documentation 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.
<!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’ and ‘stock’ modules. Next, I add the Data Adapter module that helps load the data. Finally, I include the UI and 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.
<!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 and the CSV data file here.
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.
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.
// 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.
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.
// 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.
// 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!
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 [and on AnyChart Playground] 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.
Posted on February 27, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.