# Bollinger Bands: Python Implementation

Bollinger Bands are one of the most popular technical indicators used by traders. They are very simple to understand and are utilized heavily to get buy or sell signals. Bollinger Bands, in combination with other indicators, generally have a high accuracy.

Bollinger Bands are a technical analysis tool that helps traders assess the volatility and potential price movements of an asset. Consisting of three bands – upper, middle, and lower – Bollinger Bands provide insights into market conditions and generate buy or sell signals. The middle band represents a simple moving average, while the upper and lower bands are typically set two standard deviations away from the middle band. Traders often use Bollinger Bands in conjunction with other indicators to make informed trading decisions.

In this article, we will learn what Bollinger Bands are, how they work, and how to implement this concept in the Python programming language using the Numpy library.

Recommended: Machine Learning Workflows with Pycaret in Python

Recommended: Empirical Distribution in Python: Histograms, CDFs, and PMFs

## Understanding Bollinger Bands: Components and Interpretation

Bollinger Bands is a popular technical indicator used to check an asset’s volatility and price movements. There are three types of bands i.e.: upper, middle, and lower.

• Middle Band: The Middle Band is an SMA with a period of 20. A Simple Moving Average ( SMA ) is a simple average of the past 20 days.
• Upper Band: An upper band is calculated by adding standard deviation 2 to the middle band.
• Lower Band: Similar to the upper band, it is calculated by subtracting 2 standard deviations from the middle band.

The Bollinger band gives us two types of signals, i.e. volatility and buy/sell. The volatility signal of the Bollinger Band can be understood by observing its width. If the band’s width is less, that means less volatility; similarly, if the band’s width is wide, it signals that price movement is very volatile.

If the price touches the upper band of the signal, the signal is to sell the stock as it signals potential reversal. Similarly, if the price touches the lower band, it signals to buy the stock as the price of an asset can bounce back. Let us move on to the next section to understand the Python implementation of Bollinger Bands.

The standard deviation used in calculating the upper and lower bands measures how much the price deviates from the middle band (simple moving average). By default, a factor of 2 is used, meaning that the upper band is 2 standard deviations above the middle band, and the lower band is 2 standard deviations below the middle band. This factor can be adjusted based on the trader’s preferences and the specific characteristics of the asset being analyzed.

## Implementing Bollinger Bands in Python: A Step-by-Step Guide

Let us look at the Python code for Bollinger Bands. We have randomly generated some stock prices, applied Bollinger Bands to them, and plotted the results.

```import numpy as np
import matplotlib.pyplot as plt

# Generate random stock prices
np.random.seed(42)  # for reproducibility
stock_prices = np.random.normal(100, 5, 250)

# Define parameters
window_size = 20
num_std = 2

# Calculate rolling mean and standard deviation
rolling_mean = np.convolve(stock_prices, np.ones(window_size)/window_size, mode='valid')
rolling_std = np.std([stock_prices[i:i+window_size] for i in range(len(stock_prices)-window_size+1)], axis=1)

# Calculate Bollinger Bands
upper_band = rolling_mean + num_std * rolling_std
lower_band = rolling_mean - num_std * rolling_std

# Plotting
plt.figure(figsize=(14,7))
plt.plot(stock_prices, label='Stock Price')
plt.plot(rolling_mean, label='Rolling Mean', color='red')
plt.plot(upper_band, label='Upper Bollinger Band', color='green')
plt.plot(lower_band, label='Lower Bollinger Band', color='green')
plt.fill_between(np.arange(window_size-1, len(stock_prices)), lower_band, upper_band, color='grey', alpha=0.2)
plt.title('Bollinger Bands')
plt.xlabel('Days')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.show()

```

Let us look at the output below.

## Applying Bollinger Bands to Real-World Stock Price Data using CSV Files

Let us now look at the code for implementing the program using an Excel or CSV file. You can get these files from Yahoo Finance.

```import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Read stock prices from Excel or CSV file
# Replace 'stock_prices.xlsx' or 'stock_prices.csv' with your file name
file_path = 'stock_prices.xlsx'
# If your file is in CSV format, uncomment the following line and comment out the previous line
# file_path = 'stock_prices.csv'

# Assuming the file has a single column of stock prices named 'Price'
stock_prices_df = pd.read_excel(file_path)  # for Excel
# If your file is in CSV format, uncomment the following line and comment out the previous line

# Extract stock prices from DataFrame
stock_prices = stock_prices_df['Price'].values

# Define parameters
window_size = 20
num_std = 2

# Calculate rolling mean and standard deviation
rolling_mean = np.convolve(stock_prices, np.ones(window_size)/window_size, mode='valid')
rolling_std = np.std([stock_prices[i:i+window_size] for i in range(len(stock_prices)-window_size+1)], axis=1)

# Calculate Bollinger Bands
upper_band = rolling_mean + num_std * rolling_std
lower_band = rolling_mean - num_std * rolling_std

# Plotting
plt.figure(figsize=(14,7))
plt.plot(stock_prices, label='Stock Price')
plt.plot(rolling_mean, label='Rolling Mean', color='red')
plt.plot(upper_band, label='Upper Bollinger Band', color='green')
plt.plot(lower_band, label='Lower Bollinger Band', color='green')
plt.fill_between(np.arange(window_size-1, len(stock_prices)), lower_band, upper_band, color='grey', alpha=0.2)
plt.title('Bollinger Bands')
plt.xlabel('Days')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.show()

```

## Conclusion

You now have a solid understanding of Bollinger Bands and how to implement them using Python and the NumPy library. By grasping the concepts behind this powerful technical indicator, you’ve added a valuable tool to your trading arsenal.

Bollinger Bands offer a unique perspective on market volatility and potential price movements. By combining the simplicity of moving averages with the power of standard deviations, Bollinger Bands provide clear signals for buying and selling opportunities.

But remember, no single indicator is a magic bullet. The most successful traders combine Bollinger Bands with other technical and fundamental analysis techniques to make well-informed decisions.

So, as you continue your trading journey, keep exploring and experimenting with different strategies. Who knows what new insights and opportunities you’ll discover by leveraging the power of Bollinger Bands?