Path: blob/master/Documentation/Python/Predicting-Future-Prices-With-Sklearn.ipynb
984 views
Predicting Prices Movements With sklearn
An example of sklearn model building, training, saving in the ObjectStore, and loading.
Import Libraries
Let's start by importing the functionality we'll need to build the model and to split our data into training/testing sets. We also import pickle so we can store our model in ObjectStore later.
Gather & Prepare Data
Let's retrieve some intraday data for the SPY by making a History request.
We create a function that prepares our data suitable for training and testing our Model. We use 5 steps of OHLCV data to predict the closing price of the bar right after. By tying this to a function, we increase clarity, as well as reusability, especially if we were to copy it into a class in a .py file.
Build the Model (SVR with GridSearch Hyperparameter Optimization)
Let's build the model using sklearn. We use a Support Vector Regressor as it works well with non-linear data. Furthermore, we optimize the hyperparameters of this model using GridSearchCV. We encourage users to experiment with different optimizable hyperparameters (e.g. kernel type) and models (e.g. Random Forests).
Let's build and train our model by feeding in data prepared using the prep_data function.
Analyze Performance
We then make predictions on the testing data set. We compare our Predicted Values with the Expected Values by plotting both to see if our Model has predictive power.
Save the Model to ObjectStore
We dump the model using the pickle module and save the resulting bytes to ObjectStore
Load Model from the ObjectStore
Let's first retrieve the bytes of the model from ObjectStore. When we retrieve the bytes from ObjectStore, we need to cast it into a form useable by pickle with the bytearray() method.
To ensure the model was successfully loaded, let's see if the model is able to make predictions.
Appendix
Below are some helper methods to manage the ObjectStore keys. We can use these to validate the saving and loading is successful.