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!