基于pytorch深度学习框架的股票预测代码
时间: 2023-05-26 14:05:55 浏览: 135
很抱歉,作为AI语言模型,我没有实际的库和框架的使用权限。在此提供一个基于pytorch的股票预测参考代码:
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import MinMaxScaler
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
#set seed
np.random.seed(0)
torch.manual_seed(0)
#read data
df = pd.read_csv('data.csv', index_col='Date', parse_dates=['Date'])
df = df.dropna()
data = df['Close'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(-1, 1))
data = scaler.fit_transform(data)
#Training and testing set
train_size = int(len(data) * 0.8)
test_size = len(data) - train_size
train_data, test_data = data[0:train_size, :], data[train_size:len(data), :]
# Convert to tensor
train_data_tensor = torch.FloatTensor(train_data).view(-1)
test_data_tensor = torch.FloatTensor(test_data).view(-1)
#window size
window_size = 30
#Convert data to input/output
def create_inout_sequences(input_data, seq_length):
inout_seq = []
L = len(input_data)
for i in range(L - seq_length):
train_seq = input_data[i:i+seq_length]
train_label = input_data[i+seq_length:i+seq_length+1]
inout_seq.append((train_seq, train_label))
return inout_seq
train_inout_seq = create_inout_sequences(train_data_tensor, window_size)
test_inout_seq = create_inout_sequences(test_data_tensor, window_size)
#Define LSTM Model
class LSTM(nn.Module):
def __init__(self, input_size=1, hidden_layer_size=50, output_size=1):
super().__init__()
self.hidden_layer_size = hidden_layer_size
self.lstm = nn.LSTM(input_size, hidden_layer_size)
self.linear = nn.Linear(hidden_layer_size, output_size)
def forward(self, input_seq):
lstm_out, _ = self.lstm(input_seq.view(len(input_seq), 1, -1))
predictions = self.linear(lstm_out.view(len(input_seq), -1))
return predictions[-1]
model = LSTM()
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
#Train Model
epochs = 100
model.train()
for i in range(epochs):
for seq, labels in train_inout_seq:
optimizer.zero_grad()
predicted = model(seq)
loss = loss_function(predicted, labels)
loss.backward()
optimizer.step()
if i%25 == 1:
print(f'epoch: {i:3} loss: {loss.item():10.8f}')
#Test Model
model.eval()
test_inputs = test_data_tensor[:window_size].tolist()
predicted_prices = []
for i in range(len(test_data_tensor)-window_size):
seq = torch.FloatTensor(test_inputs[-window_size:])
with torch.no_grad():
model.eval()
predicted_prices.append(model(seq).item())
test_inputs.append(predicted_prices[-1])
#Predictions back to actual scale
actual_predictions = scaler.inverse_transform(np.array(predicted_prices).reshape(-1, 1))
#Plot Predictions
fig = plt.figure(dpi=200, figsize=(5, 3))
plt.plot(df.index[train_size+window_size:], df['Close'][train_size+window_size:], label='Actual')
plt.plot(df.index[train_size+window_size:], actual_predictions, label='Prediction')
plt.legend()
plt.show()
阅读全文