听课笔记:使用RNN预测股价

课程链接:人工智能实践:Tensorflow笔记_北京大学_中国大学MOOC(慕课) (icourse163.org)

import numpy as np
from tensorflow.keras.layers import Dense,SimpleRNN,Embedding,Dropout
import matplotlib.pyplot as plt
import os
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error,mean_absolute_error
import math
import tensorflow as tf

导入包

import tushare as ts
import matplotlib.pyplot as plt
df1=ts.get_k_data('600519',ktype='D',start='2020-09-19',
                  end='2024-09-19')
datapath1='./SH600519.csv'
df1.to_csv(datapath1)

导入数据

maotai=pd.read_csv('./SH600519.csv')

读入数据

training_set=maotai.iloc[0:968-300,2:3].values
# 968天开盘价
test_set=maotai.iloc[968-300:,2:3].values
sc=MinMaxScaler(feature_range=(0,1))
training_set_scaled=sc.fit_transform(training_set)
# fit_transform方法拟合数据并计算每个特征(即每列分别计算)的最小值和最大值,
# 然后将数据缩放到指定的范围(在这个例子中是[0, 1])
test_set=sc.transform(test_set)
x_train=[]
y_train=[]
x_test=[]
y_test=[]
for i in range(60,len(training_set_scaled)):
    x_train.append(training_set_scaled[i-60:i,0])
    y_train.append(training_set_scaled[i,0])
np.random.seed(7)
np.random.shuffle(x_train)
np.random.seed(7)
np.random.shuffle(y_train)
np.random.seed(7)
x_train,y_train=np.array(x_train),np.array(y_train)
x_train=np.reshape(x_train,(x_train.shape[0],60,1))
# 送入样本数,循环核时间展开步数,每个时间步数输入特征个数
for i in range(60,len(test_set)):
    x_test.append(test_set[i-60:i,0])
    y_test.append(test_set[i,0])
x_test,y_test=np.array(x_test),np.array(y_test)
x_test=np.reshape(x_test,(x_test.shape[0],60,1))

清洗数据

model=tf.keras.Sequential([
    SimpleRNN(80,return_sequences=True),
    Dropout(0.2),
    SimpleRNN(100),
    Dropout(0.2),
    Dense(1)
])
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
              loss='mean_squared_error')
history=model.fit(x_train,y_train,batch_size=64,epochs=50,
                  validation_data=(x_test,y_test),
                  validation_freq=1)

搭建并拟合模型

model.summary()
val_loss=history.history['val_loss']
loss=history.history['loss']
plt.plot(loss,label='Training loss')
plt.plot(val_loss,label='validation loss')
plt.title('training and validation loss')
plt.legend()
plt.show()

predicted_stock_price=model.predict(x_test)
predicted_stock_price=sc.inverse_transform(predicted_stock_price)
# 反归一化
real_stock_price=sc.inverse_transform(test_set[60:])
plt.plot(real_stock_price,color='red',label='maotai stock price')
plt.plot(predicted_stock_price,color='blue',label='predicted stock price')
plt.title('maotai stock price prediction')
plt.xlabel('time')
plt.ylabel('maotai stock price')
plt.legend()
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值