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!