机器学习项目实战系列机器学习预测股价 目录机器学习项目实战系列机器学习预测股价 一、概述 二、分析数据 1。导入 2。数据导入 3。分析股票尾市数据 4。构建模型 5。测试模型 6。展示预测结果一、概述 根据上一年的数据预测股票市场的未来价格 数据集:股票价格预测数据集:TwoSigma:UsingNewstoPredictStockMovementsKaggle 源代码:股票价格预测项目:Justamoment。。。 二、分析数据1。导入importpandasaspdimportnumpyasnpimportmatplotlib。pyplotaspltmatplotlibinlinefrommatplotlib。pylabimportrcParamsrcParams〔figure。figsize〕20,10fromkeras。modelsimportSequentialfromkeras。layersimportLSTM,Dropout,Densefromsklearn。preprocessingimportMinMaxScaler2。数据导入 3。分析股票尾市数据df〔Date〕pd。todatetime(df。Date,formatYmd)df。indexdf〔Date〕plt。figure(figsize(16,8))plt。plot(df〔Close〕,labelClosePricehistory) 4。构建模型importmathCreateanewdataframewithonlytheClosecolumndatadf。filter(〔Close〕)Convertthedataframetoanumpyarraydatasetdata。valuesGetthenumberofrowstotrainthemodeltrainingdatalenmath。ceil(len(dataset)。8)trainingdatalen ScalethedatascalerMinMaxScaler(featurerange(0,1))scaleddatascaler。fittransform(dataset)scaleddata CreatethetrainingdatasetCreatethescaledtrainingdatasettraindatascaleddata〔0:trainingdatalen,:〕Splitthedataintoxtrainandytraindatasetsxtrain〔〕ytrain〔〕foriinrange(60,len(traindata)):xtrain。append(traindata〔i60:i,0〕)ytrain。append(traindata〔i,0〕)ifi60:print(xtrain)print(ytrain)print() BuildtheLSTMmodelmodelSequential()model。add(LSTM(50,returnsequencesTrue,inputshape(xtrain。shape〔1〕,1)))model。add(LSTM(50,returnsequencesFalse))model。add(Dense(25))model。add(Dense(1)) 5。测试模型CreatethetestingdatasetCreateanewarraycontainingscaledvaluesfromindex1543to2003testdatascaleddata〔trainingdatalen60:,:〕Createthedatasetsxtestandytestxtest〔〕ytestdataset〔trainingdatalen:,:〕foriinrange(60,len(testdata)):xtest。append(testdata〔i60:i,0〕) Getthemodelspredictedpricevaluespredictionsmodel。predict(xtest)predictionsscaler。inversetransform(predictions) 6。展示预测结果Plotthedatatraindata〔:trainingdatalen〕validdata〔trainingdatalen:〕valid〔Predictions〕predictionsVisualizethedataplt。figure(figsize(16,8))plt。title(Model)plt。xlabel(Date,fontsize18)plt。ylabel(ClosePriseUSD(),fontsize18)plt。plot(train〔Close〕)plt。plot(valid〔〔Close,Predictions〕〕)plt。legend(〔Train,Val,Predictions〕,loclowerright)plt。show()