Ciao, people!This is first part of my experiments on application of deep learning to finance, in particular to algorithmic trading.I want to implement trading system from scratch based only on deep learning approaches, so for any problem we have here (price prediction, trading strategy, risk management) we gonna use different variations of artificial neural networks (ANNs) and check how well they can handle this.Now I plan to work on next sections:I highly recommend you to check out code and IPython Notebook in this repository.In this, first part, I want to show how MLPs, CNNs and RNNs can be used for financial time series prediction. In this part we are not going to use any feature engineering. Let’s just consider historical dataset of S&P 500 index price movements. We have information from 1950 to 2016 about open, close, high, low prices for every day in the year and volume of trades. First, we will try just to predict close price in the end of the next day, second, we will try to predict return (close price — open price). Download the dataset from Yahoo Finance or from this repository.We will consider our problem as 1) regression problem (trying to forecast exactly close price or return next day) 2) binary classification problem (price will go up [1; 0] or down [0; 1]).For training NNs we gonna use framework Keras.First let’s prepare our data for training. We want to predict t+1 value based on N previous days information. For example, having close prices from past 30 days on the market we want to predict, what price will be tomorrow, on the 31st day.We use first 90% of time series as training set (consider it as historical data) and last 10% as testing set for model evaluation.Here is example of loading, splitting into training samples and preprocessing of raw input data:It will be just 2-hidden layer perceptron. Number of hidden neurons is chosen empirically, we will work on hyperparameters optimization in next sections. Between two hidden layers we add one Dropout layer to prevent overfitting.Important thing is Dense(1), Activation(‘linear’) and ‘mse’ in compile section. We want one output that can be in any range (we predict real value) and our loss function is defined as mean squared error.Let’s see what happens if we just pass chunks of 20-days close prices and predict price on 21st day. Final MSE= 46.3635263557, but it’s not very representative information. Below is plot of predictions for first 150 points of test dataset. Black line is actual data, blue one — predicted. We can clearly see that our algorithm is not even close by value, but can learn the trend.Let’s scale our data using sklearn’s method preprocessing.scale() to have our time series zero mean and unit variance and train the same MLP. Now we have MSE = 0.0040424330518 (but it is on scaled data). On the plot below you can see actual scaled time series (black)and our forecast (blue) for it:For using this model in real world we should return back to unscaled time series. We can do it, by multiplying or prediction by standard deviation of time series we used to make prediction (20 unscaled time steps) and add it’s mean value:MSE in this case equals 937.963649937. Here is the plot of restored predictions (red) and real data (green):Not bad, isn’t it? But let’s try more sophisticated algorithms for this problem!I am not going to dive into theory of convolutional neural networks, you can check out this amazing resourses:Let’s define 2-layer convolutional neural network (combination of convolution and max-pooling layers) with one fully-connected layer and the same output as earlier:Let’s check out results. MSEs for scaled and restored data are: 0.227074542433; 935.520550172. Plots are below:Even looking on MSE on scaled data, this network learned much worse. Most probably, deeper architecture needs more data for training, or it just overfitted due to too high number of filters or layers. We will consider this issue later.As recurrent architecture I want to use two stacked LSTM layers (read more about LSTMs here).Plots of forecasts are below, MSEs = 0.0246238639582; 939.948636707.RNN forecasting looks more like moving average model, it can’t learn and predict all fluctuations.So, it’s a bit unexpectable result, but we can see, that MLPs work better for this time series forecasting. Let’s check out what will happen if we swith from regression to classification problem. Now we will use not close prices, but daily return (close price-open price) and we want to predict if close price is higher or lower than open price based on last 20 days returns.Code is changed just a bit — we change our last Dense layer to have output [0; 1] or [1; 0] and add softmax output to expect probabilistic output.To load binary outputs, change in the code following line:Also we change loss function to binary cross-entopy and add accuracy metrics.Oh, it’s not better than random guessing (50% accuracy), let’s try something better. Check out the results below.We can see, that treating financial time series prediction as regression problem is better approach, it can learn the trend and prices close to the actual.What was surprising for me, that MLPs are treating sequence data better as CNNs or RNNs which are supposed to work better with time series. I explain it with pretty small dataset (~16k time stamps) and dummy hyperparameters choice.You can reproduce results and get better using code from repository.I think we can get better results both in regression and classification using different features (not only scaled time series) like some technical indicators, volume of sales. Also we can try more frequent data, let’s say minute-by-minute ticks to have more training data. All these things I’m going to do later, so stay tuned :)From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.🇺🇦 🇮🇹 AI entrepreneur, blogger and researcher. Making machines work 💻, learn 📕 and like 👍, but humans create 🎨, discover 🚀 and love ❤️The best about Machine Learning, Computer Vision, Deep Learning, Natural language processing and other.