Automated Trading Development in Python, Modifying Matplotlib to Plot Closing Prices and Volumes at Once

In recent years, automated trading systems have become quite popular among investors and traders in the financial markets. In particular, Python is a highly suitable language for building automated trading systems due to its various data analysis tools and libraries. In this article, we will detail how to develop an automated trading system using Python and visualize closing prices and trading volumes simultaneously using matplotlib.

1. Overview of Automated Trading Systems

An automated trading system is a program that executes trades automatically based on predefined rules. Such systems can operate on various financial products such as stocks, foreign exchange, and cryptocurrencies, using various techniques including machine learning, algorithmic analysis, and statistical methods to make trading decisions.

2. Installing Required Libraries

To develop automated trading with Python, we will use the following libraries. First, install the required libraries using the command below.

pip install numpy pandas matplotlib yfinance
    

3. Data Collection

Data for automated trading is very important. We will use the yfinance library to obtain closing price and trading volume data from Yahoo Finance. The data can be collected using the code below.

import yfinance as yf

# Data Collection
def get_stock_data(ticker, start_date, end_date):
    data = yf.download(ticker, start=start_date, end=end_date)
    return data

ticker = 'AAPL'  # Apple stock ticker
start_date = '2023-01-01'
end_date = '2023-12-31'
data = get_stock_data(ticker, start_date, end_date)
print(data.head())
    

3.1. Understanding the Data

In the code above, the get_stock_data function takes the specified stock ticker along with the start and end dates as arguments to load the data. The returned data includes the following information:

  • Open: Opening price
  • High: Highest price
  • Low: Lowest price
  • Close: Closing price
  • Volume: Trading volume

4. Data Visualization: Closing Prices and Trading Volume

Now we will visualize the collected data and plot the closing prices and trading volumes at the same time. We will generate the graphs using the matplotlib library.

4.1. Plotting the Closing Prices and Trading Volume

import matplotlib.pyplot as plt

def plot_price_volume(data):
    fig, ax1 = plt.subplots(figsize=(12, 6))

    # Plotting Closing Prices
    ax1.plot(data.index, data['Close'], color='blue', label='Closing Price')
    ax1.set_xlabel('Date')
    ax1.set_ylabel('Closing Price', color='blue')
    ax1.tick_params(axis='y', labelcolor='blue')
    ax1.legend(loc='upper left')

    # Second axis for adding Volume
    ax2 = ax1.twinx()  
    ax2.bar(data.index, data['Volume'], color='gray', alpha=0.3, label='Volume')
    ax2.set_ylabel('Volume', color='gray')
    ax2.tick_params(axis='y', labelcolor='gray')
    ax2.legend(loc='upper right')

    plt.title('Visualization of Closing Prices and Volume')
    plt.show()

# Data Visualization
plot_price_volume(data)
    

4.2. Code Explanation

The above plot_price_volume function visualizes the closing prices and volumes through the following steps:

  1. Plotting the Stock Closing Price: The closing price of the stock is plotted using ax1.plot as a blue line.
  2. Setting Axis Labels and Legend: Axes labels are set for both x and y axes, and legends are added to clarify the contents of each graph.
  3. Plotting Volume: Volume is added to the same graph as gray bars using ax2.twinx().
  4. Adding Graph Title: The title for the entire graph is set to make the visualization clear.

5. Automated Trading Simulation

After visualizing the data, we will now conduct a simple automated trading simulation. The basic strategy will utilize a moving average (MA) based strategy to generate trading signals and determine buy and sell points.

5.1. Adding Simple Moving Average (SMA)

def calculate_sma(data, window):
    return data['Close'].rolling(window=window).mean()

# Adding Simple Moving Average for Closing Price
data['SMA_20'] = calculate_sma(data, 20)
data['SMA_50'] = calculate_sma(data, 50)
print(data[['Close', 'SMA_20', 'SMA_50']].tail())
    

The above calculate_sma function calculates the simple moving average given the data and the moving average period (window). The 20-day and 50-day moving averages are calculated and added to the data frame.

5.2. Generating Trading Signals

def generate_signals(data):
    signals = []
    position = 0  # Current holding position (1: Buy, -1: Sell, 0: None)

    for i in range(len(data)):
        if data['SMA_20'][i] > data['SMA_50'][i] and position != 1:
            signals.append(1)  # Buy signal
            position = 1
        elif data['SMA_20'][i] < data['SMA_50'][i] and position != -1:
            signals.append(-1)  # Sell signal
            position = -1
        else:
            signals.append(0)  # No signal

    return signals

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

The generate_signals function generates trading signals based on the simple moving average. When SMA 20 crosses above SMA 50, a buy signal is generated, and conversely, when crossing below, a sell signal is generated.

6. Performance Analysis

Now that trading signals have been generated, we will analyze the performance. The portfolio's performance can be evaluated based on the buy and sell signals.

6.1. Calculating Returns

def calculate_returns(data):
    data['Market_Returns'] = data['Close'].pct_change()
    data['Strategy_Returns'] = data['Market_Returns'] * data['Signals'].shift(1)  # Returns based on trading signals
    data['Cumulative_Market_Returns'] = (1 + data['Market_Returns']).cumprod() - 1
    data['Cumulative_Strategy_Returns'] = (1 + data['Strategy_Returns']).cumprod() - 1

calculate_returns(data)
print(data[['Cumulative_Market_Returns', 'Cumulative_Strategy_Returns']].tail())
    

Here, the calculate_returns function calculates the returns, comparing market returns with strategy returns. Cumulative returns are calculated to easily analyze performance.

7. Comparing Performance through Graphs

Finally, we can visualize cumulative returns to compare the performance of the strategy. Let’s visualize using matplotlib.

def plot_performance(data):
    plt.figure(figsize=(14, 7))
    plt.plot(data.index, data['Cumulative_Market_Returns'], label='Market Returns', color='orange')
    plt.plot(data.index, data['Cumulative_Strategy_Returns'], label='Strategy Returns', color='green')
    plt.title('Market Returns vs Strategy Returns')
    plt.xlabel('Date')
    plt.ylabel('Cumulative Returns')
    plt.legend()
    plt.show()

plot_performance(data)
    

8. Conclusion

In this article, we examined how to visualize closing prices and trading volumes along with a simple automated trading system using Python. Additionally, we understood the basic concepts of automated trading through generating trading signals based on moving averages and performance analysis. Going forward, explore developing more complex strategies and applying various techniques to build a more effective automated trading system.

Based on proposed methods, you can also proceed to advanced modeling tasks utilizing machine learning, deep learning, etc. Furthermore, try developing more advanced trading strategies by applying various indicators and strategies.

Finally, as you practice the code and concepts, enjoy the process of building your own automated trading system!

Automated Trading Development in Python, Configuring Matplotlib

Recently, as algorithmic trading has become the trend in the financial markets, Python has gained prominence among various programming languages that can implement this. Among them, data visualization plays a crucial role in understanding analysis results, with the matplotlib library being widely used for this purpose. In this article, we will explain the construction of an automated trading system using Python and how to visualize data using matplotlib in the process.

1. Python and Automated Trading Systems

An automated trading system is a program that trades stocks, forex, cryptocurrencies, etc., based on specific algorithms or strategies. Users code their trading strategies and input them into the system, and the program analyzes market data in real-time to generate buy/sell signals.

1.1 Components of an Automated Trading System

An automated trading system mainly consists of the following elements:

  • Market Data Collection: Obtaining real-time or historical data via APIs.
  • Signal Generation: Generating buy/sell signals based on technical analysis or AI models.
  • Trade Execution: Executing actual trades according to the signals.
  • Risk Management: Setting position sizing and stop-loss strategies to minimize losses.
  • Performance Analysis: Recording and visualizing results to analyze the effectiveness of trading strategies.

2. Introduction to matplotlib

matplotlib is a Python library for 2D graphics that is useful for visually presenting data. It can create various types of charts and plots and is often used to analyze data collected in automated trading systems and visually present results.

2.1 Installing matplotlib

matplotlib can be easily installed via pip. You can use the command below to install it.

pip install matplotlib

2.2 Basic Usage of matplotlib

The most basic usage of matplotlib is to prepare data and set up to plot it. The following example code demonstrates how to create a simple line graph.


import matplotlib.pyplot as plt

# Prepare data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Draw line graph
plt.plot(x, y)
plt.title("Sample Graph")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
        

3. Implementing Automated Trading Strategies

Now let’s implement an automated trading strategy. We will take the simple moving average crossover strategy as an example. This strategy interprets a buy signal when the short-term moving average crosses above the long-term moving average and a sell signal when it crosses below.

3.1 Data Collection

Financial data is usually collected through APIs. For example, we can collect data for a specific stock using the yfinance library.


import yfinance as yf

# Collect Apple stock data
data = yf.download("AAPL", start="2020-01-01", end="2023-01-01")
data.head()
        

3.2 Calculating Moving Averages

After collecting the data, we calculate the short-term and long-term moving averages to generate trading signals. The code below shows an example of calculating the 20-day and 50-day moving averages.


# Calculate moving averages
short_window = 20
long_window = 50

data['Short_MA'] = data['Close'].rolling(window=short_window).mean()
data['Long_MA'] = data['Close'].rolling(window=long_window).mean()
        

3.3 Generating Trading Signals

We generate trading signals based on the moving averages. Signals are defined as follows:


data['Signal'] = 0
data['Signal'][short_window:] = np.where(data['Short_MA'][short_window:] > data['Long_MA'][short_window:], 1, 0)
data['Position'] = data['Signal'].diff()
        

3.4 Visualization

Now let’s visualize the price chart along with the generated trading signals. We can use matplotlib to display the price, moving averages, and trading signals together.


plt.figure(figsize=(14,7))
plt.plot(data['Close'], label='Close Price', alpha=0.5)
plt.plot(data['Short_MA'], label='20-Day Moving Average', alpha=0.75)
plt.plot(data['Long_MA'], label='50-Day Moving Average', alpha=0.75)

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

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

plt.title('Automated Trading Strategy Visualization')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(loc='best')
plt.grid()
plt.show()
        

4. Performance Analysis

Analyzing trading performance is essential for evaluating the success of the trading strategy. We will calculate returns and check the final asset size to understand the effectiveness of the strategy.


# Calculate cumulative returns
data['Returns'] = data['Close'].pct_change()
data['Strategy_Returns'] = data['Returns'] * data['Signal'].shift(1)

# Final asset size
cumulative_strategy_returns = (1 + data['Strategy_Returns']).cumprod()
cumulative_strategy_returns.plot(figsize=(14,7), label='Strategy Returns')
plt.title('Strategy Returns')
plt.xlabel('Date')
plt.ylabel('Cumulative Returns')
plt.legend()
plt.grid()
plt.show()
        

5. Conclusion

In this article, we explored the components of an automated trading system using Python and how to visualize data using matplotlib. Visualization plays a crucial role in the process of building an automated trading system and implementing trading strategies, allowing traders to evaluate and improve the validity of their strategies. Data visualization provides insights into complex data and helps facilitate effective decision-making.

Lastly, please always keep in mind that operating an automated trading system in practice involves high risks. It is important to simulate various strategies and establish appropriate risk management measures to respond sensitively to market changes.

We encourage you to continue challenging yourself in financial data analysis and the development of automated trading systems using programming languages like Python.

Python Automated Trading Development, Drawing Matplotlib Bar Charts

Python has established itself as one of the powerful tools in the world of data science and automation.
Building automated trading systems in the financial markets has become an attractive challenge for many traders.
In this article, we will detail how to draw Bar charts using Matplotlib, which is an important element in visualizing data in automated trading systems.

1. What is Matplotlib?

Matplotlib is a Python library for data visualization that provides the functionality to create various types of charts.
In particular, Bar charts are useful for visually comparing data and play a significant role in analyzing financial data.

1.1 Installing Matplotlib

Matplotlib can be easily installed using pip.
Run the command below to install Matplotlib.

pip install matplotlib

2. Overview of Bar Charts

A Bar chart is a graph that represents the values of each category as the height of rectangles.
It has the advantage of allowing for simple yet powerful comparisons of data.
For example, displaying the monthly returns of a specific stock in a Bar chart allows you to quickly see the performance for each month.

3. Practical Exercise on Visualizing Automated Trading Data Using Bar Charts

Now, let’s draw a Bar chart through a real example.
We will use hypothetical stock data to visualize trading performance.
First, let’s import the necessary libraries and generate the data.

3.1 Generating Data


import matplotlib.pyplot as plt
import numpy as np

# Generate hypothetical data
categories = ['January', 'February', 'March', 'April', 'May']
profits = [100, 200, -150, 300, 250]

# Drawing the Bar chart
def plot_bar_chart(categories, profits):
    plt.bar(categories, profits, color='blue')
    plt.title('Monthly Returns')
    plt.xlabel('Month')
    plt.ylabel('Returns')
    plt.grid(axis='y')
    plt.axhline(0, color='black', lw=1)
    plt.show()

# Call the chart drawing function
plot_bar_chart(categories, profits)

3.2 Code Explanation

The above code shows the process of creating a simple Bar chart.
Here, the `plot_bar_chart` function is responsible for drawing the Bar chart based on the provided categories and return data.

  • Creating Bar chart: The chart is created using the `plt.bar()` function.
  • Setting Title and Labels: The chart title and axis labels are set using `plt.title()`, `plt.xlabel()`, and `plt.ylabel()`.
  • Adding Grid: The Y-axis grid lines are added using `plt.grid(axis=’y’)`.
  • Adding Baseline: A baseline is added at Y-axis 0 using `plt.axhline(0, color=’black’, lw=1)`.

4. Using Real Data

Although we used hypothetical data in our exercise, we can create more meaningful charts using actual financial data.
APIs such as Yahoo Finance API or Alpha Vantage API can be used to provide financial data.
In this example, we will use the pandas and yfinance libraries to fetch real stock data and draw a Bar chart.

4.1 Importing Data with yfinance


import yfinance as yf
import pandas as pd

# Download stock data
ticker = 'AAPL'
data = yf.download(ticker, period='1y', interval='1mo')
data['Monthly Change'] = data['Close'].diff()
data = data[data['Monthly Change'].notnull()]

# Processing data
months = data.index.strftime('%Y-%m').tolist()
profits = data['Monthly Change'].tolist()

# Drawing a Bar chart with real data
plot_bar_chart(months, profits)

4.2 Code Explanation

The above code demonstrates how to download monthly stock price data for Apple Inc. (AAPL) over the past year using the yfinance library, calculate returns, and draw a Bar chart.

  • Downloading Data: Specific stock data is downloaded using `yf.download()`.
  • Calculating Returns: The monthly returns are calculated by calling `data[‘Close’].diff()`.
  • Drawing Bar Chart: Finally, the Bar chart is drawn using the `plot_bar_chart()` function.

5. Customizing Bar Charts

Matplotlib offers various customization options to make charts more beautiful and useful.
Below are a few ways to customize Bar charts.

5.1 Changing Colors and Applying Styles


def plot_custom_bar_chart(categories, profits):
    plt.bar(categories, profits, color='skyblue', edgecolor='darkblue')
    plt.title('Monthly Returns', fontsize=16)
    plt.xlabel('Months', fontsize=12)
    plt.ylabel('Returns (Currency)', fontsize=12)
    plt.xticks(rotation=45)
    plt.grid(axis='y', linestyle='--')
    plt.axhline(0, color='red', lw=1)
    plt.tight_layout()
    plt.show()

plot_custom_bar_chart(months, profits)

5.2 Code Explanation

The `plot_custom_bar_chart` function adjusts the color, font size, and axis label rotation of the Bar chart to make it more visually appealing.

  • Color and Border: The color and border color of the bars are specified using `color` and `edgecolor`.
  • Title and Label Font Size: The font size of the chart title and labels is adjusted using `fontsize`.
  • Axis Label Rotation: The X-axis labels are rotated 45 degrees using `plt.xticks(rotation=45)` to improve readability.
  • Line Style Changes: The style of the grid lines is changed using `plt.grid(axis=’y’, linestyle=’–‘)`.

6. Conclusion

Using Matplotlib to draw Bar charts is very useful for achieving effective data visualization in automated trading systems.
Through this tutorial, we learned not only the basics of generating Bar charts but also how to create realistic charts with actual data,
and how to perform custom visualizations through various styling options.
These skills will greatly help in visually analyzing and improving trading strategies.

6.1 Additional Learning Resources

References

– Python for Data Analysis, Wes McKinney
– Python Data Science Handbook, Jake VanderPlas

Developing Python Auto Trading, Drawing matplotlib Pie Chart

The development of automated trading systems that trade various financial assets such as stocks, foreign exchange, and cryptocurrencies relies heavily on data visualization. Visually understanding the patterns and trends in financial data can greatly assist traders.
In this course, we will learn how to develop an automated trading system using Python and how to create pie charts to visually represent investment ratios using the matplotlib library.

1. Understanding Automated Trading Systems

An automated trading system (X) is a program that trades financial assets based on specific rules. This system generally collects market data in real-time and analyzes it to make buy or sell decisions.
Many traders use complex mathematical models and algorithms to predict market trends and pursue more efficient trading.

2. Data Collection

To build an automated trading system, you need to collect market data from reliable data sources. It’s common to retrieve data via APIs, and in Python, you can easily send API requests using the `requests` library.


import requests

def get_stock_data(symbol):
    url = f'https://api.example.com/v1/stock/{symbol}/quote'
    response = requests.get(url)
    data = response.json()
    return data

        

3. Analysis Through Data

An analysis phase is necessary to generate trading signals based on the collected data. Here we will demonstrate a trading strategy using a simple moving average as an example.


import pandas as pd

def moving_average(df, window):
    return df['close'].rolling(window=window).mean()

def generate_signals(df):
    df['short_mavg'] = moving_average(df, 20)
    df['long_mavg'] = moving_average(df, 50)

    df['signal'] = 0
    df['signal'][20:] = np.where(df['short_mavg'][20:] > df['long_mavg'][20:], 1, 0)
    df['positions'] = df['signal'].diff()
    return df

        

4. Drawing Matplotlib Pie Chart

Now we will create a chart to visualize the investment ratios using matplotlib. Pie charts help to easily understand the proportions of specific data.
For example, it is suitable for visually displaying the investment ratios of each asset.


import matplotlib.pyplot as plt

def plot_investment_distribution(investments):
    labels = investments.keys()
    sizes = investments.values()
    explode = [0.1] * len(sizes)  # Slightly separate each slice

    plt.figure(figsize=(8, 8))
    plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=140)
    plt.axis('equal')  # Maintain circular shape
    plt.title('Investment Ratio Visualization')
    plt.show()

        

5. Example Code: Complete Automated Trading System

Below is example code that combines all the aforementioned functions to show the basic framework of a perfect automated trading system.


import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Data Collection
def get_stock_data(symbol):
    url = f'https://api.example.com/v1/stock/{symbol}/quote'
    response = requests.get(url)
    data = response.json()
    return data

# Signal Generation
def moving_average(df, window):
    return df['close'].rolling(window=window).mean()

def generate_signals(df):
    df['short_mavg'] = moving_average(df, 20)
    df['long_mavg'] = moving_average(df, 50)
    df['signal'] = 0
    df['signal'][20:] = np.where(df['short_mavg'][20:] > df['long_mavg'][20:], 1, 0)
    df['positions'] = df['signal'].diff()
    return df

# Investment Ratio Visualization
def plot_investment_distribution(investments):
    labels = investments.keys()
    sizes = investments.values()
    explode = [0.1] * len(sizes)  # Separate the slices
    plt.figure(figsize=(8, 8))
    plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=140)
    plt.axis('equal')  # Maintain circle shape
    plt.title('Investment Ratio Visualization')
    plt.show()

# Main Function
def main():
    symbol = 'AAPL'  # Example: Apple stock
    stock_data = get_stock_data(symbol)
    df = pd.DataFrame(stock_data)
    
    df = generate_signals(df)
    
    # Example investment ratios
    investments = {
        'Apple': 40,
        'Google': 30,
        'Amazon': 30
    }
    
    # Investment ratio visualization
    plot_investment_distribution(investments)

if __name__ == "__main__":
    main()

        

6. Decision-Making Through Data Analysis

The example code above shows the basic setup required to build an automated trading system using Python. In practice, you need to receive real-time data via the API, analyze it, and make immediate trading decisions.
Additionally, you can complete a more comprehensive system with features such as error handling, logging, and backtesting.

Conclusion

In this course, we learned the process of developing an automated trading system using Python and the visualization techniques for pie charts using matplotlib.
This process provides an opportunity to effectively visualize investment ratios and further review one’s trading strategies visually.
Data visualization goes beyond simple charts to provide insights, which is an essential element of a successful investment strategy.

Thank you. If you have any questions or comments, please leave them in the comments!

Automatic Trading Development in Python, Figure and Subplots

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.