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.
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:
To complete this episode, you need to have the following:
- 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
- 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
- A way to calculate the RSI (Relative Strength Index) on your market data. If you haven't got this, check out my episode xxxx
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?
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.
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.
- A statement you can prove or disprove.
- An area of the financial markets you'll be targeting
- A specified period of time required to prove or disprove the hypothesis
Here's a really simple example of what this could look like if you're into intrinsic value investing:
Let's break it down:
- 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.
- 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.
- Time Bound. The hypothesis states a one-year period to prove or disprove the idea.
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.
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!
There's three easy ways to manage risk in our trading algorithm.
- Entry price. We can set a target entry price for our chosen financial instrument that confirms our hypothesis
- 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.
- 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.
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.
- 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.
- 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.
- 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:
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:
- 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.
- 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).
- (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.
- Entry Price. Buy when the price goes 1% above the current market price
- Stop Loss. 1% below the entry price
- Take Profit. 3% above the entry price
- Market data. Alpaca Markets.
- Indicator analysis. RSI, using TA Lib
- 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!
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:
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
- Imports the pandas library, covered in this episode
- Imports the indicators library, covered in this episode
- 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
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:
- Overbought and oversold levels as defined in the RSI High (default 70) and RSI Low (default 30) settings.
- 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.
Trading Decision. The final step is capture the trading decision, which is in the
Update calc_strategy to route to RSI Strategy
Return back to your
calc_strategy() function, and update it so it looks like this:
- Check that your RSI parameters are valid
- 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
Start by adding a new import statement to your file:
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:
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"
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
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: