How to compute the Bollinger Bands using Python

1 min

Bollinger Bands are a technical analysis tool that uses moving averages and standard deviations to determine overbought and oversold conditions. Here's how to calculate Bollinger Bands in Python:

  1. Calculate the moving average: use the rolling method to calculate the moving average of the close prices.
  2. Calculate the standard deviation: use the std method to calculate the standard deviation of the close prices.
  3. Calculate the upper band: add the moving average plus two times the standard deviation.
  4. Calculate the lower band: subtract two times the standard deviation from the moving average.

Here's a sample code for calculating Bollinger Bands in Python:

import pandas as pd
import yfinance as yf

prices = yf.download(["AAPL"])["Adj Close"]

def bollinger_bands(prices, window=20, num_of_std=2):
    rolling_mean = prices.rolling(window).mean()
    rolling_std = prices.rolling(window).std()
    upper_band = rolling_mean + (rolling_std * num_of_std)
    lower_band = rolling_mean - (rolling_std * num_of_std)
    return rolling_mean, upper_band, lower_band
    
print(bollinger_bands(prices))

Replace prices with the data series of close prices. The window argument is the size of the moving average window (defaults to 20), and num_of_std is the number of standard deviations to use in the calculation (defaults to 2).