Creating an LSTM model to predict cryptocurrency data based on historical prices involves several steps: preprocessing your data, creating a model, training the model, and then evaluating its performance. Below is a simplified code example to guide you through this process. This code will assume you've already calculated the 'high_2d' and 'prior_1d' columns in your CSV files.
Step 1: Preprocessing the data
We will start by loading the data, normalizing it, and then creating sequences that the LSTM model can learn from.
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout
from sklearn.model_selection import train_test_split
# Load the dataset
df = pd.read_csv('your_file.csv')
# Assuming the file has the following columns: date, open, high, low, close, volume, high_2d, prior_1d
# We'll use the ['open', 'high', 'low', 'close', 'volume'] for training
# Select features to scale
features = df[['open', 'high', 'low', 'close', 'volume']]
target = df[['high_2d', 'prior_1d']]
# Scale the features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_features = scaler.fit_transform(features)
# Function to create sequences
def create_sequences(data, target, sequence_length):
xs = []
ys = []
for i in range(len(data)-sequence_length):
x = data[i:(i+sequence_length)]
y = target[i+sequence_length]
xs.append(x)
ys.append(y)
return np.array(xs), np.array(ys)
seq_length = 30 # Number of time steps to look back
# which is last 30 days data in our case
X, y = create_sequences(scaled_features, target.values, seq_length)
# Splitting the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 2: Building the LSTM Model
We will design a simple LSTM model for this task.
# Creating the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(LSTM(50, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(50))
model.add(Dense(2, activation='linear')) # 'linear' for regression task e.g., predicting 'high_2d' and 'sigmoid' for classification e.g., 'prior_1d'
# Compiling the model, you might want to change loss and metrics based on your targets
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
model.summary()
Step 3: Training the Model
Now, let’s train the model with our prepared dataset.
history = model.fit(X_train, y_train, epochs=50, batch_size=64, validation_split=0.1, verbose=1)
Step 4: Evaluate the Model
Finally, we can evaluate our model on the test set.
# Evaluate the model
test_performance = model.evaluate(X_test, y_test, verbose=1)
print(f'Test Loss: {test_performance[0]}, Test Accuracy: {test_performance[1]}')
Keep in mind that you might need to adjust this code based on the exact structure of your CSV file and your specific requirements (e.g., the number of features, the architecture of the LSTM model, epochs, and batch sizes).
Remember, LSTM models can be quite sensitive to the choice of hyperparameters, such as the learning rate, number of LSTM units, and dropout rate. Additionally, ensure your data is thoroughly preprocessed and normalized for better performance. Experimentation with the architecture and parameters will be key in achieving better results.