Bollinger Bands with Python

This is not an investment advice.

Bollinger Bands belong among popular stock and cryptocurrency trading indicators. Bollinger Bands consist of 3 lines - price moving average for selected window (typically 20 datapoints), upper and lower Bollinger Band.

Upper and lower Bollinger bands are situated usually 2 standard deviations (sigma) above and below the moving average. Two sigma range means that the price will stay between Upper and Lower Bollinger band around 95% of the time. This can be used as a trading signal, since once price is outside the bands we have statistical outlier that is potentially actionable. Price above Upper Bollinger Band is considered overbought and conversely price below Lower band is considered oversold.

Bollinger Band definition from investopedia: https://www.investopedia.com/terms/b/bollingerbands.asp

$$ BU = MA(TP, n) + m * \sigma(TP, n) $$


$$ BL = MA(TP, n) - m * \sigma(TP, n) $$

$BU$ = Upper Bollinger Band
$BL$ = Lower Bollinger Band

$MA(TP, n)$ ... Moving Average of Typical Price for given datapoint window n
$TP = (High + Low + Close) / 3$ ... Typical Price
$\sigma(TP, n)$ ... standard deviation computed from Typical Price for given datapoint window

$n$ = datapoint window for MA
$m$ = how many standard deviations width we are using

Bollinger Bands can also nicely visualize price volatility. Bollinger Band range expansion is followed by range contraction and vice versa. This can be used to anticipate breakouts.

Library imports

Getting stock data from Yahoo API

Function definition

Plot daily data and Bollinger Bands

Signalling noise supression

Following is consideration for swing trading or just investing during dips. When we want to get less trading signals, we can try to increase the time window, here from daily to weekly data. So we will resample our initial dataframe to weekly and then plot long and short signals.

We can generate signals by checking for situations when Closing price is out of bounds or when High or Low price is outside the Bollinge Bands.

Weekly graph with trading signals

In the example of BIDU stock we see breakouts from range contraction where price was at consolidation. It is worth considering to follow second or third buy signal after breaking down from tight range. Bollinger Bands are complementary indicator and are best to be used along RSI, MACD or other indicators.

Sources:

https://github.com/Crypto-toolbox/pandas-technical-indicators
https://www.quantopian.com/posts/technical-analysis-indicators-without-talib-code
https://www.investopedia.com/terms/b/bollingerbands.asp
https://www.youtube.com/watch?v=gEIw2iUlFYc&ab_channel=ComputerScience