Python automatic trading development, PyQt QHBoxLayout

The development of automated trading systems is a field that many traders and investors are attempting for efficient trading. Automated trading systems execute trades automatically according to algorithms set by the program, without human intervention. This article will explain the useful QHBoxLayout of PyQt for creating user interfaces while building an automated trading system, along with practical code examples.

1. What is an automated trading system?

An automated trading system is a program that automatically performs trading based on predefined rules. These systems have several advantages, including:

  • Exclusion of psychological factors: It allows for a consistent trading strategy without emotional decisions.
  • Quick trading: It reacts immediately to market volatility to execute trades, helping to reduce losses.
  • 24-hour trading: The program can continuously execute trades without human assistance, operating 24 hours a day.

2. What is PyQt?

PyQt is a framework that allows you to develop GUI applications using the Qt library in Python. PyQt provides various widgets and layouts to help users easily construct interfaces.

2.1 Overview of QHBoxLayout

QHBoxLayout is a layout that manages a group of widgets arranged horizontally. Using this layout, you can align widgets horizontally and place them with equal spacing. Since users of automated trading systems should be able to make various inputs, QHBoxLayout can be an optimal choice.

3. Basic example using PyQt

Now, let’s look at an example of creating a basic user interface for an automated trading system using PyQt and QHBoxLayout. In this example, we will build a simple GUI that takes stock codes and target prices as input from the user.

3.1 Installing the required libraries

To use PyQt, you must first install PyQt5 with the following command:

pip install PyQt5

3.2 GUI application code

Below is the basic GUI code for the automated trading system utilizing QHBoxLayout with PyQt5:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox

class AutoTradingApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # Create Horizontal Layout
        layout = QHBoxLayout()

        # Stock code input field
        self.stockLabel = QLabel('Stock Code:')
        self.stockInput = QLineEdit(self)
        layout.addWidget(self.stockLabel)
        layout.addWidget(self.stockInput)

        # Target price input field
        self.priceLabel = QLabel('Target Price:')
        self.priceInput = QLineEdit(self)
        layout.addWidget(self.priceLabel)
        layout.addWidget(self.priceInput)

        # Execute button
        self.submitButton = QPushButton('Execute', self)
        self.submitButton.clicked.connect(self.onSubmit)
        layout.addWidget(self.submitButton)

        # Set Layout
        self.setLayout(layout)

        self.setWindowTitle('Automated Trading System')
        self.show()

    def onSubmit(self):
        stock_code = self.stockInput.text()
        target_price = self.priceInput.text()
        
        if stock_code and target_price:
            QMessageBox.information(self, 'Info', f'Stock Code: {stock_code}, Target Price: {target_price}')
        else:
            QMessageBox.warning(self, 'Warning', 'Please fill in all fields.')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = AutoTradingApp()
    sys.exit(app.exec_())

3.3 Explanation of the code

The code above is an example of creating a simple GUI for an automated trading system:

  • QWidget: The base widget for all PyQt5 applications.
  • QHBoxLayout: Arranges widgets in a horizontal layout.
  • QLabel: Creates a text label.
  • QLineEdit: A widget that allows the user to input text.
  • QPushButton: Creates a button to handle click events.
  • QMessageBox: Uses a popup dialog to display information.

When the code is executed, users will see a simple interface where they can input the stock code and target price. Clicking the ‘Execute’ button will display the entered information in a popup.

4. Adding automated trading logic

Now that we have the GUI and input fields, let’s add the actual automated trading logic. In this example, we will use a library called yfinance to fetch the current price of the stock and compare it with the target price set by the user.

4.1 Installing yfinance

yfinance is a library that fetches stock data from the Yahoo Finance API. Install it using the following command:

pip install yfinance

4.2 Modifying the code

The code below adds logic to check the stock price and compare it with the target price to the existing GUI:

import sys
import yfinance as yf
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox

class AutoTradingApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QHBoxLayout()

        self.stockLabel = QLabel('Stock Code:')
        self.stockInput = QLineEdit(self)
        layout.addWidget(self.stockLabel)
        layout.addWidget(self.stockInput)

        self.priceLabel = QLabel('Target Price:')
        self.priceInput = QLineEdit(self)
        layout.addWidget(self.priceLabel)
        layout.addWidget(self.priceInput)

        self.submitButton = QPushButton('Execute', self)
        self.submitButton.clicked.connect(self.onSubmit)
        layout.addWidget(self.submitButton)

        self.setLayout(layout)

        self.setWindowTitle('Automated Trading System')
        self.show()

    def onSubmit(self):
        stock_code = self.stockInput.text()
        target_price = float(self.priceInput.text())
        
        if stock_code:
            # Fetching stock price
            stock_info = yf.Ticker(stock_code)
            current_price = stock_info.history(period='1d')['Close'].iloc[-1]

            if current_price >= target_price:
                QMessageBox.information(self, 'Info', f'Current Price: {current_price}\nReached target price! Proceed with trading.')
            else:
                QMessageBox.information(self, 'Info', f'Current Price: {current_price}\nDid not reach target price.')
        else:
            QMessageBox.warning(self, 'Warning', 'Please fill in all fields.')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = AutoTradingApp()
    sys.exit(app.exec_())

4.3 Explanation of the modified code

The modified code fetches the current price corresponding to the stock code entered by the user and compares it with the target price:

  • It uses the Ticker class of the yfinance library to fetch stock information.
  • It retrieves the latest closing price of the stock and compares it with the user-inputted target price.
  • A popup dialog is displayed based on the result.

When the above code is executed, users can check the current price for the stock code they entered and report whether it has reached the target price.

5. Conclusion

In this article, we explored the process of developing a simple GUI for an automated trading system using Python. We learned how to structure user interfaces using QHBoxLayout of PyQt and how to fetch stock data using the yfinance library. This provides users with the foundational skills to set up their trading strategies and develop systems that execute them automatically.

If you have any further questions or would like more details, please feel free to leave a comment. We will also cover more automated trading techniques and implementation methods!