目录
yfinance包
LSTM进行预测
获取指定股票数据:
建模进行预测:
建立股票预测系统
结束:
yfinance包
import yfinance
yfinance
旨在通过提供一种可靠的、线程化的(threaded)、Pythonic的方式从Yahoo! finance下载历史市场数据。该库最初命名为fix-yahoo-finance
,但后来作者将其重命名为yfinance。
Ticker()
模块可以使我们能以一种更安全更Pythonic的方式获取金融市场数据,使用方法如下:
import yfinance as yf
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
msft = yf.Ticker("MSFT")
print(msft)
msft.info
msft.history(period="max")
# show actions (dividends, splits)
msft.actions
msft.dividends
msft.splits
def fetch_stock_data(se, stock_symbol):
"""fetch stock data"""
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()
if se == 'NSE': stock_symbol += ".NS"
return pdr.get_data_yahoo(stock_symbol, period="5y")
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
og_df = fetch_stock_data(se, stock_symbol)
todataframe = og_df.reset_index(inplace=False)
print("\n<----------------------数据集的信息---------------------->")
print(todataframe.info())
print("<-------------------------------------------------------------------->\n")
#dataframe creation
seriesdata = todataframe.sort_index(ascending=True, axis=0)
new_seriesdata = pd.DataFrame(index=range(0,len(todataframe)),columns=['Date','Close'])
for i in range(0,len(seriesdata)):
new_seriesdata['Date'][i] = seriesdata['Date'][i]
new_seriesdata['Close'][i] = seriesdata['Close'][i]
#setting the index again
new_seriesdata.index = new_seriesdata.Date
new_seriesdata.drop('Date', axis=1, inplace=True)
#creating train and test sets this comprises the entire data’s present in the dataset
myseriesdataset = new_seriesdata.values
totrain = myseriesdataset
#converting dataset into x_train and y_train
scalerdata = MinMaxScaler(feature_range=(0, 1))
scale_data = scalerdata.fit_transform(myseriesdataset)
x_totrain, y_totrain = [], []
length_of_totrain=len(totrain)
for i in range(60,length_of_totrain):
x_totrain.append(scale_data[i-60:i,0])
y_totrain.append(scale_data[i,0])
x_totrain, y_totrain = np.array(x_totrain), np.array(y_totrain)
x_totrain = np.reshape(x_totrain, (x_totrain.shape[0],x_totrain.shape[1],1))
#LSTM neural network
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(x_totrain.shape[1],1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adadelta')
lstm_model.fit(x_totrain, y_totrain, epochs=3, batch_size=1, verbose=2)
#predicting next data stock price
myinputs = new_seriesdata[len(new_seriesdata) - (100) - 60:].values
myinputs = myinputs.reshape(-1,1)
myinputs = scalerdata.transform(myinputs)
tostore_test_result = []
for i in range(60,myinputs.shape[0]):
tostore_test_result.append(myinputs[i-60:i,0])
tostore_test_result = np.array(tostore_test_result)
tostore_test_result = np.reshape(tostore_test_result,(tostore_test_result.shape[0],tostore_test_result.shape[1],1))
myclosing_priceresult = lstm_model.predict(tostore_test_result)
myclosing_priceresult = scalerdata.inverse_transform(myclosing_priceresult)
#Combining og and predicted dataset for end result.
datelist = pd.date_range(pd.datetime.now().date(), periods=101)[1:]
predicted_df = pd.DataFrame(myclosing_priceresult, columns=['Close'], index=datelist)
result_df = pd.concat([og_df, predicted_df])[['Close']]
result_df = result_df.reset_index(inplace=False)
result_df.columns = ['Date', 'Close']
#to print the info of the END RESULT dataset
print("\n<----------------------预测数据结果---------------------->")
print(result_df.info())
print("<------------------------------------------------------------------------>\n")
在系统首页,读取市场观察数据,此方式采用TradingView官网给出的代码进行实现。其JavaScript代码如下:
运行依赖环境:
python 3.6.x;django;pandas ;numpy ;tensorflow-cpu;keras 等
最后,采用django框架实现加载LSTM算法模型实现股票的预测。界面如下:
进入预测页面:
例如输入苹果公司股票进行预测 :
需要等待一段时间,因为系统会调用后端神经网络进行训练所获取的历史数据,获取的数据为苹果公司最近一段时间的开盘价、最高价、最低价、成交量等;设定的训练次数为3次,然后进行再预测。
预测界面如下:
可以查看进一个月,三个月等。当然时间越长预测的越不准确。
查看往后6个月的股票市场价格,此为gif动图,可查看相关操作:
此是深度学习项目的简单应用,练习和使用LSTM神经网络进行股票价格预测,LSTM模型具有较好的投资收益和较强的抗风险能力。如何进行股票的未来N天的价格预测。这就需要构造相应的输入输出样本,以训练模型。相关构造方法在本博客前几篇文章都有概述和源码讲解,项目完整源码加Q525894654。最后,采用django框架加载LSTM模型使其应用于具体应用,是将深度学习算法应用于生活的进一步探索。