| This code starts by creating synthetic stock price data, then it proceeds to define a simple linear neural network model. The model is trained on the synthetic data, and finally, it attempts to predict the stock price for the next day based on the last 10 days of data. Remember, this is a basic example for educational purposes. Real-world applications require careful consideration of model architecture, data preprocessing, feature selection, and potentially the use of more complex models such as LSTMs or GRUs for handling sequences in time-series data. import torch
import torch.nn as nn
import numpy as np
# Seed for reproducibility
np.random.seed(42)
torch.manual_seed(42)
# Synthetic stock price data generation
prices = np.sin(np.arange(100) / 20.0) + np.random.normal(0, 0.1, 100) + 5
# Prepare the dataset
def create_inout_sequences(input_data, tw):
inout_seq = []
L = len(input_data)
for i in range(L-tw):
train_seq = input_data[i:i+tw]
train_label = input_data[i+tw:i+tw+1]
inout_seq.append((train_seq ,train_label))
return inout_seq
seq_length = 10 # Using 10 days of prices to predict the next day
sequences = create_inout_sequences(prices, seq_length)
sequences = [(torch.tensor(s, dtype=torch.float32), torch.tensor([t], dtype=torch.float32)) for s, t in sequences]
# Model definition
class StockPredictor(nn.Module):
def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
super(StockPredictor, self).__init__()
self.linear = nn.Linear(input_size * seq_length, hidden_layer_size)
self.linear2 = nn.Linear(hidden_layer_size, output_size)
def forward(self, input_seq):
input_seq = input_seq.view(-1, seq_length)
predictions = torch.relu(self.linear(input_seq))
predictions = self.linear2(predictions)
return predictions
# Model initialization
model = StockPredictor(input_size=1, hidden_layer_size=100, output_size=1)
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# Training the model
epochs = 150
for i in range(epochs):
for seq, labels in sequences:
optimizer.zero_grad()
y_pred = model(seq)
single_loss = loss_function(y_pred, labels)
single_loss.backward()
optimizer.step()
if i % 25 == 0:
print(f'epoch: {i:3} loss: {single_loss.item():10.8f}')
# Predicting the stock price
test_input = torch.tensor(prices[-seq_length:], dtype=torch.float32)
with torch.no_grad():
model.eval()
predicted_stock_price = model(test_input)
print(f'Predicted stock price for the next day: {predicted_stock_price.item():.2f}')
|