Python is a very useful language for data analysis and implementing automated trading systems. In particular, data visualization using the Matplotlib library is a great help in understanding market movements and making trading decisions. This article will explain in detail how to implement effective data visualization through the concepts of Figure and Subplots in Matplotlib. We will practice with a simple stock price data example.
1. Introduction to Matplotlib Library
Matplotlib is one of the most widely used data visualization libraries in Python, allowing you to create various types of graphs. In particular, using Figure and Subplots makes it easy to compare multiple graphs by placing them on one screen.
2. Understanding the Concept of Figure
A Figure is the top-level object in Matplotlib that can contain one or more subplots. The Figure is used to set the size and elements of the overall graph. To draw a graph using Matplotlib, you must first create a Figure.
3. Understanding the Concept of Subplots
Subplots are a way to place multiple individual graphs within a single Figure. Utilizing the subplot feature is very useful for comparing multiple data at a glance. Below is a basic method for setting up Subplots.
3.1 How to Create Subplots
To create a subplot, you can use the plt.subplots()
function to specify the desired number of rows and columns. Here’s a basic usage example:
python
import matplotlib.pyplot as plt
# Create Subplots
fig, axs = plt.subplots(2, 2) # Create a 2x2 shape subplot
# Add sample data to each subplot
axs[0, 0].plot([1, 2, 3], [1, 4, 9])
axs[0, 0].set_title('First Graph')
axs[0, 1].plot([1, 2, 3], [1, 2, 1])
axs[0, 1].set_title('Second Graph')
axs[1, 0].plot([1, 2, 3], [1, 0, 1])
axs[1, 0].set_title('Third Graph')
axs[1, 1].plot([1, 2, 3], [2, 2, 2])
axs[1, 1].set_title('Fourth Graph')
# Adjust layout
plt.tight_layout()
plt.show()
4. Example of Building a Stock Automated Trading System
In this section, we will visualize a simple stock data serving as the basis for an automated trading system. We will retrieve data via the Yahoo Finance API and visualize the price trend using Matplotlib.
4.1 Installing Required Libraries and Data Collection
We will use the yfinance
library to collect data. Please install the necessary libraries in your Python environment as follows:
bash
pip install yfinance matplotlib
4.2 Example Code for Data Collection
Below is an example code that collects and visualizes the stock data of Apple Inc.
python
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
# Retrieve data
stock = yf.Ticker("AAPL")
data = stock.history(period="1y") # Get data for one year
# Visualize data
fig, axs = plt.subplots(2, 1, figsize=(10, 10)) # 2x1 subplot
# Closing price graph
data['Close'].plot(ax=axs[0])
axs[0].set_title('AAPL Closing Price')
axs[0].set_ylabel('Price')
# Volume graph
data['Volume'].plot(ax=axs[1])
axs[1].set_title('AAPL Volume')
axs[1].set_ylabel('Volume')
plt.tight_layout()
plt.show()
5. Adding Technical Indicator
Now, let’s add a simple technical indicator, the Moving Average, to make the graph even more useful. The moving average helps in understanding the price trend by calculating the average price.
5.1 Example Code for Adding Moving Average
The code below calculates the 20-day and 50-day moving averages for the stock price data and adds them to the graph.
python
# Calculate moving average
data['MA20'] = data['Close'].rolling(window=20).mean()
data['MA50'] = data['Close'].rolling(window=50).mean()
# Visualization
fig, axs = plt.subplots(2, 1, figsize=(10, 10))
# Closing price and moving averages
axs[0].plot(data['Close'], label='Closing Price', color='blue')
axs[0].plot(data['MA20'], label='20-Day Moving Average', color='orange')
axs[0].plot(data['MA50'], label='50-Day Moving Average', color='green')
axs[0].set_title('AAPL Closing Price and Moving Averages')
axs[0].set_ylabel('Price')
axs[0].legend()
# Volume graph
data['Volume'].plot(ax=axs[1])
axs[1].set_title('AAPL Volume')
axs[1].set_ylabel('Volume')
plt.tight_layout()
plt.show()
6. Conclusion
In this article, we explained how to build the foundational visualizations necessary for an automated trading system using Python’s Matplotlib library. By understanding the concepts of Figure and Subplots, we were able to visualize multiple data simultaneously and enrich our analysis by adding a simple moving average. Integrating this visualization into actual automated trading algorithms can lead to better trading decisions.
Additionally, by practicing with real market data and applying various technical indicators, one can further improve the automated trading system. We encourage you to continue learning about data visualization and algorithmic trading with Python.