Disclaimer:
Remember that trading involves risk, and most traders lose money. This blog post is for educational purposes only. Always practice risk management and consider seeking professional advice before trading.
What Is Algorithmic Trading?
Algorithmic trading, often referred to as algo trading, uses computer algorithms to automate trading decisions based on predefined criteria. These criteria are set by the traders, for example, you might tell the program to Buy when the last 5 candlesticks have an upward trend, or Sell when the last 5 candlesticks are following a downtrend. This approach eliminates human emotions, enabling data-driven decision-making and executing trades at high speed and precision.
This approach, however, has some advantages and disadvantages.
Advantages of Algorithmic Trading
- Reduced Emotional Bias: Automated systems execute trades based on logic, not emotions.
- Faster Execution: Algorithms can process vast amounts of data and execute orders in milliseconds.
- Scalability: Algorithms can manage multiple trading strategies and assets simultaneously.
Disadvantages of Algorithmic Trading
- Technical Glitches: Systems can fail due to bugs or connectivity issues.
- Over-Optimization: Strategies may be overly fine-tuned to historical data, reducing real-world performance.
- Market Volatility: Sudden market changes can lead to significant losses.
Using Python for Algorithmic Trading
Python is a popular language for algorithmic trading due to its simplicity and extensive libraries. There are a lot of great libraries which are used for collecting trading data, processing and plotting the data, and generating technical indicators. In order to analyze the market and understand the trend and find opportunities to trade, we can use the historical data provided by Yahoo and the yfinance library (pip install yfinance):
import yfinance as yf
# Fetch historical data for EUR/USD
data = yf.download('EURUSD=X', start='2023-10-01', end='2024-07-10', interval='1d')
# Check the first 5 rows of data
print(data.head())
Technical Analysis with Python
Libraries like pandas
and numpy
are essential for data manipulation. For technical analysis, I recommend pandas_ta technical analysis library.
I am going to explain how you can use the pandas_ta library to plot simple indicators such as Simple Moving Average and RSI and then generate Buy and Sell signals.
Plotting Simple Moving Averages (SMA)
Simple Moving Average is the “Hello World” of algorithmic trading. It is very easy to calculate and plot. It shows the trend of the market by calculating the average price of an asset over a specified period, typically using closing prices.
Here’s how to calculate and plot SMA:
# remember to install pandas and pandas_ta
# we use the data we just downloaded by yfinance
import pandas as pd
import matplotlib.pyplot as plt
import pandas_ta as ta
# Calculate SMAs and add them to the data as columns
data['SMA_20'] = ta.sma(data['Close'], length=20)
data['SMA_50'] = ta.sma(data['Close'], length=50)
# Plotting SMAs
plt.figure(figsize=(12, 6))
plt.plot(data['Close'], label='Close Price')
plt.plot(data['SMA_20'], label='20-Day SMA')
plt.plot(data['SMA_50'], label='50-Day SMA')
plt.legend()
plt.show()
As you saw in the code we used the following code to calculate the SMA of the last 20 days and then added the results as a column to our data dataframe:
ta.sma(data['Close'], length=20)
If you want to know which methods are available through pandas_ta on your data, you can use the help function:
help(data.ta)
Plotting RSI
The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements. It oscillates between 0 and 100 and is typically used to identify overbought (above 70) or oversold (below 30) conditions in a market.
Here’s how you can calculate and plot RSI using pandas_ta:
# we are using the same data as before
# Calculate RSI
data['RSI'] = ta.rsi(data['Close'], length=14)
# Plotting RSI
plt.figure(figsize=(12, 6))
plt.plot(data['RSI'], label='RSI')
plt.axhline(30, linestyle='--', alpha=0.5, color='red')
plt.axhline(70, linestyle='--', alpha=0.5, color='red')
plt.title('RSI')
plt.legend()
plt.show()
A Simple Trading Strategy
Here is a simple trading strategy using SMA.
Buy Signal
- When the short-term SMA crosses above the long-term SMA.
Sell Signal
- When the short-term SMA crosses below the long-term SMA.
We’ll generate buy and sell signals based on the crossover of a short-term SMA and a long-term SMA, and plot these signals on the chart in green and red.
# use the same data as before
# Calculate indicators
data['SMA_50'] = ta.sma(data['Close'], length=50)
data['SMA_200'] = ta.sma(data['Close'], length=200)
# Generate Buy and Sell signals
data['Buy_Signal'] = np.where((data['SMA_50'] > data['SMA_200']) & (data['SMA_50'].shift(1) <= data['SMA_200'].shift(1)), 1, 0)
data['Sell_Signal'] = np.where((data['SMA_50'] < data['SMA_200']) & (data['SMA_50'].shift(1) >= data['SMA_200'].shift(1)), -1, 0)
# Plotting
plt.figure(figsize=(14, 8))
# Plot Closing Price and SMAs
plt.plot(data['Close'], label='Close Price', alpha=0.5)
plt.plot(data['SMA_50'], label='50-Day SMA', alpha=0.75, color='blue')
plt.plot(data['SMA_200'], label='200-Day SMA', alpha=0.75, color='orange')
# Plot Buy Signals
plt.plot(data[data['Buy_Signal'] == 1].index, data['Close'][data['Buy_Signal'] == 1], '^', markersize=10, color='g', lw=0, label='Buy Signal')
# Plot Sell Signals
plt.plot(data[data['Sell_Signal'] == -1].index, data['Close'][data['Sell_Signal'] == -1], 'v', markersize=10, color='r', lw=0, label='Sell Signal')
plt.title('EUR/USD Price with SMA Crossover Buy and Sell Signals')
plt.legend()
plt.show()
Summary of strategy:
Data Fetching: We use yfinance
to download historical data for EUR/USD.
Indicator Calculation: We calculate the 50-day and 200-day SMAs using pandas-ta
.
Signal Generation: Buy signals are generated when the 50-day SMA crosses above the 200-day SMA, and sell signals are generated when the 50-day SMA crosses below the 200-day SMA.
Plotting: We plot the closing price and the SMAs as line charts. Buy signals are marked with green triangles, and sell signals are marked with red triangles.
As you can see this strategy does not predict the trend well. So you need to consider other ways to generate signals.
Conclusion
In this post, I have introduced you to the pandas_ta python library for trading technical analysis to generate technical indicators and buy/sell signals. Algorithmic trading is a very complex field and requires a lot of knowledge regarding not only finance and market analysis, but also programming. You do not want to rely on these simple strategies to risk your money! Trading requires knowledge of risk and emotion management. So, this post was just an introduction to how you can start to learn a useful library and hopefully improve your knowledge of algorithmic trading.