Categories
Algorithmic Trading

Technical Analysis Using Bollinger Bands and Lumibot

Introduction 

Many technical analysis challenges, such as identifying market trends and determining entry or exit points, can be effectively addressed using Bollinger Bands in a trading bot. Bollinger Bands helps solve these issues by providing a dynamic range around the price that signals overbought or oversold conditions, making it easier for a trading bot to make informed decisions. With the rise of automated trading platforms like Lumibot, traders can seamlessly integrate Bollinger Bands into their bots for real-time technical analysis. Lumibot’s user-friendly interface and robust API make it a perfect tool for implementing Bollinger Bands strategies in an automated trading setup.

Furthermore, Lumibot empowers traders to customize their Bollinger Bands parameters, such as period length and deviation settings, based on market conditions and trading objectives. This flexibility enhances a bot’s ability to react swiftly to market fluctuations, improving overall trading efficiency. Lumibot’s extensive backtesting capabilities also allow traders to refine their Bollinger Bands strategies by testing them on historical data.

How Bollinger Bands Can Be Used for Technical Analysis of an Asset: Bollinger Bands provide crucial insights into market volatility and potential price reversals, making them a valuable tool for analyzing any asset. By observing how an asset’s price behaves relative to the upper and lower bands, traders can gauge whether the asset is overbought or oversold. This helps in formulating strategies for when to enter or exit trades based on clear market signals.

Read on to find the nitty-gritty of how Bollinger Bands can be effectively incorporated into a trading bot for technical analysis of an asset.

Using Bollinger Bands in a Trading Bot for Technical Analysis

Bollinger Bands are widely used in trading strategies due to their ability to highlight market volatility, overbought/oversold levels, and potential price reversals. By incorporating Bollinger Bands into a trading bot, traders can automate decisions and capitalize on these insights. Below are five ways Bollinger Bands can be utilized in a trading bot for technical analysis, with a breakdown of what each method is and how it can be applied effectively in an automated trading system.

1. Identifying Overbought and Oversold Conditions

What It Is:

Bollinger Bands help determine whether an asset is overbought (price touching or exceeding the upper band) or oversold (price touching or dropping below the lower band). These conditions often signal a potential price reversal.

How It Can Be Used in a Trading Bot:

In a trading bot, Bollinger Bands can be programmed to trigger buy signals when the price hits the lower band (oversold) and sell signals when it hits the upper band (overbought). This allows the bot to make decisions based on predefined criteria without human intervention.

2. Volatility Breakouts (The Squeeze)

What It Is:

When the bands contract (i.e., when they come close together), it indicates reduced volatility, commonly referred to as “the squeeze.” This phase is often followed by a volatility breakout, where the price sharply moves in either direction.

How It Can Be Used in a Trading Bot:

Traders can configure a bot to monitor for contractions in Bollinger Bands. Once the bands start expanding, the bot can place orders based on the direction of the breakout (up or down). The bot can also be set to place stop-losses to manage risk in case of a false breakout.

3. Mean Reversion Strategy

What It Is:

Bollinger Bands are centered around a moving average, which acts as a benchmark for the “fair” price of the asset. When the price moves too far from this average (toward either band), it often reverts back to the mean.

How It Can Be Used in a Trading Bot:

A trading bot can be programmed to execute trades when the price moves away from the moving average toward the bands and then place opposing trades (sell or buy) when the price reverts back to the mean. This strategy works well in range-bound markets.

4. Trend Following with Bollinger Bands

What It Is:

In a strong trend, the price tends to hug one of the Bollinger Bands. In an uptrend, the price often stays near the upper band, while in a downtrend, it stays near the lower band.

How It Can Be Used in a Trading Bot:

A trading bot can be designed to open positions following the trend direction. For example, if the price is consistently hitting the upper band, the bot can place buy orders. Conversely, if the price sticks to the lower band, the bot can open sell positions, adjusting stop-losses and profit-taking points accordingly.

5. Detecting Double Tops and Bottoms

What It Is:

Bollinger Bands can help detect double tops (two peaks near the upper band signaling a potential bearish reversal) or double bottoms (two troughs near the lower band indicating a bullish reversal).

How It Can Be Used in a Trading Bot:

Bots can be configured to recognize these patterns and automatically trigger trades when they form. For example, a bot can be set to initiate a sell order after identifying a double top or a buy order after spotting a double bottom. This pattern recognition can be enhanced by combining Bollinger Bands with other indicators for better accuracy.

By incorporating these strategies, traders can enhance their trading bot’s performance and create systems that are responsive to market conditions, taking full advantage of Bollinger Bands for technical analysis.

Steps to Get the Bollinger Bands of the Historical Price of an Asset with Lumibot

Prerequisites

Must have Python installed in the system(version 3.10 or above)

  1. Install required Python packages.

 pip install lumibot

2. Necessary imports for running the Python file.


from lumibot.strategies import Strategy
import pandas_ta as ta

3. Create ALPACA_CONFIG with API KEY and API SECRET by logging in or signing up at https://alpaca.markets/.

Steps for Using Bollinger Bands of the Historical Price of an Asset

Step 1: Add ALPACA_CONFIG Details

Alpaca is a broker, just like the interactive broker. The details below are required to use the Alpaca broker API.

ALPACA_CONFIG = {
	"API_KEY": "YOUR_API_KEY_HERE", # Get your API Key from https://alpaca.markets/
	"API_SECRET": "YOUR_SECRET_HERE", # Get your secret from https://alpaca.markets/
	"PAPER":True # Set to False for real money
}

Step 2: Create a GetHistoricalPrice Class 

Once you have added the Alpaca config detail, create a GetHistoricalPrice class, which will inherit the Strategy class as below.

class GetHistoricalPrice(Strategy):

Step 3: Add  on_trading_iteration() Method 

Once you have added the initialize method, follow with the creation of  on_trading_iteration() method as below:

def on_trading_iteration(self):

   	# Get historical prices for AAPL
       bars = self.get_historical_prices("AAPL", 30, "day")
       df = bars.df

   	# Calculate Bollinger Bands
       bbands = ta.bbands(df['close'], length=20, std=2)
       df['BB_Middle'] = bbands['BBM_20_2.0']
       df['BB_Upper'] = bbands['BBU_20_2.0']
       df['BB_Lower'] = bbands['BBL_20_2.0']

   	# Drop any rows with NaN values
       df.dropna(inplace=True)

   	print(df[['close', 'BB_Middle', 'BB_Upper', 'BB_Lower']])

In this code, the function on_trading_iteration retrieves historical price data for Apple Inc. (“AAPL”) over the last 30 days, with each data point representing a day. It then calculates the Bollinger Bands for the closing prices of AAPL using a 20-day moving average and 2 standard deviations. The calculated Bollinger Bands consist of three lines: the middle band (20-day moving average), upper band (2 standard deviations above the middle), and lower band (2 standard deviations below the middle). These values are added to the dataframe df as new columns. Afterward, any rows containing missing values (NaN) are removed, and the relevant columns (close price, middle, upper, and lower Bollinger Bands) are printed to the console for analysis.

Note 1: Running the Code in the Same File 

In Python, if __name__ == “__main__”: is a conditional statement, which allows you to control the execution of code depending on whether the script is run directly or imported as a module. This implies that the code will run only if runs as a script and not as a module. 

if __name__ == "__main__": 

Step 4: Import Alpaca and Trader 

Import Alpaca and Trader classes from Lumibot.brokers and Lumibot.traders modules. While Alpaca is an interface to the Alpaca trading platform, it leverages us with the functionalities to interact with the Alpaca API for implementing things like placing orders, managing positions, and fetching market data like Historical Price Data, which we are doing in this blog.

The Trader class helps orchestrate the trading process, managing multiple trading strategies, interacting with brokers like Alpaca, Interactive Brokers, and Tradiers, handling order execution and position management, and ensuring a framework for live trading and backtesting. 

from lumibot.brokers import Alpaca
from lumibot.traders import Trader

Step 5: Create Trader Class Object

As you import the Alpaca and Trader class, create the trader object of the Trader() class.

 trader = Trader()

Step 6: Create an Object of Alpaca Class

On creation of the trader class object, create the object of the Alpaca class by passing the Alpaca_Config array created above.

broker = Alpaca(ALPACA_CONFIG)

Step 7: Create an Object of GetHistoricalPrice Class

Once we have created the object for the Alpaca class, we will create an object of the GetHistoricalPrice class by passing the Alpaca object (broker) as a parameter to the GetHistoricalPrice class. 

 strategy = GetHistoricalPrice(broker=broker)

Step 8: Pass the Strategy to the Trader Class Object

On creation of the object of the GetHistoricalPrice class, add the strategy to the trader class object using the add_strategy() method.

trader.add_strategy(strategy)

Step 9: Start the Overall Trading Process

The code below starts the overall trading process. This typically executes backtesting or a live trading process for a collection of strategies within a trading platform. This command starts the execution engine. It establishes the connection with a broker, which is Alpaca, and starts background tasks like market data ingestion and order management. Briefly, it is the starting point of the trading process.

trader.run_all()


Complete Code

from lumibot.strategies import Strategy
import pandas_ta as ta

# Alpaca API configuration
ALPACA_CONFIG = {
    "API_KEY": "YOUR_API_KEY_HERE", # Get your API Key from https://alpaca.markets/
    "API_SECRET": "YOUR_SECRET_HERE", # Get your secret from https://alpaca.markets/
    "PAPER":True # Set to False for real money
}
class GetHistoricalPrice(Strategy):

   def on_trading_iteration(self):

   	# Get historical prices for AAPL
       bars = self.get_historical_prices("AAPL", 30, "day")
       df = bars.df

   	# Calculate Bollinger Bands
       bbands = ta.bbands(df['close'], length=20, std=2)
       df['BB_Middle'] = bbands['BBM_20_2.0']
       df['BB_Upper'] = bbands['BBU_20_2.0']
       df['BB_Lower'] = bbands['BBL_20_2.0']

   	# Drop any rows with NaN values
       df.dropna(inplace=True)

   	print(df[['close', 'BB_Middle', 'BB_Upper', 'BB_Lower']])


if __name__ == "__main__":

   from lumibot.brokers import Alpaca
   from lumibot.traders import Trader

   broker = Alpaca(ALPACA_CONFIG)
   strategy = GetHistoricalPrice(broker=broker)
  
   trader = Trader()
   trader.add_strategy(strategy)
   trader.run_all()

Output

Conclusion

Bollinger Bands provides traders with a clear framework for analyzing market trends, detecting overbought and oversold conditions, and identifying potential breakouts. When integrated into a trading bot, Bollinger Bands can automate these insights, helping traders execute strategies with precision and without emotional bias. Tools like Lumibot simplify this automation, enabling traders to fine-tune their Bollinger Bands parameters backtest strategies and set up fully autonomous trading systems based on real-time market conditions.

By leveraging Lumibot’s advanced features, traders can unlock the full potential of Bollinger Bands, increasing their chances of success in a dynamic market environment.

Take Your Trading to the Next Level with Lumibot

Ready to harness the power of Bollinger Bands and automate your trading strategies? Lumibot offers the perfect platform to build, customize, and optimize your trading bot. Whether you’re new to automated trading or a seasoned professional, Lumibot provides intuitive tools to help you stay ahead of the market.

Sign up for Lumibot today and start integrating Bollinger Bands into your trading bot for a more efficient, data-driven trading experience!

Categories
Algorithmic Trading

Algorithmic Trading Benefits And Downsides

 

Algorithmic trading is responsible for approximately 60-73% of all U.S. equity trading, according to BusinessWire. If you’re trading stocks manually, you naturally place yourself at a disadvantage; you’re competing against robots… and who do you think will win that fight? Nine times out of ten, it’s the robots.

Who Uses This Method of Trading?

You may be wondering: who runs these algorithms and who uses this method of trading? The aforementioned stats may shock you, especially if you’ve never heard the phrase “algorithmic trading” before. Hedge funds, investment firms, and other private equity trading groups all use algorithmic trading, mainly due to its decrease in costs, unrivaled speed, and increase in trading accuracy.

If you’re a little lost and don’t know what algorithmic trading is, don’t worry. To understand how this works, we must first explain how an algorithm works. An algorithm is a set of directions, usually inputted on a computer, to solve a complex problem. In basic terms, algorithmic trading, Python utilizes different algorithms to produce meaningful data, that is then used to determine whether to buy, sell, or hold during financial trades.

what is algo trading?

More often than not, when a firm utilizes algorithmic trading, they also use some form of trading technology to make thousands of trades each second. As these trades are real-time, this allows traders to maximize profit at any given moment – there are very few methods quite as accurate. 

In more recent years, and especially since the 1980s, algo trading has increased in popularity, with many investors and investment firms choosing this new method of trading to increase their profit margins and see more accurate trading results. In fact, according to Toptal, hedge funds that utilize algorithmic trading have significantly outperformed their peers and counterparts since this time, all with reduced costs in comparison to regular trading. As of 2019, quantitative funds represented 31.5% of market capitalization, compared to 24.3% of human-managed funds.

The remainder of this article will discuss algorithmic trading in more detail, in particular, how it could make you more money.

What Are The benefits of Algorithmic Trading?

As mentioned beforehand, there are several benefits of algorithmic trading. However, the main benefits include:

  • Cut down on associated trading costs
  • Faster execution of orders
  • Trades are timed perfectly 
  • Ability to backtest
  • Quantitative strategies have dominated the market and returns

Each of these benefits will now be explained below in more detail, helping to provide you with greater insight on how exactly algorithmic trading works.

make money with algo trading

Cut down on associated trading costs 

Firstly, when you use algorithmic trading, you are able to save and cut down on associated trading costs. Transaction costs are cut due to less human interaction, freeing up liquidity towards more investments. Likewise, you will also save money on fees, depending on your investment method – so it’s well worth keeping in mind.

Human interaction previously included general fees, a fundamental analysis performed by a finance manager, and the buying and selling of trades, amongst other actions. Algorithmic trading allows you to set a buy and sell price, cuts fees, and saves you money – let the robots work with you, not against you. 

Faster execution of orders 

With a faster system in place, traders are able to exploit the smallest of profit margins to create mid to large amounts of revenue in seconds. This method is called scalping and is where a trader instantly buys a set number of shares/stocks at a lower price, then rapidly sells these on for a higher price, whether for a small profit margin (which adds up in the long run) or for a slightly larger one.

When you use algorithmic trading, you can set a buy and sell price for a stock or share. For example, if one stock dips below a certain threshold, the algorithm will purchase a set number for you. Similarly, once this same stock increases in price to your pre-determined price, these stocks/shares will be sold instantly to maximize profit. This is much more accurate than human trades, and also removes the emotion involved with investing. 

Trades are timed perfectly

Human trades require you to buy and sell manually, watching particular trades all day to purchase and/or sell at the best prices. With the predetermined buy and sell thresholds, your trades are timed perfectly. 

This allows you to exploit small dips in particular trades, compounding small profits into large gains in the long run. The decision to buy or sell the trades is still yours, but you gain greater accuracy over when to buy and sell these. 

Ability to backtest

One key advantage of algorithmic trading compared to regular trading is the ability to backtest, as mentioned by Nasdaq. Essentially, you can run algorithms based on previous data to see what parts of a trading system works, and what doesn’t. This is super beneficial and removes any potential error before purchasing stock or shares in bulk, possibly reducing a large loss.

Backtesting is not as accurate when human trading and may result in large losses – so keep this in mind if you choose the old fashioned trading method. 

Quantitative strategies have dominated the market and returns

Hedge funds such as Two Sigma, DE Shaw, Renaissance, Bridgewater, and others have been the best performing investment funds in the world for several decades. Renaissance’s average of 39% annual returns have made the founder, Jim Simmons, and everyone else at the firm extraordinarily rich. Doing the math, at 39% per year for 30 years you could have turned just $100 into $1.9 million! That’s incredible, especially considering that they’re taking on much less risk than the stock market as a whole. 

These funds are managed with greater accuracy and with a quantitative strategy, other than trading blindly, with emotion, and with an increased risk of a slip-up. 

algo trading advantages

Are there any downsides?

Now that we’ve covered the benefits of algorithmic trading, you’re likely wondering if there are any downsides, and what they may be. As with all trading, there is an element of risk; however, you wouldn’t be in the business if you didn’t know this was a factor. 

Potential downsides of algorithmic trading include:

  • Loss of internet connection could prevent your order/trade from being processed
  • Without prior testing, you may use the algorithm incorrectly and create a loss 

Once again, each of these downsides will now be discussed individually below.

Loss of internet connection could prevent your order/trade from being processed 

Firstly, as these trades require an internet connection, if your connection is to drop, even for a few seconds then your automated trades may not be placed and/or processed. This could lead to a loss, so it’s integral that you have a strong internet connection and ISP. ideally, you should have business WI-FI, as this is more reliable and more suitable to learn algorithmic trading

The same risk is present with regular human trading, but it is something to be aware of, especially if trading in larger quantities. 

Without prior testing, you may use the algorithm incorrectly and create a loss

The other downside is that without prior testing of the algorithm, you could create yourself a loss. This is easy to combat; all you need to do is play around with the system before placing any large trades. Start small until your comfortable then increase the number of trades and shares you are both purchasing and selling within a short timeframe.

You can also backtest, as mentioned previously to further increase the accuracy of your algorithm. 

How does it work and how can it make you more money?

Algorithmic trading is made possible thanks to pre-programmed computers and a set of instructions to buy and sell trades in bulk. If done correctly, this allows you to make more trades than a human ever could, exploiting slight dips in the market for quick re-sales and easy profit.

First, however, you must identify an opportunity in the market. Running this through the algorithm and calculating the potential returns, deciding whether or the trade is worth it. Some trades will generate more income than others, but algorithmic trading is a long-term game, profiting off of small trades consistently for a greater ROI.

Do you want to learn more about algorithmic trading?

To find out more about algorithmic trading, you can take our unique, top-rated course designed for finance professionals and experienced programmers, allowing you to take your python for finance expertise to the next level. Not to mention make worthwhile investments, increasing your revenue, and be better equipped to solve real-world tasks and problems.

If you would like to learn more about our algorithmic trading course, click here.

Finally, we would like to draw attention to our open-sourced GitHub project, Lumibot. A great tool to use if you trade consistently and are looking to amp up your game, perhaps with algorithmic trading now on your side. 

Categories
Algorithmic Trading Python for finance python trading

How Algorithmic Trading Could Make You Money

Did you know that only one out of every five day-traders actually makes a profit? The ever-changing world of trading can be challenging to navigate. In fact, most trading on the stock market is performed by robots, making it like playing a rigged game of chess, where your chances of winning are stacked against you. 

That’s why many day-traders have started to learn algorithmic trading to improve their odds of making money through trading.  

In this post, we discuss just exactly how algo trading using python works and how you can create an algorithmic trading robot to help increase your odds of becoming the next, big money trader. 

What Is Algorithmic Trading?

Algorithmic trading uses data science and computer-automated executions, rather than human guesswork, to create instructions for trading. Since trading activities use data science techniques like technical indicators, financial fundamentals, and economic data, this also eliminates human emotions that can interfere with the success of trading.

How Can Algorithmic Trading Benefit Traders?

Algorithm trading offers numerous benefits for traders. Once you make the switch, you’ll likely be surprised that you hadn’t been incorporating algorithmic trading strategies into your investments all along. 

benefits-of-algo-trading

Here are just a few key benefits that ultimately save you time and money.

Your Trading Strategies Are Back-tested

Algorithmic trading takes the guesswork out of your trading strategies. By reviewing past back-tests, you can more clearly see patterns, which in turn helps you figure out what’s working and what isn’t working. 

Back testing Develop Your Strategies

Your Strategies Are Less Prone to Human Error

We all know just how fallible human calculations can be, and no one wants to make grave errors when it comes to their investments. That’s where algorithmic trading can be immensely beneficial for your financial trades. 

trade losses

Since algorithmic trading strategies are executed by computer software, there’s less room for error. This means that you can steer clear of common mistakes that you would otherwise make. 

You Have More Time to Develop Your Strategies

While computers do make mistakes, it’s far easier to monitor and troubleshoot, saving you time and money on your investment strategies and other areas that are in need of your attention. 

This means you can more easily branch out to other trade markets and strategies, allowing you to have less of a risk per capita of trade investments. In other words, you’re not putting all of your eggs in one investment basket.

Where Can I Learn More?

Are you ready to step up your day trading game? Though learn algorithmic trading may sound like the ultimate secret to your trading success, knowing exactly how to navigate a new arena of the data science world is no easy feat. In fact, if you don’t know what you’re doing, you could actually lose money.

How Algorithmic Trading Could Make You Money

 

That’s why we have created an algorithmic trading course to help you navigate Python software and start utilizing all that algorithmic trading has to offer & help you develop trading algorithms.  

In this course, you will learn the ins and outs of Python trading, where you can:

  • Analyze your investments
  • Make better decisions about your investments using data
  • Implement back-testing strategies
  • Automate your trades 
  • Calculate the risks and potential returns on investments
  • And, most importantly, start making money from those investments

We also have an open-sourced project, called Lumibot, that you can use to access what we use in our classes. This project is free for the public and can provide you with many resources to support your algorithmic trading journey and help you with coding trading bots yourself.  

If you’re ready to get started, sign up for our free live class, where you can download the course information on how to become the next, big algorithmic trader. 

FAQ

What is algorithmic trading?

Algorithmic trading is when software code (eg. Python) is used to automatically buy and sell securities (eg. AAPL stock). In other words, it is a robot that can automatically buy and sell stocks, options, futures, and more for you.

How do I get started with algorithmic trading?

To build an algorithmic trading robot you will usually have to first learn a software coding language such as Python, then use a library such as lumibot to connect to a broker and execute trades.

What is backtesting?

Backtesting is the process of creating a trading strategy, then using data from the past to see how the strategy would have performed in the past. This could be very valuable to see whether your algorithm will perform well in the future.

Where can I learn algorithmic trading?

Since there are many potential pitfalls (ways to lose money), the best way to learn algorithmic trading is by taking a course on the topic. At Lumiwealth we have several courses on algorithmic trading that have gotten great reviews.

algo trading