Stock Price Prediction in Python with PyTorch - Full Tutorial
Key Takeaways
This video tutorial demonstrates how to use PyTorch to build an LSTM-based architecture for stock price prediction in Python, utilizing libraries such as numpy, pandas, and matplotlib for data manipulation and visualization.
Full Transcript
What is going on guys? Welcome back. In this video today, we're going to learn how to do stock price prediction in Python using PyTorch. So, let us get right into it. All right. So, we're going to learn how to do stock price prediction in Python today by building and training a neural network using PyTorch. In particular, we're going to use an LSTM based architecture. So we're going to use LSTM cells which stands for long short-term memory. The basic idea being we have these recurrent type of cells where we have certain mechanisms for forgetting and storing information and uh it then produces an output and also hidden state that is carried on to the next layer and so on or to the next uh step and so on. And I'm not going to get too much into the technical details of LSTMs in this video today. The focus is going to be on the actual implementation, but you can think of them to be a little bit like advanced recurrent neural network cells that have a mechanism for forgetting unimportant information. That's the in a nutshell explanation. Now, since this is a financial topic, I need to mention that this video is not financial advice. None of this is financial advice. We're not building anything that can help you to make money in the stock market. You should not be using that as a strategy for investing. You should not be basing any decisions on this model. This is purely a programming tutorial. I just want to show you how we can work with sequential data like time series data which is stock information, stock price data. Uh how we can work with that, how we can take that into a recurrent type of neural network. How we can produce a prediction. We can also evaluate that. But don't treat this in any way as financial advice. Don't use this in any way to try to earn money. I'm not responsible for any mistakes that you make with this. This is purely a programming tutorial. So let us get started. Now I'm going to navigate to my working directory. And in this video today, I'm going to be working in a Jupiter notebook. To be precise, I'm going to be working in Jupiter lab. And if you want to have the exact same development environment as me, you can just go ahead and type pip or pip 3 install or nowadays UV at uh Jupiter lab as one word. You can install that and then you can easily run an instance in the directory of your choice by saying Jupiter space lab. And this is going to start an instance. It's going to open up uh a browser tab. And in this case, now let me move this to another screen. Uh now you can see this is my Jupyter Lab environment. So the basic idea behind interactive Python notebooks for those of you who don't know about them is you have these individual cells you can run. So you don't have to write everything in a single file and running from top to bottom every time you want to do something. You can execute individual cells of code. So I can say X is equal to 10 in this cell. I can say print x in this cell. I can say x is equal to 20 in this cell. Go up again, run this cell. And of course, I can have multiple lines of code here as well. So that's the basic idea behind interactive Python notebooks. And whenever I do machine learning or data science, I prefer to work in an environment like this one because we can uh import packages, load the data set, pre-process the data, explore it, visualize something, then train the model, then evaluate the model. And if you want to make a tiny change or a tiny addition, we don't have to uh rerun the whole application or the whole script. We can just run individual cells and change uh things about them. So I'm going to save this now as main ipy andb. And before we can start with the coding now, we need to install some packages. By the way, don't be confused by my voice. I have a cold again or still. Uh so yeah, I hope this is not too annoying for you guys. But we're going to have to install a couple of packages here. And these are going to be the following. We're going to need numpy for working with arrays and working with numbers in general. Uh pandas for working with the data set with a data frame structure. Uh mattplot lip for visualization. Y finance to get the stock data from Yahoo Finance. Scikitle learn for pre-processing and metrics. And of course the most important one torch for PyTorch for the neural network itself. So install all of these. And once you have that, you can close your terminal and we can start with the imports. We're going to start by saying import numpy snp. Let me just zoom in a little bit here. Import pandas spd. Uh import mattplot lib.pipplot splt the basic data science stack. Then we're also going to say import y finance syf maybe. Let's put it here. So we have this nice ascending structure here. Then we're going to say from scikit or actually from sklearn.p prepprocessing we're going to want to have a scaler. We're going to use the standard scaler that results in a somewhat normal distribution of the data. Then we're going to say from scikitlearn dometrics. We want to have the uh root mean squared error. So the rms for the evaluation. So root mean squared error. And uh in between maybe here let's say import torch import torch.n as nnn and then import torch.optim as optim. So again to recap this is going to be for working with arrays. This is going to be for working with the data set the data frame structure that we get from the Yahoo finance API with this package. Then we're going to do some visualizations with mattplot lib. We're going to build and train and everything with the neural network is going to be done in PyTorch or with PyTorch and we're going to scale our data here with scikitlearn and we're going to also evaluate our model with this metric uh root mean squared error. These are the imports. So let's run this cell and now we can start with the actual uh project today. So the first thing we want to do is we want to set a variable for the device that we're going to be using. Now, not everyone is going to have a GPU that supports CUDA. Some of you are going to have one. So, we want to keep it flexible. We're going to say the device that we want to use for all of this, so either a CPU or a GPU is going to be the following. It's going to be torch. And it's going to be uh GPU uh sorry, not GPU, CUDA if torch.CUDA dot is available. So if you have a CUDA supported GPU in your system, we're going to use CUDA. Otherwise, we're going to fall back to the CPU. So if you run this, you're going to have a device and this device is going to be either CUDA or CPU depending on your hardware and depending on your drivers. In my case now, it uses my 3060Ti, which is my GPU here. And uh because of that, it's going to be faster. But the model that we're going to train in this video today with the data that we're going to train it on in this video today is also going to be easily executable on a CPU. So it's yeah not really computationally heavy uh what we're going to do in this video today. So we have the device and now we want to get some data and we're going to get the data by saying uh I want to have a ticker symbol first. Let's say for example the Apple stock AAPL is the ticker symbol for Apple. If you want to go for a specific company and you don't know the ticker symbol, first of all, of course, make sure they're a public company. Second of all, go and Google company name, ticker symbol, and then you're going to find AAPL for Apple, MSFT for Microsoft. I'm not sure if Meta is still FB or if it's Meta, probably Meta. Uh, the different companies have different ticker symbols. So, you want to know the ticker symbol and then you want to say DF is equal to Y Finance, so YIF.d download and then the ticker symbol and the start date is now whatever you want to do here. In my case, what I want to do is I want to train uh on the data of the past couple of years and I want to predict the last year for example. So I'm going to say here the start date is going to be 2020 1st of January like this. And that is going to result now in a data frame here with close, high, low, open, and volume. We're going to only use the close price here. Our goal is to predict the close price of the next day given a certain amount of data. So that is our data frame. This is a pandas data frame. And we can also visualize that. So I can go and say df close and then plot. And that is going to maybe I should pass a figure size here 12 and 8 maybe. That is the stock price from 2020 up until today of the Apple stock. So you can see it's rising. And this is what we're going to do now. We're going to take a portion of this data. Let's say somewhere until here. We're going to use that to train the model and then we're going to evaluate it on this section here. So we're going to see if we can predict this section here. Now again, don't use this for actual trading. This is just an experiment just showing you how to do that in Python. It's not going to be relevant in terms of the predictions. They're not going to be accurate. So let's move on now with the pre-processing. I'm going to say a scaler that I want to use is going to be an instance of standard scaler. And now to keep it simple, we're just going to scale all of the data. So we're going to say here df.clo or actually I should use square brackets here. I think df close is equal to df close. But we're going to call on df close scalar.fit transform. Now, you can also just scale on the training data and then also transform the test data if you want to. I want to keep it simple here. Of course, it's cleaner if you do it the other way around, but it's not going to make that much of a difference, I guess. So, scalar.fit transform df close. And now we have the close values in a normal distribution with the mean of zero and the standard deviation of uh one. And that is what the standard scaler does. It scales the data so that it fits this distribution. So what we're going to do now is we're going to prepare the data for our neural network. And for this we need to clarify what exactly we're trying to do. Now what we're trying to do is we're trying to at any point in time look at the past x days whatever x is in your case. So we can look at 30 days, we can look at 2 days, we can look at 90 days. And the goal is then to look at this data and to say okay what is the stock price going to be tomorrow? That is the goal. So we have all these closing prices. Let's say from here to here what is going to be the next data point. Is it going to be more? Is it going to be less? Is it going to be the same? This is what our model is going to do. We're going to show it 30 days and it's going to predict the next day. So for that what we want to do now is we want to define first of all the sequence length. We're going to say sequence length is equal to how many days you want to consider. Let's go with 30 here. And then we're going to prepare an empty list uh for the data. So we're going to say data is equal to an empty list. And now we're going to add the examples. We're going to take the first days uh and then we're going to predict the last day. So we're going to do the following. I'm going to say 4 I in range length of the data frame minus sequence length because of course we don't want to go until the very end because then we don't have the sequence length anymore. Now to be precise uh we are actually looking at 29 days and predicting the 30th day here. So we could also say 31 if we want to look at uh 30 days but yeah that's just a small detail here. Uh so we're looking at the first 29 days to predict the 30th day and that is our goal. So we're going to say here data append and we want to append DF close I and I plus sequence length. So you can also see that there's an overlap. We're not going 30 days and then jumping to the next 30 days. Uh essentially maybe I can use my paint for this briefly. Uh if we have I don't know a couple of days here. Okay, seems like I cannot draw. Let's rerun this. There you go. Uh if I have day one, day two, day three, day four, day five, day six. Let's say my sequence length was three. What I would do now is I would take these three and I would consider these two the input and this one would be my prediction. And for the next data set, I would now not go to these. I would go like this. I would say these are the next three. These two are my training or my input data. And this is now my prediction. And then I go for these. So you can see they're overlapping. I'm not just going for these immediately. So the step size is one. The sequence length is um we're considering considering three items. We're looking at two in this case here and predicting the third. And in our case, we're looking at 29 items and predicting the 30th. That's the basic idea here. So, we take all of the data. Now, we don't have the XY split yet. We just have all of the data. We then turn all of this data into a numpy array by saying NP array of data just so it's easier uh to handle. And then we define a train size. And the train size is going to be 80% of the data. This is a usual value. So, 0.8 times the length of data. And of course, we want to truncate this because if that is a floatingoint number, we're going to have some problem. So we say now take the length of the data set uh so how many instances we have how many days we have um or how many how many sequences we have not how many days and then take 80% of that as the training data and now we can say x train is equal to torch now we're turning this into a torch tensor into a pytorch tensor from a numpy array so from numpy to a pietorch tensor we want to take the data everything up until train size. So train size is the index basically from zero to train size is going to be our training data. Uh and in particular we are interested in everything except for the last item. So colon -1 and everything in that dimension. The reason we do that I'm going to show you here in a second or maybe actually I can do that right away. I just have to then take this and put it down here because if I run this now and I show you the data, you're going to see what the shape looks like. So we have the first dimension. Uh here we have the second one and the third one. What we're interested in is everything from the last one since every item here is its own list so to say. Uh but from this dimension here, we're only interested in everything up until the last value. So that is -1. This is everything up until negative -1. So we're interested in everything every sequence. This is the outermost uh layer so to say every sequence uh within the first 80% of the data set and for each sequence everything except for the last item and within the items the whole item. So just everything. This is exactly what we're specifying here. First dimension, second dimension, third dimension. And now for the train data, we basically do the same thing, but we remove the colon because now we're only interested in the last element. So X train is going to be 29 elements, not the last one, and Y train is going to be the last one, the 30th element. Uh, same thing done for X test and Y test, but of course this time we say from train size to the end. So train size colon not colon train size that is the train test split here. And of course it makes sense to do it like that and not to do some shuffling or some uh other stuff because we are interested in sequentially predicting. We want to have the data up until a certain point as training data and then we want to make predictions for the future. So it makes sense to take the first 80% for training and not just any 80% for training like we would do it in a scikitlearn train test split with shuffle. Um yeah so that is our data. Now we have the X train and the Y train. Let's take a look briefly. X-rain looks like this. We have the scaled data and Y train is always going to be just the last value. So Y train is that and you can see all of this is a tensor a PyTorch tensor. All right. So that's our data. Now let's go ahead and define our model. Now let me just delete the cell here. Class prediction model which is going to inherit from nn module. And here now we're going to define our LSDM based architecture. We're going to say initi. We take self here as a keyword obviously. And then we can define the dimensions. The input dimension the hidden dimension. And we're going to keep it simple and just have the same uh dimension here for every hidden layer. Number of layers for the LSTM uh cell and or for the LSTM layers and then also the output dimension. So these are just the dimensions that we're passing here. We of course need to call the super constructor. So the parent class constructor prediction model uh selfc_init uh and then we can define some of these as attributes. So I can say self dot I think we're going to use uh hidden dimension and number of layers. So let's say number of layers is equal to number of layers. We're going to need that in the forward pass. uh hidden dimension is equal to hidden dimension just so we have that as a self attribute. And now we're going to define the layers. We're going to say self.lstm is the following. It's equal to nn.lstm in capital letters. And here now we pass the input [Music] dimension, the hidden dimension and the number of layers. So basically we have the number of neurons per layer and the number of layers and also the input uh input dimension input size and we also want to do batch first equals to true. Now again I'm not going to go into the details here when it comes to LSTMs. I gave you the basic explanation that this is a type of cell that is um used in recurrent neural networks. So we have a hidden state. the hidden state is passed on uh to the next step and uh we have mechanisms in there for forgetting information, storing information. Uh you can look up LSTM architecture, read about it or if you want an explanation for me, let me know in the comment section down below. Today I want to focus on the practical implementation. So we're just going to use it here. And after this LSTM um architecture here, we want to have a simple uh fully connected layer or linear layer. So we're going to say here FC is equal to NN.linear and we're going to say hidden dimension output dimension. And the output dimension is obviously going to be one in this case because we want to have one value that we predict. Perfect. So let's go and implement the forward pass. The forward pass is going to take self and X as input here. And essentially we start with a blank hidden state and also a blank uh uh C state. So yeah this would make sense now if you have an image of the architecture because with uh the LSTM cells we have two outputs the H and the C output which are both relevant. So yeah let's just accept this for now. We're going to initialize both as zero arrays or zero tensors. We're going to say torch.zer. Uh the shape is going to be self.num num layers x size so the size of the input zero and self do hidden dimension here and of course we need to put all of this to the proper device because everything that we use has to be on the same device be it the CPU or the GPU it has to be on the same device we're going to initialize C and H0 as just zero tensors on the GPU in my case and then we're going to pass everything through the LSTM. So we're going to say here out and then also HN and CN. So H and C at time step N is going to be equal to self.lm LSTM X and then here we're going to say H0 detach and C uh actually do we need yeah this is sorry like this uh H0 detach C 0 detach and uh then we're going to take that and feed it through the fully connected layer. You can see we're not using these two here. uh they're just being put out by the LSTM. We don't care about them. We only care about the output. So, we're going to say out is equal to self fully connected layer and we pass the output in here. To be precise, uh we do it like this. We're only interested in this one value and that is going to be returned by the forward pass. That is going to be our prediction, the last value. Perfect. So that is our architecture. Quite simple. Of course, you can tweak this. Now you can add I mean we don't have a number yet but you can add more layers. You can use different uh hidden dimensions. You can also add a dropout here. I think we just have to say dropout equals to 0.2 for example for a 20% chance. Uh play around with that. Add batch normalization if you want to. You can see how this affects the model. But that is the basic architecture. So we run this and now we're going to create an instance of this model. We're going to say model is equal to prediction model. And we're going to pass now input dimension is uh one. Hidden dimension is going to be equal to let's go with 32. Number of layers, let's keep it simple and go with two. Uh and then output dimension is going to be one. And the model of course needs to be sent to the GPU. So the model has to be where the tensors are otherwise it doesn't work. So now the model is on the GPU. These are going to be on the GPU as well. And now we're going to say I need a criterion for training. We're going to go with the MSE loss. We're going to use the RMSSE for evaluation because it's more intuitive because the root of the mean squared error is the root of the square. So it's actually in the unit that we care about which is the uh price points. Uh whereas the MSE is better for training because of the derivative. It's easier to uh take the derivative of. So we're going to say criterion is equal to nn ms loss and we're going to say optimizer is equal to optim atom classic atom choice here and we're going to optimize the model parameters and the learning rate is going to be 0.01. Again you can play around with that as well. So we define that and then finally we go to the training loop which is going to be the following number of epochs. Let's go with 200. We don't have a lot of data. We don't have a complicated architecture. 200 epochs are fine. And we're going to say now for i in range num epochs the uh train prediction. So this is the prediction that we make with the model on the training data is going to be model called onto the training data X train and then we want to see how wrong are we. So we're going to say loss is equal to criterion to this criterion we pass the prediction and we compare it to the actual output y train. So this is what we want uh to have as an answer. This is the actual price the day after the sequence and this is the prediction of the model. The loss is computed with MSE, mean squared error. We take the errors, we square them, and then we take the mean of that for all the um for all the samples. And then we say if this epoch is divisible by 25. So every 25 epochs, we want to print uh I and the loss just like that. And then we're going to say optimizer zero grad. So start with zero gradients then the loss is computed. We say actually we could do that before the loss calculation. Yeah doesn't matter. Uh we back propagate the loss. So we say backward and then we take a step in the proper direction. So in a nutshell what we do is we make a prediction. We see how wrong is that prediction. We back propagate the loss and the mistake uh through the weights and biases of the model. So we know for each uh little thing that we can tweak in what direction it would have to go to to make the model a little bit more correct in this particular way or in this particular case. And then we take a step into all of these directions at once using the optimizer. That is the training. So we can run that now. And I have a problem because what does it say? Input must have type float 32.r float 64. Oh yeah, this is because I forgot uh two things here. I need to first say of course type and we need to say torch.tensor for all of these and also we need to say to device. So we need to put all of them to the GPU as well. Obviously I said the tensors have to be where the model is. In this case the tensors were not sent to the GPU. So let's uh maybe run this here as well again. Run all of that. And now this should work. So actually I should print loss item. Let's run this again so we don't have more than 200 epochs. There you go. And you can see how the loss decreases. So maybe I should actually say 24 because then I'm going to get Or actually it's Yeah, let's go with 24. Uh, no. Actually, I don't like 24. Maybe we should say 25. Yeah, doesn't matter. Let's go with 25. Doesn't matter. Let's do it from here again. There you go. We have the model trained. And now let's go ahead and visualize how well the model performs on unseen data. So this is now the trained model trained on the training data. Now let's make predictions on the test data. Let's see what the RMSSE is. So the root mean squared error. And then also let's visualize our prediction against the actual price. So for this we're going to say y test prediction is equal to model called on the test data. Same way we did it here in the training loop for the train data. We just make the prediction. Um actually maybe I should say model eval to put it into eval mode. And uh now I make the prediction. And what I do now since I want to also get the RMSSE for the training process here is I'm going to take all these uh tensors. So I'm going to take the Y test prediction, the Y train prediction, the actual Y train data and the actual Y test data. I'm going to take all of that. I'm going to perform an inverse transform with a scaler. So we're going to take the scaled data which is in 0 something 1 point something. We're going to inverse scale it back to actual price. uh and then we're going to detach we're going to take it uh to the CPU and we're going to turn it into a numpy array and then we can calculate the RMSSE for these numpy arrays. So what I'm going to say now is I'm going to say y train prediction is equal to scalar inverse transform. This is now the the opposite of transform and in our case it was fit transform which did fitting and transforming in one but inverse transform is now the opposite. You take the scale data back into the original space which is the price space. Um and we pass here y train prediction. We detach that. We take it to the CPU. We turn it to a numpy array. Uh this is necessary because this function here, this inverse transform expects a numpy array. So we need to take it first from the GPU to the CPU turned into a numpy array. And we do the exact same thing here. Now for all these tensors. So Y train is also going to be Y train detach CPU numpy. Then we're going to say here test prediction is going to be test [Music] prediction and test is going to be test. Uh and we have a problem. What is that? Oh, okay. I see the problem. We have X test up here. And I don't have a colon here. So it was the same as Y test. Of course, that's not uh what we want to do. And we didn't notice that because we didn't use the test data yet. So let's run this again one more time. Training evaluating. Now we have these uh on the CPU inverse transformed as numpy arrays. And now what we're going to do is we're going to calculate using the root mean squared error. We're going to calculate the train RMSSE which is root mean squared error of Y train. Uh and then also Y train predictions everything and zero like this. And we're going to do the same thing for the test RMSSE but not with train. I'm going to actually say train test. There you go. So, Y test and Y test prediction. And then the train RMSSE is 2.91 and the test RMSSE probably higher is 11.99. So 12 essentially that is the RMSSE and this makes much more sense as a number than the MSE because that is in the same unit as our prices. So that is roughly uh $12 and this is roughly $3 or $2.9. That's the basic uh meaning of that. Now let's visualize that because that's going to look much more interesting to us. We're going to now plot the following. We're going to have three quarters of the plot with a price and D prediction. And below that we're going to also visualize the error. So we're going to see for each point in time how large the error is. We're also going to plot the mean. So the root mean squed error. and we're going to see uh what this looks like visually. So I'm going to say now figure is equal to plt figure. The figure size is going to be equal to 1210. So we're going to have to zoom out a little bit. Uh and then we're going to say grid spec. So gs is equal to figure add grid specification. I want to have four rows and one column. And here now we're going to have as I said three rows full of the price plot with a prediction. And then we're going to have one of these rows with the arrow. So I'm going to say here axis one is equal to figure add subplot. So we're going to add to the figure a subplot which is going to go from grid space up until three and zero. Basically means we're going to fill the first three columns uh rows sorry. and the only column that we have column with the index zero. And now we're going to say axis one plot and we want to plot the actual price. So we're going to say df illock minus length of the test data up until the end. Now this notation basically means give me all the data from the very end um or actually from go the size of the test set back. So go to the beginning of the test set and give me all the data until the end. That is going to be our uh date. So dot index to get the date on the x-axis. And then y test is going to be the actual uh price. So the actual price data for the stock. And we're going to say the color of that is going to be blue. So the actual price is going to be blue. And we're going to have the label actual price like this. Now I can copy that. I can paste that. And here now I'm going to do test predictions. This is going to be green. And I'm going to say predicted price. So we have these two plots. Then I'm going to say access one legend so that we can see which one is which one. Then we're going to say plt title. For this year, I'm going to use a formatted string which is ticker stock price prediction. And then I'm going to say plt x label is going to be date and the y label is going to be uh price. That's that. That's the first one. The second one is going to be axis 2 figure add subplot. This time we're going to go with the last row and the same column. So three because index three is row four zero because we only have one column. And then we say now first of all I want to have a horizontal line uh that is going to be at the level of the root mean squared error for the test data. So, ax hline horizontal line uh test rms. The color I want to use for this one is blue. And I also want to have the line style of a dashed line. So, dash like this. And the label of that is going to be Army. So, we know where the baseline is. And then we can see how for the individual days these vary. So I'm going to say here access to plot same as above minus length y test up until the end dot index. This is going to be the date. We're going to have the same axis uh or the same values for the x-axis. And then I'm going to say what I want to have here is the absolute error because I don't care about plus or minus. I just care about how wrong are you. I don't care in which direction you're wrong. I want to know how wrong are you. So the absolute value of y test minus y test predictions that is going to be in red color and it's going to be the prediction error for that particular time or that particular day. And now we're going to do the same thing here. access to legend, access to or actually I should say PLT title prediction error like this and then I should say pltx label is still going to be the date. Now we could also synchronize them. I don't think that's going to be the case by default. We could also share the x-axis so that if we zoom in, we're going to see that uh this changes for both of them. I don't want to do that now, especially because we're using this in a Jupyter notebook. But basically, we have date and error here. And then I want to say plt tight layout. And even though it's not necessary here, plt show that should now give us our model's performance. So you can see what happens here is the blue thing is the actual stock price. The green thing is our predicted stock price. Now this might look to you like it's super impressive. Don't think that before you understand what it actually does. This is not starting here that the model predicts now what is going the stock price uh what is the stock price going to look like over the next year. This is not how it works. What it does is it always looks at 30 days or 29 days and predicts the next day. Which means that it's actually quite bad because I have already all this information here and then I predict a point that's down here and not up here. So you can see that even where it looks that this model actually does a good prediction, it's always shifted to the right, which means that the moment the model realizes that something is uh about to change and trend for example, it's essentially after it already happened. So here for example, we go up, the model goes up after the actual stock price went up. Then here the actual stock price goes down. We can zoom in a little bit. the actual stock price goes down and our model goes down only after it sees that as a data point. So yes, the curve sometimes looks quite similar to the actual stock price, but it's always because things already happened that the model picked up on them and now uses them in the prediction. And considering that the model sees all of that, it's quite bad that it's so much under uh this curve here. So this is kind of okay. This one here is not uh really a good performance. And we can actually see that if we go down here, the RMS RMSSE here is the root mean squared error. And here you can see that we have much more error than anywhere else. And this is exactly this section here where the actual stock price is much higher than our predicted stock price. Now you can just go ahead now change the ticker up here and do the exact same thing for different stocks. So we can go now with Microsoft just run all the cells and in this case now we have a much better curve. So you can see it's still always to the right. So whenever our model recognizes something it's when it already happened. Now maybe you can find examples of this uh being recognized earlier. This would be kind of cool if you see that actually the predicted price goes up before the actual price goes up. That would be a very interesting finding. Uh but yeah this is what our model does. So to understand it, every point here, if I go here for example, every point here means this was the stock price on this day and this is what the model thought the stock price on this day is going to be. And yeah, that's basically it. So even if it looks very close, it's always to the right, which means the model only adjusted after it actually happened. So it already had the information of the trend changing. But still, it's a pretty good exercise and you can try to tweak this. You can try to play around with that. I also think about making a video in more detail about maybe using indicators, using stuff like the relative strength index, RSI, different technical uh analysis indicators, different uh information that we can incorporate here, volume or something like that and then train a model on all of that to predict the stock price. Maybe also predict for multiple days. So produce a sequence of predictions, not just one value. And maybe we can evaluate that. If you want to see that, let me know in the comment section down below. But this is how you can do basic stock price prediction in Python using neural networks in PyTorch. So that's it for today's video. I hope you enjoyed it and hope you learned something. If so, let me know by hitting a like button and leaving a comment in the comment section down below. Also, let me know if you want to see more similar videos like this one. Maybe some advanced techniques, maybe more details on the theory, like what are LSTMs, how do how do they work, maybe you want me to implement different architectures, maybe incorporate more indicators. Let me know in the comment section down below. And besides that, thank you very much for watching. See you in the next video and bye.
Original Description
In this video we will learn how to do stock price prediction in Python with PyTorch using an LSTM-based architecture.
DISCLAIMER: None of this is financial advice. This is purely a programming tutorial and I am not responsible for any financial decisions you make. Don't use this for actually trying to predict stock prices.
◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚
🐍 The Python Bible Book: https://www.neuralnine.com/books/
💻 The Algorithm Bible Book: https://www.neuralnine.com/books/
👕 Programming Merch: https://www.neuralnine.com/shop
💼 Services 💼
💻 Freelancing & Tutoring: https://www.neuralnine.com/services
🖥️ Setup & Gear 🖥️: https://neuralnine.com/extras/
🌐 Social Media & Contact 🌐
📱 Website: https://www.neuralnine.com/
📷 Instagram: https://www.instagram.com/neuralnine
🐦 Twitter: https://twitter.com/neuralnine
🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/
📁 GitHub: https://github.com/NeuralNine
🎙 Discord: https://discord.gg/JU4xr8U3dm
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeuralNine · NeuralNine · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
Python Beginner Tutorial #5 - Loops
NeuralNine
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
Python Beginner Tutorial #7 - Functions
NeuralNine
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
Python Beginner Tutorial #9 - File Operations
NeuralNine
Python Beginner Tutorial #10 - String Functions
NeuralNine
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
Python Intermediate Tutorial #6 - Queues
NeuralNine
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
Python Intermediate Tutorial #9 - Recursion
NeuralNine
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
Python Intermediate Tutorial #11 - Logging
NeuralNine
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
Python Machine Learning #4 - Support Vector Machines
NeuralNine
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
Making Text Images Readable Again with Python and OpenCV
NeuralNine
Neural Networks Simply Explained (Theory)
NeuralNine
Motion Filtering with OpenCV in Python
NeuralNine
Top 5 Programming Languages To Learn in 2020
NeuralNine
Simple TCP Chat Room in Python
NeuralNine
Image Classification with Neural Networks in Python
NeuralNine
Edge Detection with OpenCV in Python
NeuralNine
S&P 500 Web Scraping with Python
NeuralNine
Simple Sentiment Text Analysis in Python
NeuralNine
Introduction - Algorithms & Data Structures #1
NeuralNine
More on: Supervised Learning
View skill →Related Reads
📰
📰
📰
📰
Help Choosing Neural Network Architecture for Matrix Classification
Reddit r/deeplearning
How to Choose the Best Deep Learning Model for Medical Imaging
Medium · Deep Learning
Another Way to Read Neural Geometry
Medium · Data Science
Another Way to Read Neural Geometry
Medium · Deep Learning
🎓
Tutor Explanation
DeepCamp AI