- Solve real problems with our hands-on interface
- Progress from basic puts and calls to advanced strategies

Posted September 24, 2024 at 1:59 pm
The article “Basic Trading Algorithms in Python” was originally posted on PyQuant News.
The rise of algorithmic trading has transformed financial markets, allowing traders to make precise, data-driven decisions. Python, with its powerful libraries like pandas and NumPy, is a top choice for developing trading algorithms. This article will guide you through creating basic trading algorithms in Python, making use of these libraries.
Algorithmic trading uses computer programs to perform trades at speeds and frequencies beyond human capability. These algorithms analyze market data, spot trading opportunities, and execute orders based on predefined criteria. The key benefits include:
Python’s simplicity and versatility make it ideal for trading algorithms. This article focuses on two primary libraries:
Other useful Python libraries include:
Before we begin coding, ensure you have Python along with the necessary libraries installed. Install pandas and NumPy using pip:
pip install pandas pip install numpy
The first step in developing trading algorithms is acquiring and preparing the data. We’ll use historical stock price data from Yahoo Finance, fetched using the pandas_datareader library.
import pandas_datareader.data as web
import datetime
# Define the start and end date
start = datetime.datetime(2020, 1, 1)
end = datetime.datetime(2022, 1, 1)
# Fetch data for a particular stock
stock_data = web.DataReader('AAPL', 'yahoo', start, end)
print(stock_data.head())This data includes columns like ‘High’, ‘Low’, ‘Open’, ‘Close’, ‘Volume’, and ‘Adj Close’. We will focus on ‘Adj Close’ prices.
Technical indicators are mathematical calculations based on historical price, volume, or open interest information, and they help predict future price movements. We will calculate two simple indicators: Moving Average (MA) and Relative Strength Index (RSI).
A moving average smooths out price data by creating a constantly updated average price. The most common types are the Simple Moving Average (SMA) and the Exponential Moving Average (EMA).
# Simple Moving Average (SMA) stock_data['SMA_20'] = stock_data['Adj Close'].rolling(window=20).mean() # Exponential Moving Average (EMA) stock_data['EMA_20'] = stock_data['Adj Close'].ewm(span=20, adjust=False).mean()
The RSI measures the speed and change of price movements, oscillating between 0 and 100, typically identifying overbought or oversold conditions.
def calculate_rsi(data, window): delta = data['Adj Close'].diff(1) gain = (delta.where(delta > 0, 0)).rolling(window=window).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean() rs = gain / loss rsi = 100 - (100 / (1 + rs)) return rsi stock_data['RSI_14'] = calculate_rsi(stock_data, 14)
With our indicators in place, we can develop a simple trading algorithm. Let’s create a basic strategy that buys a stock when its 20-day SMA is above the 50-day SMA and sells when it’s below.
# Calculate longer-term SMA stock_data['SMA_50'] = stock_data['Adj Close'].rolling(window=50).mean() # Create buy/sell signals stock_data['Signal'] = 0 stock_data['Signal'][20:] = np.where(stock_data['SMA_20'][20:] > stock_data['SMA_50'][20:], 1, 0) stock_data['Position'] = stock_data['Signal'].diff()
In this code:
Position column indicates changes in position based on the difference between consecutive signals.Backtesting involves testing the trading strategy on historical data to evaluate its performance.
initial_capital = 100000.0
stock_data['Holdings'] = stock_data['Adj Close'] * stock_data['Position'].cumsum()
stock_data['Cash'] = initial_capital - (stock_data['Adj Close'] * stock_data['Position']).cumsum()
stock_data['Total'] = stock_data['Cash'] + stock_data['Holdings']
# Calculate returns
stock_data['Returns'] = stock_data['Total'].pct_change()
# Print final portfolio value
print("Final Portfolio Value: ${}".format(stock_data['Total'].iloc[-1]))Analyzing the performance involves evaluating metrics such as cumulative returns, average returns, and volatility.
cumulative_returns = (stock_data['Total'].iloc[-1] - initial_capital) / initial_capital
average_daily_returns = stock_data['Returns'].mean()
volatility = stock_data['Returns'].std()
print("Cumulative Returns: {:.2f}%".format(cumulative_returns * 100))
print("Average Daily Returns: {:.4f}".format(average_daily_returns))
print("Volatility: {:.4f}".format(volatility))These metrics provide a snapshot of the strategy’s effectiveness and risk.
Developing trading algorithms is a continuous learning process. Here are some resources to deepen your understanding:
Developing basic trading algorithms using Python’s pandas and NumPy libraries is a powerful way to harness data for informed trading decisions. This article provided a foundational guide to acquiring data, calculating technical indicators, implementing a simple trading strategy, and evaluating its performance. As you continue to explore and refine your algorithms, remember that financial markets are complex and ever-changing. Continuous learning and adaptation are key to success in algorithmic trading.
For specific platform feedback and suggestions, please submit it directly to our team using these instructions.
If you have an account-specific question or concern, please reach out to Client Services.
We encourage you to look through our FAQs before posting. Your question may already be covered!
Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.
This material is from PyQuant News and is being posted with its permission. The views expressed in this material are solely those of the author and/or PyQuant News and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.
what a vague article!