Skip to content

Bollinger Bands (ta.bbands)

View Markdown

Construct upper and lower bands around a moving average using standard deviation, providing bandwidth and relative position.

Indicator catalog · How to use indicators

Run this example

This complete script uses bundled data. It observes the selected output without placing trades.

import numpy as np
from openbacktesting import Backtest, Strategy
from openbacktesting.test import GOOG

data = GOOG.copy()

class Example(Strategy):
    def init(self):
        self.value = self.ta.bbands(self.close)
        self.latest_value = None

    def next(self):
        channel = self.value.lower
        if channel.valid[-1]:
            self.latest_value = float(channel[-1])

result = Backtest(data, Example).run()
print(result["_strategy"].latest_value)

Call and parameters

self.ta.bbands(
    source=None,
    *,
    length=5,
    std=2.0,
    ddof=0,
    mamode='sma',
    inputs=None,
    backend=None,
    required_outputs=None,
)

Register in init(). Read the returned channel in next() after checking valid[-1].

Parameter Meaning Type Default Allowed values
length Calculation window in observations. int 5 Minimum: 2
std Standard-deviation multiplier. float 2.0 Minimum: 1e-08
ddof Degrees of freedom subtracted from the variance denominator. int 0 Minimum: 0
mamode Moving-average algorithm; choose one of the listed values. str sma Allowed values: ['sma', 'ema', 'rma', 'wma']

source/named source arguments accept a column name or same-run single-channel handle. Alternatively, inputs maps each input below to a column or handle. backend selects a supported implementation; required_outputs selects channels for readiness diagnostics. See shared arguments and handles.

Inputs and outputs

Required inputs: close.

Channel Meaning
lower Lower band
middle Middle line
upper Upper band
bandwidth Band width relative to the middle line
percent Position between the lower and upper bands (fraction)

Reading values safely

Insufficient history or missing inputs can make a channel invalid. Check that channel's valid mask; ready is diagnostic and never suppresses next(). Multi-output results may have different valid channels on the same bar.

Indicator catalog · Custom calculations