Skip to content

JYS1025/python_auto_trading

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LLM-Powered Stock Prediction and Trading Bot

Overview

This project is a proof-of-concept for an automated stock trading system using the Korea Investment & Securities (KIS) API. It leverages a fine-tuned DistilBERT language model to predict daily stock price movements based on historical price data and a rich set of technical indicators.

The system is an end-to-end pipeline that handles data fetching, feature engineering, model training, strategy backtesting, and finally, live paper/real trading.

The core of the project is to transform time-series data into a natural language format (prompts), which allows the LLM to be fine-tuned for a classification task—predicting if the stock price will go up or down.

Features

  • Data Handling: Fetches historical stock data using the yfinance library.
  • Rich Feature Engineering: Uses pandas-ta to calculate technical indicators (SMA, RSI, MACD, ATR, ADX).
  • LLM-based Prediction: Fine-tunes a DistilBERT model on prompts generated from financial time-series data.
  • Class Imbalance Handling: Implements a custom Trainer with class weights for robust model training.
  • Backtesting: Simulates trading strategies on historical data to evaluate performance.
  • Live/Paper Trading: Integrates with the Korea Investment & Securities (KIS) API via the python-kis library to automate trades in both paper and live accounts.
  • Automated Pipeline: A main script orchestrates the entire workflow from data to backtesting.
  • Logging: Logs all live trading activities, including predictions, orders, and errors.

Performance (Backtest)

The strategy was backtested on AAPL stock data from 2020-01-01 to 2023-12-31. Adding a richer set of technical indicators significantly improved performance over a simpler model.

Strategy Total Return Sharpe Ratio
LLM-Powered Trading (Improved) 183.38% 1.43
Buy-and-Hold Baseline 189.23% -

Project Structure

python_auto_trading/
├── data/                   # Processed data for training
├── logs/                   # Log files for training and live trading
├── models/                 # Fine-tuned model files
├── src/
│   ├── __init__.py
│   ├── data_handler.py   # Fetches and processes stock data
│   ├── model.py          # Handles model fine-tuning
│   ├── strategy.py       # Defines the trading logic
│   ├── trader.py         # KIS API communication wrapper
│   └── ...
├── .env                    # Environment variables for API keys and config
├── live_bot.py             # Main script for live/paper trading
├── main.py                 # Main script for backtesting pipeline
└── requirements.txt

Setup and Installation

  1. Clone the repository:

    git clone <repository-url>
    cd python_auto_trading
  2. Create and activate a virtual environment:

    python -m venv venv
    source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
  3. Install dependencies:

    pip install -r requirements.txt
  4. Configure the environment: Create a .env file by copying the .env.example or creating it manually. You must fill in your KIS API credentials.

    # Stock ticker to analyze (e.g., 005930 for Samsung Electronics)
    TICKER=005930
    
    # For Korea Investment & Securities API
    KIS_APP_KEY=YOUR_APP_KEY
    KIS_APP_SECRET=YOUR_APP_SECRET
    KIS_ACCOUNT_NO=YOUR_REAL_ACCOUNT_NUMBER
    KIS_VIRTUAL_ACCOUNT_NO=YOUR_PAPER_TRADING_ACCOUNT_NUMBER
    

How to Run

There are two main ways to run this project:

1. Backtesting

To run the full data processing, model training, and backtesting pipeline, execute main.py.

python main.py

This will use the TICKER from your .env file to generate a new model and evaluate its performance on historical data.

2. Live / Paper Trading

To run the automated trading bot, execute live_bot.py.

python live_bot.py

By default, the bot runs in paper trading mode and does not execute real orders (they are commented out for safety). See the detailed guide for activation instructions.

Disclaimer

This project is for educational and research purposes only. The backtesting results are not indicative of future returns. Financial markets are complex and unpredictable. This is not financial advice. Any action you take upon the information on this project is strictly at your own risk. The developers assume no liability for any losses or damages in connection with the use of this software. Do not use this system for live trading with real money unless you fully understand the code and the risks involved.