How to Create a Fully Automated AI-Based Trading System With Python

·

Introduction

A few weeks ago, I had an eye-opening conversation with a friend who was trying to "detox" from his stock trading app. He explained that his self-imposed trading rules—like selling stocks after a 1% profit threshold—required constant phone checks, leading to exhaustion. This sparked an idea: Can trading rules be automated using AI and Python?

The answer is yes! Here’s what we’ll cover:

  1. Real-time stock data collection (1-minute intervals via Yahoo Finance).
  2. AI integration (basic ARIMA model for price predictions).
  3. Broker connectivity (executing trades via Robinhood or Alpaca).
  4. Deployment & monitoring (AWS Lambda + Telegram alerts).

Let’s dive in.


Step 1: Fetching Real-Time Stock Data

Why Yahoo Finance?

Implementation

Install the library:

pip install yfinance --user

Fetch Google’s stock data (example):

import yfinance as yf

google = yf.Ticker("GOOG")
df = google.history(period='1d', interval="1m")[['Low']]  # Focus on "Low" prices
df.index = pd.to_datetime(df.index).time  # Simplify datetime index
print(df.head())

👉 Explore advanced financial APIs for production systems.


Step 2: AI-Powered Predictions

Model Choice: ARIMA

A simple ARIMA(5,0,1) model suffices for this demo (though cross-validation is recommended for real use).

Training & Prediction

from statsmodels.tsa.arima.model import ARIMA

# Split data
train, test = y[:-int(0.1*len(y))], y[-int(0.1*len(y)):]  

# Train model
model = ARIMA(train, order=(5,0,1)).fit()
forecast = model.forecast(steps=1)[0]  
print(f"Predicted: {forecast:.2f} | Actual: {test[0]:.2f}")

Output:

Predicted: 1776.39 | Actual: 1776.40

Step 3: Executing Trades

Broker Options

BrokerLibraryKey Features
Robinhoodrobin_stocksFree trades, rate limits apply
Alpacaalpaca-trade-apiPaper trading, 200 requests/minute

Example: Buy/Sell with Alpaca

import alpaca_trade_api as alpaca

api = alpaca.REST('KEY_ID', 'SECRET_KEY', base_url='https://paper-api.alpaca.markets')

# Buy 5 Google shares
api.submit_order(
    symbol='GOOG', 
    qty=5, 
    side='buy', 
    type='market', 
    time_in_force='day'
)

👉 Secure your API keys with environment variables.


Step 4: Deployment & Monitoring

AWS Lambda Setup

  1. Telegram Bot:

    • Create via BotFather.
    • Store the token in AWS environment variables (TELEGRAM_TOKEN).
  2. Serverless Deployment:

    # serverless.yml  
    service: ai_trading_system  
    provider:  
      environment:  
     TELEGRAM_TOKEN: ${env:TELEGRAM_TOKEN}  
    functions:  
      cron:  
     handler: handler.send_message  
     events:  
       - schedule: cron(00 21 * * ? *)  # Daily at 21:00 UTC
  3. Monitoring:

    • Lambda sends trade confirmations via Telegram.

FAQs

1. Is this system production-ready?

No. This is a proof of concept. Use robust models (e.g., LSTM) and professional APIs (Alpha Vantage) for live trading.

2. How accurate is ARIMA for trading?

Limited. ARIMA assumes linear trends; real markets are volatile. Combine with other indicators (RSI, MACD).

3. Can I use this with other brokers?

Yes! Most brokers (e.g., Interactive Brokers) offer APIs—adjust the code accordingly.

4. What’s the cost of running this on AWS?

AWS Lambda offers 1M free requests/month. Monitor usage to avoid surprises.

5. How do I backtest this strategy?

Use libraries like backtrader or zipline to simulate trades on historical data.


Conclusion

This guide walked you through:

  1. Data collection with yfinance.
  2. AI predictions via ARIMA.
  3. Trade execution with Robinhood/Alpaca.
  4. Deployment on AWS Lambda.

For a real-world system:

🚀 Happy coding!

Code available on GitHub.


References

  1. Collins, P. (2020). Best Stock APIs and Industry Landscape. Medium.
  2. Brownlee, J. (2017). ARIMA Hyperparameter Tuning. Machine Learning Mastery.
  3. Yahoo Finance Unofficial API. yfinance GitHub.