10

Build a Stock Chart Using AnyChart JavaScript Library

 2 years ago
source link: https://betterprogramming.pub/how-to-create-a-stock-chart-in-javascript-c250769045c2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Build a Stock Chart Using AnyChart JavaScript Library

A step by step tutorial for building an interactive stock chart that displays the price of Tesla over the years

Image by author

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.

0*vF2Ewjef0eW3MMpx?q=20
how-to-create-a-stock-chart-in-javascript-c250769045c2
Image by author

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.

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.

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.

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.

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.

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.

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

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

0*B_d-iLVzDfwf-0Qk?q=20
how-to-create-a-stock-chart-in-javascript-c250769045c2
Image by author

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 with the full code.

Customizing the JavaScript Stock chart

This interactive stock chart already looks pretty good and showcases useful information that can be delved into with ease. But, this is just the beginning.

Follow along as I’ll show you how to customize the JS stock chart by adding more features (changing series, adding technical indicators, annotations, and more) and fine-tuning its visualization, all in just a handful of streamlined actions.

A. Series type and conditional coloring

A stock chart is most commonly represented with candlesticks. But it’s not compulsory. Here, I want to show you how to quickly switch the type of data visualization from a candlestick stock chart, where all the four values are displayed (open, high, low, and close), to a line graph, where you can specify which value you want to plot (by default it’s the first value, i.e. the opening price in this case). Since only one value is represented, the mapping that I did earlier is not required here.

So, I simply specify the series as “line” and directly pass the datatable as the parameter.

To showcase the rising and falling prices in the line stock chart, I add conditional coloring where I specify the color of the line to be red if the price is decreasing and green if it’s going up. This can be very conveniently done using the in-built risingStroke and fallingStroke functions. The options to specify are the stroke color, stroke width, stroke type, and stroke endings.

I also change the scroller series to the line graph representation.

You can take a closer look at this new JS stock chart version on CodePen. In the next steps, I go back to plotting the candlestick series to represent the data.

B. Technical indicators: EMA and Envelope

Traders and investors often rely on technical analysis to identify trends, understand whether a financial instrument is overbought or oversold, and decide when to sell or buy. And there are multiple technical indicators out there that can be helpful in that. Let’s see how to quickly add them to stock charts.

I want to include two popular technical indicators: Exponential Moving Average (EMA) and Envelope. Both these indicators can be very easily drawn with quite minimal code.

All I have to do is map the data value that I want to use, which I specify as the closing value, indicate the stroke width and color, and the EMA line gets plotted over the candlestick chart. I can indicate the EMA period and the default is 50 if no custom value is set.

Similarly, for the Envelope indicator, I just specify the plotting, and the lower and higher band lines are drawn over the chart.

Check out how this JS stock chart version with EMA and Envelope looks below. You are also welcome to play with its interactive version (and its full code) on CodePen, where you can, for example, hide and show these additional technical indicator lines by clicking on the corresponding legend items.

0*RUC9BdhsMQwM57bh?q=20
how-to-create-a-stock-chart-in-javascript-c250769045c2
Image by author

C. MACD indicator

MACD or Moving Average Convergence Divergence is a momentum indicator generally plotted with a signal line. It is calculated with 26 and 12 period EMA and indicates buy or sell signs when it crosses above or below the signal line respectively.

I plot the MACD indicator as a separate plot representing the MACD line, the signal line, and a histogram as an area chart below the candlestick chart. The first thing I do is disable the X-axis for the candlestick chart since I will have that in the MACD plot. Now, I define a second plot and map the data values.

Next, I set the series type as an area histogram and define the stroke and fill settings for positive and negative values. Lastly, I just set the height of this plot as 40% of the total.

D. Awesome Oscillator

The Awesome Oscillator (AO) indicates the strength or weakness of an instrument by comparing the market momentum with the overall stock price fluctuation over a larger time reference.

I also plot this indicator as a second chart below the main chart, just like in the previous step. I am just showing you this to bring home the point of how various technical indicators can be plotted quite easily.

As I did for the MACD plot, similarly, I define the second plot and map the data using the ao function here for the awesome oscillator indicator.

I specify the colors of the stroke lines as green for rising and red for falling prices and set the height of the chart to 40%.

If you hover over either of the top or bottom charts, you will see two icons on the top right that let you move that plot up or down as well as make it render full screen hiding the other chart.

You can play around with these JS stock chart versions on CodePen, with the MACD plot here and the AO plot here.

E. Color palette

An easy and effective way to make your stock chart look personalized is to change the colors of the chart. The AnyChart library has pre-built design themes, so I’ll just need to add the necessary script to the head section and simply set it in the code. Here, I apply a monochrome theme.

See how sophisticated and polished the stock chart looks!

0*UWTplsPa4NDc8Sl1?q=20
how-to-create-a-stock-chart-in-javascript-c250769045c2
Image by author

Now, in the final customization, I will show you one more cool thing that is often demanded in stock charts.

F. Illustrating and annotating

In stock charts, it may be needed to add custom objects that additionally display or highlight something. For example, in the AnyChart JS library, there is a useful feature that lets you create drawings and annotations.

I will show you here how to highlight a specific period and also provide it with an explanatory note. I will showcase the time when the stock prices of Tesla fell due to Elon Musk selling a bunch of his own stocks.

To start, I define the annotation and then create a rectangle. I set the various parameters like the width and height of the rectangle along with the dates that indicate the starting and ending of the rectangle. I also set the stroke and fill values where I choose the red color from the company’s logo.

Next, I create the annotation label below the rectangle. I again define where to start the label, the dimensions, the colors, and, of course, the text.

This was just a simple illustration. If you want to learn more about how such drawing and annotation options can look and work in real life, play with this demo tool.

And that wraps up the customizations, and a lovely, interactive, and insightful JS stock chart is all done. Take a look at the final version below. Doesn’t it look like something you will put your money on? You can look into the full HTML/CSS/JavaScript code and keep customizing this stock chart to your liking on CodePen.

1*ZJAfGDU_YoQoILlMFVh7NA.png?q=20
how-to-create-a-stock-chart-in-javascript-c250769045c2
Image by author

Conclusion

As you can see, creating a stylish interactive stock chart with technical indicators and annotations looks complicated initially but can be quite hassle-free and convenient in reality. JavaScript charting libraries are many, and the process of building a stock chart is similar for most of those that support this chart type. So you can choose which one to use based on your requirements and particular tasks.

In this tutorial, I showed you how to create one type of stock chart — candlestick — and explained how to quickly change the series making a line one out of it. But there are also other interesting stock chart types that you can look at closer by yourself, for example, here.

Go on then, create stock charts and see if you can predict what will happen next. Of course, no particular stock can be a sure shot bet in the stock markets. But learning how to plot one is definitely guaranteed to be a winning decision! Please get in touch if you need any help.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK