img

Step-by-Step Guide to Add Bollinger Bands™️ to Your Trading Bot with Python, Alpaca Markets and TA Lib

img
valuezone 16 March 2024

Step-by-Step Guide to Add Bollinger Bands™️ to Your Trading Bot with Python, Alpaca Markets and TA Lib

The Bollinger Bands technical indicator is a technical indicator that is widely used to calculate the movements of financial assets. Adding it to your trading bot can be a powerful way to analyze crypto, forex, and stock data patterns and use the insights you gain to level up your trading strategies.

In this episode, I’ll show you how to add the Bollinger Bands technical indicator to your trading bot and customize it for your trading bot strategies.

Legal Stuff

  • DYOR. Note that all trading is at your own risk. My goal is to provide you with the self-developed methods, systems, and tools I use — it is up to you to figure out if this solution works for you AND if I’ve provided credible content. Always DYOR (Do Your Own Research).
  • Not Financial Advice. At no point should you consider anything in these articles to be financial advice. Any opinions expressed are about the technical aspects of the topic, not financial suitability.
  • Referrals. I receive no commissions for any of the products I mention in this blog. They’re all free (or have a free tier), and I simply provide links to simplify your learning experience.
  • AI Use. No AI was harmed in the creation of this blog. Some of the images are partially generated or enhanced through AI tools, we always use a real human to put them together. I do not use AI to generate the text, just spell check.

How to Set up Your Trading Bot for Indicators

Algorithmic trading relies on analysis to inform decision-making. Almost always, this means adding some kind of indicator.

The thing about indicators and trading bots is that they tend to breed. The more you analyze data, the more likely it is that you’ll have more and more indicators you want to add to your trading bot.

A common way to manage this complexity is by building your own indicator library

In this library, you can add any indicator you choose.

  • Bollinger Bands✅
  • Other indicators from TradeOxy ✅
  • Indicators from other content creators✅

It’s a powerful way to simplify much of your future autotrading development 🚀🚀🚀

Add an indicators.py file

If you haven’t done this in a previous episode, add the indicators.py file to your trading bot. This file will handle anything to do with indicators in the rest of your TradeOxy Trading Bot development.

Get the Python Pandas Library

The Python Pandas Library is considered a gold standard in data analysis. It’s transcended the into the ranks of mythical status in Python and is widely used in an incredible set of industries.

Adding this exceptionally powerful analysis tool to your trading is as simple as 4 steps:

  1. Navigate to requirements.txt
  2. Add the word pandas to the bottom
  3. Save
  4. Run pip install -r requirements.txt

Here’s what your should look like if you used my dev environment episode to get started:


Your requirements.txt should look like this. Part of the Medium blog article, “Step-by-Step Guide to Add Bollinger Bands ©️ to Your Trading Bot” by AppnologyJames

Dynamic Indicator Selection

To prepare for a multi-indicator future for your trading bot, we’re going to add some routing to your indicators.py file. This routing allows you to simply specify the indicator you want to use at any stage of your algorithm by using normal human language.

Add this code to your indicators.py (note that we’ll be adding in the Bollinger Bands technical indicator in the next section):

# Part of the Medium blog article, "Step-by-Step Guide to Add Bollinger Bands ©️ to Your Trading Bot" by AppnologyJames
# URL to access article: https://appnologyjames.medium.com/step-by-step-guide-to-add-bollinger-bands-%EF%B8%8F-to-your-trading-bot-c3b858926e12
# Main GitHub Trading Bot Repo: https://github.com/jimtin/tradeoxy-trading-bot
import talib
import pandas
def calc_indicator(indicator_name: str, historical_data: pandas.DataFrame, **kwargs) -> dict:
"""
Function to calculate a specified indicator
:param indicator_name: The name of the indicator to calculate
:param historical_data: The historical data to calculate the indicator from
:param kwargs: Any additional arguments to pass to the indicator function
"""
# Create a return dictionary
return_dictionary = {
"outcome": "unsuccessful",
"indicator": indicator_name,
"values": None,
"indicator_outcome": None
}
# Get the name of the indicator from the indicator name
indicator_name = indicator_name.lower()
if indicator_name == "bollinger":
# Set the indicator to bollinger in the return dictionary
return_dictionary["indicator"] = "bollinger"
try:
# Check the kwargs for the Bollinger Bands period and Bollinger Bands standard deviation
bollinger_period = kwargs["bollinger_period"]
bollinger_std = kwargs["bollinger_std"]
# Get the Bollinger Bands values
bollinger_data = calc_bollinger(
historical_data=historical_data,
bollinger_period=bollinger_period,
bollinger_std=bollinger_std
)
# Set the values in the return dictionary
return_dictionary["values"] = bollinger_data["values"]
# Set the indicator outcome in the return dictionary
return_dictionary["indicator_outcome"] = bollinger_data["indicator_outcome"]
# Set the outcome to successful
return_dictionary["outcome"] = "calculated"
except Exception as exception:
print(f"An exception occurred when calculating the Bollinger Bands: {exception}")
raise exception
# If the indicator name not recognised, raise a ValueError
else:
raise ValueError(f"The indicator {indicator_name} is not recognised.")
# Return the indicator values
return return_dictionary
view rawindicators.py hosted with ❤ by GitHub
Gist code for to add indicator routing to your stock trading bot. Part of the Medium blog article, “Step-by-Step Guide to Add Bollinger Bands ©️ to Your Trading Bot” by AppnologyJames.

Here you can see:

  1. We create a parent routing function
  2. We use the **kwargs special Python argument to allow us to add the components specific to each indicator
  3. We add in some helpful error handling

To see how this might work when you have multiple indicators, check out the indicators.py file in the main trading bot repo.

How to Add the Bollinger Bands Indicator to Your Trading Bot

Now that we can route to the Bollinger Bands indicator, we can go ahead and add the code to calculate it.

Default Values

I used the following default values for the Bollinger Bands indicator:

  1. Bollinger Period: 20
  2. Bollinger Standard Deviation: 2

You could easily expand the standard deviation to provide a differential between the upper and lower standard deviations, but I’ve left that aside for a more advanced approach in a future episode.

P.S. A great reference article to read more about Bollinger Bands is from Investopedia here.

Python Code + TA Lib for the Bollinger Bands Indicator

TA Lib is considered by many traders to be the go-to library for calculating technical indicators. It’s also a part of the dev environment.

The code below adds the Bollinger Bands indicator to your library using Python and TA Lib:

# Part of the Medium blog article, "Step-by-Step Guide to Add Bollinger Bands ©️ to Your Trading Bot" by AppnologyJames
# URL to access article: https://appnologyjames.medium.com/step-by-step-guide-to-add-bollinger-bands-%EF%B8%8F-to-your-trading-bot-c3b858926e12
# Main GitHub Trading Bot Repo: https://github.com/jimtin/tradeoxy-trading-bot
# Function to calculate Bollinger Bands
def calc_bollinger(historical_data: pandas.DataFrame, bollinger_period: int=20, bollinger_std: int=2) -> dict:
"""
Function to calculate Bollinger Bands
:param historical_data: The historical data to calculate the Bollinger Bands from
:param bollinger_period: The Bollinger Bands period
:param bollinger_std: The Bollinger Bands standard deviation
"""
# Create a return dictionary
return_dictionary = {
"outcome": "unsuccessful",
"indicator": "bollinger",
"values": None,
"indicator_outcome": None
}
# Check that the Bollinger Bands period is greater than 0
if bollinger_period <= 0:
raise ValueError("The Bollinger Bands period must be greater than 0.")
# Check that the length of the dataframe is greater than the Bollinger Bands period
if len(historical_data) < bollinger_period:
raise ValueError("The length of the dataframe must be greater than the Bollinger Bands period.")
try:
# Get the Bollinger Bands values
upper_band, middle_band, lower_band = talib.BBANDS(
historical_data["candle_close"],
timeperiod=bollinger_period,
nbdevup=bollinger_std,
nbdevdn=bollinger_std
)
except Exception as exception:
print(f"An exception occurred when calculating the Bollinger Bands: {exception}")
raise exception
# Add the Bollinger Bands values to the historical data
historical_data["bollinger_upper_band"] = upper_band
historical_data["bollinger_middle_band"] = middle_band
historical_data["bollinger_lower_band"] = lower_band
# Create a new column called bollinger_signal and set the value to hold
historical_data["bollinger_signal"] = "hold"
# Set the bollinger_signal to oversold when the candle_close is less than the lower_band
historical_data.loc[historical_data["candle_close"] < lower_band, "bollinger_signal"] = "oversold"
# Set the bollinger_signal to overbought when the candle_close is greater than the upper_band
historical_data.loc[historical_data["candle_close"] > upper_band, "bollinger_signal"] = "overbought"
# Get the last row of the historical data and get the Bollinger Bands signal. Set this to value of indicator_outcome in return_dictionary
return_dictionary["indicator_outcome"] = historical_data["bollinger_signal"].iloc[-1]
# Add the values to the return dictionary
return_dictionary["values"] = historical_data
# Set the outcome to successful
return_dictionary["outcome"] = "calculated"
# Return the dictionary
return return_dictionary
view rawindicators.py hosted with ❤ by GitHub
Gist to add Bollinger Band code to your trading bot. Part of the Medium blog article, “Step-by-Step Guide to Add Bollinger Bands ©️ to Your Trading Bot” by AppnologyJames

You’re all set!

Check out the Bollinger Bands in Action on Your Trading Bot!

  1. Navigate to your app.py
  2. Update the code in your file to look like this:
    # Part of the Medium blog article, "Step-by-Step Guide to Add Bollinger Bands ©️ to Your Trading Bot" by AppnologyJames
    # URL to access article: https://appnologyjames.medium.com/step-by-step-guide-to-add-bollinger-bands-%EF%B8%8F-to-your-trading-bot-c3b858926e12
    # Main GitHub Trading Bot Repo: https://github.com/jimtin/tradeoxy-trading-bot
    import alpaca_interactions as alpaca
    import datetime
    import indicators
    # List of symbols
    symbols = ["AAPL"]
    max_number_of_candles = 1000
    timeframe = "1hour"
    indicator = "bollinger"
    # Function to run the trading bot
    def auto_run_trading_bot():
    """
    Function to run the trading bot
    """
    # Print Welcome to your very own trading bot
    print("Welcome to your very own trading bot")
    # Set the end date to yesterday
    end_date = datetime.datetime.now() - datetime.timedelta(days=1) # Note that if you have a premium subscription you can remove this restriction
    # Set the start date to one year ago
    start_date = end_date - datetime.timedelta(days=365)
    #### Calculate the an indicator ####
    for symbol in symbols:
    # Save the symbol text
    symbol_text = symbol
    # Convert symbol to a list
    symbol = [symbol]
    # Get the historical data for the symbol
    symbol_historical_data = alpaca.get_historic_bars(
    symbols=symbol,
    timeframe=timeframe,
    start_date=start_date,
    end_date=end_date,
    limit=max_number_of_candles
    )
    # Calculate the specified indicator
    print(f"Calculating the {indicator} for {symbol_text}")
    indicator_result = indicators.calc_indicator(
    indicator_name=indicator,
    historical_data=symbol_historical_data,
    bollinger_period=20,
    bollinger_std=2
    )
    # Branch based on indicator_result
    if indicator_result["outcome"] == "calculated":
    # Print succcess
    print(f"The {indicator} was successfully calculated for {symbol_text}")
    # Extract the values
    values_dataframe = indicator_result["values"]
    print(values_dataframe)
    else:
    # Print and error
    print(f"An error occurred when calculating the {indicator} for {symbol_text}")
    # Print the full message
    print(indicator_result)
    # Main function for program
    if __name__ == "__main__":
    auto_run_trading_bot()
    view rawapp.py hosted with ❤ by GitHub
Update your app.py to see your Bollinger Bands indicator in action. Part of the Medium blog article, “Step-by-Step Guide to Add Bollinger Bands ©️ to Your Trading Bot” by AppnologyJames.