当前位置:   article > 正文

LSTM 股价预测pytorch_data = raw_data.loc[:, ['close']]

data = raw_data.loc[:, ['close']]

1.查看数据

 

2. 结果

        

 

 

 

3.代码

  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # In[1]:
  4. get_ipython().run_line_magic('config', 'Completer.use_jedi = False')
  5. # In[2]:
  6. import torch
  7. import pandas as pd
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. import torch.nn as nn
  11. from torch.utils.data import Dataset,DataLoader
  12. from sklearn.preprocessing import MinMaxScaler
  13. # In[3]:
  14. filePath = './000001SH_index.csv'
  15. seq_len = 8
  16. batch_size = 64
  17. input_size = 1
  18. hidden_size = 8
  19. num_layers = 1
  20. # In[4]:
  21. sc = MinMaxScaler(feature_range=(-1,1))
  22. # In[5]:
  23. raw_data = pd.read_csv(filePath)
  24. data = raw_data.loc[:,['close']]
  25. data = pd.DataFrame(sc.fit_transform(data))
  26. X = []
  27. Y = []
  28. for i in range(data.shape[0]-seq_len):
  29. X.append(np.array(data.iloc[i:i+seq_len,:].values,dtype=np.float32))
  30. Y.append(np.array(data.iloc[i+seq_len,0],dtype=np.float32))
  31. x_train,x_test = X[:int(len(Y)*0.9)],X[int(len(Y)*0.9):]
  32. y_train,y_test = Y[:int(len(Y)*0.9)],Y[int(len(Y)*0.9):]
  33. print(np.array(x_test).shape)
  34. print(np.array(x_train).shape)
  35. # In[6]:
  36. raw_data.close[:int(len(Y)*0.9)].plot(figsize=(16,4))
  37. raw_data.close[int(len(Y)*0.9):].plot(figsize=(16,4))
  38. plt.show()
  39. # In[7]:
  40. class MyDataSet(Dataset):
  41. def __init__(self,X,Y):
  42. super().__init__()
  43. self.xx,self.yy = X,Y
  44. def __getitem__(self,index):
  45. return self.xx[index],self.yy[index]
  46. def __len__(self):
  47. return len(self.yy)
  48. trainDataSet = MyDataSet(x_train,y_train)
  49. testDataSet = MyDataSet(x_test,y_test)
  50. trainLoader = DataLoader(dataset=trainDataSet, batch_size=batch_size,shuffle=True)
  51. testLoader = DataLoader(dataset=testDataSet, batch_size=batch_size,shuffle=True)
  52. # In[8]:
  53. class LSTM(nn.Module):
  54. def __init__(self,input_size,hidden_size,num_layers):
  55. super().__init__()
  56. self.input_size = input_size
  57. self.hidden_size = hidden_size
  58. self.num_layers = num_layers
  59. self.lstm = nn.LSTM(input_size = self.input_size,hidden_size = self.hidden_size,num_layers=self.num_layers,batch_first=True)
  60. self.liner = nn.Linear(in_features=self.hidden_size,out_features=1)
  61. def forward(self, x):
  62. _, (hidden, cell) = self.lstm(x)
  63. out = self.liner(hidden)
  64. return out.reshape(-1,1)
  65. model = LSTM(input_size,hidden_size,num_layers)
  66. # In[9]:
  67. optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
  68. loss_function = nn.MSELoss()
  69. # In[10]:
  70. epochs = 200
  71. """
  72. data_x batch_size, seq_size, input_size=1
  73. data_y batch_size, 1
  74. """
  75. for epoch in range(epochs):
  76. for i,(data_x,data_y) in enumerate(trainLoader):
  77. pred = model(data_x)
  78. pred = pred.reshape(-1)
  79. loss = loss_function(pred, data_y)
  80. optimizer.zero_grad()
  81. loss.backward()
  82. optimizer.step()
  83. if epoch % 10 ==0:
  84. print("epoch:{},loss========{}".format(epoch+10,loss.item()))
  85. # In[11]:
  86. y_pred = []
  87. y_label = []
  88. with torch.no_grad():
  89. pred = model(torch.from_numpy(np.array(X)))
  90. y_pred.extend(sc.inverse_transform(pred))
  91. y_label = np.array(Y).reshape(-1,1)
  92. y_label = sc.inverse_transform(y_label)
  93. plt.figure(figsize=(16,4))
  94. plt.plot(y_label)
  95. plt.plot(y_pred)
  96. plt.show()
  97. plt.figure(figsize=(16,4))
  98. plt.plot(y_label[0:100],label='raw data')
  99. plt.plot(y_pred[0:100], label='pred data')
  100. plt.legend()
  101. plt.show()
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/168013?site
推荐阅读
相关标签
  

闽ICP备14008679号