import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pandas as pd
from model import BitcoinPricePredictor
# Определение датасета
class BitcoinDataset(Dataset):
def __init__(self, data, sequence_length=100):
self.sequence_length = sequence_length
self.data = data
def __len__(self):
return len(self.data) - self.sequence_length
def __getitem__(self, idx):
seq = self.data.iloc[idx:idx + self.sequence_length].values
target = self.data.iloc[idx + self.sequence_length]['Close']
return torch.tensor(seq, dtype=torch.float32), torch.tensor(target, dtype=torch.float32)
def train():
# Загружаем данные
train_df = pd.read_csv('data/train_data.csv')
# Параметры
sequence_length = 100
batch_size = 64
num_epochs = 5#20
learning_rate = 0.001
input_size = train_df.shape[1] # Количество признаков
# Создаём датасет и загрузчик
train_dataset = BitcoinDataset(train_df, sequence_length)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
# Инициализируем модель, функцию потерь и оптимизатор
model = BitcoinPricePredictor(input_size=input_size)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Переносим модель на устройство (CPU или GPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Обучение модели
model.train()
for epoch in range(num_epochs):
epoch_loss = 0
for sequences, targets in train_loader:
sequences = sequences.to(device)
targets = targets.to(device)
# Прямой проход
outputs = model(sequences)
loss = criterion(outputs.squeeze(), targets)
# Обратный проход и оптимизация
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_loss += loss.item()
avg_loss = epoch_loss / len(train_loader)
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {avg_loss:.6f}')
# Сохраняем модель
torch.save(model.state_dict(), 'models/model.pth')
print("Модель сохранена в models/model.pth")
if __name__ == "__main__":
train()
test.py
py
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from model import BitcoinPricePredictor
import joblib
# Определение датасета для тестирования
class BitcoinTestDataset:
def __init__(self, data, sequence_length=100):
self.sequence_length = sequence_length
self.data = data
def get_random_sequence(self):
idx = np.random.randint(0, len(self.data) - self.sequence_length - 1)
seq = self.data.iloc[idx:idx + self.sequence_length].values
target = self.data.iloc[idx + self.sequence_length]['Close']
return seq, target, idx
def test():
# Загружаем данные
test_df = pd.read_csv('data/test_data.csv')
# Загружаем скейлер
scaler = joblib.load('models/scaler.gz')
# Переносим данные в исходный масштаб для визуализации
test_df_scaled = pd.DataFrame(scaler.inverse_transform(test_df), columns=test_df.columns)
# Инициализируем модель
input_size = test_df.shape[1]
model = BitcoinPricePredictor(input_size=input_size)
model.load_state_dict(torch.load('models/model.pth'))
model.eval()
# Переносим модель на устройство (CPU или GPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Создаём датасет
test_dataset = BitcoinTestDataset(test_df, sequence_length=100)
# Получаем случайную последовательность
seq, real_value, idx = test_dataset.get_random_sequence()
# Подготовка данных для модели
seq_tensor = torch.tensor(seq, dtype=torch.float32).unsqueeze(0).to(device)
# Предсказание
with torch.no_grad():
predicted_value = model(seq_tensor).cpu().item()
# Обратное преобразование предсказанного значения
close_index = test_df.columns.get_loc('Close')
mean = scaler.mean_[close_index]
var = scaler.var_[close_index]
std = np.sqrt(var)
predicted_value = predicted_value * std + mean
real_value = real_value * std + mean
# Подготовка данных для визуализации
seq_denorm = seq[:, close_index] * std + mean
print(f"Предсказанное значение: {predicted_value:.2f} USD")
print(f"Реальное значение: {real_value:.2f} USD")
# Визуализация
time_steps = np.arange(len(seq_denorm) + 1)
# Построение графика
plt.plot(time_steps[:-1], seq_denorm, color='blue', label='Входная последовательность')
plt.plot(time_steps[-2:], [seq_denorm[-1], predicted_value], color='orange', marker='o', label='Предсказанный шаг')
plt.plot(time_steps[-2:], [seq_denorm[-1], real_value], color='green', marker='o', label='Реальный шаг')
plt.legend()
plt.xlabel('Временные шаги')
plt.ylabel('Цена Bitcoin (USD)')
plt.title('Предсказание цены Bitcoin')
plt.show()
if __name__ == "__main__":
test()
data_loader.py
py
import requests
import pandas as pd
import time
from datetime import datetime, timedelta
from tqdm import tqdm
def get_data(start_time, end_time, interval):
url = "https://api.binance.com/api/v3/klines"
params = {
'symbol': 'BTCUSDT',
'interval': interval,
'startTime': start_time,
'endTime': end_time,
'limit': 1000
}
response = requests.get(url, params=params)
data = response.json()
return data
def add_indicators(df):
# Простая скользящая средняя (SMA)
df['SMA_10'] = df['Close'].rolling(window=10).mean()
df['SMA_30'] = df['Close'].rolling(window=30).mean()
# Экспоненциальная скользящая средняя (EMA)
df['EMA_10'] = df['Close'].ewm(span=10, adjust=False).mean()
df['EMA_30'] = df['Close'].ewm(span=30, adjust=False).mean()
# Индекс относительной силы (RSI)
delta = df['Close'].diff()
up = delta.clip(lower=0)
down = -delta.clip(upper=0)
ema_up = up.ewm(com=13, adjust=False).mean()
ema_down = down.ewm(com=13, adjust=False).mean()
rs = ema_up / ema_down
df['RSI'] = 100 - (100 / (1 + rs))
return df
def collect_data(start_date_str, end_date_str):
# Устанавливаем интервал в 5 минут
interval = '5m'
# Преобразуем строки дат в объекты datetime
start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
# Начальное и конечное время в формате миллисекунд
start_time = int(start_date.timestamp() * 1000)
end_time = int(end_date.timestamp() * 1000)
# Вычисляем общее количество запросов
total_requests = (end_time - start_time) // (1000 * 60 * 5 * 1000) + 1
all_data = []
with tqdm(total=total_requests, desc="Collecting data") as pbar:
while start_time < end_time:
data = get_data(start_time, end_time, interval)
if not data:
break
all_data.extend(data)
start_time = data[-1][6] + 1 # Обновляем время начала
time.sleep(0.5) # Задержка, чтобы не перегружать API
pbar.update(1)
# Преобразуем данные в DataFrame
columns = ['Open Time', 'Open', 'High', 'Low', 'Close', 'Volume',
'Close Time', 'Quote Asset Volume', 'Number of Trades',
'Taker Buy Base Asset Volume', 'Taker Buy Quote Asset Volume', 'Ignore']
df = pd.DataFrame(all_data, columns=columns)
# Конвертируем необходимые столбцы в нужные типы
df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms')
df['Close Time'] = pd.to_datetime(df['Close Time'], unit='ms')
numeric_columns = ['Open', 'High', 'Low', 'Close', 'Volume']
df[numeric_columns] = df[numeric_columns].astype(float)
# Сохраняем данные в CSV
df.to_csv('data/raw_data.csv', index=False)
print("Данные успешно сохранены в data/raw_data.csv")
# Добавляем индикаторы
df = add_indicators(df)
# Удаляем начальные строки с NaN (из-за расчёта индикаторов)
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)
# Сохраняем данные в CSV
df.to_csv('data/raw_data.csv', index=False)
print("Данные успешно сохранены в data/raw_data.csv")
def preprocess_data():
df = pd.read_csv('data/raw_data.csv')
# Выбираем нужные столбцы для модели
features = ['Open', 'High', 'Low', 'Close', 'Volume', 'SMA_10', 'SMA_30', 'EMA_10', 'EMA_30', 'RSI']
# Нормализация данных
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_features = scaler.fit_transform(df[features])
# Сохраняем скейлер для использования при тестировании
import joblib
joblib.dump(scaler, 'models/scaler.gz')
# Создаём DataFrame с нормализованными данными
scaled_df = pd.DataFrame(scaled_features, columns=features)
# Разбиваем данные на обучающую и тестовую выборки
train_size = int(len(scaled_df) * 0.8)
train_data = scaled_df.iloc[:train_size]
test_data = scaled_df.iloc[train_size:]
# Сохраняем данные
train_data.to_csv('data/train_data.csv', index=False)
test_data.to_csv('data/test_data.csv', index=False)
print("Данные успешно разбиты на train_data.csv и test_data.csv")
if __name__ == "__main__":
start_date_str = '2022-09-01' # Задайте дату начала в формате YYYY-MM-DD
end_date_str = '2023-09-30' # Задайте дату окончания в формате YYYY-MM-DD
print(f"collecting data from {start_date_str} to {end_date_str}")
collect_data(start_date_str, end_date_str)
print(f"preprocess data")
preprocess_data()
Это моя модель для предсказания цены BitcoinUSDT, основываясь на предыдущих шагах.
Вот так выглядит обучение:
Epoch [1/8], Train Loss: 0.000977, Val Loss: 0.000083
Epoch [2/8], Train Loss: 0.000111, Val Loss: 0.000059
Epoch [3/8], Train Loss: 0.000062, Val Loss: 0.000033
Epoch [4/8], Train Loss: 0.000056, Val Loss: 0.000035
Epoch [5/8], Train Loss: 0.000053, Val Loss: 0.000043
Epoch [6/8], Train Loss: 0.000045, Val Loss: 0.000035
Epoch [7/8], Train Loss: 0.000041, Val Loss: 0.000025
Вот так выглядит test:
Test RMSE: 76.41
Test MAE: 52.25
Test MAPE: 0.19%
Нужно убрать Bidirectional LSTM, ведь в реальности мы не можем получить данные из будущего.
Проверь, не перемешиваются ли тренировочные и тестовые наборы данных.
Важно, чтобы при обучении выборки по 100 шагов были последовательно
Примени все свои навыки ML-специалиста и произведи улучшения.
Приведи обновленные файлы.
Я хочу, чтобы test.py работал иначе - он брал бы случайные 100 шагов из тестового набора, рисовал бы их. После чего, оранжевым рисовал бы 101-й шаг, предсказанный моделью. И поверх него зеленым цветом реальный 101-й шаг.
Sure, I'd be happy to help you improve your model. Below are the updated code files with the requested changes and improvements:
Data Preparation (data_loader.py)
Split the data into training, validation, and test sets to monitor the model's performance and prevent data leakage.
Ensure sequences are sequential by not shuffling the data.
python
import requests
import pandas as pd
import time
from datetime import datetime, timedelta
from tqdm import tqdm
def get_data(start_time, end_time, interval):
url = "https://api.binance.com/api/v3/klines"
params = {
'symbol': 'BTCUSDT',
'interval': interval,
'startTime': start_time,
'endTime': end_time,
'limit': 1000
}
response = requests.get(url, params=params)
data = response.json()
return data
def add_indicators(df):
# Simple Moving Averages (SMA)
df['SMA_10'] = df['Close'].rolling(window=10).mean()
df['SMA_30'] = df['Close'].rolling(window=30).mean()
# Exponential Moving Averages (EMA)
df['EMA_10'] = df['Close'].ewm(span=10, adjust=False).mean()
df['EMA_30'] = df['Close'].ewm(span=30, adjust=False).mean()
# Relative Strength Index (RSI)
delta = df['Close'].diff()
up = delta.clip(lower=0)
down = -delta.clip(upper=0)
ema_up = up.ewm(com=13, adjust=False).mean()
ema_down = down.ewm(com=13, adjust=False).mean()
rs = ema_up / ema_down
df['RSI'] = 100 - (100 / (1 + rs))
return df
def collect_data(start_date_str, end_date_str):
# Set interval to 5 minutes
interval = '5m'
# Convert date strings to datetime objects
start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
# Start and end times in milliseconds
start_time = int(start_date.timestamp() * 1000)
end_time = int(end_date.timestamp() * 1000)
# Calculate total requests
total_requests = (end_time - start_time) // (1000 * 60 * 5 * 1000) + 1
all_data = []
with tqdm(total=total_requests, desc="Collecting data") as pbar:
while start_time < end_time:
data = get_data(start_time, end_time, interval)
if not data:
break
all_data.extend(data)
start_time = data[-1][6] + 1 # Update start time
time.sleep(0.5) # Delay to avoid API overload
pbar.update(1)
# Convert data to DataFrame
columns = ['Open Time', 'Open', 'High', 'Low', 'Close', 'Volume',
'Close Time', 'Quote Asset Volume', 'Number of Trades',
'Taker Buy Base Asset Volume', 'Taker Buy Quote Asset Volume', 'Ignore']
df = pd.DataFrame(all_data, columns=columns)
# Convert necessary columns to appropriate types
df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms')
df['Close Time'] = pd.to_datetime(df['Close Time'], unit='ms')
numeric_columns = ['Open', 'High', 'Low', 'Close', 'Volume']
df[numeric_columns] = df[numeric_columns].astype(float)
# Save data to CSV
df.to_csv('data/raw_data.csv', index=False)
print("Data successfully saved to data/raw_data.csv")
# Add indicators
df = add_indicators(df)
# Drop initial rows with NaN (due to indicators calculation)
df.dropna(inplace=True)
df.reset_index(drop=True, inplace=True)
# Save data to CSV
df.to_csv('data/raw_data.csv', index=False)
print("Data successfully saved to data/raw_data.csv")
def preprocess_data():
df = pd.read_csv('data/raw_data.csv')
# Select features for the model
features = ['Open', 'High', 'Low', 'Close', 'Volume', 'SMA_10', 'SMA_30', 'EMA_10', 'EMA_30', 'RSI']
# Normalize data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_features = scaler.fit_transform(df[features])
# Save scaler for use during testing
import joblib
joblib.dump(scaler, 'models/scaler.gz')
# Create DataFrame with scaled data
scaled_df = pd.DataFrame(scaled_features, columns=features)
# Split data into training, validation, and testing sets
train_size = int(len(scaled_df) * 0.7)
val_size = int(len(scaled_df) * 0.1)
train_data = scaled_df.iloc[:train_size]
val_data = scaled_df.iloc[train_size:train_size + val_size]
test_data = scaled_df.iloc[train_size + val_size:]
# Save data
train_data.to_csv('data/train_data.csv', index=False)
val_data.to_csv('data/val_data.csv', index=False)
test_data.to_csv('data/test_data.csv', index=False)
print("Data successfully split into train_data.csv, val_data.csv, and test_data.csv")
if __name__ == "__main__":
start_date_str = '2022-09-01' # Start date in YYYY-MM-DD format
end_date_str = '2023-09-30' # End date in YYYY-MM-DD format
print(f"Collecting data from {start_date_str} to {end_date_str}")
collect_data(start_date_str, end_date_str)
print("Preprocessing data")
preprocess_data()
Model Definition (model.py)
Increased model capacity by adjusting hidden_size and num_layers.
Added dropout to prevent overfitting.
Ensured no bidirectional LSTM is used.
python
import torch
import torch.nn as nn
class BitcoinPricePredictor(nn.Module):
def __init__(self, input_size, hidden_size=128, num_layers=3, dropout=0.2):
super(BitcoinPricePredictor, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
# LSTM layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, dropout=dropout)
# Fully connected layer
self.fc = nn.Linear(hidden_size, 1)
def forward(self, x):
# Initialize hidden states
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
# Pass through LSTM
out, _ = self.lstm(x, (h0, c0))
# Take output of last time step
out = self.fc(out[:, -1, :])
return out
Training Script (train.py)
Disabled shuffling in the DataLoader to ensure sequences remain sequential.
Added validation set to monitor model performance during training.
Implemented early stopping to prevent overfitting.
Increased the number of epochs and adjusted hyperparameters for better training.
Added dropout in the model for regularization.
python
Testing Script (test.py)
Updated test script to select a random sequence of 100 steps from the test set.
Plotted the sequence, along with the predicted 101st step and the actual 101st step.
Ensured proper denormalization of the data for accurate plotting.
python
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from model import BitcoinPricePredictor
import joblib
def test():
# Load test data
test_df = pd.read_csv('data/test_data.csv')
# Load scaler
scaler = joblib.load('models/scaler.gz')
# Initialize model
input_size = test_df.shape[1]
model = BitcoinPricePredictor(input_size=input_size, hidden_size=128, num_layers=3)
model.load_state_dict(torch.load('models/model.pth'))
model.eval()
# Move model to device (CPU or GPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Prepare test data
sequence_length = 100
test_data_length = len(test_df) - sequence_length
# Get random sequence
idx = np.random.randint(0, test_data_length)
seq = test_df.iloc[idx:idx + sequence_length].values
real_value = test_df.iloc[idx + sequence_length]['Close']
# Prepare input tensor
seq_tensor = torch.tensor(seq, dtype=torch.float32).unsqueeze(0).to(device)
# Predict
with torch.no_grad():
predicted_value = model(seq_tensor).cpu().item()
# Denormalize the data
close_index = test_df.columns.get_loc('Close')
mean = scaler.mean_[close_index]
std = np.sqrt(scaler.var_[close_index])
seq_close = seq[:, close_index]
seq_denorm = seq_close * std + mean
predicted_value_denorm = predicted_value * std + mean
real_value_denorm = real_value * std + mean
print(f"Predicted value: {predicted_value_denorm:.2f} USD")
print(f"Real value: {real_value_denorm:.2f} USD")
# Plotting
time_steps = np.arange(len(seq_denorm) + 1)
plt.figure(figsize=(12, 6))
# Plot the input sequence
plt.plot(time_steps[:-1], seq_denorm, color='blue', label='Input sequence')
# Plot predicted 101st step
plt.plot(time_steps[-2:], [seq_denorm[-1], predicted_value_denorm], color='orange', marker='o', label='Predicted step')
# Plot real 101st step
plt.plot(time_steps[-2:], [seq_denorm[-1], real_value_denorm], color='green', marker='o', label='Real step')
plt.legend()
plt.xlabel('Time Steps')
plt.ylabel('Bitcoin Price (USD)')
plt.title('Bitcoin Price Prediction')
plt.show()
if __name__ == "__main__":
test()
Improvements Made
Removed Data Shuffling:
Disabled shuffling in the DataLoader to ensure that sequences during training remain sequential.
This is crucial for time series data where the order of data points matters.
No Bidirectional LSTM:
Ensured the LSTM is unidirectional since future data is not available in real-time predictions.
Validation Set:
Added a validation set to monitor the model's performance during training and to implement early stopping.
This helps prevent overfitting to the training data.
Early Stopping:
Implemented early stopping based on validation loss to prevent overfitting and reduce training time.
Model Regularization:
Added dropout layers in the LSTM to prevent overfitting by randomly dropping units during training.
Adjusted Hyperparameters:
Increased hidden_size and num_layers in the LSTM to allow the model to capture more complex patterns.
Adjusted the number of epochs and added patience for early stopping.
Test Script Update:
Modified test.py to meet your requirements: it selects a random sequence from the test set, plots it, and then plots the predicted and real 101st step.
This provides a visual comparison of the model's prediction against the actual value.
Usage Instructions
Data Collection and Preprocessing:
Run data_loader.py to collect and preprocess the data.
code
python data_loader.py
Model Training:
Run train.py to train the model.
code
python train.py
Model Testing:
Run test.py to test the model and visualize the prediction.
code
python test.py
Notes
Ensure the models/ and data/ directories exist before running the scripts, or modify the paths accordingly.
Monitor the training and validation loss to ensure the model is learning appropriately.
Experiment with hyperparameters such as learning rate, batch size, sequence length, etc., to further improve the model.
Next Steps
Feature Engineering:
Explore adding more technical indicators or external features that might influence Bitcoin prices.
Model Enhancements:
Experiment with other architectures like GRU or Transformer models.
Try using a sequence-to-sequence model if predicting multiple future time steps.
Hyperparameter Tuning:
Use tools like Grid Search or Bayesian Optimization to find the optimal hyperparameters.
Evaluation Metrics:
Implement additional evaluation metrics to get a comprehensive understanding of the model's performance.
By applying these changes, your model should now be better suited for time series prediction, avoiding common pitfalls, and is more likely to generalize well to unseen data.
Dataset releases
Not yet included in a published release.
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pandas as pd
from model import BitcoinPricePredictor
import numpy as np
# Define dataset
class BitcoinDataset(Dataset):
def __init__(self, data, sequence_length=100):
self.sequence_length = sequence_length
self.data = data
def __len__(self):
return len(self.data) - self.sequence_length
def __getitem__(self, idx):
seq = self.data.iloc[idx:idx + self.sequence_length].values
target = self.data.iloc[idx + self.sequence_length]['Close']
return torch.tensor(seq, dtype=torch.float32), torch.tensor(target, dtype=torch.float32)
def train():
# Load data
train_df = pd.read_csv('data/train_data.csv')
val_df = pd.read_csv('data/val_data.csv')
# Parameters
sequence_length = 100
batch_size = 64
num_epochs = 50
learning_rate = 0.001
input_size = train_df.shape[1] # Number of features
# Create datasets and data loaders
train_dataset = BitcoinDataset(train_df, sequence_length)
val_dataset = BitcoinDataset(val_df, sequence_length)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=False)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
# Initialize model, loss function and optimizer
model = BitcoinPricePredictor(input_size=input_size, hidden_size=128, num_layers=3, dropout=0.2)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Move model to device (CPU or GPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# Early stopping parameters
best_val_loss = np.inf
patience = 5
counter = 0
# Training the model
for epoch in range(num_epochs):
model.train()
epoch_loss = 0
for sequences, targets in train_loader:
sequences = sequences.to(device)
targets = targets.to(device)
# Forward pass
outputs = model(sequences)
loss = criterion(outputs.squeeze(), targets)
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_loss += loss.item()
avg_loss = epoch_loss / len(train_loader)
# Validation
model.eval()
with torch.no_grad():
val_loss = 0
for sequences, targets in val_loader:
sequences = sequences.to(device)
targets = targets.to(device)
outputs = model(sequences)
loss = criterion(outputs.squeeze(), targets)
val_loss += loss.item()
avg_val_loss = val_loss / len(val_loader)
print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {avg_loss:.6f}, Val Loss: {avg_val_loss:.6f}')
# Early stopping
if avg_val_loss < best_val_loss:
best_val_loss = avg_val_loss
counter = 0
# Save the best model
torch.save(model.state_dict(), 'models/model.pth')
else:
counter +=1
if counter >= patience:
print("Early stopping")
break
print("Training completed. Best model saved to models/model.pth")
if __name__ == "__main__":
train()