Calculate Bollinger Z-score using Pandas

184 views Asked by At

Given a series, I want to calculate its Bollinger Z-score (not the Bollinger band) using Pandas. There exists a prior question which discusses how to calculate the band, but not the z-score.

Given a variable series of type pandas.Series with dtype float64, I have the formula for calculating the z-score using this answer:

zs = (data - SMA(data, n=20)) / SD(data, n=20)

The above formula however is not Pandas code which I require.

1

There are 1 answers

0
Asclepius On BEST ANSWER

Consider this function. Its output looks to match that of TradingView.

import pandas as pd

def bollinger_zscore(series: pd.Series, length: int = 20) -> pd.Series:
    # Ref: https://stackoverflow.com/a/77499303/
    rolling = series.rolling(length)
    mean = rolling.mean()
    std = rolling.std(ddof=0)
    return (series - mean) / std

To calculate the Bollinger bands instead, see this answer.