Build Your Own Algorithmic Trading Strategies: RSI High Low Trading Strategy

Build Your Own Algorithmic Trading Strategies: RSI High Low Trading Strategy
Title Image for TradeOxy Blog Episode: Build Your Own Algorithmic Trading Strategies. RSI High Low Trading Strategy

How good would it be if there was a strategy to build your own trading strategy?

A repeatable way to convert your exciting, powerful, possibly profitable trading strategy and convert it into an algorithmic trading bot?

I cannot count the number of times this would have been useful for me prior to developing this process. Instead of filling notepads with complex formulas (scribbles) and ideas, I could have focused my time on converting my thoughts into trading bots. Establishing hypothesis' and testing them on the market.

In today's episode, I'm going to show you a really simple way to take your amazing trading strategies and convert them into useable computer algorithms. In the process, you'll learn how to build your own RSI Trading Strategy.

If that resonates with you, read on to find out more!


What You'll Learn Through My Blog

I'm going to show you everything you need to build your own trading bot from scratch, including:

  • Your own completely customizable development environment, including the worlds most popular technical indicators, and cutting-edge AI from ChatGPT
  • The ability to retrieve historical stock data on over 10,000 US based stocks
  • The power to calculate stock technical indicators on any stock you retrieve
  • The insight to manage your risk

The premium episodes expand this amazing knowledge base to include:

  • The technical indicators you can include
  • Advanced risk management
  • Advanced strategy building

What You'll Have by the End of this Episode

By the end of this episode, you'll have built your own, fully customizable algorithmic trading strategy using the RSI technical indicator. More importantly, you'll have worked through a completely repeatable process to get there, empowering you to figure out your own trading algorithms in the future.

As a free bonus, my team at TradeOxy has also developed this free "Algo Trading Builder" PDF which you can use as a quick cheat sheet.

Check it out, and if you need someone to build a complex trading strategy for you, then get in touch.

💡
A quick note. The process I outline in this article is something that works for me, however it's by no means the only way to do it. Feel absolutely free to change, modify, and discard whatever doesn't work for you.

GitHub Code

All code for this episode can be found on the something-cool GitHub repository. It is open-sourced under the MIT licence, and you can access it here:

Prior Knowledge

To complete this episode, you need to have the following:

  1. A dev environment with Python and TA Lib installed. If you haven't got this, check out my episode: Build Your Own Trading Bot Dev Environment that works from Anywhere and includes TA Lib, AI
  2. A way to retrieve historic market pricing data from the stock market. If you haven't got this, check out my episode: Build Your Own Trading Stock Trading Bot with Alpaca Markets: Historical Data Retrieval
  3. A way to calculate the RSI (Relative Strength Index) on your market data. If you haven't got this, check out my episode xxxx
💡
While completing this episode, please remember that all trading is at your own risk. My goal is to explain and demonstrate, not provide any kind of advice on what will or won't work. Make sure you do your own research before risking any actual money.

Helpful Help from TradeOxy

TradeOxy's mission is to democratize algorithmic trading, and that mission extends to my blog.

If at any point you get stuck in this series, then reach out to us on our Discord chat. I and my team will be more than happy to help out (just make sure it's about our content).


How Do I Design My Own Trading Algorithms?

💡
To help you design your own algorithms, my team has created a FREE document you can use any time you want. Check it out here (and the associated Privacy Policy)

The first stage when building your own algo trading strategies is designing your algorithm. Your goal is to define the characteristics of your strategy. There are three components.

The three pillars of algorithmic systems. Part of the TradeOxy Blog Episode: Build Your Own Algorithmic Trading Strategies. RSI High Low Trading Strategy.

Algorithmic Trading System Design 101: Algorithm Hypothesis

When building trading algorithms for my customers, I find that the best starting point is to define the the hypothesis of your algorithm.

Your hypothesis should consist of three components, in whatever order makes sense to you.

  1. A statement you can prove or disprove.
  2. An area of the financial markets you'll be targeting
  3. A specified period of time required to prove or disprove the hypothesis
Circular diagram of three elements feeding into each other. Part of the TradeOxy Blog Episode: Build Your Own Algorithmic Trading Strategies. RSI High Low Trading Strategy.

Here's a really simple example of what this could look like if you're into intrinsic value investing:

💡
Example. I believe that AAPL is going to increase their iPhone sales. I believe that when AAPL iPhone sales increase year-on-year, their market cap will increase. Profit opportunities exist if I purchase the AAPL stock now and the iPhone sales increase.

Let's break it down:

  1. Statement. The hypothesis states two thing we can measure. iPhone sales and market cap. We also know that both must increase in order for the hypothesis to be proven true. We can get the iPhone sales from AAPL's financial data, and the market cap from market data feeds.
  2. Financial markets. The hypothesis identifies that we will be using the NASDAQ stock market data, as this is where AAPL's market cap is recorded.
  3. Time Bound. The hypothesis states a one-year period to prove or disprove the idea.
Three elements image with an example attached. Part of the TradeOxy Blog Episode: Build Your Own Algorithmic Trading Strategies. RSI High Low Trading Strategy.

Of course, this is a very simplistic hypothesis! For instance, in true value investing, we might want to understand how we can predict that AAPL is going to increase their iPhone sales. This in turn might lead to more hypothesis...and so on.

Now, let's see if we can come up with a technical indicator-based hypothesis for the AMZN stock.

💡
DIY Challenge: I challenge you to download our FREE Resource and have a go yourself before checking out the next paragraph 😄

Algorithmic Trading System Design 102: Algorithm Risk Management

All trading involves risk. There is very rarely, if ever, risk free profit. If there was, we'd all be doing that, and not reading this blog!

💡
For this blog post, we'll be considering risk management as it applies to our specific algorithm. This is different and separate to overall investment strategy risk management, a topic I write about in other episodes.

There's three easy ways to manage risk in our trading algorithm.

  1. Entry price. We can set a target entry price for our chosen financial instrument that confirms our hypothesis
  2. Stop loss. We can limit our losses by setting a target price that will automatically execute if our chosen financial instrument crosses a certain threshhold.
  3. Take profit. We can lock in our profits by setting a target price that will automatically execute if our chosen financial instrument crosses a certain threshold.
Three pillars of simple risk management for your trading bot. Part of the TradeOxy Blog Episode: Build Your Own Algorithmic Trading Strategies. RSI High Low Trading Strategy.

Trading Volume Note. Experienced algorithmic traders can also use trading volume to manage their risk. This makes algorithmic trading systems more complex, and can head into high frequency trading. As a result, I decided to cover this in its own episode. Check out my blog list if that's of interest to you.

Example. Let's look at this using the original AAPL hypothesis. Keep in mind that we don't know for sure if our hypothetical iPhone sales are going to increase.

  1. Entry price. We could set the entry price for our AAPL stock to be 1% higher than the current market price, making the assumption that this would confirm that the AAPL price will rise.
  2. Stop loss. We could set a stop loss on our AAPL stock that is set to the current level, knowing that by the time a stock purchase is executed at our entry price, this would provide us with a 1% buffer.
  3. Take profit. We could set a take profit on our AAPL stock that is 5% higher than the entry price, meaning that if the stock rose at least 5% we would be a profit.

Here's what that would look like:

Example of a trade with a BUY, STOP LOSS, and TAKE PROFIT. Part of the TradeOxy Blog Episode: Build Your Own Algorithmic Trading Strategies. RSI High Low Trading Strategy.
💡
DIY Challenge: I challenge you to download our FREE Resource and have a go yourself before checking out the next paragraph 😄

Algorithmic Trading System Design 103: Choose Your Trading Systems

Finally, you need to choose your trading systems. This will most likely include some combination of the following:

  1. Your market access system to get historical market data. For instance, it might be MT5 for Foreign Exchange Traded funds (FOREX), or TD Ameritrade for Stock Market prices.
  2. Your indicator analysis system - i.e. how you are going to go about automatically calculating buy and sell orders (we are building an algo trading bot after all).
  3. (Covered in another episode) Your trade execution system - i.e. how you are going to go about executing trades.

How Do I Capture Future Market Movements with Automated Trading Decisions?

With our theory complete, let's design and build an automated trading algorithm.

Define Your Trading Strategy Design

Using the steps outlined in the theory, here's the trading strategy design I've come up with for our algorithmic trades.

Hypothesis. I believe that the AMZN stock will oscillate around a price range month-to-month given a certain momentum. Profit opportunities exist if I can buy when the stock is oversold and sell when the stock is overbought.

Risk management.

  1. Entry Price. Buy when the price goes 1% above the current market price
  2. Stop Loss. 1% below the entry price
  3. Take Profit. 3% above the entry price

Trading systems.

  1. Market data. Alpaca Markets.
  2. Indicator analysis. RSI, using TA Lib
  3. Trade execution. Alpaca Markets, covered in a future episode.

P.S. If you want to learn more about the RSI and why it is well suited to this hypothesis, you can check out my article here.

Automated Decision Environment Setup

We're finally about to write some code! Thank goodness!

💡
If you've previously added a strategy to your trading bot, then skip this section. If not, carry on below.

In the RSI episode, I showed you how to calculate your own RSI indicator. Now we're going to use this to build our strategy.

In your dev environment, create a new file called `strategies.py`. This file will contain all the different strategies you'll build through my blog. Here's what your file structure should look like:

Addition of strategies.py to trading bot

Now, we're going to add some routing to the file so we can branch based on the strategy we're calculating. To do this, add the following function to your strategies.py:

This function:

  1. Imports the pandas library, covered in this episode
  2. Imports the indicators library, covered in this episode
  3. Creates a framework to get ready to branch based on the trading algorithm selected

How to Code Your RSI Trading Algorithm

With your routing set up, let's define your RSI strategy in code. Add the following to the bottom of your strategies.py

This is the heart of our strategy, so I'll go through it in a bit more detail.

Indicator Calculation. We start by calculating our RSI indicator. If you recall from the RSI episode, this indicator calculates high and low prices through a quantitative analysis process. It returns several pieces of information to us, including:

  1. Overbought and oversold levels as defined in the RSI High (default 70) and RSI Low (default 30) settings.
  2. A RSI Signal which is 'Buy' when the price is below the RSI Low and 'Sell' when the price is abobe the RSI High

Risk Management Addition. Once we've calculated the RSI, the next stage in our trading process is to define our trading range. Because this stock algorithm is only considering 'Buys' for the entry point, I simply calculate an Entry Price, Stop Loss and Take Profit for every candlestick in the DataFrame, defining my accepted risk tolerance for the trading algorithm.

💡
Note. The reason I do this for every candlestick, not just the last one is a bit counterintuitive. Basically, the way Pandas DataFrames work is through matrix calculation. It is nearly 100 times faster to do it this way than any other way, and while we're not looking to perform any crazy fast high frequency trading, it's just a good habit to get into. It will also really help us undertake backtest which I cover in a another episode.

Trading Decision. The final step is capture the trading decision, which is in the return_dictionary['strategy_outcome'] field.

Update calc_strategy to route to RSI Strategy

Return back to your calc_strategy() function, and update it so it looks like this:

This will:

  1. Check that your RSI parameters are valid
  2. Calculate the RSI strategy

Make Your Algorithmic Systems WORK!

Ha! We're about to make it so your RSI strategy takes flight! Who knows what could happen next!

In all seriousness, if this is your first movement away from a human traders approach and into the world of algorithmic trades, then congratulations. This is a huge step!

In your dev envrionment, head to your app.py file.

Start by adding a new import statement to your file: import strategies

Delete the import indicators line as it's no longer needed.

Now, head to your auto_run_trading_bot() function and update it so that it looks like this:

Press play on your IDE and see what happens!

Here's what mine looked like:

RSI High Low Strategy in all its glory. How good is that!

Congratulations on designing your first trading algorithm!

Some Easy LEVEL UP moves for Algorithmic Traders!

If you've reached this point by following my blog episodes, then I've got some really easy level up suggestions you can play with for your algorithms. Let me know if the comments if you've got any more.

Multi Asset Trading

What if you could trade not just one stock, but a list of any stocks you wanted on Alpaca Markets? With the trading bot we've built, you can do this really easily. Simply update the symbols variable near the top of your app.py. For instance:

symbols = ["AAPL", "GOOGL", "META"]

Changing Your Timeframe: No Time At All

What if your trading activities are more focused on different timeframes? Or maybe you'd like to test your hypothesis on different timeframes to see what happens?

You can do this by simply changing the timeframe variable near the top of your app.py to a different timeframe. For instance:

timeframe = "30min"

Other Episodes

Hopefully by now you're getting excited about the awesome possibilities the algo trading bot we're building can offer. Check out my other content to see:

  • Different strategies
  • Different indicators
  • Advanced risk management

Wrapping Up

I hope you enjoyed this introduction to the RSI in stocks and enjoyed seeing how to use it in your trading bot!

I'm always interested to hear what my readers and followers want to know more about, so if you've got an idea, why not drop us a suggestion in our suggestion box (aka contact form).

Join the TradeOxy Revolution

At TradeOxy, we're on a mission to democratize algorithmic trading. Why not join our journey and check out our list of amazing indicators and helpful education?

Full Code For app.py

Full code for app.py at end of episode:

Full Code For strategies.py