Algorithmic trading with Keras
The goal of this article is to provide the necessary notions to perform time-series forecasting on financial data using the library Keras for Deep Learning.
In particular, we will use two models involving LSTM recurrent neural networks and 1-dimensional convolutions to develop an investment strategy for the S&P 500 index.
We will test that, in a period of 4 years which includes the 2008 crisis, these deep learning strategies performed far better than the buy and hold strategy (stay always in the market) and the moving average strategy (stay in the market when the current price is greater than the moving average of past 12 months and sell when it becomes smaller). To quantify these performances, we will compute the gross and net yield (considering the tax on capital gain and the fee to the broker at each transaction).
import pandas as pd
import numpy as np
import datetime
import time
import matplotlib.pyplot as plt
from pandas_datareader import data as pdr
import keras
from keras.models import Sequential
from keras.optimizers import RMSprop,Adam
from keras.layers import Dense,Dropout,BatchNormalization,Conv1D,Flatten,MaxPooling1D,LSTM
from keras.callbacks import EarlyStopping,ModelCheckpoint,TensorBoard,ReduceLROnPlateau
from keras.wrappers.scikit_learn import KerasRegressor
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
This code sets up a simple deep learning model for automated stock trading using Keras. It loads essential packages like pandas and numpy for handling data, datetime for managing times, and matplotlib for plotting charts. It also brings in financial data using the pandas_datareader. For the neural network, it gets key components from Keras, including models and layers, and connects with scikit-learn for model fitting. The MinMaxScaler from scikit-learn is used to normalize the data before it goes into the neural network. The code prepares everything needed to create and run the trading algorithm.