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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this is how to create an AI powered trading bot that's 100% automated and makes money some of the biggest hedge funds in the world are powered by algorithmic trading Cel Renaissance two Sigma but they're shrouded in secrecy why these guys may look like your average Bankers by day but by night they're bulk buying Yachts they're beating the market using some of the most sophisticated algorithms in the world channeling my inner wolf for Wall Street I'm going to try to create my own but what makes a good AI trading bot can anyone build this or is it just limited to hedge fundies and does machine learning or AI even make a difference I've been working on this for months researching strategies using different ml models and test coding over 600 lines of experiments I'm going to break it down in just five steps and it begins with building our Baseline block all righty guys so the first thing that we need to go on ahead and do is build our Baseline but in the interest of time I'm going to set a 15minute timer and kick things off the first thing that we need to go on ahead and do is create a new file and I'm going to call this trading bot. pip we then need to import a bunch of dependencies the main set are going to be from a library called lumot which sort of gives us a trading framework so from lumot Brokers we're going to import our Pacer from lumot dob testing we're going to be importing Yahoo data back testing from lumot do strategies. strategy we're going to import strategy so super quickly our pack is going to be broker Yahoo data back testing is going to give us our framework for back testing and strategy is going to be our actual trading bot we also need one more thing so Lumi bot dot Trader Traders we're going to import Trader so n why do I keep hitting the wrong Keys uh so that is going to give us our deployment capability if you wanted to go and run this live then we're also going to go from date time we're going to import date time and then we actually need to create a couple of variables to to hold our API Keys cuz we need to get some data so we're going to create a variable called API key set that to a blank uh string for now we're going to create one called API secret also a blank string and then a base URL also a blank string now we actually need to pass through a dictionary to this alpaca broker over here so let's create that so I'm going to say alpaca creds is equal to a blank dictionary and then inside of that we're going to create a variable called API key and we're going to set it to our API key which is currently blank so we're effectively creating a dictionary key and we're setting it equal to what we've got over here and that's because we're going to need to use it in two ways later on so let's close that we don't need that uh let's go and set our API secret and then we need to determine whether or not we're going to be paper trading so for now we're going to paper trade cuz we're not dropping real cach just yet or maybe we will all right so where do we get our API key our API secret and our base URL well if you go to an alpaca account you can actually go and hit view API keys and then in this particular case we can go and hit regenerate generate new keys we can then copy this key let's bring that over here so we can that's our API key we then want our API secret where's it going now down here on our API secret and we also need that base URL which is this over here cool so once you go and generate it's going to disappear so if you need it again make sure you copy it put it in a safe place don't share it with anyone all right so those are the main variables that we need already so what we're going to do is we're going to create our broker we're going to set that to our Pacer and then pass through our our Paca creds we'll come back to that a little bit later okay but let's get on to our strategy so we're going to create a bit of a framework for our strategy so we're going to create a new class we're going to call it ml strategy actually we'll call it ml Trader to that we're going to allow it to inherit from the strategy class which we imported up here and so this is going to form the backbone of our actual trading bot so everything that we encapsulate in terms of our trading logic goes in sort of inside of that class we're going to create a new function or new method so we're going to say def initialize that spell that i n i t i a yep cool all right going to pass through the same instance just going to set it to pass for now and then we need the uh on trading iteration function or method perfect okay so the initial these are called life cycle methods so basically when you start up your Bot the initialized method is going to run once the on trading iteration is going to run every time we get a tick so every time we get new data from our data source we're going to be able to execute a trade or do something with it so we're going to effectively have all of our trading logic in here all of our setup stuff in here okay that's looking good now what we actually want to do is create an instance of our strategy so let's do that so I'm going to say strategy is equal to ml Trader and then we actually need to pass through a couple of things to this so the first thing that we need to do is specify a name so I'm going to set it to ml Strat can name it whatever you like we also need to pass to our broker which is why we set it up already and then eventually we're going to be able to specify a number of parameters so we're just going to set that to a blank dictionary for now but eventually we'll come back and use that then what we want to do is we want to actually set up our back testing so we're going to this is how we're going to evaluate how well we're going to be able to run our b or at least a guess of how well it's actually going to run so we've got our strategy there to our strategy we want to pass through that Yahoo data so Yahoo data back testing then we need a start date and end date as well as any parameters here as well and our parameters are just going to be a blank dictionary for now so we'll come back to that but we actually need to create our start date and our end date so our start date start date is going to to be equal to date time so that's why we imported this date time function up here cuz it just makes it a bit easier to create datetime objects so for now we're just going to keep this pretty simple we're just going to set our date time to 2023 we're going to set it to uh let's say halfway through the month halfway through December and our end date is going to be date is going to be the end of December we'll say 2023 comma 12 comma 1 beautiful right so these two start and end dates are going into our back test so if you wanted to go and test for longer or shorter you can adjust these we're going to bring this back way later once we actually go and do our final run okay but that is pretty much some of most of the admin stuff actually now done inside of our initialized function we want to create a parameter so we're going to create a parameter called symbol that's going to be a string and we're going to set that equal to spy so it's going to be the Spy index for now then what we want to do over here is make this avail ailable as an attribute inside of our class so we're going to say self. symbol is equal to symbol over here to actually pass this through when we going and initialize our strategy we just go and create a new parameter and we're going to set that equal to spy over here and I'm going to copy this kind of a little bit of a weird way to set this up if I'm completely honest but it works we also need to set self. sleep time so this basically dictates how frequently we're going to trade so self. sleep time we're going to set this equal to 24 hour we're not playing in the minutes here but if you could if you wanted to you definitely could I like sort of bringing it up to a high level we also need to set self. last trade or creative attribute for self. last trade so this is going to capture what our last trade was so if we want to go and undo some of our sells or undo some of our buys we've got the ability to do that right so I've got symbol sleep time last trade that is looking good now what we want to do is let's just go and create like a baseline trade right so we're going to say um if self. last trade equals equals none then we're going to create a trade and this is like sort of the backbone of how to actually build these trading Bots we can create an order we're going to say order is equal to self do create order and then we got to pass through a couple of variables here so we need to pass through first up the symbol so we're going to say self. symbol we then need to pass through how many of that particular symbol we want to buy we're going to set it 10 for now but we're definitely going to do Dynamic order pricing and position management little bit later we'll get to that okay so we've got self do symbol we also want to specify what type of order we want to create so we want to buy and then we also want to specify what type of actual order so the order type so whether or not we want to Market a limit whether or not we want a bracket order I'll explain that a little bit more okay so that is our order now created but that hasn't actually executed yet so if I went and run this we wouldn't actually have an order generated so let's actually go and just pass this order and then we'll actually be able to test it out quickly and see this working so let's go and how do we go and execute this order so we can say self. submit order and then pass through that order and then just for good measure we're going to say self. last trade is equal to buy because that's effectively what we've gone and done okay so we've gone and done a ton of stuff so let's go and test this out so I'm going to say python trading botp and all things holding equal we should get a back test kickoff I am getting these weird SSL errors you can see one right there let's just try that again sucking up our time not happy about this all right that's our back test starting so you can see take a look it's all done all right and that is our trade created so you can see that right down here we've gone and created a trade so I bought 10 spy uh contracts at a price of $469 49 it went and had a total of$ 4,694 this is our tear sheet so it tells us how well we actually performed kind of crap right now so we've built our Baseline bot but right now we're just randomly buying 10 units here or there how do we make sure that we're appropriately managing our money this brings us to part two position sizing and limits we are now on to position sizing and limits so rather than just buying 10 we're going to make this a little bit more Dynamic so let's actually go and create this so we're going to say uh dep position sizing so this is a good part of actually building and trading B position management and cash management absolutely critical so we're going to create our position size and to do that we're going to first need to get our cash so how much cash we've got left in our account and if you actually go back and take a look at our trade that green line is the cash value so you can see it started out at 100K and then when we went and bought it went down to 95k so we can get that dynamically using the self. getet cach method so we can say self. getet cash we actually need to pass through self into here so that'll give us our cache we then want to go and determine what the last price was so we can say last price is equal to self. getet last price and to that method we need to pass through the symbol so we can pass self dot my head Block in that I hope not uh close self. symbol and then we actually want to calculate our position size our position size is going to be calculated based on a metric called cash at risk so how much of our cash balance do we want to risk on every trade so we're going to create a variable called cach at risk it's going to be a float and we are going to set it initially to.5 so then what we can do is we can make this available as an attribute so self. at risk and we're going to set it to cash at risk beautiful and then what we can do is calculate our position sizing we should also set it down here just so we don't forget so we're going to say inside of Val parameters dash at risk let's just put this on another line we are going to set that 2.5 and again if you want a riskier bot or a less risky bot you can adjust this up or down see heart all right cool so we've now got and added that parameter to our parameters inside of our back test and inside of our strategy up here as well so what we now need to do is calculate our sizing so I'm just going to use the formula I've kind of always used so we're going to say quantity is equal to our cash multiplied by our cash at risk so that effectively determines how much of our cash balance we want to risk cash at risk and then we are going to divide it by the last price so that's going to tell us how many units we're going to get per amount that we want to risk and then we're we're going to round it down to the nearest whole value perfect so this should give us a single quantity so we can return our cash our last price and our quantity there we go all right cool and we are going to dynamically set that when we actually go and place our trade so up here we're going to get our cash just copy this we're going to get it back by running self do position sizing beautiful and then we are going to specify that we want to buy that many down there now I like having another check so I like going and saying if the cash balance is greater than the last price so that effectively means that we're not just buying when we don't have cash then we are going to then execute the trade okay so that's looking much better now so we've now gone and sort of started our position sizing the the other thing that I sort of wanted to do is set limits so I always like to set a take profit and a stop loss so a take profit effectively starts a trade which basically sort of sets a bound so if we're going to hit that point then we're automatically going to sell and we're going to take some of our profit back rather than just leaving it out there in the market or willy-nilly so let's go and set this so we can change our type of order to a bracket and then we can set a take profit by setting take profit price and that is going to be equal to our last price and for now we're going to set it to 20% so we ideally wanted to go up by 20% to have a sufficient takeprofit and we're also going to set a stoploss price and we're going to set that to our last price so this is going to need to change depending on whether or not we're placing a short order or long order and we'll we'll update that in a sec as well once we sort of get into the nitty-gritty of the algorithm our stop loss price is going to be 5% right so that sort of gives us a bit of a barrier ideally we're hopefully making more money than we're losing okay so that is our position sizing so if we go and run this now we should effectively get dynamically sized um trades but we're still really going to be executing one trades please not SSL Error find if I don't have a time limit I just sort of drag on all right cool that that happened so it looked like we place the trade that's our next trade let's take a look so take a look so this time we went and spent 50% of our cash at risk so we actually spent oh we actually bought 106 spy contracts we at a price of the total value is 49765 TE sheet there as well okay so now we've got that's our timer gone now we're going to keep cracking on cuz we want to build this bot all right Baseline bot's done and we've set some appropriate cash management strategies in place but so far we haven't actually done any machine learning or used any AI this brings us to part three getting some news the next thing that we want to go on ahead and do is finally get some news so this is where we begin to get to our ml component so the way that we're actually going to build this up is we're going to dynamically find out what news is happening over the last 3 days and then we're going to take that news and we're going to pass it through to a machine learning model to calculate the sentiment based on that and so ideally we should get a good feel for where the market is going based on that news so that means that we need two key parts we need the news and we're also going to need a machine learning model let's start taking a look at our news first so first things first let's Zoom back in so we are going to create a new method and we're going to say def get the news and we are going to set that to self over here so we need a bunch of stuff so we actually need an API to be able to get the news back and that is why I created these values over here because we're actually going to get the news back directly from alpaca so we can go from alpaca trade API and you can just do a pip install I'll include a complete set of requirements in the GitHub so from alpaca trade API we are going to import rest and this means that we can go and dynamically get a bunch of stuff from the trade alpaca trade API we also need one additional thing here so we're going to say from time Delta we're going to import time Delta so this just makes it a way easier to actually calculate the difference between days and weeks and time so on we're going to just use that now all right so let's go and create an instance of our API so we're going to say self. API is equal to rest and then we want to go and set a bunch of stuff so we need to set our base URL which is equal to this over here we need to set now uh what else do we need we need our API key AP what's it called called key ID and we also need my head's not blocking that uh we need secret secret key which is this secret key perfect let's paste that in all right cool so now we can go and call this API to get our new so we can effectively go self. api. get some news uh where is it get get news okay yep cool all right cool cool so we got news so when we call this we should get our news back now to this we need to pass through our symbol so we're going to say self these keyword arguments yeah self. symbol is equal to self. symbol we also need a start date so start date is going to be equal actually no it's just start and we need an end date over here so how do we go and calculate these well because we're going to be back testing we want to get the dynamic date based on our back test so we can't just go and get today's date we actually need to get the date based on when we're trading so we can actually go and do this and rather than just doing it right here let's actually just go and create another method to do this so we're going to say self. getet dates and let's do a little magic here so we're going to grab uh today's date which is today with respect to the back test or to the live training so self do get what is it get dat time right and so this is going to return the current date based on the back test or wherever we're actually going and deploying this then we need to get the we're going to get grab three days worth of news right so we need 3 days prior so 3 days prior it's a terrible variable name let's say three days prior okay that's still not great whatever all right so we're going to say today is equal to uh no so 3 days PRI is equal to today minus 3 days so we can use our time Delta method that we just imported in over here and what we're going to do is we're going to set that equal to days equal 3 so that will effectively give us 3 days prior cuz we're taking today we're minusing 3 math then what we want to do is we want to return today and we want to format it as a string CU that's the way that the API expects it so we're going to say today is equal to St R format time it's like this weird set of St today dot here somewhere data get weird okay it's stft time get the feeling that there's an error there but we will soon find out um okay so that's our daytime and then we want to set that equal to percentage year- percentage month- percentage day cool so that should return year month day as a string and then we also want to do the same thing for 3 days prior so we're just going to copy that and we are going to copy this weird method which doesn't seem to be doing syntax highlighting so that is effectively what we've got now so we're going to be getting today's date we're going to get 3 days prior and then we're going to return those two values then inside of our get news function we're going to call that so we're going to say self. get dates and we will uh unpack that so we're going to say today and then 3 days let's just copy this let's not write that beautiful okay so today is going to be equal to the n end because that's the end and then the start is going to be 3 days prior perfect right so that is effectively what that looks like now so we've now got our symbol we've got our start and we've got our end cool so we've now got the news now we I want to do a little bit of processing on this rather than just returning it because it returns it like a jumble and I'm just going to show you how to do this so news is actually going to be equal to we're going to Loop through each value so for event in news I'm going to say EV not elect vehicle EV doore dict Took a ton of time to work out how to do thisor raw and then this should be a string and then I love it when it's a nightmare then a headline okay cool all right that should give us our news right so now we're going to get our dates get our news and then format our news so now if we return our news return news let's actually go and call it inside of our trading Loop so our trading Loop is over here on trading iteration so let's say that we are going to go and initialize another trade let's actually just cheuck it here so we can say news equals uh self. getet news getor news it is self dog news yeah Okay cool so and then let's print out our news Perfect all right so now effectively when we go and run our trading Loop let's go and run it we can run it by running that's weird can run it by running python Trading BP but you knew that all right cool again SEL error we shall see SSL beautiful great let's try again this looks promising all right cool this is starting and what happened all right so we had an error there uh self knew that we had an error I could tell let's zoom out it should not be double T's there you go all right let's try that string format time all right let's try again probably a seller I might not have saved that let's do that again okay take a look all right so that is our news so let's just wait for this pop up to go so you can see that we've now printed out our news over here well we popping out with a whole bunch of stuff okay um so we've got all of these different headlines so if you invested a th000 in X on mobile when Joe Biden was elected president here's how much you have today US senators blah blah blah whole bunch of news so we've got our news but that by itself doesn't really help us make trades this brings us to part four bring in the machine learning model aka the AI we actually want to bring some ml into the mix so this is where we bring in our ml powered sentiment model so what we want to do is rather than go and write a new function I'm actually just going to sub this out so I'm going to change a get news function and I'm going to get news method and I'm going to convert that to get sentiment and all we really need to do is import this from my finbert utils utility so if you've seen a couple of my sentiment based videos on the channel before really really similar basically we're using Transformers and pytorch we're setting whether or not we're going to use Cuda or our CPU we're then taking the process AI finbert model which is an amazing model when it comes to finding and if you actually go to the hugging face model repository you can read all about it it's an brilliant model which has been fine-tuned on finance sentiment so we're going to be using that so we're going to be passing our news to the tokenizer to the model and then what we're going to do is we're going to effectively sum it all up and then take the highest result so to that we're going to get back our probability and we are also going to get back our sentiment um so let's go on ahead and do that this is all extra stuff oh uh we don't need this I think I added that my bad um also in here I included a little example so if you actually wanted to go and test this out let's actually go and test it out so over here I've got two examples so markets responded positively to the news trasers were pleasantly surprised so if we actually go and run that function so we're going to run Python finbert utils and this will all be available inside of the GitHub repository you can test it out as well ideally what we're going to get back is we're going to get back a sentiment so positive or negative and then the position or the the actual probability so over here my head's probably blocking that let me bring it over and bring it up let me just bring it up so you can see that all right you can see that so you can see that we're getting back positive sentiment and we've also got our probability of 89.7 n% so this tells us that we have positive sentiment if we change it negatively so Traders responded negatively to the news and were pleasantly uh were unha uh dis please let's set a 10minute timer let's let's try to crack on 10 minutes left all right let's go let's go um so let's not screw around all right let's try this again so now we should get Negative sentiment back as well as the probability hopefully and take a look we got negative and we've got our probability all right cool so we're effectively going to be passing our news in the same way but we're going to be integrating that signal into our trading algorithm so let's actually go and bring that in first so rather than leaving it as get sentiment we are going to bring back our function so we actually need to import it up here so from bin BT utils we are going to import get sentiment actually it's estimate sentiment beautiful okay so this method or this function over here is going to be used down here and we are going to get back what's the order again we're going to get back probability and sentiment so jump back into our trading bot so over here we're going to say we're going to get back probability and sentiment and we're going to set that equal to estimate sentiment and then we're going to pass through our news into it beautiful and then we're going to take this probability and sentiment and that's what we're going to return back so now rather than running get news we're going to run get sentiment beautiful and let's print out uh so we're going to our probability and we are also going to be getting back our sentiment over here so let's print out these and see how we go we're going to run our trading bot again so this time we should execute the back back test and then we should also get our sentiment back and take a look we've effectively got it so over here wait for this second one to pop up so over here you can see that we've got our sentiment so in this case it is 100% and we also have the fact that we have neutral sentiment so we're not going to actually trade on a neutral sentiment we actually only want to trade on strong positive or strong negative sentiment which is why we need that probability home stretch now we've got our machine learning model up and running and generating sentiment but how do we bring this into our trading strategy this brings up to part five integrating our trading signal but this brings us to our final segment we're actually going to bring it all together and integrate our sentiment signal into our trading algorithm because we've brought it in we haven't actually made any decisions based on it as of yet so let's go on ahead and do that so what we're going to do is we're going to grab this line over here and we're actually going to bring it out so we don't really care whether or not our last trade was none so we're going to get rid of that as well we're going to get rid of these two lines so really we want to be left with our order and we're going to create two different types of orders we're going to create a sell order and we're going or a buy order and a sell order so we're effectively going to short or go long so this is really good the only thing is we just need a bit of decision logic so we're going to say if the probability actually let's start with sentiment if sentiment is positive and the probability is greater than .999 then we're going to issue a buy order which is looking good we need to tab this in the only thing is if we've got an existing sell order and we the market goes positive we sort of want to cut that other one out right so we can do that pretty easily so we can say if this is why we implemented last order right if self. last order equals equals cell then we're going to sell all of those existing positions so self do sell all beautiful and then we're going to issue our buy order and then we're effectively just going to replicate this so we can copy that over and bring this out perfect we're going to say l if the sentiment is negative and the probability is at 99999 and if the last order was buy then we're going to sell all and then down here we're going to change this to a sell and we're going to change a couple of things in this order so rather than doing a buy here we're going to convert this to a sell and we need to change our take profit and our stop- loss price so our take profit this time we're going to go the other way so effectively we're subtracting a profit margin from a value of one so it's going to be8 here and our take profit is going to be adding 05 or 5% so we're going to say this is 1.05 and I think that is it so we should effectively have our trading algorithm now up and running okay so that's looking pretty good let's actually go and test this out so let's test it out on half month and then we're going to unleash it on the full back test period so let's clear this and we're going to run it again okay so it looks like we're making some trades looks like we made one trade what's happened there all right let's extend this out and unleash it so it looks like we did definitely made one trade at least we made a Buy trade over here so we bought uh $49,000 worth of spy over here looks like the market went up which is probably a good thing how much do we make off that first one so we made 5.2% not too bad considering that just sort of mimic the market but now we want to unleash this for all time so rather than testing from 2023 we're going to set it to 2020 we're going to set the first date we're going to convert it to January the 1st 2020 and unleash this I'm going to save it and let's let it run okay and we've got a bunch of Errors so let's go and debug this uh what's happened ml Trader has no object last order did we use last order oh this should be the last trade right my bad all righty guys and there we have our results so this is the tear sheet and this is a breakdown of all the trades that were placed over a 4year back testing period so if we quickly take a look at the tear sheet we can see the yellow line is the SP index so effectively what you would have invested or what you would have returned if you invested in The Benchmark our blue line is how our ml strategy performed so right at the start looks like we sort of went into the negative and then we sort of came back and eventually produced some pretty significant returns but then sort of Crash back down which I still think is not too bad cuz when you take a look at these performance metrics over here our cumulative return was 234.40 over 4 years with a compound annual growth rate of 23.8% personally I think that's actually really really good but what I'm actually going to do is I'm going to include all of the trade logs including what you're seeing on the screen right now inside of the GitHub repo so you can go and investigate this yourself plus keep in mind the only thing that I do want to call out is this is obviously paper trading so it doesn't include commissions doesn't include fees so when you go and trade be careful out there guys I'm showing you how to build this but when you go and deploy it it's really important to to remember that lot trading live is so different to to paper trading but it does give a glimpse as to what is possible with AI powered or machine learning powered trading because over here if you actually go and scroll on over we actually short sold appropriately when the market went down short sold short sold and the market was trending down so we did get a cash bump there over here we managed to get some massive performance gain so we got some short cells and we managed to to bump out our our profit or our portfolio value so if you actually take a look at one point our portfolio value is 537,500 our Trader and then effectively run all and that will run our strategy inside of our broker and all we need to do is sort of comment out our back test cuz we don't need that anymore catch you later
Info
Channel: Nicholas Renotte
Views: 436,186
Rating: undefined out of 5
Keywords: ai trading bot, ai trading, algorithmic trading, machine learning trading bot, ml trading bot
Id: c9OjEThuJjY
Channel Id: undefined
Length: 35min 8sec (2108 seconds)
Published: Fri Jan 19 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.