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.



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
| Item | Rule | |------|------| | Stop-loss | Auto-liquidate on a loss of 2% or more | | Position sizing | At most 10% of total capital | | Diversification | No concentration in a single ticker | | Max drawdown | Halt 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%
Project details
January 20, 2025
3 min read