Get in touch
or send us a question?
CONTACT

Using LSTM to train model

import matplotlib.pyplot as plt

from keras.layers import LSTM, Dense, Dropout

from keras import Sequential

from sklearn.preprocessing import MinMaxScaler

import pandas as pd

import numpy as np

# Load the dataset

# https://raw.githubusercontent.com/datasets/finance-vix/master/data/vix-daily.csv

df = pd.read_csv(‘data\\vix-daily.csv’)

data = df[‘CLOSE’].values.reshape(-1, 1)

# Normalize the data

scaler = MinMaxScaler(feature_range=(0, 1))

scaled_data = scaler.fit_transform(data)

# Prepare the training data

train_size = int(len(scaled_data) * 0.8)

train_data = scaled_data[:train_size]

test_data = scaled_data[train_size:]

def create_dataset(data, time_step=1):

    X, y = [], []

    for i in range(len(data) – time_step):

        X.append(data[i:(i + time_step), 0])

        y.append(data[i + time_step, 0])

    return np.array(X), np.array(y)

time_step = 60

X_train, y_train = create_dataset(train_data, time_step)

X_test, y_test = create_dataset(test_data, time_step)

# Reshape input to be [samples, time steps, features]

X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

# Build the LSTM model

model = Sequential()

model.add(LSTM(50, return_sequences=True,

               input_shape=(X_train.shape[1], 1)))

model.add(Dropout(0.2))

model.add(LSTM(50, return_sequences=False))

model.add(Dropout(0.2))

model.add(Dense(25))

model.add(Dense(1))

# Compile the model

model.compile(optimizer=’adam’, loss=’mean_squared_error’)

# Train the model

model.fit(X_train, y_train, batch_size=1, epochs=1)

# Predict the stock prices

train_predict = model.predict(X_train)

test_predict = model.predict(X_test)

# Inverse transform the predictions

train_predict = scaler.inverse_transform(train_predict)

test_predict = scaler.inverse_transform(test_predict)

# Plot the results for the most recent 6 months

train_data_len = len(train_data)

# Plot only the most recent 6 months of data in three different charts

recent_6_months = 6 * 30  # Approximate number of days in 6 months

plt.figure(figsize=(16, 8))

# Plot actual stock price

plt.subplot(3, 1, 1)

plt.plot(df[‘CLOSE’][-recent_6_months:], label=’Actual Stock Price’)

plt.title(‘Actual Stock Price’)

plt.legend()

# Plot train predictions

plt.subplot(3, 1, 2)

plt.plot(range(time_step, train_data_len)

         [-recent_6_months:], train_predict[-recent_6_months:], label=’Train Predict’)

plt.title(‘Train Predictions’)

plt.legend()

# Plot test predictions

plt.subplot(3, 1, 3)

plt.plot(range(train_data_len + time_step, len(df))

         [-recent_6_months:], test_predict[-recent_6_months:], label=’Test Predict’)

plt.title(‘Test Predictions’)

plt.legend()

plt.tight_layout()

plt.legend()

plt.show()