当前位置:网站首页>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()

边栏推荐
- 108页(4万字)未来公寓智能化设计平台项目方案建议书2022版
- 我想问一下兴业证券怎么开户?通过链接办理股票开户安全吗
- EVM Brief
- 2022年起重机司机(限桥式起重机)考试题库模拟考试平台操作
- Use of file class filenamefilter & filefilter in io
- 2022R1快开门式压力容器操作考题及答案
- A plug-in framework for implementing registration free and login verification with hook technology
- 扎克伯格上手演示四款VR头显原型机,Meta透露元宇宙「家底」
- 移动安全工具-jarsigner
- Scala trait inheritance class
猜你喜欢

Preliminary understanding of qtoolbutton

I 刷题 I — 复制带随机指针的链表
![[redis realizes seckill service ②] solution to oversold problem](/img/b6/3073def06a56565894c28e49767e3e.png)
[redis realizes seckill service ②] solution to oversold problem

51 single chip microcomputer multi computer communication

Deploy a production cluster using Loki microservice pattern

Custom control - round dot progress bar (imitating one key acceleration in security guard)

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

丹麦技术大学首创将量子计算应用于能源系统潮流建模

108 pages (40000 words) proposal for future apartment intelligent design platform project (version 2022)

LLVM TargetPassConfig
随机推荐
Which securities company should I choose to open an account online? Is it safe to open an account online?
戴尔为何一直拒绝将商用本的超薄推向极致?
程序员:是花光积蓄在深圳买房?还是回到长沙过“富余”生活?
2022r1 quick opening pressure vessel operation test questions and answers
Danish Technical University pioneered the application of quantum computing to power flow modeling of energy system
2022R1快开门式压力容器操作考题及答案
Super detailed description and derivation of convolution and deconvolution (deconvolution is also called transpose convolution and fractional step convolution)
51 single chip microcomputer multi computer communication
[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS
2022熔化焊接与热切割复训题库模拟考试平台操作
How about compass stock trading software? Is it safe?
QT(36)-rapidjson解析嵌套的json
图片旋转移动缩放渐变
我想问一下兴业证券怎么开户?通过链接办理股票开户安全吗
I'd like to ask how to open an account at industrial securities? Is it safe to open a stock account through the link
VB learning notes
【无标题】
Convolution and transpose convolution
Programmer: did you spend all your savings to buy a house in Shenzhen? Or return to Changsha to live a "surplus" life?
Distinguish between i++ and ++i seconds