CodeX
Published in

CodeX

Image Source

Algorithmic Trading with Bollinger Bands in Python

An automated way to trade stocks with Bollinger Bands in Python

Bollinger Bands

Image by Author
UPPER_BB = STOCK SMA + SMA STANDARD DEVIATION * 2
LOWER_BB = STOCK SMA - SMA STANDARD DEVIATION * 2
IF PREV_STOCK > PREV_LOWERBB & CUR_STOCK < CUR_LOWER_BB => BUY
IF PREV_STOCK < PREV_UPPERBB & CUR_STOCK > CUR_UPPER_BB => SELL

Implementation in Python

Importing packages

Extracting data from IEX Cloud

Image by Author

Bollinger Bands calculation

Image by Author
Image by Author

Plotting Bollinger Bands values

Image by Author

Creating the Trading Strategy

Plotting the Trading lists

Image by Author

Creating our Position

Image by Author

Backtesting

Profit gained from the BB strategy by investing $100k in TSLA : 18426.42
Profit percentage of the BB strategy : 18%

SPY ETF Comparison

Benchmark profit by investing $100k : 13270.5
Benchmark Profit percentage : 13%
BB Strategy profit is 5% higher than the Benchmark Profit

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikhil Adithyan

Founder @CodeX (medium.com/codex), a medium publication connected with code and technology | Top Writer | Connect with me on LinkedIn: https://bit.ly/3yNuwCJ