Python has become a popular language among traders and financial analysts due to its versatility and extensive data analysis and visualization libraries. One powerful application of Python in the trading world is backtesting strategies, allowing traders to evaluate the performance of their trading ideas using historical data. Today we show you a **Python Bollinger Band trading strategy**.

**Bollinger bands are a widely technical indicator that helps identify potential price reversals and volatility in financial markets. John Bollinger developed them and are very simple and intuitive to use. We show a complete trading strategy with trading rules and results.**

This article will walk through the essential steps of backtesting a Bollinger Band trading strategy. We will start by explaining the rules and logic behind the strategy, discussing how to set up the necessary data, and finally, providing a Python code implementation for backtesting.

**Related reading:**

## Downloading the data

In order to backtest a trading strategy, we first need to download the historical data of the stocks or ETFs. In Python, the yfinance library provides a convenient and efficient means of accomplishing this task. If you want to learn more about the yfinance library see this post:

- Best Python Libraries For Algorithmic Trading (Examples)
- How To Download Data For Your Trading Strategy From Yahoo!Finance With Python
- How To Build A Trading Strategy From FRED Data In Python (Strategy, Backtest, Rules)
- Python and RSI Trading Strategy (Backtest, Rules, Code, Setup)
- Python and Trend Following Trading Strategy (Backtest, Rules, Code, Setup)
- Python and Momentum Trading Strategy (Backtest, Rules, Code, Setup)
- Python and MACD Trading Strategy: Backtest, Rules, Code, Setup, Performance

First, we need to import the libraries. We will be using pandas, numpy, matplotlib.pyplot and, as we just mentioned, yfinance.

To download the historical data, we will define a variable (df) and utilize the **yf.download()** function, placing the ticker symbol within the parentheses. It’s as straightforward as that.

If we print df here is the output:

We now have all the daily open, high, low, close, adjusted close, and volume values for Microsoft since 1986!

## Calculating the Bollinger Bands

The Bollinger Bands is a technical indicator that is plotted two standard deviations, both positively and negatively, away from a simple moving average (SMA) of a security’s price. In this backtest, we are going to use the usual configuration that is 2 standard deviations +/- from a 20-day simple moving average.

To calculate this in Python, we will create two new columns in df: one for the simple moving average and the other for the standard deviation. In both cases, we are going to use the **.rolling()** function from pandas. The only distinction lies in the method appended at the end: **.mean()** for computing the SMA and **.std()** for calculating the standard deviation.

Now the only thing left is to create another two columns in df for the upper and lower band. In the upper band column, we will sum two standard deviations to the SMA, and in the lower band, we will rest to standard deviations from the SMA.

Now that we have calculated the Bollinger Bands, we can begin doing the backtest.

## Calculating the returns of the strategy

The strategy we are going to backtest is pretty easy:

- We buy when the closing price is under the lower Bollinger Band
- We sell the price crosses above the upper Bollinger Band

In order to do this, we are going to create a new empty column called â€˜positionâ€™. Then, starting from the 20th index (because we choose the 20-day SMA), we will assign a 1 value to the row in the â€˜positionâ€™ column when the adjusted close is below the value in the lower band. Otherwise, it assigns a value of 0.

To calculate the sell signal we will use the same function. Starting from the 20th index, we will assign a value of -1 to the row in the â€˜positionâ€™ column if the adjusted close is above the upper band. If not, it retains the previous value from the â€˜positionâ€™ column. All of this is done using the **np.where()** function from numpy.

Last, we create another column to calculate the daily returns of the strategy. To do this, we will multiply the daily change in the security by the lagged values in the â€˜positionâ€™ columns(shifted by 1), and then add 1 to the result.

Once we did this, we successfully calculated the returns of the trading strategy.

## Plotting the results of the strategy

Now, the only thing left to do is plot the returns to see the strategy’s equity curve.

We will create one last new column called â€˜cumulative returnsâ€™ in df where we will calculate the cumulative returns of the â€˜returnsâ€™ column using the **.cumprod()** method.

Finally, we will generate a plot showcasing the “cumulative returns” column. Utilizing the **.plot()** function, we create the plot with **figsize=(11,7)** to specify the dimensions of the figure. The title of the plot is set as “Equity Curve” using **title=’Equity Curve’**. This visual representation portrays the trading strategy’s performance over time, providing insights into the evolution of cumulative returns. By invoking **plt.show()**, the plot is displayed on the screen for observation.

The Bollinger Band trading strategy compounded money at a 2.65% per year while it was only invested 10.6% of the time. Please keep in mind that the purpose of the article is to show how you can use Python. The strategy itself is only for informational purposes.

## How to backtest a Bollinger Band trading strategy in Python – conclusion

To sum up, today we explored the process of backtesting a Bollinger Band trading strategy using Python. The strategy may not have had a stellar performance, but with this knowledge, you can confidently explore and refine your own trading ideas, employing Bollinger Bands as a powerful tool in your decision-making process.