Calculate Bollinger Band using Pandas

Question:

Given a series, I want to calculate its Bollinger Band using Pandas. There exists a prior question, an answer to which discusses only the std aspect of the calculation, but not the entire calculation.

Given a variable series of type pandas.Series with dtype float64, to compute a band having a length of 20 and a standard deviation of 2, I tried:

2 * (series.rolling(20).mean() + series.rolling(20).std(ddof=0))

The above formula however produces a grossly incorrect result.

Asked By: Asclepius

||

Answers:

Consider this function. Its output matches that of TradingView.

import pandas as pd


def bollinger_bands(series: pd.Series, length: int = 20, *, num_stds: tuple[float, ...] = (2, 0, -2), prefix: str = '') -> pd.DataFrame:
    # Ref: https://stackoverflow.com/a/74283044/
    rolling = series.rolling(length)
    bband0 = rolling.mean()
    bband_std = rolling.std(ddof=0)
    return pd.DataFrame({f'{prefix}{num_std}': (bband0 + (bband_std * num_std)) for num_std in num_stds})
Answered By: Asclepius

You can also consider talib:

import talib

upper_bands, middle_bands, lower_bands = talib.BBANDS(
    real=candles['close'],
    timeperiod=20,
    nbdevup=1,
    nbdevdn=1,
    matype=talib.MA_Type.SMA
)
Answered By: Philippe Remy