pythonpandastechnical-indicator

Calculate Bollinger Band using Pandas


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.


Solution

  • 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})
    

    To calculate the Bollinger Z-score instead, see this answer.