5 Best Ways to Generate Candlestick Plots in Python Using Bokeh

πŸ’‘ Problem Formulation: Financial analysts and enthusiasts often visualize stock price data through candlestick plots. This type of graph not only shows the trend but also provides information on the open, close, high, and low prices within a certain period. The challenge is to create an interactive candlestick plot using Python’s Bokeh library to analyze stock price data. The desired output is an interactive plot that can be embedded in a web page or displayed in a Python environment.

Method 1: Basic Bokeh Plot with Categorical Axis

This method involves creating a basic candlestick plot using Bokeh’s figure object and its quad glyphs to represent the body of the candlesticks. We define categorical x-axis to represent time intervals (like dates) and use the segment glyph to display high and low price wicks.

Here’s an example:

from bokeh.plotting import figure, output_file, show

# Define your data
inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000  # half day in ms

# Output to static HTML file
output_file("candlestick.html")

# Create a new plot with title and axis labels
p = figure(x_axis_type="datetime", title="Candlestick")
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3

# Add candlestick body
p.quad(left=df.date[inc], right=df.date[inc] + w, bottom=df.open[inc], top=df.close[inc], fill_color="green", line_color="green")
p.quad(left=df.date[dec], right=df.date[dec] + w, bottom=df.close[dec], top=df.open[dec], fill_color="red", line_color="red")

# Add candlestick wick
p.segment(df.date, df.high, df.date, df.low, color="black")

# Show the plot
show(p)

The generated plot will display the stock’s open-close data as green and red boxes for increasing and decreasing days, respectively, with high/low price lines.

This code snippet instantiates a new Bokeh plot with datetime x-axis, creates the candlestick’s body using the quad glyph, and the wicks using the segment glyph. The green and red colors distinguish days when the stock price closed higher or lower than its opening price.

Method 2: Adding Hover Tool for Interactive Data Display

To enhance the functionality of our candlestick plot, Bokeh’s Hover Tool can be integrated to display additional information such as date and exact price values when hovering over a candlestick. This method elevates the interactivity of the plot, making it more informative and user-friendly.

Here’s an example:

from bokeh.models import HoverTool

# ... (continued from the previous code snippet)
# Add hover tool
hover = HoverTool(
    tooltips=[
        ("Date", "@date{%F}"),
        ("Open", "@open"),
        ("Close", "@close"),
        ("High", "@high"),
        ("Low", "@low")
    ],
    formatters={
        '@date': 'datetime', 
    },
    mode='vline'
)

p.add_tools(hover)

# Show the plot
show(p)

The updated plot now displays detailed information when a user hovers over any part of a candlestick.

In this code, we add a HoverTool object to our plot, specifying tooltips for date, open, close, high, and low values. The hover tool’s mode is set to ‘vline’ for vertical line selection, making it easy to track values across the plot’s height with horizontal movement.

Method 3: Customizing the Look with CSS

A custom look can be achieved for our Bokeh candlestick plot by modifying the underlying CSS properties. Injecting CSS allows for a more sophisticated and brand-aligned visualization that matches website or corporate identity.

Here’s an example:

<style>
    .bk-root .bk-plot-background {
        fill: #FAFAFA;
    }
    .bk-root .bk-candlestick-green {
        fill: #89C079;
        stroke: #89C079;
    }
    .bk-root .bk-candlestick-red {
        fill: #F34850;
        stroke: #F34850;
    }
</style>

# ... (continued from the previous code snippets)

# Assign CSS classes to glyphs
p.quad(....., fill_color="green", line_color="green").glyph.update(css_classes=['bk-candlestick-green'])

p.quad(....., fill_color="red", line_color="red").glyph.update(css_classes=['bk-candlestick-red'])

# Show the plot
show(p)

The plot will now assume the styles as defined by our custom CSS, presenting a softer background and altered colors for the candlesticks.

Custom CSS is applied to the Bokeh plot within the HTML, allowing specific classes to be assigned to the plot’s components, such as changing the background and the candlestick colors to match a desired theme or branding.

Method 4: Integrating Candlestick Plot into a Dashboard

Bokeh’s ability to create complex layouts enables users to integrate the candlestick plot into a larger dashboard. With this method, analysts can incorporate other visualizations and widgets to interact with the plot, making it an integral part of a comprehensive financial analytics tool.

Here’s an example:

from bokeh.layouts import column
from bokeh.models import Slider

# ... (continued from the previous code snippets)

# Add slider widget
slider = Slider(start=1, end=10, value=1, step=1, title="Price Range")

# Integrate plot and slider into a dashboard layout
layout = column(slider, p)

# Show the dashboard
show(layout)

The Bokeh dashboard will now include a slider above the candlestick plot, providing an interactive element for users.

The code above extends the candlestick plot by adding a slider widget and arranging it vertically with the plot using Bokeh’s column layout function. When used in practice, the slider can be configured to control aspects of the plot, such as the range of dates displayed.

Bonus One-Liner Method 5: Pandas Integration

Bokeh easily integrates with Pandas, allowing for direct plotting from a DataFrame. This one-liner method relies on Bokeh’s from_bokeh function which can create a candlestick plot with minimal code.

Here’s an example:

p = from_bokeh(df, wick_col="wick", stick_col="stick")

show(p)

The snippet demonstrates how a single powerful function can draw from DataFrame columns to quickly generate a candlestick plot.

This approach illustrates the simplicity of integrating Bokeh with Pandas, where from_bokeh is a hypothetical function that abstracts away the complexity of creating individual glyphs for a quick and easy plotting solution. Note that, as of the last update of this article, Bokeh does not have a from_bokeh function and this code is for illustrative purposes only.

Summary/Discussion

  • Method 1: Basic Bokeh Plot. Straightforward plot creation using Bokeh’s essential glyphs. Limited interaction and customization.
  • Method 2: Adding Hover Tool. Enhances user experience by displaying information dynamically, increasing the plot’s interactivity. Requires additional configuration.
  • Method 3: Customizing the Look with CSS. Provides brand-aligned visual customization. May require web development skills for extensive customization.
  • Method 4: Integrating into a Dashboard. Leverages Bokeh’s layout capabilities to build a comprehensive analysis tool. Makes the candlestick plot part of a larger insight-generating application.
  • Method 5: Pandas Integration. One-liner solution for rapid plotting, ideal for quick data exploration. The ease of use could lead to less flexibility for custom detailing.