Hello!
Creating a robust and accurate stock price prediction model using a Transformer architecture is an ambitious and exciting project. Below, I've provided two comprehensive Python scripts:
-
Training Code: This script preprocesses the data, constructs a state-of-the-art Transformer model tailored for time series forecasting, and trains the model using time-series cross-validation.
-
Prediction Code: This script loads the trained model, preprocesses new data, makes predictions for the next day's closing price, and saves the results for further analysis.
⚠️ Disclaimer:
Stock price prediction involves significant financial risk. The provided code is for educational purposes only and should not be construed as financial advice. Always conduct thorough research or consult a financial advisor before making investment decisions.
1. Training Code: train_transformer_model.py
import pandas as pd
import numpy as np
import os
import datetime
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import mean_squared_error, mean_absolute_error
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torch.optim import Adam
import math
import matplotlib.pyplot as plt
# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)
# ====== Data Preprocessing ======
def load_and_preprocess_data(daily_path, intraday_path):
# Load Daily Data
daily_df = pd.read_csv(daily_path, parse_dates=['Date'])
daily_df['Time'] = '00:00:00' # Placeholder for daily data
daily_df = daily_df[['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']]
# Load Intraday Data
intraday_df = pd.read_csv(intraday_path, parse_dates=['Date'])
intraday_df.rename(columns={'Close': 'Close'}, inplace=True)
# Combine Date and Time into a single DateTime column if needed
# For simplicity, keeping Date and Time separate
intraday_df = intraday_df[['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']]
# Standardize Data
# Ensure both datasets have the same columns
combined_df = pd.concat([daily_df, intraday_df], ignore_index=True)
combined_df.sort_values(['Date', 'Time'], inplace=True)
combined_df.reset_index(drop=True, inplace=True)
# Handle Missing Values
combined_df.fillna(method='ffill', inplace=True)
combined_df.fillna(method='bfill', inplace=True)
# Feature Engineering (Placeholders for future features)
# combined_df['Feature_X'] = ... # Example placeholder
return combined_df
# ====== Dataset Preparation ======
class StockDataset(Dataset):
def __init__(self, data, seq_length=60):
self.seq_length = seq_length
self.data = data
self.features = ['Open', 'High', 'Low', 'Close', 'Volume']
self.X = []
self.Y = []
self.prepare_sequences()
def prepare_sequences(self):
for i in range(len(self.data) - self.seq_length):
seq = self.data[self.features].iloc[i:i+self.seq_length].values
target = self.data['Close'].iloc[i+self.seq_length]
self.X.append(seq)
self.Y.append(target)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return torch.tensor(self.X[idx], dtype=torch.float32), torch.tensor(self.Y[idx], dtype=torch.float32)
# ====== Transformer Model ======
class TimeSeriesTransformer(nn.Module):
def __init__(self, feature_size=5, num_layers=4, dropout=0.1, nhead=8, dim_feedforward=512):
super(TimeSeriesTransformer, self).__init__()
self.model_type = 'Transformer'
self.src_mask = None
self.pos_encoder = PositionalEncoding(feature_size, dropout)
encoder_layers = nn.TransformerEncoderLayer(d_model=feature_size, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout)
self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers=num_layers)
self.decoder = nn.Linear(feature_size, 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 shape: [batch_size, seq_length, feature_size]
src = self.pos_encoder(src)
src = src.permute(1, 0, 2) # Transformer expects [seq_length, batch_size, feature_size]
output = self.transformer_encoder(src)
output = output.permute(1, 0, 2) # [batch_size, seq_length, feature_size]
output = output[:, -1, :] # Take the last time step
output = self.decoder(output)
return output.squeeze()
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
if d_model % 2 == 0:
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
else:
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)[:,:pe[:,1::2].shape[1]]
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
# x shape: [batch_size, seq_length, feature_size]
x = x + self.pe[:, :x.size(1), :]
return self.dropout(x)
# ====== Training Function ======
def train_model(model, train_loader, val_loader, criterion, optimizer, epochs=50, device='cpu'):
model.to(device)
train_losses = []
val_losses = []
for epoch in range(1, epochs + 1):
model.train()
epoch_train_loss = 0
for X_batch, Y_batch in train_loader:
X_batch = X_batch.to(device)
Y_batch = Y_batch.to(device)
optimizer.zero_grad()
output = model(X_batch)
loss = criterion(output, Y_batch)
loss.backward()
optimizer.step()
epoch_train_loss += loss.item() * X_batch.size(0)
epoch_train_loss /= len(train_loader.dataset)
train_losses.append(epoch_train_loss)
model.eval()
epoch_val_loss = 0
with torch.no_grad():
for X_batch, Y_batch in val_loader:
X_batch = X_batch.to(device)
Y_batch = Y_batch.to(device)
output = model(X_batch)
loss = criterion(output, Y_batch)
epoch_val_loss += loss.item() * X_batch.size(0)
epoch_val_loss /= len(val_loader.dataset)
val_losses.append(epoch_val_loss)
print(f'Epoch {epoch}, Training Loss: {epoch_train_loss:.4f}, Validation Loss: {epoch_val_loss:.4f}')
# Plotting Loss
plt.figure(figsize=(10,6))
plt.plot(range(1, epochs +1), train_losses, label='Training Loss')
plt.plot(range(1, epochs +1), val_losses, label='Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.title('Training and Validation Loss')
plt.show()
return model
# ====== Main Training Pipeline ======
def main():
# Paths to data
daily_data_path = 'cleaned_spy_historical_data.csv'
intraday_data_path = 'intraday_data_tradier.csv'
# Load and preprocess data
data = load_and_preprocess_data(daily_data_path, intraday_data_path)
# Sort data by Date and Time
data.sort_values(['Date', 'Time'], inplace=True)
data.reset_index(drop=True, inplace=True)
# Initialize Dataset
dataset = StockDataset(data, seq_length=60)
# TimeSeries Split
n_splits = 5
tscv = TimeSeriesSplit(n_splits=n_splits)
fold = 1
best_model = None
best_val_loss = float('inf')
for train_index, val_index in tscv.split(dataset):
print(f'Fold {fold}')
train_subset = torch.utils.data.Subset(dataset, train_index)
val_subset = torch.utils.data.Subset(dataset, val_index)
train_loader = DataLoader(train_subset, batch_size=64, shuffle=False)
val_loader = DataLoader(val_subset, batch_size=64, shuffle=False)
# Initialize model, loss, optimizer
model = TimeSeriesTransformer(feature_size=5, num_layers=4, nhead=8, dim_feedforward=512, dropout=0.1)
criterion = nn.MSELoss()
optimizer = Adam(model.parameters(), lr=0.001)
# Train
model = train_model(model, train_loader, val_loader, criterion, optimizer, epochs=50, device='cuda' if torch.cuda.is_available() else 'cpu')
# Evaluate
model.eval()
val_loss = 0
with torch.no_grad():
for X_batch, Y_batch in val_loader:
X_batch = X_batch.to('cuda' if torch.cuda.is_available() else 'cpu')
Y_batch = Y_batch.to('cuda' if torch.cuda.is_available() else 'cpu')
output = model(X_batch)
loss = criterion(output, Y_batch)
val_loss += loss.item() * X_batch.size(0)
val_loss /= len(val_loader.dataset)
print(f'Fold {fold} Validation Loss: {val_loss:.4f}')
# Save best model
if val_loss < best_val_loss:
best_val_loss = val_loss
best_model = model
torch.save(model.state_dict(), 'best_transformer_model.pth')
fold +=1
print('Training complete. Best Validation Loss:', best_val_loss)
if __name__ == '__main__':
main()
Explanation:
-
Data Preprocessing:
- Loading Data: Both daily and intraday data are loaded and standardized to have consistent columns.
- Handling Missing Values: Forward-fill and backward-fill methods are used to handle missing data.
- Feature Engineering: Placeholders are included for future feature additions.
-
Dataset Preparation:
- StockDataset: Custom
Dataset class prepares sequences of a fixed length (seq_length) for the Transformer model.
-
Model Architecture:
- TimeSeriesTransformer: A Transformer-based model with positional encoding, multiple encoder layers, and a linear decoder to predict the closing price.
- PositionalEncoding: Adds positional information to the input features to help the model understand the sequence.
-
Training Function:
- Trains the model for a specified number of epochs.
- Utilizes Mean Squared Error (MSE) as the loss function.
- Displays training and validation loss for each epoch and plots the loss curves at the end.
-
Time-Series Cross-Validation:
- Implements
TimeSeriesSplit to preserve the temporal order of the data.
- Trains and evaluates the model across multiple folds, saving the model with the best validation loss.
-
Model Saving:
- The best-performing model is saved as
best_transformer_model.pth for later use in predictions.
Dependencies:
Ensure you have the necessary libraries installed. You can install them using:
pip install pandas numpy scikit-learn torch matplotlib
2. Prediction Code: predict_stock_price.py
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import datetime
import csv
# ====== Dataset Class for Inference ======
class InferenceDataset(Dataset):
def __init__(self, data, seq_length=60):
self.seq_length = seq_length
self.data = data
self.features = ['Open', 'High', 'Low', 'Close', 'Volume']
self.X = []
self.prepare_sequences()
def prepare_sequences(self):
if len(self.data) < self.seq_length:
raise ValueError("Not enough data points to create a sequence")
seq = self.data[self.features].iloc[-self.seq_length:].values
self.X.append(seq)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return torch.tensor(self.X[idx], dtype=torch.float32)
# ====== Transformer Model Definition ======
class TimeSeriesTransformer(nn.Module):
def __init__(self, feature_size=5, num_layers=4, dropout=0.1, nhead=8, dim_feedforward=512):
super(TimeSeriesTransformer, self).__init__()
self.model_type = 'Transformer'
self.src_mask = None
self.pos_encoder = PositionalEncoding(feature_size, dropout)
encoder_layers = nn.TransformerEncoderLayer(d_model=feature_size, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout)
self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers=num_layers)
self.decoder = nn.Linear(feature_size, 1)
def forward(self, src):
src = self.pos_encoder(src)
src = src.permute(1, 0, 2) # [seq_length, batch_size, feature_size]
output = self.transformer_encoder(src)
output = output.permute(1, 0, 2) # [batch_size, seq_length, feature_size]
output = output[:, -1, :] # Take the last time step
output = self.decoder(output)
return output.squeeze()
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
if d_model % 2 == 0:
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
else:
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)[:,:pe[:,1::2].shape[1]]
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:, :x.size(1), :]
return self.dropout(x)
import math
# ====== Prediction Function ======
def predict_next_close(model, data, device='cpu'):
dataset = InferenceDataset(data)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
model.to(device)
model.eval()
with torch.no_grad():
for X_batch in loader:
X_batch = X_batch.to(device)
prediction = model(X_batch)
predicted_close = prediction.item()
# If using a regression without normalization, it's direct. If normalized, apply inverse transform here.
# confidence_score can be derived from model outputs or uncertainty estimation methods
confidence_score = 1.0 # Placeholder
return predicted_close, confidence_score
# ====== Main Prediction Pipeline ======
def main():
# Paths
data_path = 'cleaned_spy_historical_data.csv' # Update if using intraday data
model_path = 'best_transformer_model.pth'
output_csv = 'predictions.csv'
# Load latest data for prediction
data = pd.read_csv(data_path, parse_dates=['Date'])
data['Time'] = '00:00:00' # Assuming daily data
data = data[['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']]
data.sort_values(['Date', 'Time'], inplace=True)
data.reset_index(drop=True, inplace=True)
# Handle missing values
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)
# Initialize and load model
model = TimeSeriesTransformer(feature_size=5, num_layers=4, nhead=8, dim_feedforward=512, dropout=0.1)
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
# Predict
predicted_close, confidence = predict_next_close(model, data, device='cpu') # Change 'cpu' to 'cuda' if using GPU
# Output
print(f"Predicted Closing Price for next day: {predicted_close:.2f}")
# Save to CSV
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
prediction_data = {
'Timestamp': [timestamp],
'Predicted_Close': [predicted_close],
'Confidence_Score': [confidence]
}
prediction_df = pd.DataFrame(prediction_data)
if not os.path.exists(output_csv):
prediction_df.to_csv(output_csv, index=False)
else:
prediction_df.to_csv(output_csv, mode='a', header=False, index=False)
print(f"Prediction saved to {output_csv}")
if __name__ == '__main__':
main()
Explanation:
-
Dataset Class for Inference:
- InferenceDataset: Prepares the latest sequence of data for prediction. It ensures that the sequence length matches what the model expects.
-
Model Definition:
- The
TimeSeriesTransformer and PositionalEncoding classes are replicated to match the architecture used during training. Ensure that the model architecture here matches exactly with the training script.
-
Prediction Function:
- predict_next_close: Loads the prepared data, feeds it to the model, and generates the predicted closing price. A placeholder
confidence_score is included, which can be enhanced using uncertainty estimation techniques.
-
Main Prediction Pipeline:
- Data Loading: Reads the latest data from the CSV file. Ensure that this data is updated with the most recent market information before running the prediction.
- Model Loading: Loads the trained model weights.
- Prediction: Generates the predicted closing price and prints it.
- Saving Predictions: Appends the prediction along with a timestamp and confidence score to
predictions.csv for future analysis.
Dependencies:
Ensure you have the necessary libraries installed. You can install them using:
pip install pandas numpy torch
3. Suggestions for Improvements and Alternative Approaches
-
Feature Engineering:
- Incorporate additional features such as moving averages, exponential moving averages, or other relevant financial indicators to provide the model with more context.
- Incorporate macroeconomic indicators or sentiment analysis from news sources.
-
Model Enhancements:
- Experiment with different Transformer architectures, such as the Informer or Transformer-XL, which might offer better performance for time series data.
- Incorporate attention mechanisms that focus on specific time steps or features.
-
Hyperparameter Tuning:
- Utilize libraries like Optuna or Hyperopt for more efficient and automated hyperparameter optimization.
- Explore different learning rates, batch sizes, and optimizer algorithms.
-
Validation Metrics:
- Incorporate additional metrics such as Mean Absolute Percentage Error (MAPE) or R² Score to gain more insight into model performance.
- Implement early stopping based on validation loss to prevent overfitting.
-
Ensemble Methods:
- Combine predictions from multiple models to improve robustness and accuracy.
- Use techniques like stacking or averaging to leverage the strengths of different models.
-
Data Augmentation:
- Introduce noise or perform time warping on the data to make the model more resilient to variations in the input data.
-
Deployment Considerations:
- Optimize the model for faster inference, especially if deploying in a real-time trading environment.
- Implement proper error handling and logging mechanisms in the prediction script.
-
Backtesting:
- Before deploying the model for live trading, perform rigorous backtesting using historical data to evaluate its performance.
-
Scalability:
- For handling larger datasets or more frequent predictions, consider scaling the data pipeline and model training using distributed computing frameworks.
-
Documentation and Modularity:
- Enhance code readability and maintenance by breaking down scripts into modular functions or classes.
- Implement comprehensive documentation and usage instructions.
Final Note: Building a high-performing stock prediction model is a complex task that requires careful consideration of data quality, feature selection, model architecture, and continuous evaluation. The provided scripts offer a foundational framework, but achieving state-of-the-art performance will require iterative experimentation and refinement.
Good luck with your project!