As soon as you start searching for stock market data you quickly get your feeds on social media platforms flooded with trading tips. Stay sceptical and try them out before you jump in. In most cases the shortcomings show up sooner than you think. Let us play around with a simplified Bollinger Bands algorithm and write some code to compare multiple strategies.
Bollinger Bands?
Bollinger Bands are a technical analysis indicator made up of three lines plotted around an asset's price: a middle band that is typically a 20-period moving average, and an upper and lower band set a certain number of standard deviations (usually two) above and below that average. Because the bands are based on standard deviation, they automatically widen when price volatility increases and narrow when volatility decreases, giving a visual way to judge whether prices are relatively high or low compared to their recent history.
We use the crossing of the closing line with the lower band as a buy indicator and sell when the closing line crosses the upper band. This is an intentional simplification because that is what most LLMs will generate if you ask to build such a tool.
Implement the strategy
Since we want to test multiple strategies, we will need to implement multiple algorithms. For that I prefer to have a defined contract that we can enforce for each implementation. We can use this abstract class to make sure that the methods we need are there:
After we calculated the buy and sell signals, we want to run through our data and see how much money we could have made. For that we start with an initial cash amount and go all-in when a buy signal shows up and sell everything on a sell indicator. We ignore all details like trading costs to focus on the strategy.
The baseline() method is there as a benchmark and shows what would have been if we bought the stocks at the first trading day and sold them on the last day.
Plot the stock and the trades
To visually control the trades, we can use this little helper function to plot the stock price and the trading signals:
We see that our base line of Buy & Hold would have given us a return of 35.63%, while the Bollinger Bands strategy would have a return of 39.35% - or $371.80 more for an investment of $10000.
The plot shows us when we made the trades and what happened afterwards on the stock market:
Next
We needed a lot more code than I anticipated to test the Bollinger Bands strategy. But our investment in code pays its dividend when we add more strategies as we see in the next post.