当前位置:网站首页>Deep learning LSTM model for stock analysis and prediction
Deep learning LSTM model for stock analysis and prediction
2022-06-25 01:12:00 【A Xiaobai who likes Technology】
Project description :
This program uses the long-term and short-term memory model in the cyclic neural network (LSTM) With Apple The company used to 60 To predict the closing price
LSTM The model is equivalent to RNN An improved version of the model
RNN: Want to remember all the information , Whether it's useful information or useless information ( Heavy burden of memory )
LSTM: Design a memory cell , It has the function of selective memory , You can choose to remember important information , Filter out noise information , Lighten the burden of memory
About LSTM The principle of this does not need to be repeated , Recommended viewing B Stop video .
Use Anaconda3 Medium Jupyter To write the ( Personal recommendation is very easy to use )
Environment building :
Anaconda install
Anaconda Add a new library

Call directly after entering pip that will do 
pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple --user
hold tensorflow Change to the package name you want to import
Project steps :
1、 Import library first :
# Import library
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras. layers import Dense,LSTM
import matplotlib.pyplot as plt
2、 Get stock quotes :
# Solve the font display exception bug
sns.set_style("whitegrid", {
"font.sans-serif": ['KaiTi', 'Arial']})
# Get stock quotes
df=web.DataReader("AAPL",data_source='yahoo',start='2013-01-01',end='2022-02-15')
# Display the data
df
The display data is as follows : 
3、 Plot the historical closing price of the stock :
# Visualize closing price history
plt.figure(figsize=(16,8))
plt.title(' Historical price ')
plt.plot(df['Close'])
plt.xlabel(' date ',fontsize=18)
plt.ylabel(' Closing price $ ($)',fontsize=18)
plt.show()

4、 Create one that only “Close” Data set for column
# Create one that only “Close” Data set for column
data = df.filter(['Close'])
## Convert dataset to numpy Array
dataset = data.values
5、 Get the number of rows of the training model
training_data_len = math.ceil( len (dataset)*.8)
training_data_len

6、 Data normalization
# Data normalization
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
scaled_data

7、 Create training data sets
# Data normalization
# Create training data sets
# Create a scaled training dataset train_data
train_data = scaled_data[0:training_data_len,:]
# Split data into x_train and y_train Data sets
x_train = []
y_train = []
for i in range(60,len(train_data)):
x_train.append(train_data[i-60:i,0])
y_train.append(train_data[i,0])
if i <= 61:
print(x_train)
print(y_train)
8、 take x_train and y_train Convert to numpy Array
x_train,y_train = np.array(x_train),np.array(y_train)
9、 Reshaped data
x_train = np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1))
10、 establish LSTM Model
model = Sequential()
model.add(LSTM(50,return_sequences=True, input_shape=(x_train.shape[1],1)))
model.add(LSTM(50,return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
11、 Compile model
model.compile(optimizer='adam',loss='mean_squared_error')
12、 Training models
model.fit(x_train,y_train,batch_size=1,epochs=1)
13、 Create test data sets
# Create a new array , Include from index 1978 To 2438 Zoom value of
test_data = scaled_data[training_data_len - 60:,:]
# Create a dataset x test and y_test
x_test = []
y_test = dataset[training_data_len:,:]
for i in range(60,len(test_data)):
x_test.append(test_data[i-60:i,0])
# Convert data to numpy Array
x_test = np.array(x_test)
# Reshaped data
x_test = np.reshape(x_test,(x_test.shape[0],x_test.shape[1],1))
14、 Get the predicted price value of the model
# Get the predicted price value of the model
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
15、 Calculate the root mean square error (RMSE)
rmse = np.sqrt(np.mean( predictions - y_test)**2 )
16、 Charting
train = data[:training_data_len]
valid = data[training_data_len:]
valid['Predictions'] = predictions
# Visualization data
plt.figure(figsize=(16,8))
plt.title('LSTM Model to predict ')
plt.xlabel(' date ', fontsize=18)
plt.ylabel(' Closing price $ ($)', fontsize=18)
plt.plot(train['Close'])
plt.plot(valid[['Close','Predictions']])
plt.legend([" Model training value ",' True value ',' Predictive value '],loc='lower right')
plt.show()

边栏推荐
- 移动安全工具-dex2jar
- 使用 Loki 微服务模式部署生产集群
- Scala adapter pattern
- Mysql database Chapter 1 Summary
- Scala IO read by line
- Scala trait construction mechanism
- Text border format and text block of rich text
- Go language operators (under Lesson 8)
- Use of file class filenamefilter & filefilter in io
- Leetcode 1248. 统计「优美子数组」(害,突然发现只会暴力枚举了)
猜你喜欢

2022年起重机司机(限桥式起重机)考试题库模拟考试平台操作

Thermodynamic diagram display correlation matrix

The basic principle and application of iterator and enhanced for

2022 crane driver (limited to bridge crane) examination question bank simulated examination platform operation

Text editor for QT project practice - Episode 10

利用 Redis 的 sorted set 做每周热评的功能

QT(35)-操作EXCEL-QXlsx-QAxObject

2022 melting welding and thermal cutting recurrent training question bank simulated examination platform operation

2022安全员-C证考试模拟100题及在线模拟考试

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
随机推荐
Custom control - round dot progress bar (imitating one key acceleration in security guard)
Redis + Lua implementation of distributed interface current limiting
Scala sample object
移动安全工具-dex2jar
Rich text tables, lists, pictures
EVM Brief
51单片机多机通信
ImageView展示网络图片
用手机在同花顺上开户靠谱吗?这样炒股有没有什么安全隐患
卷积与转置卷积
Mobile security tool jar
Transform BeanUtils to achieve list data copy gracefully
Scala trait construction mechanism
Super detailed description and derivation of convolution and deconvolution (deconvolution is also called transpose convolution and fractional step convolution)
Première application de l'informatique quantique à la modélisation des flux de puissance dans les systèmes énergétiques à l'Université technique danoise
戴尔为何一直拒绝将商用本的超薄推向极致?
Scala IO read by line
Using tcp/udp tools to debug the yeelight ribbon
2022 melting welding and thermal cutting recurrent training question bank simulated examination platform operation
汇编语言(4)函数传参