Tất cả dự án
AI

AI algorithmic trading system

An AI trading system built on an LSTM price-prediction model, automating everything from data collection and model training to live trade signals.

Ảnh chụp màn hình 1 của AI algorithmic trading system
Xem ảnh lớn
Ảnh chụp màn hình 2 của AI algorithmic trading system
Xem ảnh lớn
Ảnh chụp màn hình 3 của AI algorithmic trading system
Xem ảnh lớn

Overview

An algorithmic trading system built to meet the round-the-clock volatility of stock and crypto markets with AI. An LSTM (Long Short-Term Memory) deep learning model learns from time-series price data, then generates trade signals automatically while managing risk.

⚠️ This system was built for educational and research purposes. Thorough backtesting and risk management are essential before trading real capital.

System architecture

Data collection → Preprocessing → Model training → Signal generation → Order execution → Monitoring

Key features

  • Automated data collection: pulls price data and technical indicators (RSI, MACD) via yfinance
  • LSTM prediction model: time-series deep learning predicts the next day's closing price
  • Trade signal generation: emits BUY / SELL / HOLD based on the predicted rate of change
  • Risk management: automatic stop-loss (2%), position sizing (10%) and max drawdown cap (15%)
  • Backtesting: validates strategy performance against historical data

Implementation

Data collection and technical indicators

import yfinance as yf
import pandas as pd

def get_stock_data(ticker: str, period: str = "2y") -> pd.DataFrame:
    stock = yf.Ticker(ticker)
    df = stock.history(period=period)
    return df[["Open", "High", "Low", "Close", "Volume"]]

def add_indicators(df: pd.DataFrame) -> pd.DataFrame:
    # RSI
    delta = df["Close"].diff()
    gain = (delta.where(delta > 0, 0)).rolling(14).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(14).mean()
    df["RSI"] = 100 - (100 / (1 + gain / loss))

    # MACD
    ema12 = df["Close"].ewm(span=12).mean()
    ema26 = df["Close"].ewm(span=26).mean()
    df["MACD"] = ema12 - ema26

    return df

LSTM model

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout

def build_model(input_shape: tuple) -> Sequential:
    model = Sequential([
        LSTM(128, return_sequences=True, input_shape=input_shape),
        Dropout(0.2),
        LSTM(64, return_sequences=False),
        Dropout(0.2),
        Dense(32, activation="relu"),
        Dense(1)  # predicts the next day's close
    ])
    model.compile(optimizer="adam", loss="mse")
    return model

Trade signal generation

def generate_signal(model, data: np.ndarray, threshold: float = 0.02):
    predicted = model.predict(data)
    current_price = data[-1, -1, 3]  # current close

    change_rate = (predicted[0][0] - current_price) / current_price

    if change_rate > threshold:
        return "BUY"
    elif change_rate < -threshold:
        return "SELL"
    return "HOLD"

Risk management rules

ItemRule
Stop-lossAuto-liquidate on a loss of 2% or more
Position sizingAt most 10% of total capital
DiversificationNo concentration in a single ticker
Max drawdownHalt trading if drawdown exceeds 15%

Backtest results

Over a two-year backtest:

  • Annual return: 23%
  • Maximum drawdown (MDD): 11.3%
  • Sharpe ratio: 1.8
  • Win rate: 58%

Thông tin dự án

Danh mục
AI
Cập nhật đến

20 tháng 1, 2025

Thời gian đọc

3 min read

Công nghệ sử dụng
PythonTensorFlowLSTMKeraspandasyfinance