Certainly! Below is a Python script that includes functions for:
- Data Gathering: Fetching historical cryptocurrency data.
- Data Preprocessing: Cleaning and preparing the data for model input.
- Model Definition: Defining a deep learning model suitable for time series forecasting.
- Training the Model: Training the model on the historical data.
- Making Predictions: Using the trained model to make trading decisions.
Note: Since the TinyTimeMixer model from IBM Granite is proprietary, we'll implement a similar architecture using PyTorch. We'll use a lightweight Transformer-based model adapted for time series forecasting.
import pandas as pd
import numpy as np
import requests
import datetime
import time
from sklearn.preprocessing import MinMaxScaler
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
import matplotlib.pyplot as plt
# 1. Data Gathering
def fetch_crypto_data(symbol='BTCUSDT', interval='1h', start_str='1 Jan 2020', end_str=None):
"""
Fetch historical cryptocurrency data from Binance API.
"""
url = "https://api.binance.com/api/v3/klines"
start_ts = int(pd.to_datetime(start_str).timestamp() * 1000)
end_ts = int(pd.to_datetime(end_str).timestamp() * 1000) if end_str else None
params = {
'symbol': symbol,
'interval': interval,
'startTime': start_ts,
'endTime': end_ts,
'limit': 1000
}
df = pd.DataFrame()
while True:
response = requests.get(url, params=params)
data = response.json()
if not data:
break
temp_df = pd.DataFrame(data, 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 = df.append(temp_df, ignore_index=True)
params['startTime'] = int(temp_df['Close time'].iloc[-1]) + 1
time.sleep(0.5) # To avoid hitting the API rate limit
if end_ts and params['startTime'] >= end_ts:
break
df['Open time'] = pd.to_datetime(df['Open time'], unit='ms')
df.set_index('Open time', inplace=True)
numeric_columns = ['Open', 'High', 'Low', 'Close', 'Volume']
df[numeric_columns] = df[numeric_columns].astype(float)
return df[numeric_columns]
# 2. Data Preprocessing
def preprocess_data(df, sequence_length=60):
"""
Preprocess the data:
- Feature scaling
- Creating sequences for model input
"""
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(df)
sequences = []
targets = []
for i in range(len(scaled_data) - sequence_length):
sequences.append(scaled_data[i:i+sequence_length])
targets.append(scaled_data[i+sequence_length][3]) # Close price as target
sequences = np.array(sequences)
targets = np.array(targets)
return sequences, targets, scaler
# Custom Dataset
class CryptoDataset(Dataset):
def __init__(self, sequences, targets):
self.sequences = torch.from_numpy(sequences).float()
self.targets = torch.from_numpy(targets).float().unsqueeze(1)
def __len__(self):
return len(self.sequences)
def __getitem__(self, idx):
return self.sequences[idx], self.targets[idx]
# 3. Model Definition
class TimeSeriesTransformer(nn.Module):
def __init__(self, feature_size=5, num_layers=2, dropout=0.1):
super(TimeSeriesTransformer, self).__init__()
self.model_type = 'Transformer'
self.src_mask = None
self.pos_encoder = nn.Sequential(
nn.Linear(feature_size, 128),
nn.ReLU(),
nn.Dropout(dropout)
)
encoder_layers = nn.TransformerEncoderLayer(d_model=128, nhead=8, dropout=dropout)
self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers=num_layers)
self.decoder = nn.Linear(128, 1)
self.init_weights()
def init_weights(self):
initrange = 0.1
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self, src):
src = self.pos_encoder(src)
output = self.transformer_encoder(src)
output = output.mean(dim=1) # Global average pooling
output = self.decoder(output)
return output
# 4. Training the Model
def train_model(model, dataloader, epochs=20):
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
model.train()
for epoch in range(epochs):
epoch_loss = 0
for sequences, targets in dataloader:
optimizer.zero_grad()
output = model(sequences)
loss = criterion(output, targets)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
avg_loss = epoch_loss / len(dataloader)
print(f'Epoch {epoch+1}/{epochs}, Loss: {avg_loss:.6f}')
return model
# 5. Making Predictions
def make_trading_decision(model, recent_sequence, scaler):
model.eval()
with torch.no_grad():
input_seq = torch.from_numpy(recent_sequence).float().unsqueeze(0)
predicted_price = model(input_seq).item()
predicted_price = scaler.inverse_transform([[0, 0, 0, predicted_price, 0]])[0][3]
current_price = scaler.inverse_transform([recent_sequence[-1]])[0][3]
if predicted_price > current_price * 1.005:
action = "Go Long"
elif predicted_price < current_price * 0.995:
action = "Go Short"
else:
action = "Do Nothing"
return action, predicted_price
# Main Execution
if __name__ == "__main__":
# Fetch data
df = fetch_crypto_data(symbol='BTCUSDT', interval='1h', start_str='1 Jan 2020')
# Preprocess data
sequence_length = 60 # Using past 60 time steps
sequences, targets, scaler = preprocess_data(df, sequence_length)
# Split data into training and testing
split_ratio = 0.8
split = int(len(sequences) * split_ratio)
train_sequences = sequences[:split]
train_targets = targets[:split]
test_sequences = sequences[split:]
test_targets = targets[split:]
# Create Datasets and DataLoaders
train_dataset = CryptoDataset(train_sequences, train_targets)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
# Initialize model
model = TimeSeriesTransformer(feature_size=5, num_layers=2, dropout=0.1)
# Train model
trained_model = train_model(model, train_loader, epochs=20)
# Testing and Predictions
test_dataset = CryptoDataset(test_sequences, test_targets)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
actions = []
actual_prices = []
predicted_prices = []
for sequences, targets in test_loader:
action, predicted_price = make_trading_decision(trained_model, sequences.numpy()[0], scaler)
actions.append(action)
actual_price = scaler.inverse_transform([sequences.numpy()[0][-1]])[0][3]
actual_prices.append(actual_price)
predicted_prices.append(predicted_price)
# Output results
results_df = pd.DataFrame({
'Actual Price': actual_prices,
'Predicted Price': predicted_prices,
'Action': actions
})
print(results_df.head())
# Plotting the actual vs predicted prices
plt.figure(figsize=(14,7))
plt.plot(actual_prices, label='Actual Prices')
plt.plot(predicted_prices, label='Predicted Prices')
plt.legend()
plt.show()
Explanation:
-
Data Gathering (fetch_crypto_data): Uses Binance API to fetch historical OHLCV (Open, High, Low, Close, Volume) data for a specified cryptocurrency symbol and interval.
-
Data Preprocessing (preprocess_data):
- Scaling: Normalizes the data using
MinMaxScaler for better neural network performance.
- Sequencing: Creates sequences of past data (
sequence_length) to use as input features.
-
Custom Dataset (CryptoDataset): A PyTorch Dataset class to handle our time series data.
-
Model Definition (TimeSeriesTransformer):
- A simplified Transformer-based model adapted for time series forecasting.
- Consists of positional encoding, transformer encoder layers, and a linear decoder.
-
Training the Model (train_model): Trains the model using Mean Squared Error loss and Adam optimizer.
-
Making Predictions (make_trading_decision):
- Predicts the future price based on the recent sequence.
- Determines the action:
- Go Long: If the predicted price is significantly higher than the current price.
- Go Short: If the predicted price is significantly lower.
- Do Nothing: If the predicted price is similar to the current price.
-
Main Execution:
- Fetches and preprocesses the data.
- Splits the data into training and testing sets.
- Trains the model.
- Makes predictions on the test set and decides trading actions.
- Outputs a DataFrame with actual prices, predicted prices, and suggested actions.
- Plots the actual vs. predicted prices for visual evaluation.
Note: This script is a simplified example for educational purposes. In a real-world scenario:
- Data: You might include more features (technical indicators, sentiment analysis, etc.).
- Model Tuning: Hyperparameters would need thorough tuning for optimal performance.
- Risk Management: Implement strategies to manage risk (stop-loss, take-profit levels).
- Backtesting: Rigorously backtest the strategy over historical data before deployment.
- Live Trading: Additional code would be needed to interact with trading platforms for live trading.
Disclaimer: Trading cryptocurrencies involves significant risk, and past performance is not indicative of future results. This script is for educational purposes and should not be used as-is for live trading without proper testing and validation.