Automated Trading Development in Python, Drawing Moving Averages

The automated trading system refers to a program that automatically executes investment decisions in various financial markets such as stocks, forex, and cryptocurrencies. When developing such systems, various technical indicators are used to generate trading signals, one of which is the Moving Average (MA). The moving average is a useful tool for identifying price trend changes over a specific period. In this article, we will explain in detail how to plot moving averages using Python.

Overview of Moving Averages

A moving average is calculated by averaging the prices of a stock or other price indicators over a specific period and displayed on a chart. There are several types based on the form of the moving average:

  • Simple Moving Average (SMA): The simple average of prices over the selected period.
  • Exponential Moving Average (EMA): An average calculated with more weight on recent prices, showing a more sensitive response.
  • Weighted Moving Average (WMA): An average calculated by assigning weights to each price.

In this tutorial, we will use the simple moving average (SMA) as an example to demonstrate how to plot it on a graph.

Installing Required Libraries

To plot moving averages in Python, the following libraries are needed:

  • pandas: A library for data processing and analysis.
  • numpy: A library for numerical calculations.
  • matplotlib: A library for data visualization.
  • yfinance: A library to fetch data from Yahoo Finance.

You can install the libraries using the following command:

pip install pandas numpy matplotlib yfinance

Fetching Stock Data

Now, let’s learn how to fetch stock data from Yahoo Finance. The following code can be used to fetch data for Apple Inc.:

import yfinance as yf

# Download Apple stock data
ticker = 'AAPL'
data = yf.download(ticker, start='2020-01-01', end='2021-01-01')
print(data.head())

The above code retrieves and prints the Apple stock data from January 1, 2020, to January 1, 2021. The data consists of columns such as Date, Open, High, Low, Close, and Volume.

Calculating the Simple Moving Average

Calculating the moving average is very simple. Using the rolling function from the pandas library, you can easily calculate the moving average for a specific period. For example, the code to calculate the 20-day moving average is as follows:

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

The above code adds a new column ‘SMA_20’ based on the closing prices of Apple stock data for the 20-day moving average.

Visualizing the Moving Average

Now it’s time to visualize the calculated moving average on a chart. We will proceed with the visualization using the matplotlib library:

import matplotlib.pyplot as plt

# Visualization
plt.figure(figsize=(14, 7))
plt.plot(data['Close'], label='Close Price', color='blue')
plt.plot(data['SMA_20'], label='20-Day Moving Average', color='orange')
plt.title('Apple Stock (Weekly) Closing Price and Moving Average')
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.legend()
plt.grid()
plt.show()

When you run the code, a chart will appear showing both the closing price and the 20-day moving average of Apple stock. The blue line represents the closing price, and the orange line represents the 20-day moving average.

Changing Parameters to Plot Different Moving Averages

You can also add moving averages for different periods. For example, let’s add the 50-day and 200-day moving averages:

# Calculate the 50-day and 200-day moving averages
data['SMA_50'] = data['Close'].rolling(window=50).mean()
data['SMA_200'] = data['Close'].rolling(window=200).mean()

# Visualization
plt.figure(figsize=(14, 7))
plt.plot(data['Close'], label='Close Price', color='blue')
plt.plot(data['SMA_20'], label='20-Day Moving Average', color='orange')
plt.plot(data['SMA_50'], label='50-Day Moving Average', color='green')
plt.plot(data['SMA_200'], label='200-Day Moving Average', color='red')
plt.title('Apple Stock (Weekly) Closing Price and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.legend()
plt.grid()
plt.show()

Executing this code will generate a chart displaying three different moving averages. Visualizing different moving averages can provide clearer insights into market trends.

Conclusion

In this article, we discussed how to calculate and visualize moving averages using Python. Moving averages are helpful in understanding market trends and generating trading signals. We can integrate moving averages into automated trading systems, enabling smarter trading strategies. The moving average is one of the most fundamental yet effective tools in the development of automated trading systems.

Next Steps

Building upon this foundation, you can develop more complex trading strategies and extend the system by using other technical indicators or algorithms. For example, you can use moving averages along with the RSI (Relative Strength Index). Diversify and experiment with your strategy!

References