How to compute the Bollinger Bands using Python

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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).

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.