Building and Deploying a Stock Trading Bot in Python with Alpaca: Relative Strength Index (RSI)
Building and Deploying a Stock Trading Bot in Python: Relative Strength Index (RSI)
Algorithmic trading is becoming increasingly popular among retail investors, thanks to the advancements in technology and accessible trading platforms. In this tutorial, we will walk through the process of building a Relative Strength Index (RSI)-based trading bot in Python and deploying it using the Alpaca trading API. We will backtest our trading bot against the SPY ETF to evaluate its performance. This guide will help you create an algorithmic trading bot from scratch, even if you're a beginner to Python and have minimal coding experience. Note: No machine learning is necessary for this tutorial.
This article will focus on the application of algorithmic trading in the realm of stocks and ETFs. Note: You can also adapt the strategy below to look into cryptocurrencies like Bitcoin and Ethereum with platforms such as Binance.
Strategy Overview
A very simple and popular trading strategy using the RSI is known as the "RSI Overbought/Oversold Strategy". This strategy involves generating buy and sell signals based on the RSI crossing predefined threshold levels. These levels indicate when an asset is overbought or oversold, suggesting a potential price reversal.
Here's a brief overview of the strategy:
RSI calculation: Calculate the RSI using a typical period of 14 days (or any other preferred period).
Overbought level: Set an overbought threshold, commonly at 70.
Oversold level: Set an oversold threshold, commonly at 30.
Buy signal: When the RSI crosses below the oversold level (30) and then rises back above it, consider it a buy signal, indicating the asset may be undervalued.
In this tutorial, we'll use this RSI strategy on the QQQ ETF but you can test it out on different tickers too.
1. Setting up the environment:
To begin, we need to install the necessary Python libraries. We will use the following:
pandas: For data manipulation using dataframes
numpy: For numerical computations
matplotlib: For plotting
yfinance: For historical stock market data (there are also other paid financial data platforms available)
alpaca-trade-api: For connecting to the Alpaca brokerage platform
time: to wait x time period between each trading period
pip install pandas numpy matplotlib yfinance alpaca-trade-api time
I’d also recommend using version control in a github repo to ensure you can track any changes you make to your trading bot over time.
2. Importing the libraries and fetching historical data:
Next, we will import the necessary libraries and fetch historical stock data using the yfinance library.
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
# Fetch historical data
symbol = 'QQQ'
start_date = '2015-01-01'
end_date = '2022-12-31'
data = yf.download(symbol, start=start_date, end=end_date)
3. Calculating the RSI:
Now, let's calculate the 14-day RSI using the close price for our stock data and add it as a new column in our DataFrame.
def rsi(data, period):
delta = data.diff().dropna()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=period).mean()
avg_loss = loss.rolling(window=period).mean()
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))
# Calculate the 14-day RSI
data['RSI'] = rsi(data['Close'], 14)
4. Implementing the trading strategy:
Our trading strategy is simple: buy when RSI is below 30 (oversold) and sell when RSI is above 70 (overbought). We will create a new DataFrame column called 'Signal' that indicates whether we should buy (1), sell (-1), or hold (0) the stock.
data['Signal'] = 0
data.loc[data['RSI'] < 30, 'Signal'] = 1
data.loc[data['RSI'] > 70, 'Signal'] = -1
5. Backtesting the strategy and comparing it with SPY:
Now that we have our signals, we can backtest our strategy. For this, we will calculate the daily returns and the cumulative returns for our strategy.
data['Daily_Return'] = data['Close'].pct_change()
data['Strategy_Return'] = data['Daily_Return'] * data['Signal'].shift(1)
data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()
6. Plotting the results:
Let's visualize our strategy's performance by plotting the cumulative returns. Ensure that your strategy isn't overfit (you can find more information on overfitting here).
# Fetch historical data for SPY
spy_data = yf.download('SPY', start=start_date, end=end_date)
# Calculate daily returns and cumulative returns for SPY
spy_data['Daily_Return'] = spy_data['Close'].pct_change()
spy_data['Cumulative_Return'] = (1 + spy_data['Daily_Return']).cumprod()
# Plot both cumulative returns on the same chart
plt.figure(figsize=(12, 6))
plt.plot(data.index, data['Cumulative_Return'], label='SMA Strategy')
plt.plot(spy_data.index, spy_data['Cumulative_Return'], label='SPY')
plt.xlabel('Date')
plt.ylabel('Cumulative Returns')
plt.legend()
plt.show()

7. Connecting to Alpaca:
To deploy our trading algorithm live with real money, we will connect to the Alpaca brokerage platform. Alpaca provides live real-time data for execution. First, sign up for an account on Alpaca, then generate your API key and secret. Replace "YOUR_API_KEY" and "YOUR_SECRET_KEY" with your actual credentials. Please ensure you keep them in safely in a .env file and do not share them with anyone.
from alpaca_trade_api import REST
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_SECRET_KEY'
base_url = 'https://paper-api.alpaca.markets' # Use the paper trading URL for testing
api = REST(api_key, api_secret, base_url)
8. Implementing the trading algorithm for live trading:
To deploy our trading algorithm live, we will create a function that checks the current QQQ RSI against the upper and lower bounds we set, and places an order if the condition is met. We will also need a function to check our existing positions. Using both the live trading algorithm and the backtests, you can optimize your strategy by adjust the metrics/timeframe.
import time
def check_positions(symbol):
positions = api.list_positions()
for position in positions:
if position.symbol == symbol:
return int(position.qty)
return 0
def trade(symbol, qty):
current_rsi = rsi(yf.download(symbol, start=start_date, end=end_date, interval='1d')['Close'], 14)[-1]
position_qty = check_positions(symbol)
if current_rsi < 30 and position_qty == 0:
api.submit_order(
symbol=symbol,
qty=qty,
side='buy',
type='market',
time_in_force='gtc'
)
print("Buy order placed for", symbol)
elif current_rsi > 70 and position_qty > 0:
api.submit_order(
symbol=symbol,
qty=position_qty,
side='sell',
type='market',
time_in_force='gtc'
)
print("Sell order placed for", symbol)
else:
print("Holding", symbol)
9. Running the algorithm:
Now that we have our functions in place, we can run the algorithm by calling the 'trade()' function in a loop. We will use a time delay of one day (86400 seconds) to simulate daily trading. If you want to switch the algorithm from day trading to weekly trading etc, you can adjust the time.sleep(...) function.
symbol = 'QQQ'
qty = 10
while True:
trade(symbol, qty)
time.sleep(86400)
This will run the algorithm indefinitely, checking the stock price against the RSI every day and placing buy or sell orders if the conditions are met.
Disclaimer: Please note that the above example is for educational purposes only and should not be considered as financial advice. Always do thorough research and testing before deploying a trading algorithm with real money.
What other brokerage APIs and platforms can I create this with?
While this tutorial focused on the Alpaca API, there are many ways to create your trading bot. Other alternatives include:
Interactive brokers API, TD Ameritrade API, Binance API (crypto only)
If you're looking for options with less or no coding, check out the following:
Composer: Composer is a no-code trading platform (with an AI copilot powered by ChatGPT4). It offers an intuitive drag-and-drop interface that allows you to build, test, and deploy sophisticated trading strategies with ease. With a comprehensive library of pre-built indicators, professional grade data, and trading actions, Composer empowers you to create a wide range of strategies without writing a single line of code.
EquBot AI Watson: EquBot uses IBM Watson’s AI to make trading decisions, including analysis of news articles and social media. If you're looking for an AI trading bot that uses alternative data this could be a platform to consider.
Tickeron: Tickeron is a subsidiary of SAS Global Corp. with customizable AI bots, providing dynamic price alerts for trade timing for stock, exchange-traded fund (ETF), forex and crypto pattern recognition. Tickeron’s AI pattern recognition surfaces daily top-ranked stock price patterns and provides a confidence level for trading ideas. It also has robust trend forecasting tools that can help provide predictions for future price levels.
Summary
There you have it - A simple trading system in python!
In this article, we demonstrated how to build a simple Relative Strength Index (RSI) algorithm in Python and deploy it for live trading using the Alpaca brokerage platform. While this example showcases a basic trading strategy, there's a whole world of possibilities when it comes to algorithmic trading.
You may also like
Important Disclosures
Investing in securities involves risks, including the risk of loss, including principal. Composer Securities LLC is a broker-dealer registered with the SEC and member of FINRA / SIPC. The SEC has not approved this message.
Certain information contained in here has been obtained from third-party sources. While taken from sources believed to be reliable, Composer has not independently verified such information and makes no representations about the accuracy of the information or its appropriateness for a given situation. In addition, this content may include third-party advertisements; Composer has not reviewed such advertisements and does not endorse any advertising content contained therein.
This content is provided for informational purposes only, as it was prepared without regard to any specific objectives, or financial circumstances, and should not be relied upon as legal, business, investment, or tax advice. You should consult your own advisers as to those matters. References to any securities or digital assets are for illustrative purposes only and do not constitute an investment recommendation or offer to provide investment advisory services. Furthermore, this content is not intended as a recommendation to purchase or sell any security and performance of certain hypothetical scenarios described herein is not necessarily indicative of actual results. Any investments referred to, or described are not representative of all investments in strategies managed by Composer, and there can be no assurance that the investments will be profitable or that other investments made in the future will have similar characteristics or results.
Charts and graphs provided within are for informational purposes solely and should not be relied upon when making any investment decision. Past performance is not indicative of future results. The content speaks only as of the date indicated. Any projections, estimates, forecasts, targets, prospects, and/or opinions expressed in these materials are subject to change without notice and may differ or be contrary to opinions expressed by others. Please see Composer's Legal Page for additional important information.