Sling Academy
Home/Python/Creating Multi-Indicator Trading Systems with pandas-ta

Creating Multi-Indicator Trading Systems with pandas-ta

Last updated: December 22, 2024

Trading systems based on multiple indicators can provide a robust strategy by using a combination of signals to enter or exit trades. Using Python, and specifically the pandas-ta library, we can easily calculate indicators and create complex trading systems. In this article, we'll walk through setting up a trading system with multiple indicators using pandas-ta.

Installing Required Libraries

To begin, we need to ensure that the necessary libraries are installed: pandas for data manipulation, pandas-ta for technical indicators, and matplotlib for visualization.

pip install pandas pandas-ta matplotlib

Importing Libraries and Loading Data

Next, we'll import the required libraries and load historical stock data. For this tutorial, we'll use Yahoo Finance's API via yfinance. If you don't have it installed, you can install it using:

pip install yfinance

Now, let's import these libraries and load the data:

import pandas as pd
import pandas_ta as ta
import yfinance as yf
import matplotlib.pyplot as plt

# Download historical data for Apple
data = yf.download('AAPL', start='2022-01-01', end='2022-12-31')

print(data.head())

Calculating Indicators

We'll calculate two popular indicators: the Simple Moving Average (SMA) and the Relative Strength Index (RSI). These will serve as the backbone of our trading strategy.

# Calculate 10-day Simple Moving Average
data['SMA_10'] = ta.sma(data['Close'], length=10)

# Calculate 14-day Relative Strength Index
data['RSI_14'] = ta.rsi(data['Close'], length=14)

Defining The Trading Strategy

Our strategy is simple. We'll buy when the stock is above its 10-day SMA, and the RSI is below 30, indicating potential upside momentum following an oversold condition. We'll consider selling when the RSI goes above 70.

def strategy(data):
    buy_signals = []
    sell_signals = []
    position = False

    for i in range(len(data)):
        if data['Close'][i] > data['SMA_10'][i] and data['RSI_14'][i] < 30:
            if not position:
                buy_signals.append(data['Close'][i])
                sell_signals.append(float('nan'))
                position = True
            else:
                buy_signals.append(float('nan'))
                sell_signals.append(float('nan'))
        elif data['RSI_14'][i] > 70:
            if position:
                sell_signals.append(data['Close'][i])
                buy_signals.append(float('nan'))
                position = False
            else:
                buy_signals.append(float('nan'))
                sell_signals.append(float('nan'))
        else:
            buy_signals.append(float('nan'))
            sell_signals.append(float('nan'))

    return buy_signals, sell_signals

# Apply the strategy function to the data
buy_signals, sell_signals = strategy(data)

# Add signals to DataFrame
data['Buy_Signal'] = buy_signals
data['Sell_Signal'] = sell_signals

Visualizing the Results

Finally, we'll use matplotlib to visualize the buy and sell signals on the stock chart.

plt.figure(figsize=(14, 7))

plt.plot(data['Close'], label='Close Price', alpha=0.5)
plt.plot(data['SMA_10'], label='10 Day SMA', alpha=0.5)
plt.scatter(data.index, data['Buy_Signal'], color='green', label='Buy Signal', marker='^', alpha=1)
plt.scatter(data.index, data['Sell_Signal'], color='red', label='Sell Signal', marker='v', alpha=1)

plt.title('Apple Trading Signals')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(loc='upper left')
plt.show()

That's it! You've now implemented a simple multi-indicator trading system with pandas-ta. Keep in mind that this is a basic approach, and it is crucial to further test and optimize any trading strategy before considering real capital allocation. Happy trading!

Next Article: Handling Outliers and Missing Data in pandas-ta

Previous Article: Debugging Common Errors When Using pandas-ta

Series: Algorithmic trading with Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots