How To Calculate Bollinger Bands in Python?

by norberto_waelchi , in category: Technical Analysis , a month ago

How To Calculate Bollinger Bands in Python?

Facebook Twitter LinkedIn Whatsapp

1 answer

by shirley.reilly , a month ago

@norberto_waelchi 

To calculate Bollinger Bands in Python, you can use the following steps:

  1. Import the necessary libraries:
1
2
import pandas as pd
import numpy as np


  1. Define a function to calculate the Bollinger Bands:
1
2
3
4
5
6
7
8
9
def calculate_bollinger_bands(data, window_size, num_std):
    # Calculate rolling mean and standard deviation
    rolling_mean = data.rolling(window=window_size).mean()
    rolling_std = data.rolling(window=window_size).std()
    
    upper_band = rolling_mean + (rolling_std * num_std)
    lower_band = rolling_mean - (rolling_std * num_std)
    
    return upper_band, lower_band


  1. Replace data with the time series data you want to calculate the Bollinger Bands for, window_size with the number of periods to use for the rolling mean and standard deviation calculations, and num_std with the number of standard deviations to use for the bands.
  2. Call the calculate_bollinger_bands function with your data:
1
2
3
4
5
data = pd.Series([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1])
window_size = 5
num_std = 2

upper_band, lower_band = calculate_bollinger_bands(data, window_size, num_std)


  1. Plot the Bollinger Bands:
1
2
3
4
5
6
7
import matplotlib.pyplot as plt

plt.plot(data, label='Data')
plt.plot(upper_band, label='Upper Band')
plt.plot(lower_band, label='Lower Band')
plt.legend()
plt.show()


This will plot the Bollinger Bands along with the data. You can customize the plot further with different colors, labels, etc.