Using Highcharts Stock for Python – Basic Tutorial-2

Using Highcharts Stock for Python - Basic Tutorial logo

Highcharts Core is the gold-standard in JavaScript data visualization libraries, enabling you to design rich, beautiful, and highly interactive data visualizations of (almost) any kind imaginable, and to render those visualizations in your web or mobile applications. And the Highcharts Stock extension is a powerful tool for the visualization of time series data – such as stock/bond prices and the like.
Highcharts Stock for Python is a Python wrapper for the Highcharts Stock JavaScript library, which means that it is designed to give developers working in Python a simple and Pythonic way of interacting with Highcharts Stock. It is part of the broader Highcharts for Python Toolkit, and includes the core Highcharts for Python library.
Highcharts Stock for Python will not render data visualizations itself – that’s what Highcharts Stock does – but it will allow you to:

  1. Configure your data visualizations in Python.
  2. Supply data you have in Python to your data visualizations.
  3. Programmatically produce the Highcharts Stock JavaScript code that will actually render your data visualization.
  4. Programmatically download a static version of your visualization (as needed) within Python.

Think of Highcharts Stock for Python as a translator to bridge your data visualization needs between Python and JavaScript.

Getting Started with Highcharts Stock for Python

To use Highcharts Stock for Python, like with any Python library, you first have to install it. That’s super easy: just open your Python project (in your virtual environment – you are using virtual environments, right?) and execute:

$ pip install highcharts-stock

And that’s it! Highcharts Stock for Python will now be installed in your project and available for use. To use it in your code, you just have to import it the way you would any other library.

What’s Included in Highcharts Stock for Python?

Highcharts Stock for Python is specifically designed to provide rich time series visualization in your Python code. While the base Highcharts for Python library is designed to provide rich interactive visualizations, Highcharts Stock for Python goes further to provide you with:

  • A Powerful Control Panel. Using the Stock Tools functionality, you can give your users a rich interactive control panel that allows them to:
    • zoom in and out to various time intervals.
    • annotate the chart with pins, lines, and notes.
    • add multiple (or even custom) banding to your chart.
    • change the chart type how they wish (within constraints you impose).
    • add technical indicators to your chart, automatically calculated based on your data.
  • Robust Navigation across Your Time Series. Highcharts Stock for Python provides you with the ability to let your users easily navigate to different time periods in your data, using any combination of:
    • mouse and touch-enabled scrolling and panning.
    • mouse and touch-enabled zooming.
    • a zoomed-out navigator time series accompanying your “main” data series.
    • preset data ranges, or
  • Easily Add 40+ Technical Indicators. Highcharts Stock supports over 40 different technical indicators, including various types of banding, pivot point calculation, momentum calculation, regression calculation, moving averages, and more. These technical indicators are calculated and visualized automatically.
  • Highcharts for Python. Highcharts Stock for Python includes the complete Highcharts for Python library, with the exact same API. You can integrate Highcharts Core visualizations with the added features of Highcharts Stock (even if they are not time series!), or use the same code for time series and other visualization types. All you need to do is to change where you are importing from.

Importing Highcharts Stock for Python

The Highcharts Stock for Python library is quite big. It’s got a rich (read: complicated) API, with lots of different objects and modules. That’s a reflection of the visualization power that Highcharts offers you, but it does make the decision of what to import and how to import it a little more complicated.
Python best practice is to import only what you need, which helps to maximize the performance of your Python code and prevents your application’s namespace from getting cluttered with various things (and further reducing the memory footprint of your Python code, which is always good).
You can either import specific things from their precise locations, or you can also just import the catch-all highcharts module, which flattens the entire API and exposes just about every class/object in one location. We definitely recommend importing things from their precise location like so:

# Import classes using precise module indications. For example:
from highcharts_stock.chart import Chart
from highcharts_stock.global_options.shared_options import SharedStockOptions
from highcharts_stock.options import HighchartsStockOptions
from highcharts_stock.options.plot_options.candlestick import CandlestickOptions
from highcharts_stock.options.series.candlestick import CandlestickSeries

As you can see, the import pattern for Highcharts Stock for Python is very similar to Highcharts for Python. That is because Highcharts Stock for Python is an extension of the Highcharts for Python library, and it maintains the full API. Highcharts Stock features are additive in relation to that API, so you can import from one toolkit library throughout your application.
For example, if you wish to render a Candlestick chart of a set of stock prices (only possible in Highcharts Stock for Python) but also render a separate Sankey chart (available in Highcharts for Python), you can do both while using the Highcharts for Stock library:

from highcharts_stock.chart import Chart
from highcharts_stock.global_options.shared_options import SharedStockOptions
from highcharts_stock.options import HighchartsStockOptions
from highcharts_stock.options.plot_options.candlestick import CandlestickOptions
from highcharts_stock.options.plot_options.sankey import SankeyOptions
from highcharts_stock.options.series.candlestick import CandlestickSeries
from highcharts_stock.options.series.sankey import SankeySeries

A Super Simple Example

While your project is likely more complicated, let’s take a look at the easiest use case: visualizing some data quickly and easily. You likely have your data in a CSV file, or perhaps in a Pandas dataframe, or maybe just stored in a list in your Python code. Highcharts Stock for Python can work with all of those scenarios.

Let’s assume you have your data stored in a CSV file named “my-csv-file.csv” (creative, right?).
You can create a chart from a CSV file by:

  1. Importing the Chart type from highcharts_stock.chart:
    from highcharts_stock.chart import Chart
  2. Calling the Chart.from_csv() class method, which will create a new Chart instance:
    from highcharts_stock.chart
    import Chart
    # Create a new Chart instance from the CSV file "my-csv-file.csv".
    my_chart = Chart.from_csv('my-csv-file.csv',
      property_column_map = {
        'open': 1,
        'high': 2,
        'low': 3,
        'close': 4,
        'x': 0,
        'data_label': 'ticker_symbol',
        'id': 'id'
      series_type = 'candlestick',
      chart_kwargs = {
        'container: '
        target_div ',
        'variable_name': 'myChart'

And that’s it! Let’s breakdown what’s happening in the method call above:
First, you’re telling the .from_csv() method which CSV file to use. That’s pretty straightforward. But the magic really happens in the next three arguments:

  • The property_column_map argument, which tells the method which CSV columns correspond to which properties in the series’ data points, and
  • The series_type argument, which tells the method that you want to plot the CSV data in a line series (plot the data points as a line).
  • The chart_kwargs argument, which supplies other keyword arguments used to configure your Chart instance.

The property_column_map Argument

The property_column_map argument takes a dict whose keys correspond to the properties in the series type’s .data property. That can seem a little complicated, but think of it this way:
Highcharts Stock for Python supports over 130 different series types in its visualization suite. Different series types may have different properties for their data points. Some (like the CandlestickSeries shown above) may be very simple:

  • They get “open”, “high”, “low”, and “close” values for the asset price.
  • An “x” value for the data point’s position on the x-axis.
  • A “data_label” value for the label to apply to the data point, in this case the value of the column labeled “ticker_symbol”
  • An “id” that uniquely identifies the data point.

So the property_column_map argument tells Highcharts for Python which CSV column maps to which property. Pretty straightforward!
If you use convenience methods like .from_csv(), make sure to review the series type’s data points to map your data to the appropriate properties. You can do so in the extensive API Reference for the series type you want to chart.

Some CSV files may contain headers, others might not contain headers. For that reason, the column_property_map values accept either integers (which indicate which column in your CSV file should map to that property) or they also accept strings (which contain the column name if your CSV file contains a header). In the example above, the “open”, “high”, “low”, “close”, and “x” properties are found in the second, third, fourth, fifth, and first column of the CSV respectively.

By default, Highcharts Stock for Python expects that your CSV file has a header row, but you can override this expectation by supplying an argument has_header_row = False to the .from_csv() method.

The series_type Argument

Using the series_type argument, you determine which series type will be used to visualize your data. You can find a complete list of supported series types in the Supported Visualizations section of our documentation.
In the example above, we use all of the default settings for the CandlestickSeries that gets created, but you can further configure your series by passing its configuration options in a series_kwargs argument. That argument expects a dict whose keys map to the series properties you wish to configure, and whose values are the values that you want to apply.

The chart_kwargs Argument

Just as you can use the optional series_kwargs argument to configure the series of data you are creating, you can use the chart_kwargs argument to configure your Chart instance. This argument expects a dict whose keys map to the Chart properties you wish to configure, and whose values are the values that you want to apply.
In the example above, we are setting the my_chart.container property (giving it the value “target_div”) and the my_chart.variable_name property (giving it the value “myChart”). These chart properties are very important for rendering your chart in a web environment, so we’ll discuss them in greater detail below.

Other Approaches

The example above focuses on using a CSV file, but Highcharts Stock for Python has you covered regardless of how you are managing your data in your Python application. You have similar convenience functions for loading data:

  • .from_pandas() which loads data from a Pandas Dataframe.
  • .from_pyspark() which loads data from a PySpark Dataframe.
  • .from_array() which loads data from an iterable

You can call these convenience methods on the Chart class as shown above, or you can also call the exact same convenience methods on a series type, and then add the series to a chart instance using the my_chart.add_series() method.
Our other tutorials show you in detail how to use these different convenience methods to rapidly build great visualizations – we recommend you check out here: Highcharts for Python Tutorials.

And that’s it! You now have a fully-configured Chart instance containing the data from your CSV file. We’ll describe how to actually use this Chart instance down below.

Visualizing Your Chart

Now that we’ve built a Chart instance and populated it with data, our next step is to visualize it. How you actually do this depends to some extent on how you are building your Python application.

Maybe you are using a web framework like Flask, Django, or FastAPI and relying on their templating engines for creating your views. Or maybe you are providing a Python backend API which delivers data to an entirely separate app via RESTful API calls. In any case, to visualize your new chart you need to somehow get its configuration to your web-based front-end. And that is super simple as well.
Using the example above, you can generate the full set of HTML and JavaScript content to render your chart with one method call:

as_js_literal = my_chart.to_js_literal()
# This will produce a string similar to:
# document.addEventListener('DOMContentLoaded', function() {
#   const myChart = Highcharts.stockChart('target_div', {
#      series: {
#          type: 'caneldstick',
#          data: [
#              [1463753252, 7, 2, 0, 4],
#              [1463753252, 1, 4, 2, 8],
#              [1463753252, 3, 3, 9, 3]
#      }
#   });
# });

So what is this method call doing? It is taking the entire set of instructions included in your my_chart variable, creating a JavaScript literal string that represents them, and putting that string in the as_js_literal Python variable. This string can then be piped into your web front end using whatever templating engine you are using, or delivered to your front-end in an API response, and it will then render your chart as you configured it.
In the example above, if you place the as_js_literal string in what gets rendered in your user’s browser, your chart will be automatically rendered by Highcharts Stock, placing the chart inside the div element in your content whose id is “target_div”.
And that’s it! You should now see a beautiful line chart in your web content.

Downloading Your Chart

Often when you’ve created a visualization, you may want to download a static version of it as an image that can be embedded in other documents. With Highcharts Stock for Python, that is a fairly trivial exercise. Given the example above, you can produce a PNG image very simply with one method call:

# Download a PNG version of the chart in memory within your Python code.
my_png_image = my_chart.download_chart(format = 'png')
# Download a PNG version of the chart and save it the file "/images/my-chart-file.png"
my_png_image = my_chart.download_chart(
    format = 'png',
    filename = '/images/my-chart-file.png'

The two examples shown above both download a PNG of your chart:
The first example keeps that PNG image in your Python code only, storing its binary data in the my_png_image variable. The second example not only stores its binary data in the my_png_image variable, but it also saves the PNG image to the file “/images/my-chart-file.png”.

The format argument is really the one doing the heavy lifting above. In the example above, it tells the method to generate a PNG image, but you can also create “jpeg”, “pdf”, and “svg”.
And that’s it! You should know that the .download_chart() method defaults to using the Highcharts Export Server provided by Highsoft (creators of Highcharts Core), however you can configure the method to use your own custom Highcharts Export Server if you choose. For more details on how to do this, please review our tutorial on Exporting Static Charts using Highcharts for Python.

More Resources

The above tutorial is just a really simple example of how you can create rich visualizations with just a handful of method calls using Highcharts for Python. But the library offers so much more! We recommend you take a look at the following additional resources which you may find useful: