|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense,LSTM
import matplotlib.pyplot as plt
df=web.DataReader('AAPL',data_source='yahoo',start='2012-01-01',end='2019-12-07')
data=df.filter(['Close'])
dataset=data.values#数据转换
training_data_len=math.ceil(len(dataset)*0.8)
#数据归一化,减小误差
scaler=MinMaxScaler(feature_range=(0,1))
scaled_data=scaler.fit_transform(dataset)
#训练样本为80
train_data=scaled_data[0:training_data_len,:]
x_train=[]
y_train=[]
for i in range(80,len(train_data)):
x_train.append(train_data[i-80:i,0])
y_train.append(train_data[i,0])
if i<=80:
print(x_train)
print(y_train)
print()
x_train,y_train=np.array(x_train),np.array(y_train)
#将x_train,y_train转换为三维数组
x_train=np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1))
#构建模型LSTM
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))
#编译模型
model.compile(optimizer='adam',loss='mean_squared_error')
#训练模型
model.fit(x_train,y_train,batch_size=1,epochs=1)
#评估模型
text_data=scaled_data[training_data_len-80:,:]
x_text=[]
y_text=dataset[training_data_len:,:]
for i in range(80,len(text_data)):
x_text.append(text_data[i-80:i,0])
x_text=np.array(x_text)
x_text=np.reshape(x_text,(x_text.shape[0],x_text.shape[1],1))
#得到预测值
predictions=model.predict(x_text)
predictions=scaler.inverse_transform(predictions)
#评价模型
rmse=np.sqrt(np.mean((predictions-y_text)**2))
print(rmse)
#图像
train=data[:training_data_len]
valid=data[training_data_len:]
valid['Predictions']=predictions
plt.figure(figsize=(17,9))
plt.title('Model')
plt.xlabel('Date',fontsize=17)
plt.ylabel('Closing Price USD($)',fontsize=17)
plt.plot(train['Close'])
plt.plot(valid[['Close','Predictions']])
plt.legend(['Train','Val','Predictions'],loc='lower right')
plt.show()
apple_quote=web.DataReader('AAPL',data_source='yahoo',start='2012-01-01',end='2019-12-07')
new_df=apple_quote.filter(['Close'])
last_80_days=new_df[-80:].values
last_80_days_scaled=scaler.transform(last_80_days)
X_text=[]
X_text.append(last_80_days)
X_text=np.array(X_text)
X_text=np.reshape(X_text,(X_text.shape[0],X_text.shape[1],1))
pred_price=model.predict(X_text)
pred_price=scaler.inverse_transform(pred_price)
print(pred_price)
大佬们,来帮忙改改这个 股票预测 代码。
改后功能:画出预测今后一段时间股票闭市价格趋势图 |
|