Build a LIVE Algorithmic Trading Bot with Python, Lumibot and Alpaca: A Step-by-Step Guide

Matt Macarty · Beginner ·🛠️ AI Tools & Apps ·1y ago

About this lesson

@MattMacarty #lumibot #algotrading #python #alpacaapi #tradingbots **Start your Algorithmic Trading journey with this step-by-step Python guide.** In Part 1 of our series, we build a "Live" trading bot from scratch using Python, the LumiBot framework, and the Alpaca Markets API. We cover the entire environment setup—from creating a paper trading account to handling secure API keys—and implement a "Buy and Hold" strategy to demonstrate real-time order execution and backtesting. ### ⏱️ Technical Milestones 0:00 - Series Introduction & Educational Disclaimer 0:00:40 - **Account Setup:** Creating an Alpaca Markets Paper Trading account 0:01:27 - API Key Management: Generating Secret Keys for secure access 0:02:08 - **Environment Variables:** Setting up your .env file for Python 0:03:50 - Documentation Deep-Dive: Getting started with LumiBot 0:04:10 - **Installation:** Pip install and upgrade procedures 0:05:01 - **The Framework:** Understanding LumiBot Life Cycle Methods 0:06:10 - Importing Strategy, Trader, and Broker modules 0:06:58 - **Coding the Bot:** Custom Buy-and-Hold class implementation 0:08:15 - Logic: Calculating Quantity based on Real-Time Cash Balance 0:09:32 - **Execution:** Setting up Start/End dates for Backtesting 0:10:45 - Live Demo: Running the bot and verifying trades on Alpaca 0:12:15 - **Performance Reports:** Analyzing QuantStats and Equity Curves 0:13:53 - Preview: Moving to more advanced momentum strategies --- ### 🏛️ Implementation Highlights This video establishes the "LumiBot Workflow" you will use for the rest of the series: **1. Secure Architecture:** * We use a `.env` file to store API keys. This is a critical professional standard to ensure your private brokerage credentials are never hard-coded or exposed in your scripts. **2. Life Cycle Mastery:** * Learn the difference between `initialize()` (setting up parameters) and `on_trading_iteration()` (the engine that runs your actual trading logic every 10 seconds, minute, or day).

Full Transcript

this is going to be the first video in a series on algorithmic trading using lumot from Lumi wealth and I should say from the outset that this video is for educational purposes only uh you should not use it as trading advice okay so we are going to be using a paper account and we're going to implement a very simple algorithm that just places an order and then we're going to see that in action and then we're going to go ahead and back test the strategy okay so that means the first thing we need is an account in which to place these paper orders and so I'm going to be using alpaca so you can find it at alpaca markets if you don't already have an account you're going to want to sign up and uh you're going to want this one the trading API okay I already have an account so I'll just go ahead and log in and same thing I'm going to log into the trading API all right and pretty much the reason I'm using alpaca is because you can sign up for an account or a paper account with just your email address all right so you don't need to put in a bunch of personal information and you can just kind of test drive uh how algorithmic trading works so once I get logged in I'm just going to go to the homepage and uh just before I started this video I reset my portfolio with $100,000 in paper money and what we're going to need here Beyond this dashboard is eventually going to be these uh API keys so I'll come back to that in a minute all right so I'm going to go back back to the lumot documentation and I'm going to go down to where it says broker configuration here and they have a bunch of Brokers all right so Trader all right there's alpaca all right they have interact with broker coinbase Kraken all right and they're going to be adding more as they go along all right so for whatever broker you're going to be using you're going to need to set up these environment variables all right so we're going to need an API key we're going to need this API secret and then uh we're going to need to set this alpaca is paper to true all right so I'm going to jump into python then and start setting this up okay so when we launch our trading bot lumot is going to be looking for a file that has these environment variables in it all right and the file is going to be the EnV file okay so it wanted alpaca is paper all right it wants me to set that to True okay then it needs an alpaca API key okay and it also needs alpaca API secret all right and just a word of warning here the alpaca API keys are pretty Dynamic so anytime you refresh the portfolio you're going to have to go ahead and get new API Keys all right so I will go back to the alpaca site and do that right so if you just sort of scroll down right from that dashboard and we're going to generate new API keys so I'll just copy and get my secret all right and then one more environment variable I'm going to set is is back testing all right so you can set these up to either just go live or to just see how they would have performed over some historical period in the past all right so I going to set this as fault so we're going to set it up both ways I'm going to first write the trading bar and make it work so we can see it place an order on alpaca and then I'll come back and back test it so we can see what you get when you do that all right so that's all I need for the environment I'll go ahead and save that and then the next thing I'm going to do is uh start writing the trading bot and this is going to be very simple we're going to buy on day one and just hold it all right so I'll call it Buy and Hold okay so before I write any code uh I want to go ahead and review some of the documentation for lumib bot so I will go back there and I'm going to go down to where it says uh getting started with lumot all right so yeah the first thing you're going to want to do is to uh install it right so you can do that in the terminal right so in vs code here it's just going to be pip install and if it's your first install it's just going to be lumot and that will install the latest version if you have a version because you tried this in the past you're probably going to want to upgrade it cuz it's a pretty Dynamic library and yep they've made some changes recently so that would just be upgrade all right I'm not going to bother to run it because I already have it installed but this is how you do it all right so we're pretty much following through what it says to do here right so make a an account at alpaca so all this stuff was already handled in thatv file that I made all right and then eventually we're going to be uh making our own class and and we'll have to get some imports from lumot to do that okay before I start writing the actual code here I want to take a look at what they call their life cycle methods so you can get a better understanding of what's going on so I will go in here and it's it's a graphic and essentially what we're going to do is import that strategy class and we're going to write our own custom strategy that inherits from that and the strategy class has all of these what they call life cycle methods all right so they all have defaults and if you want to implement your own trading logic you're going to need to override or overload uh some or all of these methods all right so I'm just going to be in this simple strategy overriding the initialize method and overriding the on trading iteration all right so this is the main method that uh you implement a a trading bot in all right but you can do other things like something before the Market opens maybe you need to update a model all right uh you can do something before the the first trade all right and then you can do things right before the market closes and then right after the market closes okay and then there there's some diagnostic tools here but like I said we're just going to look at initialize and on trading iteration okay so now we're ready to actually write some code and uh the first thing I'm going to do is import date time so I can do some back testing all right and then everything else is going to come from uh lumot okay so I'm importing the back testing module uh I'm importing the broker is back testing all right these are both coming from that EnV file all right and then I'm going to import strategy and Trader so strategy is what's going to be making use of those life cycle methods and then Trader is actually going to be managing our trading activity all right so next thing is I will set up a custom class and I'll just call it by hold and uh yep that will inherit from strategy all right and as I mentioned I am going to overload the initialize method and I'm just going to set one parameter here and it's going to be what is the sleep time so how often do I want the algorithm to run all right and and so we can see it I'll just set it at 10 seconds but you can set it as a day you can set it at every second you can set it at minutes all right so that's all I'm going to do there okay and then the only other method that I'm going to override here is on trading itation all right so inside here I am going to just check and see oh is this the first time through because for this particular strategy I'm just going to take all my available cash and invest it in a in a single security so I don't want to keep doing that but this thing is going to try to refresh every 10 seconds all right so I'm going to test and see if it is first iteration all right so the first time time through we're going to set a symbol all right and uh let's let's try Nvidia uh I'm going to uh get a price so for this I'm going to go out to alpaca and get the last price all right pass in that symbol and then I'm going to get a quantity and again I'm going to base this on oh how much cash do I have on alpaca all right so it's going to be self. and uh I am going to do some floor division there divided by the price so I won't use exactly all my cash I'll kind of round down a little bit here and this will also prevent me from trying to buy a fractional share right so I'll just use most of my cache all right so I got a symbol I got a price I got a quantity and now uh we're ready to set up an order all right so I'm going to access this create order method and there's a bunch of parameters for this I'm just going to set a symbol a quantity and what side of the trade am I going to be taking buy or sell so I'll pass in that symbol I'll pass in my Cor quantity all right and uh this will be a buy all right so I'll leave it up to you to kind of explore all the different parameters all right this will just be a market order so obviously we can set some limit and and that kind of stuff all right so there's my order and then uh I'm just going to submit it okay so that's all there is to it right very simple let's get our feet wet and see how this thing just kind of roughly works all right I will set up the uh run conditions here so all right so we're going to just want to see okay are we really trading or is it a back test so I will test that value in is back testing and when it's true we will back test and I'm going to need a start date and I'll use date time here and uh it's November 12th here I'll go back about a year all right and then I have to set an end all right I'm going to take my buy whole class and I'm going to access the method doback test and I'll pass in a couple parameters here so I'm going to use that Yahoo datab back testing that I imported and I'm going to use the start and I'm going to use the end all right so the first time through is back testing is going to be false so we'll ignore all this and we will fire this else block and I'm going to set a variable strategy and it's going to be that buold and I'm going to pass in the brok broker all right this is coming from that environment variable file all right I'm going to instantiate a Trader all right and then I'm going to add the strategy to the trader okay and then we'll just tell the trader to run all right so very simple you can see a lot of the stuff is is kind of intuitive once you get used to it all right we're going to have a strategy we're going to have a Trader we're going to add a strategy to the trader and then we're going to run it the only thing that's going to be different is oh we probably have some more more sophisticating trading logic than just buying something and sitting on it all right so let's try it and see if I can do all that without making any mistakes all right so it looks pretty good and all right so it looks like it has in fact execut it looks like I did uh I did write that without uh making any errors and that's now every 10 seconds it's going to keep trying to do the same thing again but oh there's not going to be any trades so let's go take a look at alpaca and see what happened there all right so we can see that yep we bought 673 shares and uh so far we've lost about $27 all right so that is working and yeah just like that I'm up $27 okay let's go and stop the trader and we'll try it as a back test so we can see what that looks like all right so I'm just going to get in here and control C to stop the code all right I'm going to open up thatv file and set back back testing to true so we can see what the back testing Reports look like all right and then uh let me kill this terminal and then we'll try it one more time okay so it is running the back test okay so since the algorithm runs every 10 seconds the back test takes quite a while so keep that in mind once it's done it should automatically load a couple of reports okay so this is from Quant stats which you can run as a standalone back tester and I have a video that shows you how to do that without using lumot but we can see that oh yeah Nvidia over the last year all right is about a 3X uh where we started all right but some nice portfolio metrics here from Quant stats and then if I'm in the market 100% of the time uh it would it comes out as 69% right so that's 252 trading days over 365 5 all right so it looks like I'm in pretty much the whole time all right this is kind of unique to how uh Lumi wealth has implemented Quant stats all right so you if you just run Quant stats by itself it'll say we were in the market 100% of the time all right but we can see the right compounding annual gross returns there and uh all kinds of stuff about uh how this thing performed over over that time period the second report you get is just your equity line all right and this is generated by Lumi wealth right so there's my equity line under my strategy all right here it is if I had just invested in uh the S&P 500 ETF all right and then we can see at the beginning all right I kind of used all my cash and I'm sure I have a few dollars there but it looks like I use pretty much all my cash and uh this is what it looked like over that time period okay so that's it for this video I will go into something a little bit more involved in the next video so we can see oh how does a real trading algorithm that fires periodically throughout a day how does that work so for now I hope this helps you get started and I hope to see you at the next video

Original Description

@MattMacarty #lumibot #algotrading #python #alpacaapi #tradingbots **Start your Algorithmic Trading journey with this step-by-step Python guide.** In Part 1 of our series, we build a "Live" trading bot from scratch using Python, the LumiBot framework, and the Alpaca Markets API. We cover the entire environment setup—from creating a paper trading account to handling secure API keys—and implement a "Buy and Hold" strategy to demonstrate real-time order execution and backtesting. ### ⏱️ Technical Milestones 0:00 - Series Introduction & Educational Disclaimer 0:00:40 - **Account Setup:** Creating an Alpaca Markets Paper Trading account 0:01:27 - API Key Management: Generating Secret Keys for secure access 0:02:08 - **Environment Variables:** Setting up your .env file for Python 0:03:50 - Documentation Deep-Dive: Getting started with LumiBot 0:04:10 - **Installation:** Pip install and upgrade procedures 0:05:01 - **The Framework:** Understanding LumiBot Life Cycle Methods 0:06:10 - Importing Strategy, Trader, and Broker modules 0:06:58 - **Coding the Bot:** Custom Buy-and-Hold class implementation 0:08:15 - Logic: Calculating Quantity based on Real-Time Cash Balance 0:09:32 - **Execution:** Setting up Start/End dates for Backtesting 0:10:45 - Live Demo: Running the bot and verifying trades on Alpaca 0:12:15 - **Performance Reports:** Analyzing QuantStats and Equity Curves 0:13:53 - Preview: Moving to more advanced momentum strategies --- ### 🏛️ Implementation Highlights This video establishes the "LumiBot Workflow" you will use for the rest of the series: **1. Secure Architecture:** * We use a `.env` file to store API keys. This is a critical professional standard to ensure your private brokerage credentials are never hard-coded or exposed in your scripts. **2. Life Cycle Mastery:** * Learn the difference between `initialize()` (setting up parameters) and `on_trading_iteration()` (the engine that runs your actual trading logic every 10 seconds, minute, or day).
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Related Reads

📰
VaultSort REVIEW AI-Powered File Organization and Secure Storage Management for Mac
Learn how VaultSort uses AI to organize and secure Mac files, and why it matters for productivity and security
Medium · Machine Learning
📰
Build a Self-Improving Second Brain on Oracle AI Database
Learn to build a self-improving second brain on Oracle AI Database to enhance your productivity and knowledge management
Dev.to · Anya Summers
📰
The Circuit Boards Keeping the New Space Race Alive
Learn how circuit boards are designed to survive in space for a decade without maintenance, a crucial aspect of the new space race
Medium · AI
📰
DeepSeek: The Good, The Bad, and The Bounty 🧠💸
Learn about DeepSeek, a community issue tracker, and its potential impact on AI development and collaboration
Dev.to · Daniel Ioni

Chapters (14)

Series Introduction & Educational Disclaimer
0:40 **Account Setup:** Creating an Alpaca Markets Paper Trading account
1:27 API Key Management: Generating Secret Keys for secure access
2:08 **Environment Variables:** Setting up your .env file for Python
3:50 Documentation Deep-Dive: Getting started with LumiBot
4:10 **Installation:** Pip install and upgrade procedures
5:01 **The Framework:** Understanding LumiBot Life Cycle Methods
6:10 Importing Strategy, Trader, and Broker modules
6:58 **Coding the Bot:** Custom Buy-and-Hold class implementation
8:15 Logic: Calculating Quantity based on Real-Time Cash Balance
9:32 **Execution:** Setting up Start/End dates for Backtesting
10:45 Live Demo: Running the bot and verifying trades on Alpaca
12:15 **Performance Reports:** Analyzing QuantStats and Equity Curves
13:53 Preview: Moving to more advanced momentum strategies
Up next
This AI Books Appointments AND Gets 5-Star Reviews Automatically (I'll Show You How)
Kevin Farugia AI Automation
Watch →