Technical indicators Bollinger Bands


Background

Bollinger Bands are a type of statistical chart characterizing the prices and volatility over time of an asset, using a formulaic method propounded by John Bollinger in the 1980s.

Bollinger Bands consist of an N-period moving average (MA), an upper band at K times an N-period standard deviation above the moving average (MA + Kσ), and a lower band at K times an N-period standard deviation below the moving average (MA − Kσ). Typical values for N and K are 20 days and 2, respectively.

Bollinger Bands can be used to provide a relative definition of high and low prices of a market, that is to say, prices are high at the upper band and low at the lower band. Traders often use Bollinger Bands to determine whether an asset is overbought or oversold. When prices approach the upper band, it suggests that the asset may be overbought and due for a correction, while prices near the lower band suggest that the asset may be oversold and due for a rebound.

Python Implementation

import pandas as pd
import sqlite3

# load S&P500 data from stored database
sp500_db = sqlite3.connect(database="sp500_data.sqlite")

df = pd.read_sql_query(sql="SELECT * FROM SP500",
                       con=sp500_db,
                       parse_dates={"Date"})
df.head()

level_0indexDateTickerAdj CloseCloseHighLowOpenVolumegarmin_klass_volrsi
0002014-04-29A35.04953438.12589338.30472237.17453438.1187404688612.0-0.002274NaN
1112014-04-29AAL33.47674235.50999835.65000234.97000135.2000018994200.0-0.000788NaN
2222014-04-29AAPL18.63333321.15464221.28500021.05392821.205000337377600.0-0.006397NaN
3332014-04-29ABBV34.03498551.36999951.52999950.75999850.9399995601300.0-0.062705NaN
4442014-04-29ABT31.83151838.54000138.72000138.25999838.3699994415600.0-0.013411NaN
import pandas_ta
import numpy as np

# calculate bollinger bands for AAPL
aapl = df[df['Ticker'] == 'AAPL'].set_index('Date').drop('index',axis=1).drop('level_0',axis=1)
aapl['bb_low'] = pandas_ta.bbands(close=aapl['Adj Close'], length=20).iloc[:,0]
aapl['bb_mid'] = pandas_ta.bbands(close=aapl['Adj Close'], length=20).iloc[:,1]
aapl['bb_high'] = pandas_ta.bbands(close=aapl['Adj Close'], length=20).iloc[:,2]
aapl.tail()

TickerAdj CloseCloseHighLowOpenVolumegarmin_klass_volrsibb_lowbb_midbb_high
Date
2024-04-19AAPL165.000000165.000000166.399994164.080002166.21000767772100.00.00007837.902497164.869819170.207500175.545180
2024-04-22AAPL165.839996165.839996167.259995164.770004165.52000448116400.00.00011139.784337164.314856169.885500175.456143
2024-04-23AAPL166.899994166.899994167.050003164.919998165.35000649537800.00.00004942.166124163.989522169.687999175.386475
2024-04-24AAPL169.020004169.020004169.300003166.210007166.53999348251800.00.00008546.706439163.947623169.653499175.359375
2024-04-25AAPL169.889999169.889999170.610001168.149994169.52999950558300.00.00010448.493460164.025646169.482499174.939352
import plotly.graph_objs as go
from datetime import datetime

# only select the data from 2023-01-01
aapl_new = aapl[aapl.index > datetime(2023,1,1)]

# Create a Plotly figure
fig = go.Figure()

# Add the price chart
fig.add_trace(go.Scatter(x=aapl_new.index, y=aapl_new['Adj Close'], mode='lines', name='Adj Close Price'))

# Add the Upper Bollinger Band and shade the area
fig.add_trace(go.Scatter(x=aapl_new.index, y=aapl_new['bb_high'], mode='lines', name='Upper Bollinger Band', line=dict(color='red')))
fig.add_trace(go.Scatter(x=aapl_new.index, y=aapl_new['bb_low'], fill='tonexty', mode='lines', name='Lower Bollinger Band', line=dict(color='green')))

# Add the Middle Bollinger Band (MA)
fig.add_trace(go.Scatter(x=aapl_new.index, y=aapl_new['bb_mid'], mode='lines', name='Middle Bollinger Band', line=dict(color='blue')))

# Customize the chart layout
fig.update_layout(title='AAPL Stock Price with Bollinger Bands',
                  xaxis_title='Date',
                  yaxis_title='Price',
                  showlegend=True)

# Show the chart
fig.show()

AAPL Bollinger Bands


Author: wenvenn
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source wenvenn !