Building a Real-Time Trading Bot Using AI and Python

Over the past few months, I’ve been diving deep into the world of AI, but this time, I set my sights on the financial markets. I wanted to see if someone with basic tools could build a trading bot capable of analysing real stock market data. Simulating buy/sell strategies, all with free tools and real-time APIs. The idea wasn’t just to follow trends, but to build something functional and real. This article is part of my continuing journey to test the limits of accessible AI development, one project at a time.
Breaking It Down with AI
I had a specific challenge: could I build a real-time trading bot using real financial data without relying on expensive software?
ChatGPT helped break down the process into manageable steps:
- How to connect to a real-time stock data API.
- How to calculate basic indicators like the Simple Moving Average (SMA).
- How to implement a strategy using those indicators.
- How to simulate trades and log results.
- How to convert the Python script into a working .exe to make it accessible to people without Python installed.
Of course, there were technical hiccups, dependency issues, model packaging, and API rate limits, but with every step, I gained new insights into trading logic and automation.
How Does the Trading Bot Work?
1. The bot is built on a simple strategy:
When a short-term moving average (like a 5-day SMA) crosses above a longer-term average (like a 15-day SMA), that’s a potential buy signal. When it crosses below, that’s a sell signal.
2. Logic Example (Simplified)
# Detect SMA crossover
if sma_5.iloc[i] > sma_15.iloc[i] and sma_5.iloc[i - 1] <= sma_15.iloc[i - 1]:
signal = 'buy'
elif sma_5.iloc[i] < sma_15.iloc[i] and sma_5.iloc[i - 1] >= sma_15.iloc[i - 1]:
signal = 'sell'
This logic checks for a crossover by comparing the current and previous values of the short-term and long-term moving averages.
3. Key Steps in the Bot:
Using an API like Twelve Data or Yahoo Finance, it fetches intraday or daily stock prices.
from twelvedata import TDClient
td = TDClient(apikey="YOUR_API_KEY")
data = td.time_series(symbol="AAPL", interval="1min").as_pandas()
We calculate moving averages with pandas:
data['SMA_5'] = data['close'].rolling(window=5).mean()
data['SMA_15'] = data['close'].rolling(window=15).mean()
The bot scans each new data point, evaluates crossover logic, and determines if a trade should be made.
Each buy/sell signal is recorded in a log with timestamp, price, and profit/loss info.
A CSV file is generated to store the trade history, and optionally, a plot is displayed.
data.to_csv("trades.csv")
Chart the price and signals using matplotlib:
plt.plot(data['close']) plt.plot(data['SMA_5']) plt.plot(data['SMA_15']) plt.scatter(buy_signals, ...)
Python Integrations Used
Here are the core tools and integrations used in this project:
Tool/Library Purpose
- pandas: Data manipulation and indicator calculation
- matplotlib: Visualization of price and trades
- twelvedata API: Real-time stock market data (free tier available)
- pyinstaller: Convert .py script to .exe application
Optional:
- yfinance as an alternative API for daily data.
- ta for prebuilt technical indicators if needed.
Why I Built It
This wasn’t about beating the stock market. It was about proving that with today’s tools and some AI guidance, anyone can build a useful, working project, even in the complex world of financial data.
A bot like this can serve many purposes:
- A learning tool for people studying algorithmic trading.
- A prototype for developers building full trading platforms.
- A sandbox for testing different strategies without risking money.
Final Thoughts
The trading project taught me something valuable: you don’t need expensive tools to start building. You just need a question and a willingness to keep iterating.
If you’re interested in creating your own version, I’ve uploaded everything to GitHub, including:
The Python code, The .exe files, A full README.
And a page to see the results yourself.
If you’re reading this asking whether you can build something like it, stop asking. Start building.