How to Code a AI Trading bot (so you can make $$$)

Nicholas RenotteAbout 6 min readMay 27, 2025Watch original
THE SUMMARYAI-generated

AI-Powered Trading Bot: A Comprehensive Breakdown

Key Concepts:

  • Algorithmic Trading
  • Machine Learning (ML)
  • Sentiment Analysis
  • Backtesting
  • Position Sizing
  • Risk Management
  • Alpaca API
  • FinBERT

1. Building the Baseline Bot

  • Objective: Establish a basic trading bot framework using the lumot library.
  • Dependencies:
    • lumot.brokers.Alpaca: Broker integration.
    • lumot.data_testing.YahooDataBacktesting: Backtesting framework.
    • lumot.strategies.Strategy: Base class for trading strategies.
    • lumot.traders.Trader: Deployment capabilities.
    • datetime: For handling dates and times.
  • Process:
    1. Import necessary libraries from lumot.
    2. Define variables for Alpaca API keys (API_key, API_secret, base_URL).
    3. Create an alpaca_creds dictionary to store API credentials.
    4. Instantiate the Alpaca broker with the credentials: broker = Alpaca(alpaca_creds).
    5. Create a class MLTrader inheriting from Strategy to encapsulate trading logic.
    6. Define lifecycle methods:
      • initialize(self): Runs once at the start of the bot.
      • on_trading_iteration(self): Runs every time new data is received.
    7. Create an instance of the MLTrader strategy: strategy = MLTrader(name="ML_Strat", broker=broker, parameters={}).
    8. Set up backtesting using YahooDataBacktesting with a start and end date.
    9. Define a symbol parameter (e.g., "SPY") within the initialize method and make it accessible as an attribute (self.symbol).
    10. Set self.sleep_time to 24 hours for daily trading.
    11. Set self.last_trade = None to track the last trade.
    12. Implement a basic trading logic within on_trading_iteration:
      • If self.last_trade is None, create an order to buy 10 units of the specified symbol.
      • Submit the order using self.submit_order(order).
      • Update self.last_trade to "buy".
  • Example:
    • Buying 10 shares of "SPY" on each trading iteration if no previous trade exists.
  • Outcome: A basic bot that buys a fixed quantity of a specified asset at regular intervals.
  • Limitation: Lacks position sizing, risk management, and any form of intelligent decision-making.

2. Position Sizing and Limits

  • Objective: Implement dynamic position sizing and set take-profit/stop-loss limits.
  • Process:
    1. Create a position_sizing(self) method to calculate the quantity of assets to buy.
    2. Get the available cash balance using self.get_cash().
    3. Get the last price of the asset using self.get_last_price(self.symbol).
    4. Define a cash_at_risk parameter (e.g., 0.5 for 50% risk).
    5. Calculate the quantity to buy using the formula: quantity = (cash * cash_at_risk) / last_price.
    6. Round down the quantity to the nearest whole number.
    7. In on_trading_iteration, call self.position_sizing() to get the cash, last price, and quantity.
    8. Implement a check to ensure sufficient cash before placing the order: if cash > last_price.
    9. Set order type to "bracket" to enable take-profit and stop-loss orders.
    10. Set take_profit_price to last_price * 1.2 (20% profit target).
    11. Set stop_loss_price to last_price * 0.95 (5% stop-loss).
  • Technical Terms:
    • Cash at Risk: The percentage of the total cash balance that is risked on a single trade.
    • Bracket Order: An order that includes a take-profit and a stop-loss order.
  • Example:
    • If the cash balance is $100,000, cash at risk is 0.5, and the last price of "SPY" is $500, the quantity to buy would be (100000 * 0.5) / 500 = 100 shares.
  • Outcome: The bot now dynamically adjusts the quantity of assets purchased based on the available cash and the defined risk tolerance. It also sets take-profit and stop-loss orders to manage risk and secure profits.

3. Getting Some News

  • Objective: Integrate news data from the Alpaca API to inform trading decisions.
  • Process:
    1. Create a get_news(self) method to fetch news articles.
    2. Import rest from alpaca_trade_api and timedelta from datetime.
    3. Instantiate the Alpaca API client using the API keys and base URL: self.api = rest(base_url=base_URL, api_key_id=API_key, secret_key=API_secret).
    4. Create a get_dates(self) method to calculate the start and end dates for the news query.
    5. Get today's date using self.get_datetime().
    6. Calculate the date 3 days prior using timedelta(days=3).
    7. Format the dates as strings in "YYYY-MM-DD" format using strftime("%Y-%m-%d").
    8. Call the Alpaca API to get news articles: news = self.api.get_news(symbol=self.symbol, start=start, end=end).
    9. Extract the headline from each news article and store it in a list.
  • Technical Terms:
    • TimeDelta: A class in the datetime module used to represent a duration or difference between two dates or times.
  • Example:
    • Fetching news articles for "SPY" from December 12, 2023, to December 15, 2023.
  • Outcome: The bot can now retrieve news headlines related to the specified asset from the Alpaca API.

4. Bringing in the Machine Learning Model (FinBERT)

  • Objective: Integrate a sentiment analysis model (FinBERT) to analyze news headlines and generate sentiment scores.
  • Process:
    1. Replace the get_news method with a get_sentiment method.
    2. Import the estimate_sentiment function from a custom finbert_utils module.
    3. The estimate_sentiment function uses the FinBERT model to analyze the sentiment of the news headlines.
    4. The function returns a probability score and a sentiment label (positive, negative, or neutral).
  • Technical Terms:
    • FinBERT: A pre-trained language model fine-tuned for financial sentiment analysis.
    • Sentiment Analysis: The process of determining the emotional tone or attitude expressed in a piece of text.
  • Example:
    • Passing the headline "Markets responded positively to the news" to the estimate_sentiment function, which returns a probability of 0.8979 and a sentiment label of "positive".
  • Outcome: The bot can now analyze news headlines and generate sentiment scores, providing a basis for informed trading decisions.

5. Integrating the Trading Signal

  • Objective: Integrate the sentiment signal into the trading algorithm to make buy/sell decisions.
  • Process:
    1. In the on_trading_iteration method, call self.get_sentiment() to get the probability and sentiment.
    2. Implement decision logic based on the sentiment and probability:
      • If the sentiment is positive and the probability is greater than 0.999, issue a buy order.
      • If the sentiment is negative and the probability is greater than 0.999, issue a sell order.
    3. Implement logic to sell existing positions before placing a new order in the opposite direction:
      • If the last order was a sell and the current sentiment is positive, sell all existing positions using self.sell_all().
      • If the last order was a buy and the current sentiment is negative, sell all existing positions using self.sell_all().
    4. Adjust the take-profit and stop-loss prices for sell orders:
      • take_profit_price = last_price * 0.98 (2% profit target).
      • stop_loss_price = last_price * 1.05 (5% stop-loss).
    5. Update self.last_trade to "buy" or "sell" after placing an order.
  • Example:
    • If the sentiment is positive with a probability of 0.9995 and the last trade was a sell, the bot will sell all existing positions and then place a buy order.
  • Outcome: The bot now makes trading decisions based on the sentiment of news headlines, dynamically adjusting its positions based on market sentiment.

Conclusion

The video demonstrates the creation of an AI-powered trading bot using the lumot library, Alpaca API, and FinBERT sentiment analysis model. The bot integrates news sentiment into its trading strategy, dynamically adjusting its positions based on market sentiment. The backtesting results show promising returns, but it's crucial to remember that paper trading doesn't account for real-world factors like commissions and fees. The video provides a valuable starting point for building and experimenting with AI-powered trading strategies.

AI summaries can miss context or contain errors. Check important details against the original video.

Go a little deeper.

Have a question about this video? Load its transcript to open the video chat.