Dhruv Toshniwal

Using Bollinger Bands for Trading Strategy in Python

July 2023

Using Bollinger Bands for Trading Strategy in Python

Introduction to the Project

This project involved creating a Bollinger Bands based trading strategy using Python. Bollinger Bands are a tool traders use to measure price volatility, consisting of three lines:

  • A middle line (moving average of price)
  • An upper line (standard deviation above the moving average)
  • A lower line (standard deviation below the moving average)

Why Bollinger Bands?

Bollinger Bands help identify relative price levels:

  • When prices move closer to the upper band, the security may be "overbought"
  • When prices approach the lower band, it could be "oversold"

Trading based on these bands can provide insights into potential reversals and trend continuations.

Getting Hands Dirty with Python

Python provides an excellent platform for implementing this strategy, using libraries like:

  • Pandas (data handling)
  • Yfinance (fetching historical stock data)
  • Matplotlib (data visualization)

The code fetches historical stock data, calculates Bollinger Bands, and additional technical indicators including:

  • Simple Moving Averages (SMA)
  • Exponential Moving Averages (EMA)
  • Moving Average Convergence Divergence (MACD)
  • Relative Strength Index (RSI)

How Does It Perform?

The strategy involves:

  • Buying 100 shares when the closing price is below the lower Bollinger Band
  • Selling all shares when the closing price is above the upper Bollinger Band

Compared to a 'Buy and Hold' strategy for the S&P 500, this Bollinger Bands strategy outperforms the benchmark.

Final Thoughts

The Python script is flexible and can be easily customized:

  • Replace ticker symbols
  • Adjust time periods
  • Enhance with more sophisticated algorithms

Check out the code on GitHub