Algorithmic Trading Strategy in Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what is going on guys welcome back in today's video we're going to implement an algorithmic stock trading strategy in python so let us get right into it well i think it goes without saying but as always i need to include this disclaimer here this video is not investment advice it is not financial advice don't listen to me when it comes to finances and investing i am no stock professional i'm no investing professional i'm not a financial professional the only thing i'm doing in this video is presenting an algorithmic uh trading strategy in python so i'm showing you how you can do something in python if you choose to uh to use it for your investments or not that's your decision your responsibility i'm just showing you the programming part i'm going to use a financial strategy i don't say it's good i don't say it's bad i'm just showing you how to do it so don't take this as investment advice so having said that uh what are we going to do we're going to just load some stock data and we're going to apply a very simple rule um which is when the averages the moving averages cross we're going to sell or buy depending on which one crossed the other one we're going to talk about that in a second first of all what we need is we need to open up a cmd command prompt and we need to install two libraries uh one is pandas data reader like that in order to get the stock data and the other one is matplotlib for the visualization part so we're going to start by importing datetime s dt by the way let me just reposition my camera i always forget this before i start the video so i need to do it right uh while i'm recording there you go so import daytime sdt then we're going to say import matplotlib dot pi plot splt and last but not least import pandas data reader as web so first of all we need to decide which moving averages we're going to look at so a moving average is basically just the average price over the last 30 days 50 days 10 days 100 days 200 days whatever and i'm going to create two variables here which i'm going to call ma1 and it's going to be 30 for example and m82 which is going to be 100 for example so we're looking at the 30-day moving average or the 100-day moving average and we're looking about uh we're looking into the graphs and we're trying to figure out okay when are they crossing and once they cross we're either going to buy or sell this is the basic strategy i don't say it's a good strategy i just say it's a strategy that we can use here um and you can then see the results you can test it on past data and see if it would have worked or not so what we're then going to do is we're going to define a time frame we're going to say okay start equals time dt.daytime.net now minus dt dot time delta this basically means we take the exact moment right now when we run the script minus a certain time delta minus for example in this case we're just going to say days equals 365 times three so the last three years and the end is going to be dt date time dot now so we're looking at that time horizon here and what we're now going to do is we're going to get the data for a specific stock in that time frame so we're going to say data equals web dot data reader for example we're going to look at facebook from the yahoo finance api from start to end so we have the data now and what we want to do now is want to get the moving averages uh for that data so we're just going to add two new columns we can first of all run this to see what it looks like without the two columns that we introduced so i'm going to run this and you can see what this looks like it's going to take a while there you go we have high low and in between we have open close volume and adjusted close so it's not displaying all columns here but we don't have anything like uh moving averages so we're going to add those by saying data and now we're going to just say um fstring sma underscore and now ma1 so basically a moving average of that size is going to be data adjusted close adjusted basically just means close value adjusted for stock splits because sometimes companies uh do stock splits and then the price changes but the market cap does not change uh and we're going to just get the rolling window is going to be ma1 so that's just a time frame and we're going to get the mean we're going to do the same thing for the second moving average and we're also going to adjust this here there you go and then what we're going to do is we're going to say the data is basically the data from uh or the data.i lock and we're going to start uh displaying the data from ma2 why are we going to do that because uh up until this point we don't have any moving averages really or we have uh biased moving averages because we cannot look at the past in this case 100 days because we have no 100 days to look back to so we're just going to cut off the data in the beginning this is just my way of doing it and what we're now going to do is we're just going to say plt.plot and we're going to visualize the whole thing so we're going to say uh plt.plot we're going to plot the adjusted close uh value here and we're going to say the label is share price because we're going to add a legend later on and the color is going to be [Music] light gray so this is just the stock price um by the way let me just also add a style here so what we're going to do is we're going to say plt dot style dot use and we're going to use dark background just because we can and down here we're going to sorry we're going to plot the data sma and again we need to use an f string because we don't have static values ma1 we're going to plot that the label is also going to be an f string sma ma1 and the color in this case is going to be let's say orange and we're going to do the same thing here with two and a color here is going to be purple and last but not least let's add a legend so plt legend location equals upper left and plt dot show so this is not the strategy yet we're just looking at the data set we're just looking at the moving averages so that we see what we're actually working with uh we have a problem yeah purple is not color i mean purple is but what i wrote is not a color so let's see what happens now there you go so this is what we're working with this here is the stock price this uh almost white line here is the stock price and those are the moving averages so the the purple line here is the 100 day moving average basically just the average of the last 100 days and you can see that it moves slower and smoother whereas this is more sensitive to local changes because it's only 30 days and basically just for understanding a one one day moving average would be the stock price itself so because we're just looking at one day so the larger the number is the smoother and the more linear a curve is going to be you could say uh and what we're going to do now is as a trading strategy is we're just going to uh buy and sell on those uh crossings here so whenever these two lines these moving averages here cross we're going to either buy or sell this is what we're going to implement and again i'm not claiming that this is a super intelligent strategy i mean after all it's just uh technical analysis so we're not doing any any fundamental value investing here but this is one thing that we can try and we can see if it works or not so what we're going to do here next is we're going to implement the algorithmic trading so we're going to say okay we have a set of buy signals buy signals is an empty list and we're also going to have the cell signals those are just going to be the signals that indicate okay sell at this point by at this point and we're going to have a trigger and this trigger is going to change uh because when we buy we're going to change this trigger when we sell we're going to change this trigger so that we know okay um what is the current state and when do we actually pass into another state or are we all the time in the same state uh so we need to notice changes and without the trigger we cannot really notice changes and what we're now going to do is we're just going to say okay for x in range the length of the data so basically for everything in the data we're going to say if data if the moving average in this case m a one if that dot i lock x so that position at this particular row if the moving average one here is larger than the same thing so sma but this time ma2 so the second moving average i lock x if that is the case and the trigger is not equal to one uh i think i have a mistake here there you go and it's not uh not equal to one then we're going to have a buy signal so then we're going to say buy signal append and we're going to append the adjusted close value at the location x which is the current iteration and we're going to append cell signals as when as well because we want to have none or not necessarily none in this case we're going to use nan which is not a number we want to have a not a number value if there is no signal basically so that we have a full list and we don't just have some gaps that can be misinterpreted so we're going to say sell signals in this case uh we're going to append float nan which is going to append and not a number value and we're going to set the trigger to one because remember up here we're saying okay if it's not equal to one which means that now it is equal to one so even if that is the case we're not going to get into that again so this is what i mean by trigger we're checking for that condition but only once if we have saw if we have seen this condition and we have acted on it we don't want to do it again right away we want to wait for the trigger to change before we get into that case again because otherwise we would constantly have some signals for buying or selling which is not what we're trying to do here so now we're going to do uh the other case which is let's say the sma ma1 iloc x is less than the data sma m82 i lock x and the trigger is not equal to negative one so we're going to use a different trigger here by the way you can also use enums or whatever you want i just think it's convenient to use a number here so this is basically just the opposite case if the moving averages uh are the opposite way so ma1 is less than ma2 if that is the case and it's the case for the first time so a change happened here uh when we passed that point we're just going to say buy signals append append float come on nan and we're going to say sell signals append the actual price so in this case data adjusted close at the location that we're currently at and the trigger is going to be set to negative one and last but not least if nothing happens we're just going to append nan values so that we fill up the list so if we don't have any change in the trigger we're just going to continue to put in nan values so append with two piece not with three piece float nan and come on sell signals there you go so we're almost done the only thing we now need to do is we need to create two more columns and then we're going to visualize everything so we're going to say data by signals is going to be buy signals and data cell signals is going to be cell signals there you go and print data by the way because sometimes people are asking the comments how i'm also always editing stuff like that so for example how i change a word here with my keyboard this uh this is vim so those are vim bindings if you're interested you can just look into them i have a tutorial on bim and there's a plugin in pycharm that allows you to do that just the side information here because some people are asking all the time um so we can print the data yes but before we just go ahead and print the data we're also going to plot everything so we're going to say plt plot and we're going to start with the basic adjusted close values so just adjust it close and the label is going to be share price by the way i think we can just copy at least these three lines here uh with slight changes because uh we don't want to have a color here necessarily we're going to say alpha equals 0.5 this is basically just transparency here um and we're now going to also change the color here to pink and we're going to change the line style so that we're not too confused we need to have a way to distinguish all these individual lines so line style of the moving averages is going to be just a dashed line the price is going to be a normal line and now we're also going to uh scatter the uh buying signal so we're going to say plt scatter and we're going to scatter on data index which is the x value we're going to scatter the buy signals so nands are not going to be scattered and all the other values are going to be at the prices where we have to sell so this what we're going to do label buy signal and the important thing is the marker we're going to buy with a hat symbol like that and the color of that is going to be green so basically a hex value rgb red is zero green is ff and b for blue is zero zero again and the line width is going to be three we're going to copy that line and we're going to do the same thing for the cell signals oh come on for the cell signal here but we're going to use a different marker we're going to use the downward arrow which is which is just a v uh and the color is going to be red so ff000 there you go and last but not least plt.legend location upper left and finally plt show there you go that's all we need to do let's see if we don't have any mistakes if we don't have mistakes we should see the result uh this is the first plot and this is the second plot it seems to work first of all let's see down here you can see we have sell signal right away then we have nan nan and n and in between some buy and sell signals and the result is this this is the result we have a sell signal in the beginning a buy signal here selling it here buying it here selling it here buying it here selling it here buying it here and so on uh and of course this goes up until today so right now we don't have a signal the last signal was buy so up until now we shouldn't have sold according to this algorithm but you can see that it does not always perform very well you can see for example here it says to sell here it says to buy okay in this case here we would even have a small gain so we buy here sell here then we buy here but we sell here so this is a loss we buy here we sell here which is again and then we buy here and we don't know what happens in the future but this is what our algorithm says now we can also change the moving averages if we're interested in that so we can go ahead and say okay let's look at 50 days and 100 days and we can see what the result for that is let me just comment that out because we're not interested in that um and we don't want to waste time with the first plot but you can adjust that so in this case you would see a bit different signals or are they actually the same signals no they're actually the same signals um did i actually [Music] did i actually use the windows to write windows where was it oh yeah so maybe just doesn't change for this particular company but let's go with another company let's say tesla for example let's go back to 30 because i think that's a reasonable thing to look at and for tesla you're going to get different results now again this is just a technical analysis trading strategy so there's no reason to believe that it's going to give you extraordinary results here you can see tesla basically buys cell by cell on a very similar level it says sell here buy here and sell here so actually if you would have listened to this algorithm here when it comes to tesla and of course you shouldn't listen to that algorithm it's just a programming tutorial but if you would have listened to this algorithm you would have made a lot of money in this particular case i'm sure i can find some counter examples if i just look long enough but we can look at a bunch of different companies and see how this model would have performed and this graph that we see here all the time it's not just a past prediction it's also a current prediction as you can see here right away so even though it's not necessarily today the last signal for apple was a buy so if you were following that model you would have to buy apple now and sell it the next time it says to sell so we would have a cell here a buy here a cell here which is a tiny gain a buy here and a cell here which is a good gain a buy here a cell here which is a small loss and now we have a buy here and who knows where it's going right so this is something that you can look into you can also manipulate this uh this thing here to do what you want but that's up to you this is how you build an algorithmic trading strategy in python so that's it for today's video hope you enjoyed i hope you learned something i just saw that my camera was blocking the last buy signal for the apple stock so before i maximized you saw the buy signal then it was covered by my camera i hope this was not too annoying uh however if you liked that video let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this channel and hit the notification bell to not miss a single future video for free other than that thank you much for watching see you next video and bye [Music] you
Info
Channel: NeuralNine
Views: 23,844
Rating: 4.9111109 out of 5
Keywords: algorithmic trading, stock trading, stocks, stock, trading bot, python, python algorithmic trading, python trading bot, stock trading bot, algotrading, trading strategy
Id: FEDBsbTFG1o
Channel Id: undefined
Length: 20min 53sec (1253 seconds)
Published: Sun Jul 04 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.