Automated Trading Development in Python, Calculating Stock Price Moving Averages Using Pandas

One of the most important factors in developing an automated trading system is data analysis. To analyze stock price data and generate appropriate trading signals, various techniques are required. One of the most basic and widely used techniques is moving averages. In this article, we will detail how to calculate stock price moving averages using Python’s Pandas library and apply them to an automated trading system.

1. What is a Moving Average?

A moving average smooths out stock price fluctuations by calculating the average over a certain period. It is useful for identifying trends when stock price volatility is high.

  • Simple Moving Average (SMA): This is calculated by simply averaging past stock prices over a certain period.
  • Exponential Moving Average (EMA): This is calculated by giving more weight to recent stock prices.

Generally, SMA and EMA are used to generate trading signals. This tutorial will focus on SMA.

2. Installing Python and Pandas

First, you need to install Python and Pandas. Using Anaconda makes the installation convenient. Once installed, perform the following basic setup:

pip install pandas matplotlib yfinance

3. Getting Stock Price Data

Here, we will use the Yahoo Finance API to fetch stock price data. The yfinance library can be used for this purpose.


import yfinance as yf

# Getting Apple stock price data (e.g., from January 1, 2020, to the present)
data = yf.download('AAPL', start='2020-01-01', end='2023-12-31')
print(data.head())
    

4. Calculating Moving Averages

Now that the stock price data is prepared, let’s calculate the moving averages. Pandas provides a simple method for calculating moving averages.


import pandas as pd

# Calculating the 20-day moving average
data['SMA_20'] = data['Close'].rolling(window=20).mean()
# Calculating the 50-day moving average
data['SMA_50'] = data['Close'].rolling(window=50).mean()

print(data[['Close', 'SMA_20', 'SMA_50']].tail())
    

5. Plotting Moving Average Charts

Now we will use the matplotlib library to plot the moving average charts. This will allow us to visually examine the relationship between stock prices and moving averages.


import matplotlib.pyplot as plt

plt.figure(figsize=(14,7))
plt.plot(data['Close'], label='AAPL Close Price', color='blue', alpha=0.5)
plt.plot(data['SMA_20'], label='20-Day SMA', color='orange', alpha=0.75)
plt.plot(data['SMA_50'], label='50-Day SMA', color='green', alpha=0.75)
plt.title('Apple Stock Price and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.show()
    

6. Generating Trading Signals

Trading signals can be generated using moving averages. Typically, a buy signal is generated when the short-term moving average crosses above the long-term moving average, and a sell signal is triggered when it crosses below.


data['Signal'] = 0.0  # Set initial signal to 0

# Buy signal
data['Signal'][20:] = np.where(data['SMA_20'][20:] > data['SMA_50'][20:], 1.0, 0.0)   
# Sell signal
data['Position'] = data['Signal'].diff()  # Check position change

plt.figure(figsize=(14,7))
plt.plot(data['Close'], label='Close Price', color='blue', alpha=0.5)
plt.plot(data['SMA_20'], label='20-Day SMA', color='orange', alpha=0.75)
plt.plot(data['SMA_50'], label='50-Day SMA', color='green', alpha=0.75)

# Plotting buy signals
plt.plot(data[data['Position'] == 1].index, 
         data['SMA_20'][data['Position'] == 1],
         '^', markersize=10, color='g', lw=0, label='Buy Signal')

# Plotting sell signals
plt.plot(data[data['Position'] == -1].index, 
         data['SMA_20'][data['Position'] == -1],
         'v', markersize=10, color='r', lw=0, label='Sell Signal')

plt.title('Buy & Sell Signals')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.show()
    

7. Implementing an Automated Trading System

Now, let’s implement a simple automated trading system. We will add logic to determine whether to buy or sell when trading signals are generated. In this example, we assume a starting capital of $10,000 for trading.


initial_capital = 10000
shares = 0
cash = initial_capital

for i in range(len(data)):
    if data['Position'][i] == 1:  # Buy signal
        shares = cash // data['Close'][i]  # Calculate number of shares to buy
        cash -= shares * data['Close'][i]  # Deduct stock purchase cost from cash
    elif data['Position'][i] == -1:  # Sell signal
        cash += shares * data['Close'][i]  # Add stock sale proceeds to cash
        shares = 0  # Sell all shares
    
final_value = cash + shares * data['Close'].iloc[-1]  # Calculate final assets
print(f'Initial Capital: ${initial_capital} -> Final Value: ${final_value}')
    

8. Performance Analysis

To analyze the performance of the automated trading system, we can calculate the final return and win rate. The following code provides a simple way to evaluate the performance of this system.


trades = data['Position'].diff()  # Check trading signals
successful_trades = trades[trades == 1].count()  # Count sell signals
win_trades = trades[trades == -1].count()  # Count buy signals
win_ratio = (successful_trades / (successful_trades + win_trades)) * 100

print(f'Total Trades: {successful_trades + win_trades}, Winning Trades: {successful_trades}, Win Ratio: {win_ratio}%')
    

9. Conclusion

In this tutorial, we calculated stock price moving averages using Python’s Pandas library, generated trading signals based on them, and implemented a simple automated trading system. While moving averages are a fundamental technique, they can be appropriately adjusted to develop more complex automated trading strategies. In the future, it would be beneficial to consider strategies using Exponential Moving Averages (EMA) or other technical indicators. We wish you successful automated trading!

10. References

Author: Your Name | Date: October 1, 2023