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:
- Real-time stock data collection (1-minute intervals via Yahoo Finance).
- AI integration (basic ARIMA model for price predictions).
- Broker connectivity (executing trades via Robinhood or Alpaca).
- Deployment & monitoring (AWS Lambda + Telegram alerts).
Let’s dive in.
Step 1: Fetching Real-Time Stock Data
Why Yahoo Finance?
- Free & high-rate limits: Ideal for prototyping.
- Real-time granularity: 1-minute intervals via
yfinance(unofficial Yahoo Finance API).
Implementation
Install the library:
pip install yfinance --userFetch 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.40Step 3: Executing Trades
Broker Options
| Broker | Library | Key Features |
|---|---|---|
| Robinhood | robin_stocks | Free trades, rate limits apply |
| Alpaca | alpaca-trade-api | Paper 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
Telegram Bot:
- Create via BotFather.
- Store the token in AWS environment variables (
TELEGRAM_TOKEN).
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 UTCMonitoring:
- 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:
- Data collection with
yfinance. - AI predictions via ARIMA.
- Trade execution with Robinhood/Alpaca.
- Deployment on AWS Lambda.
For a real-world system:
- Improve the model (e.g., ensemble methods).
- Add risk management (stop-loss, position sizing).
- Monitor performance rigorously.
🚀 Happy coding!
Code available on GitHub.
References
- Collins, P. (2020). Best Stock APIs and Industry Landscape. Medium.
- Brownlee, J. (2017). ARIMA Hyperparameter Tuning. Machine Learning Mastery.
- Yahoo Finance Unofficial API.
yfinanceGitHub.