Predict the direction of the stock closing price with biLSTM for mega profit

Source: Deep Learning on Medium

Today we will look at how to apply Bidirectional LSTM in predicting the direction of the closing price of the next Microsoft stock day (MSFT)

I prefer to use anaconda and yml env file with all dependencies. You can find this file in the repository.

First we need to load the data from the csv file and normalize open and close price through MinMaxScaler.

I would like to see what the difference between the logarithms of closing prices looks like. We will not use this data in this article, but it can be very useful when you classify predictive data for cleaner signals.

log diff close price

let’s look at out test split:

Accumulate every 50 daily bars and function prepare data with calculation ema.

Next step we make model. I prefer to split data of different nature and concatenate at the last stages

Parameters for our models

len = 50
test_size = 0.2
neurons = 100
epochs = 10
batch_size = 32
loss = 'mse'
dropout = 0.2
optimizer = 'adam'

Little by little, get data for training and testing and train our model

_train, x_test, x_open_train, x_open_test, y_train, y_test, x_tech_train, x_tech_test = prepare_data(df.values, target_col, len, test_size)

print(x_train.shape) # (3988, 50, 5)
print(x_test.shape) # (996, 50, 5)
print(x_open_train.shape) # (3988, 1)
print(x_open_test.shape) # (996, 1)
print(x_tech_train.shape) # (3988, 5)
print(x_tech_test.shape) # (996, 5)
y_train = np.array(y_train).reshape(1, -1).squeeze()
y_test = np.array(y_test).reshape(1, -1).squeeze()

print(y_train.shape) # (3988,)
print(y_test.shape) # (996,)

Learning…

model = build_lstm_model(x_train, x_tech_train, x_open_train, output_size=1, neurons=neurons, dropout=dropout, loss=loss, optimizer=optimizer)history = model.fit(x=[x_train, x_tech_train, x_open_train], y=y_train, epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True, validation_split=0.05)