To train an LSTM model on your cryptocurrency data without merging the CSV files, you can iterate through each file and train separate models or, if you're aiming to train a single model that learns from all currencies while keeping their data distinct, consider a data structure that feeds each currency's data into the LSTM separately during training. Given your case and the desire to predict both a continuous variable (high_2d) and a binary variable (prior_2d), it's possible to approach this with a multi-output model. However, designing a model to output both continuous and binary predictions requires careful consideration of the model architecture and loss functions.
Let's walk through a general solution using Python and TensorFlow/Keras, focusing on training an LSTM model for one cryptocurrency. You can then adapt this approach for multiple currencies by iterating over your CSV files or incorporating multiple datasets into the training process in a unified way if desired. The model architecture will be relatively simple for illustrative purposes.
Note: This example assumes you have a basic understanding of Python, Pandas, TensorFlow, and LSTM networks. It also assumes you've preprocessed your data to some extent (e.g., normalization).
import pandas as pd
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Dense, concatenate
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
# Load your data
def load_data(file_name):
data = pd.read_csv(file_name)
return data
# Preprocess data: Generate sequences of 30-day windows for training
def create_dataset(X, Y, time_steps=30):
Xs, Ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X.iloc[i:(i + time_steps)].values)
Ys.append(Y.iloc[i + time_steps])
return np.array(Xs), np.array(Ys)
# Assuming 'high_2d' is continuous and 'prior_2d' is binary
def preprocess_data(file_name):
data = load_data(file_name)
# Normalize data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_features = scaler.fit_transform(data.drop(['high_2d', 'prior_2d'], axis=1))
scaled_features_df = pd.DataFrame(scaled_features, index=data.index, columns=data.drop(['high_2d', 'prior_2d'], axis=1).columns)
# Generate sequences
X, Y = create_dataset(scaled_features_df, data[['high_2d', 'prior_2d']])
return X, Y[:, 0], Y[:, 1] # Separate Y into two outputs
# Define LSTM model
def create_model(input_shape):
input_layer = Input(shape=input_shape)
x = LSTM(50, return_sequences=False)(input_layer)
# For continuous output (high_2d)
high_2d_output = Dense(1, name='high_2d')(x)
# For binary output (prior_2d)
prior_2d_output = Dense(1, activation='sigmoid', name='prior_2d')(x)
model = Model(inputs=input_layer, outputs=[high_2d_output, prior_2d_output])
model.compile(optimizer='adam',
loss={'high_2d': 'mean_squared_error', 'prior_2d': 'binary_crossentropy'},
metrics={'high_2d': ['mae'], 'prior_2d': ['accuracy']})
return model
# Prepare your data
file_name = 'your_crypto_file.csv'
X, high_2d, prior_2d = preprocess_data(file_name)
# Split the data for training and testing
X_train, X_test, high_2d_train, high_2d_test, prior_2d_train, prior_2d_test = train_test_split(X, high_2d, prior_2d, test_size=0.2, random_state=42)
# Reshape inputs for LSTM [samples, time steps, features]
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], X_train.shape[2]))
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], X_test.shape[2]))
# Create and train your model
model = create_model((X_train.shape[1], X_train.shape[2]))
history = model.fit(X_train, [high_2d_train, prior_2d_train], epochs=10, batch_size=32, validation_data=(X_test, [high_2d_test, prior_2d_test]), verbose=1)
Notes on this script:
- You must replace
'your_crypto_file.csv' with the actual path to your CSV files. To handle multiple files, consider a loop or a function that processes files one by one or concurrently, depending on your requirements.
- The
create_dataset function creates sequences from your time series data. Each sequence (last 30 days) is used to predict the next day's high_2d and prior_2d.
- This architecture uses one LSTM layer followed by two separate Dense layers for predicting
high_2d (continuous) and prior_2d (binary). Adjust the model according to the complexity of your problem, sizes, and nature of your datasets.
- Model optimization and performance: Experiment with different architectures, hyperparameters, and preprocessing techniques to optimize performance for your specific datasets.