Automated Trading using Python
Automated trading using Python involves building a program that can analyze market data and make trading decisions. We’ll use yfinance to get stock market data, Pandas and NumPy to organize and analyze it and Matplotlib to create simple charts to see trends and patterns. The idea is to use past stock prices and some basic calculations to decide when to buy or sell. Before using it in real trading, we’ll test the system with historical data to see how well it works. This will help us create a simple, smart trading system that runs on its own.
Step 1: Install Required Libraries
These libraries will be used for fetching data, performing calculations and visualizing results.
- Install yfinance: Fetch stock market data.
- Install pandas and numpy: Perform data manipulation and numerical operations.
- Install matplotlib: Create visualizations.
pip install yfinance pandas numpy matplotlib
Step 2: Import Libraries
Once the libraries are installed, import them into Python script or notebook.
import yfinance as yf # For stock data
import pandas as pd # For data manipulation
import numpy as np # For numerical operations
import matplotlib.pyplot as plt # For visualizations
Step 3: Fetch Historical Stock Data
We need historical price data to analyze and backtest our trading strategy.
- Define the stock ticker (e.g., AAPL for Apple).
- Setting the start and end dates for our analysis.
- Use yfinance to fetch the data.
# Define parameters
ticker = "AAPL" # Apple stock
start_date = "2010-01-01"
end_date = "2020-01-01"
# Fetch historical stock data
data = yf.download(ticker, start=start_date, end=end_date)
# Display first few rows
print(data.head())
Output:
[*********************100%***********************] 1 of 1 completed
Price Close High Low Open Volume
Ticker AAPL AAPL AAPL AAPL AAPL
Date
2010-01-04 6.447412 6.462175 6.398306 6.429939 493729600
2010-01-05 6.458560 6.495014 6.424517 6.465188 601904800
2010-01-06 6.355828 6.484168 6.349200 6.458560 552160000
2010-01-07 6.344079 6.386859 6.297985 6.379327 477131200
2010-01-08 6.386256 6.386859 6.298287 6.335643 447610800
Explanation:
- yf.download(ticker, start=start_date, end=end_date) downloads historical stock data for the given ticker and date range.
- This is done to backtest trading strategies using historical data. To analyze price trends, volatility and other market characteristics.
Step 4: Calculate Technical Indicators
Indicators help identify trends and generate trading signals. Moving averages smooth out the price data over a set number of days, making it easier to identify trends and filter out short-term noise.
1. Simple Moving Averages (SMA):
- SMA50 (short-term trend).
- SMA200 (long-term trend).
2. Use rolling().mean() to compute the averages over a specified window.
# Calculate Simple Moving Averages
short_window = 50 # Short-term SMA
long_window = 200 # Long-term SMA
data['SMA50'] = data['Close'].rolling(window=short_window).mean()
data['SMA200'] = data['Close'].rolling(window=long_window).mean()
Step 5: Define Buy/Sell Signals
Why signals are used:
- Helps in making trading decisions based on historical trends.
- A clear visual guide for when to enter or exit the market based on crossovers.
Trading signals are created based on SMA crossovers:
- Buy Signal (1): When SMA50 > SMA200.
- Sell Signal (-1): When SMA50 < SMA200.
# Define signals
data['Signal'] = 0 # Initialize Signal column with 0
data.loc[data['SMA50'] > data['SMA200'], 'Signal'] = 1 # Buy
data.loc[data['SMA50'] < data['SMA200'], 'Signal'] = -1 # Sell
Explanation:
- Signal column is updated with 1 for Buy and -1 for Sell based on the conditions.
Step 6: Simulate Trades
Simulate the strategy by calculating daily and cumulative returns.
# Create positions (shift signals to avoid look-ahead bias)
data['Position'] = data['Signal'].shift(1)
# Calculate daily percentage change in stock prices
data['Daily Return'] = data['Close'].pct_change()
# Calculate returns based on the strategy
data['Strategy Return'] = data['Position'] * data['Daily Return']
# Calculate cumulative returns
data['Cumulative Market Return'] = (1 + data['Daily Return']).cumprod()
data['Cumulative Strategy Return'] = (1 + data['Strategy Return']).cumprod()
Explanation:
- Position: Reflects the previous day’s signal.
- Daily Return: The percentage change in stock price from the previous day.
- Strategy Return: Returns achieved using the trading strategy.
- Cumulative Returns: Tracks the growth of $1 invested.
Step 7: Visualize Data
Visualize the stock price, SMA and returns to better understand the strategy.
(a) Plot Stock Price and SMAs:
plt.figure(figsize=(14, 7))
plt.plot(data['Close'], label='Close Price', alpha=0.5)
plt.plot(data['SMA50'], label='SMA50', alpha=0.75)
plt.plot(data['SMA200'], label='SMA200', alpha=0.75)
plt.title(f"{ticker} Price and Moving Averages")
plt.legend()
plt.show()
Output:

Output
(b) Plot Cumulative Returns:
plt.figure(figsize=(14, 7))
plt.plot(data['Cumulative Market Return'], label='Market Return', alpha=0.75)
plt.plot(data['Cumulative Strategy Return'], label='Strategy Return', alpha=0.75)
plt.title("Cumulative Returns")
plt.legend()
plt.show()
Output:

Output
Explanation:
- Visualizing SMAs: Helps in identifying buy/sell zones when SMA50 crosses above or below SMA200.
- Cumulative Returns Plot: Compares how the strategy performs against holding the stock without any active trading strategy.
Step 8: Evaluate Performance
Compare the cumulative returns of the strategy vs. holding the market.
total_strategy_return = data['Cumulative Strategy Return'].iloc[-1] - 1
total_market_return = data['Cumulative Market Return'].iloc[-1] - 1
print(f"Total Strategy Return: {total_strategy_return:.2%}")
print(f"Total Market Return: {total_market_return:.2%}")
Output:
Total Strategy Return: 291.62%
Total Market Return: 1003.89%
Why this step is important:
- Measures the profitability of the trading strategy against a buy-and-hold approach.
- Helps evaluate how well the strategy performs on historical data and provides a sense of risk-adjusted returns.