AutoPlot#

from autotrader import AutoPlot

AutoPlot is the automated plotting module of AutoTrader. It is automatically used when visualising backtest results, but can also be interacted with to create charts and visualise indicators. Refer to this blog post for an example.

class autotrader.autoplot.AutoPlot(data: DataFrame | Series | None = None)

Automated trading chart generator.

configure()

Configure the plot settings.

add_tool(tool_name)

Add bokeh tool to plot. This adds the tool_name string to the fig_tools attribute.

plot()

Creates a trading chart of OHLC price data and indicators.

Methods#

Configure#

AutoPlot.configure(max_indis_over: int | None = None, max_indis_below: int | None = None, fig_tools: str | None = None, ohlc_height: int | None = None, ohlc_width: int | None = None, top_fig_height: int | None = None, bottom_fig_height: int | None = None, jupyter_notebook: bool | None = None, show_cancelled: bool | None = None, chart_theme: str | None = None, use_strat_plot_data: bool = False) None#

Configures the plot settings.

Parameters:
  • max_indis_over (int, optional) – Maximum number of indicators overlaid on the main chart. The default is 3.

  • max_indis_below (int, optional) – Maximum number of indicators below the main chart. The default is 2.

  • fig_tools (str, optional) – The figure tools. The default is “pan,wheel_zoom,box_zoom,undo, redo,reset,save,crosshair”.

  • ohlc_height (int, optional) – The height (px) of the main chart. The default is 400.

  • ohlc_width (int, optional) – The width (px) of the main chart. The default is 800.

  • top_fig_height (int, optional) – The height (px) of the figure above the main chart. The default is 150.

  • bottom_fig_height (int, optional) – The height (px) of the figure(s) below the main chart. The default is 150.

  • jupyter_notebook (bool, optional) – Boolean flag when running in Jupyter Notebooks, to allow inline plotting. The default is False.

  • show_cancelled (bool, optional) – Show/hide cancelled trades. The default is True.

  • chart_theme (bool, optional) – The theme of the Bokeh chart generated. The default is “caliber”.

Returns:

The plot settings will be saved to the active AutoTrader instance.

Return type:

None

See also

Refer to the Bokeh documentation for more details of the different themes.

Add Plot Tools#

To customise the tools of the figures produced with AutoPlot, the add_tool should be used. This method simply appends the tool_name to the fig_tools attribute of the class instance. Refer to the Bokeh documentation for details on the tools available.

AutoPlot.add_tool(tool_name: str) None#

Adds a tool to the plot.

Parameters:

tool_name (str) – The name of tool to add (see Bokeh documentation).

Returns:

The tool will be added to the chart produced.

Return type:

None

Create Plot#

The plot method is used to generate a chart. It is used in both backtest plotting and indicator viewing.

AutoPlot.plot(instrument: str | None = None, indicators: dict | None = None, trade_results: TradeAnalysis | None = None, show_fig: bool = True) None#

Creates a trading chart of OHLC price data and indicators.

Extended Summary#

The following lists the keys corresponding to various indicators, which can be included in the chart using the indicators argument.

overover

Generic line indicator over chart with key: data

belowbelow

Generic line indicator below chart with key: data

MACDbelow

MACD indicator with keys: macd, signal, histogram

MAover

Moving average overlay indicator with key: data

RSIbelow

RSI indicator with key: data

Heikin-Ashibelow

Heikin Ashi candlesticks with key: data

Supertrendover

Supertrend indicator with key: data

Swingsover

Swing levels indicator with key: data

Engulfingbelow

Engulfing candlestick pattern with key: data

Crossoverbelow

Crossover indicator with key: data

Gridover

Grid levels with key: data

Pivotover

Pivot points with keys: data

HalfTrendover

Halftrend indicator with key: data

multibelow

Multiple indicator type

signalsover

Trading signals plot with key: data

bandsover

Shaded bands indicator type

thresholdbelow

Threshold indicator type

trading-sessionover

Highlighted trading session times with key: data

bricksbelow

Price-based bricks with keys: data (DataFrame), timescale (bool)

param instrument:

The traded instrument name. The default is None.

type instrument:

str, optional

param trade_results:

The TradeAnalysis results object. The default is None.

type trade_results:

TradeAnalysis, optional

param indicators:

Indicators dictionary. The default is None.

type indicators:

dict, optional

param show_fig:

Flag to show the chart. The default is True.

type show_fig:

bool, optional

returns:

Calling this method will automatically generate and open a chart.

rtype:

None

See also

autotrader.autotrader.AutoTrader.analyse_backtest

Usage#

Indicator Specification#

To plot indicators with AutoPlot, you must provide a dictionary containing each indicator. This dictionary must be structured according to the example provided below.

self.indicators = {'indicator 1 name': {'type': 'indicator 2 type',
                                        'data': self.indicator_data},
                   'indicator 2 name': {'type': 'indicator 1 type',
                                        'data': self.indicator_data},
		  ...
                  }

In this dictionary, each key ‘indicator name’ is used to create the legend entry corresponding to the indicator. The sub-dictionary assigned to each indicator contains the specific information and associated data. The type key should be a string corresponding to the type of indicator, as defined in the table below. It is used to determine whether the indicator should be plotted overlayed on the OHLC chart, or below it on a separate plot. Finally, the data associated with the indicator must also be provided. For indicators with one set of data, such as a moving average, simply provide the data with the data key. For indicators with multiple sets of data, such as MACD, provide a key for each set named according to the keys specified in the table below.

Indicator

Type

Keys

Generic overlay indicator

over

data

Generic below-figure indicator

below

data

MACD

MACD

macd, signal, histogram

EMA

MA

data

SMA

MA

data

RSI

RSI

data

Stochastics

STOCHASTIC

K, D

Heikin-Ashi

Heikin-Ashi

data

Supertrend

Supertrend

data

HalfTrend

HalfTrend

data

Swings

Swings

data

Engulfing

Engulfing

data

Crossover

Crossover

data

Pivot Points

Pivot

data, optionally levels

Multiple line plot

multi

See below

Shaded bands

bands

See below

Shaded threshold

threshold

See below

Trade signals

signals

data

Example Indicator Dictionary#

In this dictionary, each key is used to create a legend entry corresponding to the indicator. The sub-dictionary assigned to each key contains the specific information and associated data. The type key is a string corresponding to the type of indicator, for example:

  • 'type': 'MA' for an exponential moving average (or any type of moving average)

  • 'type': 'STOCH' for stochastics Finally, the data associated with the indicator must also be provided. For indicators with one set of data, such as a moving average, simply provide the data with the data key. For indicators with multiple sets of data, such as MACD, provide a key for each set named according to the indicator specification. See the example below for a strategy with MACD, two RSI’s and two EMA’s.

self.indicators = {'MACD (12/26/9)': {'type': 'MACD',
                                      'macd': self.MACD,
                                      'signal': self.MACDsignal,
                                      'histogram': self.MACDhist},
                   'EMA (200)': {'type': 'MA',
                                 'data': self.ema200},
                   'RSI (14)': {'type': 'RSI',
                                'data': self.rsi14},
                   'RSI (7)': {'type': 'RSI',
                               'data': self.rsi7},
                   'EMA (21)': {'type': 'MA',
                                'data': self.ema21}
                  }

Multiple line plot#

To plot multiple lines on the same figure, the multi indicator type can be used. In the example below, a figure with title ‘Figure title’ will be created below the OHLC chart. On this figure, two lines will be plotted, with legend names of ‘Line 1 name’ and ‘Line 2 name’. Line 1 will be blue and line 2 will be red, as set using the ‘color’ key specifier.

indicator_dict = {'Figure title': {'type': 'multi',
                                   'Line 1 name': {'data': line1_data,
                                                   'color': 'blue'},
                                   'Line 2 name': {'data': line2_data,
                                                   'color': 'red'},
                                   }
                  }

Shaded bands plot#

To plot shaded bands, such as Bollinger Bands®, the bands indicator type can be used. An example of using this indicator type is provided below.

indicator_dict = {'Bollinger Bands': {'type': 'bands',
                                      'lower': bb.lower,
                                      'upper': bb.upper,
                                      'mid': bb.mid,
                                      'mid_name': 'Bollinger Mid Line'},
                  }

The full list of keys which can be provided with the indicator type is shown in the table below.

Key

Required/Optional

Description

Default value

band_name

Optional

legend name for bands

String provided for indicator (eg. ‘Bollinger Bands’)

fill_color

Optional

color filling upper and lower bands

‘blue’

fill_alpha

Optional

transparency of fill (0 - 1)

0.6

mid

Optional

data for a mid line

None

mid_name

Optional

legend name for mid line

‘Band Mid Line’

line_color

Optional

line color for mid line

‘black’

Shaded threshold plot#

The threshold plot indicator type is the standalone-figure version of the bands indicator type. That is, instead of overlaying shaded bands on the OHLC chart, a new figure is created below. The same keys apply to this method as the
keys of the bands indicator type, as documented in the table above. An example of using this indicator is provided below.

'RSI threshold': {'type': 'threshold',
                  'lower': 30,
                  'upper': 70,
                  'mid': rsi,
                  'mid_name': 'RSI'},

Trade signals plot#

The signals plot indicator type can be used to overlay buy and sell signals onto the OHLC chart. To do so, pass a DataFrame with columns named “buy” and “sell” with the data key. Note that the values in these coloumns are the prices at which the signal occurs. This means that if you have a DataFrame with Booleans corresponding to the buy and sell points, you will need to multiply them by the price data to shift them.

Unrecognised indicator type#

If an indicator type isn’t recognised, AutoPlot will attempt to plot it as a line plot on a new chart below the OHLC chart using the data key of the indicator. A warning message stating that the indicator is not recognised will also be printed. Also note that a type key can be used for an indicator that isn’t specified above if it has similar plotting behaviour. See the indicators for details on the indicators listed above.

Minimum Working Example#

As a plotting class, each instance of AutoPlot must be provided with price data in the form of OHLC data. A minimal working example is provided below to visualise the price data of Apple from the Yahoo finance feed of AutoData.

from autotrader import AutoPlot, AutoData

instrument = 'AAPL'
get_data = AutoData({'data_source': 'yahoo'})
data = get_data.fetch(instrument, '1d', 
                      start_time='2020-01-01', 
                      end_time='2021-01-01')

ap = AutoPlot(data)
ap.plot(instrument=instrument)