使用机器学习建立股票走势预测程序


股票指标结合机器学习能否预测股票的价格走势?
在本文中,我们会尝试创建一个模型,该模型使用机器学习、技术指标和 python ,根据股票数据确定资产价格第二天上涨还是下跌!虽然试图预测股市动能方向非常困难,但让我们试一试。
什么是股市技术指标?
股票市场技术指标是用于解释股票或金融数据趋势的信号,以试图预测市场内的未来价格走势。股票指标帮助投资者做出交易决策。
技术指标的类型
1
简单移动平均线 (SMA)
简单移动平均线是一种技术趋势指标,可以帮助确定资产价格是否会继续,或者是否会逆转牛市或熊市趋势。一个简单的移动平均线可以增强为指数移动平均线 (EMA),它在最近的价格行为上具有更大的权重。
2
指数移动平均线 (EMA)
EMA 是一种移动平均线,它在最近的数据点上具有更大的权重和重要性。与所有移动平均线一样,此技术趋势指标用于根据与历史平均线的交叉和背离产生买入和卖出信号。
3
移动平均收敛散度 (MACD)
移动平均收敛散度 (MACD) 是一种趋势跟踪动量指标,显示证券价格的两个移动平均线之间的关系。MACD 的计算方法是从 12 周期 EMA 中减去 26 周期指数移动平均线 (EMA)。
4
相对强弱指数 (RSI)
相对强弱指数 (RSI) 是用于技术分析的动量指标,用于衡量近期价格变化的幅度,以评估股票或其他资产价格的超买或超卖状况。
以上这些是我们将在本文中使用 python 编程的指标。
什么是机器学习?
机器学习是人工智能的一个子集,它是让计算机在没有明确编程的情况下采取行动的科学,并且主要是统计数据。机器学习用于查找数据中的模式,然后您可以对其进行预测。它可以细分为监督学习和无监督学习或两者的混合。
机器学习是如何工作的
开始
首先,这里创建一个关于程序的描述,以便大家可以简单地阅读描述并知道程序应该做什么或程序是关于什么的。
#Description: Use stock indicators with machine learning to try to predict the direction of a stock price:
#1 means the stock price goes up
#0 means the stock price goes down or stays the same
导入我们在整个程序中需要的库。
#Import the libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
加载数据并将其存储到变量中。这里我们是用Google Collab写这个程序,所以我们需要使用Google的库来上传数据集。
#Load the data set
from google.colab import files
files.upload()
#Store the data into the data frame
df = pd.read_csv('GOOG_Stock.csv')
#show the data frame
df
创建和计算指标
创建函数来计算简单移动平均线 (SMA) 和指数移动平均线 (EMA)。
#Create functions to calculate the SMA, & the EMA
#Create the Simple Moving Average Indicator
#Typical time periods for moving averages are 15, 20,& 30
#Create the Simple Moving Average Indicator
def SMA(data, period=30, column='Close'):
return data[column].rolling(window=period).mean()
#Create the Exponential Moving Average Indicator
def EMA(data, period=20, column='Close'):
return data[column].ewm(span=period, adjust=False).mean()
接下来,创建一个函数来计算移动平均收敛散度 (MACD)。
#Create a function to calculate the Moving Average Convergence/Divergence (MACD)
def MACD(data, period_long=26, period_short=12, period_signal=9, column='Close'):
#Calculate the Short Term Exponential Moving Average ShortEMA = EMA(data, period_short, column=column) #AKA Fast moving average
#Calculate the Long Term Exponential Moving Average
LongEMA = EMA(data, period_long, column=column) #AKA Slow moving average
#Calculate the Moving Average Convergence / Divergence (MACD)
data['MACD'] = ShortEMA - LongEMA
#Calcualte the signal line
data['Signal_Line'] = EMA(data, period_signal, column='MACD')#data['MACD'].ewm(span=period_signal, adjust=False).mean()
return data
最后但并非最不重要的一点是创建一个函数来计算相对强度指数 (RSI)。
#Create a function to calculate the Relative Strength Index (RSI)
def RSI(data, period = 14, column = 'Close'):
delta = data[column].diff(1) #Use diff() function to find the discrete difference over the column axis with period value equal to 1
delta = delta.dropna() # or delta[1:]
up = delta.copy() #Make a copy of this object’s indices and data
down = delta.copy() #Make a copy of this object’s indices and data
up[up < 0] = 0
down[down > 0] = 0
data['up'] = up
data['down'] = down
AVG_Gain = SMA(data, period, column='up')#up.rolling(window=period).mean()
AVG_Loss = abs(SMA(data, period, column='down'))#abs(down.rolling(window=period).mean())
RS = AVG_Gain / AVG_Loss
RSI = 100.0 - (100.0/ (1.0 + RS))
data['RSI'] = RSI
return data
为机器学习准备数据集将指标添加到数据集中并显示数据。
#Add the indicators to the data set
#Creating the data set
MACD(df)
RSI(df)
df['SMA'] = SMA(df)
df['EMA'] = EMA(df)
#Show the data
df
创建目标
#Create the target column
df['Target'] = np.where(df['Close'].shift(-1) > df['Close'], 1, 0) # if tomorrows price is greater than todays price put 1 else put 0
#Remove the date column
#remove_list = ['Date']
#df = df.drop(columns=remove_list)
#Show the datadf
删除前 29 行数据或日期。
#Remove the first 29 days of data
df = df[29:]
#Show the data set
df
将数据集拆分为特征/独立数据集 (X) 和目标/依赖数据集 (Y)。
#Split the data set into a feature or independent data set (X) and a target or dependent data set (Y)
keep_columns = ['Close', 'MACD', 'Signal_Line', 'RSI', 'SMA', 'EMA']
X = df[keep_columns].values
Y = df['Target'].values
再次拆分数据,但这次分为 80% 的训练数据集和 20% 的测试数据集。
#Split the data again but this time into 80% training and 20% testing data sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2)
创建和训练机器学习模型
创建和训练模型。
#Create and train the model
tree = DecisionTreeClassifier().fit(X_train, Y_train)
验证模型在训练数据上的表现。
#Check how well the SVC Model on training data
print(tree.score(X_train, Y_train))
验证模型在测试数据上的表现。
#Check the SVC Model on the test data set
print(tree.score(X_test, Y_test))
获取分类报告以查看模型的执行情况。
from sklearn.metrics import classification_report
print(classification_report(Y_test, rbf_svc_prediction))
看起来这个模型给出了大约 68.18% 的准确度得分。这个模型比猜测或抛硬币做得更好,这是令人鼓舞的,但在这组小数据上的准确度为 68.18%,模型显然还没有为现实世界的交易做好准备。我们可以通过使用其他指标、更多数据、参数调整和更多分析来改进模型。
如果你有兴趣阅读有关机器学习的更多信息以立即开始解决问题和示例,那么强烈建议您查看使用 《Scikit-Learn 和 TensorFlow 进行机器学习实践:构建智能系统的概念、工具和技术》。这是一本帮助初学者学习如何编写机器学习程序和理解机器学习概念的好书。
更多“机器学习”相关内容
-
Spark机器学习.pdf
向AI转型的程序员都关注了这个号👇👇👇人工智能大数据与深度学习 公众号:datayxPDF 获取方式关注微信公众号 datay
-
本科生如何自学机器学习?
点击上方“AI遇见机器学习”,选择“星标”公众号重磅干货,第一时间送达链接:https://www.zhihu.com/ques
-
机器学习的基础图表!
机器学习是一种重在寻找数据中的模式并使用这些模式来做出预测的研究和算法的门类。
-
近期神奇机器学习应用大赏
众所周知,Arxiv本质上是一个预注册研究想法的网站,优点是文章更新又多又快,缺点是文章质量良莠不齐。
-
机器学习的前沿发展与应用分享
疫情爆发近四个月的时间,我们的生活习惯也在不知不觉发生了变化。从出入都要出示的健康码,到居家隔离的线上购物、办公等等。互联网已经
推荐阅读
IT科技▪2021年度十佳创作者