Automated Trading Development in Python, Kiwoom Securities API, Development Environment Setup

As interest in stock investment has recently increased, many investors are looking to build automated trading systems. In particular, Python is favored by many developers due to its powerful libraries and ease of use. This article will provide a detailed explanation of the development process for automated trading using Python, as well as how to set up a development environment using the Kiwoom Securities API. After reading this article, you will gain a foundational understanding to create your own automated trading program, along with practical development examples.

1. What is an Automated Trading System?

An automated trading system is designed for a computer program to analyze market data and execute trades automatically without user instructions. This helps traders make consistent investment decisions without being swayed by emotions in the market. The automated trading system generates trading signals based on specific algorithms and uses these signals to make buy or sell decisions. This system requires a combination of programming knowledge and trading strategies to operate successfully.

2. What is the Kiwoom Securities API?

The Kiwoom Securities API is a tool that enables trading various financial products such as stocks, futures, and options through a program provided by Kiwoom Securities. This API offers users a range of functions, including real-time data, trade execution, balance checking, and yield analysis. Using the Kiwoom Securities API, you can easily develop and operate your own trading system.

3. Setting Up the Development Environment

3.1. Preparation Steps

To develop an automated trading system, the following preparations are necessary.

  • Install Python: Download and install Python version 3.6 or higher.
  • Open a Kiwoom Securities Account: Open an account with Kiwoom Securities and apply for API usage.
  • Install Python Libraries: The following libraries will be used for development.
    • pykiwoom: A library that helps use the Kiwoom Securities API in Python.
    • pandas: A library for data analysis and manipulation.
    • numpy: A library for numerical calculations.
    • matplotlib: A library for data visualization.

3.2. Installing Python

To install Python, download the installation file suitable for your operating system from [python.org](https://www.python.org/downloads/) and install it. After installation, open the command prompt or terminal and enter the command `python –version` to verify if it was installed correctly.

3.3. Installing Libraries

Use pip to install the previously mentioned libraries. Enter the following commands in the command prompt one by one.

        pip install pykiwoom
        pip install pandas
        pip install numpy
        pip install matplotlib
    

3.4. Configuring the Kiwoom Securities API

To use the Kiwoom Securities API, you need to install and log in to the Kiwoom Securities HTS ‘Hero Moon’. After logging in, you can apply for API usage through the ‘Option’ – ‘API Settings’ menu. Once the application is completed, you can receive an API key.

4. Creating a Basic Trading System

Now that the development environment is ready, let’s implement a basic trading system. The basic structure of an automated trading system is as follows.

  1. Collect market data
  2. Generate trading signals according to the algorithm
  3. Execute trades
  4. Record and analyze results

4.1. Data Collection

First, let’s collect stock data using the Kiwoom Securities API. Below is an example of requesting data for a specific stock using pykiwoom.

        
        from pykiwoom.kiwoom import Kiwoom
        import pandas as pd

        kiwoom = Kiwoom()
        kiwoom.CommConnect()

        # Set stock code
        code = "005930"  # Samsung Electronics

        # Request data
        df = kiwoom.get_master_last_price(code)  # Request current price
        print(df)
        
    

4.2. Generating Trading Signals

Now let’s set a basic trading algorithm. For example, we can generate trading signals based on the Simple Moving Average (SMA).

        
        def generate_signal(data):
            data['SMA_5'] = data['close'].rolling(window=5).mean()
            data['SMA_20'] = data['close'].rolling(window=20).mean()
            data['signal'] = 0
            data['signal'][5:] = np.where(data['SMA_5'][5:] > data['SMA_20'][5:], 1, 0)  # Buy signal
            return data
        
    

4.3. Executing Trades

You can write code to execute trades based on signals as follows.

        
        def execute_trade(signal):
            if signal == 1:
                # Execute buy
                kiwoom.SendOrder("buysignal", "0101", code, 1, 0, 0, "03", "")
            elif signal == 0:
                # Execute sell
                kiwoom.SendOrder("sellsignal", "0101", code, 1, 0, 0, "03", "")
        
    

5. Integrating the Entire System

Finally, let’s integrate all the above elements into a single program. We will periodically collect market data, generate signals, and execute trades.

        
        import time

        while True:
            # Collect data
            data = kiwoom.get_market_data(code)
            
            # Generate trading signal
            signal_data = generate_signal(data)
            latest_signal = signal_data['signal'].iloc[-1]
            
            # Execute trade
            execute_trade(latest_signal)
            
            # Wait for 30 seconds
            time.sleep(30)
        
    

6. Conclusion

In this article, we explored how to build a basic automated trading system using Python and the Kiwoom Securities API. We examined the flow from data collection to generating trading signals and executing trades. I hope this script helps you in developing your own more complex and sophisticated trading systems. Based on a deep understanding of programming and investing, I encourage you to try various strategies.

In the future, I also plan to prepare articles on how to enhance automated trading systems using machine learning and data analysis techniques. Thank you for your interest!