Algorithmic Trading with Python: The RSI-Bollinger Band Strategy (2024)

Algorithmic Trading with Python: The RSI-Bollinger Band Strategy (1)

Published in

InsiderFinance Wire

·

6 min read

·

Aug 19, 2021

--

Algorithmic Trading with Python: The RSI-Bollinger Band Strategy (3)

If there’s one thing that’s for certain, trading psychology plays a major role in evaluating the direction of share prices. Containing those emotions could be the difference in producing a successful or an unsuccessful trade. The ability to think quickly whilst exercising discipline are important skills to hone, however there’s always two things which control the market…

Fear and Greed

oh yeah, can’t forget…

Hedge Funds

So maybe three things.

Speaking of the two emotions, they are an important sentiment in moving the market and it’s what drives share prices to all time highs … and all time lows. But what if we could create an investment/trading strategy not based on emotions, but on cold hard data? It is what they say…

Data is the new oil

And hedge funds are paying top dollar for specialists with the skills to harness the power behind it, to create complex models in helping predict and ascertain the stock market. And what is this so called “skill”? Algorithmic Trading.

Don’t get me wrong, human oversight is also an important aspect of Algorithmic Trading but it also combines the power of machines and mathematics to help make decisions in buying, selling and even holding onto securities. Plus, there’s another big advantage:

A computer doesn’t have feelings … well not right now at least.

Having the ability to model the intricacies of the stock market using mathematics and programming could make all the difference in spotting new opportunities.

So let’s take a close look at a well known strategy … and code it of course. I mean it does have the word “Algorithmic” right?

Algorithmic Trading with Python: The RSI-Bollinger Band Strategy (4)

First of, lets talk about this strategy. The RSI and Bollinger-Band strategy combines two technical indicators: momentum and volatility. This tells us two important things:

  • when a share is trading high or low,
  • when a share price is overbought and oversold

This is what makes this strategy such an extremely powerful tool. I’m not by all means a financial advisor but every trader or investor should at least know this.

The Bollinger Bands utilizes 3 time-series plots/lines:

  • An upper band which is 2 standard deviations above the moving average
  • A middle band which is the moving average of the closing price
  • A lower band which is 2 standard deviations below the moving average

Whenever the market closes above the upper band, this indicates that the share is trading at a high price whilst if it closes below the lower band, this may indicate that the price is trading too low.

Statistically, these upper and lower bands utilize standard deviations to measure how far they are from the average. A high standard deviation means that prices are trading far from the average whilst a low deviation means that prices are trading close to the average. Hence, we use to 2 standard deviations from the average price, this gives a 13.6% chance of meeting either the upper or lower bands and a 2.1% chance of crossing either.

Now, let’s talk about RSI. The RSI (Relative Strength Index) is a type of momentum oscillator which fluctuates between 0 and 100. Typically, if the RSI goes above 70 this indicates that the stock is overpriced whilst if it goes below 30 the stock is oversold. This helps traders or investors measure the speed and change of a share price.

This will form the basis of our program. Let’s start coding!

Firstly, we’ll need a function which automatically reads stock price data. We’ll obtain this function from a previous article that I wrote A Complete Guide: Implementing Aroon Indicators using Python. This function will receive a ticker symbol, a start date and end date:

Next, we’ll create a function which will calculate the relative strength:

The relative strength is based on calculating a certain period’s gains and losses. Afterwards, we’ll take the rolling average of each of those gains and losses to help calculate our RSI:

The relative strength is further calculated by dividing the average gains by the average losses. We then plug those values into the RSI formula.

We’ll now plot the results of the RSI:

The function above helps visualize the RSI and it’s levels, each of which are color-coded. It also labels the most recent RSI with a “Sell” if it crosses more than 70 and a “Buy” if it crosses 30.

Next we’ll combine all the functions above to create one main function, the reason why I decided to implement several helper functions was to breakdown the process:

Thus, we can clearly see how the RSI is calculated and the number of steps it takes.

We’ll implement our Bollinger Bands now:

This function may look daunting and confusing, so let me summarize it into three key points:

  • The Bollinger Bands are calculated using three formulas. This is achieved by taking the moving average (middle band), then the moving average plus the standard deviation of the middle band and the moving average minus the standard deviation of the middle band.
  • The first for loop essentially determines whether the closing price crosses the upper and lower bands. It will display the signals if and only if it crosses either bands.
  • Finally, we plot the results and label each signal with their corresponding closing price.

Finally, we can combine the Bollinger Band and RSI functions into one unified function which will display the Bollinger Band in the top plot and the RSI in the bottom plot:

There we have it!, the complete implementation of the RSI and Bollinger Band strategy. Let’s backtest it using Microsoft’s historical stock prices (MSFT) between 2020–01–02 to 2021–08–16. We’re also going to specify a 14-day period for RSI and a 13-day period for the Bollinger Bands. Let’s run the driver method below:

Using Jupyter Labs or Notebooks, we attain the following results:

Algorithmic Trading with Python: The RSI-Bollinger Band Strategy (5)

The number of periods can be specified at will and it’s ultimately your decision to determine the number of days to base your analysis on.

Every Algorithmic Trading strategy has it’s faults and so too does this strategy. In theory, it does looks nice and simplified on the outside, however its not clearly sufficient on relying on such logic to make buy or sell decisions. Ultimately, we need to analyze other factors such market conditions, upward or downward trends and company fundamentals, this is the “human oversight” i was talking about. There’s also one more reason…

Randomness

The stock market is a dynamic and crazy place. Any negative or positive news could cause the share price to fly or tank. Nevertheless, it’s ultimately your decision to decide whether to exit or enter a position. This strategy is merely for guidance and intuition and trading in real-time is a completely different ball game and you need to adjust your strategies accordingly.

I am an expert in algorithmic trading and financial markets, with a deep understanding of trading psychology, technical indicators, and quantitative strategies. My expertise is demonstrated through years of practical experience in analyzing market trends, developing trading algorithms, and implementing trading strategies based on mathematical models and statistical analysis.

In the article you provided, several key concepts related to algorithmic trading and technical analysis are discussed:

  1. Trading Psychology: The article emphasizes the importance of controlling emotions such as fear and greed in trading, highlighting how they influence market movements and trading decisions.

  2. Technical Indicators: The article introduces two key technical indicators: Relative Strength Index (RSI) and Bollinger Bands. These indicators are used to analyze momentum, volatility, and overbought/oversold conditions in the market.

  3. Algorithmic Trading: The article discusses algorithmic trading as a method to remove emotional biases from trading decisions and leverage data-driven strategies to predict market movements.

  4. Bollinger Bands: Bollinger Bands consist of three lines – an upper band, a middle band (which is the moving average), and a lower band. These bands are used to identify potential overbought or oversold conditions in the market based on standard deviations from the moving average.

  5. RSI (Relative Strength Index): RSI is a momentum oscillator that fluctuates between 0 and 100. It is used to identify overbought or oversold conditions in the market based on the speed and change of price movements.

  6. Python Programming for Financial Analysis: The article demonstrates how to implement the RSI and Bollinger Bands strategy using Python programming. It includes functions to calculate RSI, plot RSI levels, calculate Bollinger Bands, and combine both indicators into a unified function.

  7. Backtesting: The article discusses the importance of backtesting trading strategies using historical stock price data to evaluate their effectiveness in different market conditions.

  8. Limitations of Technical Analysis: While technical analysis using indicators like RSI and Bollinger Bands can provide valuable insights, the article acknowledges its limitations, such as not accounting for other market factors like news events and fundamental analysis.

Overall, the article provides a comprehensive overview of using technical indicators and algorithmic trading strategies, while also highlighting the importance of human oversight and adapting strategies to real-time market conditions.

Algorithmic Trading with Python: The RSI-Bollinger Band Strategy (2024)

References

Top Articles
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 5916

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.