【阿旭机器学习实战】【31】股票价格预测案例--线性回归

【阿旭机器学习实战】系列文章主要介绍机器学习的各种算法模型及其实战案例,欢迎点赞,关注共同学习交流。

注:本文模型结果不好,仅做学习参考使用,提供思路。了解数据处理思路,训练模型和预测数值的过程。

1. 读取数据

import numpy as np # 数学计算
import pandas as pd # 数据处理
import matplotlib.pyplot as plt
from datetime import datetime as dt

关注公众号:阿旭算法与机器学习,回复:“ML31”即可获取本文数据集、源码与项目文档,欢迎共同学习交流

df = pd.read_csv('./000001.csv') 
print(np.shape(df))
df.head()
(611, 14)
dateopenhighcloselowvolumeprice_changep_changema5ma10ma20v_ma5v_ma10v_ma20
02019-05-3012.3212.3812.2212.11646284.62-0.18-1.4512.36612.39012.579747470.29739308.42953969.39
12019-05-2912.3612.5912.4012.26666411.50-0.09-0.7212.38012.45312.673751584.45738170.10973189.95
22019-05-2812.3112.5512.4912.26880703.120.120.9712.38012.50512.742719548.29781927.80990340.43
32019-05-2712.2112.4212.3711.931048426.000.020.1612.39412.50512.824689649.77812117.301001879.10
42019-05-2412.3512.4512.3512.31495526.190.060.4912.39612.49812.928637251.61781466.471046943.98

股票数据的特征

  • date:日期
  • open:开盘价
  • high:最高价
  • close:收盘价
  • low:最低价
  • volume:成交量
  • price_change:价格变动
  • p_change:涨跌幅
  • ma5:5日均价
  • ma10:10日均价
  • ma20:20日均价
  • v_ma5:5日均量
  • v_ma10:10日均量
  • v_ma20:20日均量
# 将每一个数据的键值的类型从字符串转为日期
df['date'] = pd.to_datetime(df['date'])
# 将日期变为索引
df = df.set_index('date')
# 按照时间升序排列
df.sort_values(by=['date'], inplace=True, ascending=True)
df.tail()
openhighcloselowvolumeprice_changep_changema5ma10ma20v_ma5v_ma10v_ma20
date
2019-05-2412.3512.4512.3512.31495526.190.060.4912.39612.49812.928637251.61781466.471046943.98
2019-05-2712.2112.4212.3711.931048426.000.020.1612.39412.50512.824689649.77812117.301001879.10
2019-05-2812.3112.5512.4912.26880703.120.120.9712.38012.50512.742719548.29781927.80990340.43
2019-05-2912.3612.5912.4012.26666411.50-0.09-0.7212.38012.45312.673751584.45738170.10973189.95
2019-05-3012.3212.3812.2212.11646284.62-0.18-1.4512.36612.39012.579747470.29739308.42953969.39
# 检测是否有缺失数据 NaNs
df.dropna(axis=0 , inplace=True)
df.isna().sum()
open            0
high            0
close           0
low             0
volume          0
price_change    0
p_change        0
ma5             0
ma10            0
ma20            0
v_ma5           0
v_ma10          0
v_ma20          0
dtype: int64

K线图绘制

Min_date = df.index.min()
Max_date = df.index.max()
print ("First date is",Min_date)
print ("Last date is",Max_date)
print (Max_date - Min_date)
First date is 2016-11-29 00:00:00
Last date is 2019-05-30 00:00:00
912 days 00:00:00
from plotly import tools
from plotly.graph_objs import *
from plotly.offline import init_notebook_mode, iplot, iplot_mpl
init_notebook_mode()
import chart_studio.plotly as py
import plotly.graph_objs as go

trace = go.Ohlc(x=df.index, open=df['open'], high=df['high'], low=df['low'], close=df['close'])
data = [trace]
iplot(data, filename='simple_ohlc')

在这里插入图片描述

2.构建回归模型

from sklearn.linear_model import LinearRegression
from sklearn import preprocessing
# 创建标签数据:即预测值, 根据当前的数据预测5天以后的收盘价
num = 5 # 预测5天后的情况
df['label'] = df['close'].shift(-num) # 预测值,将5天后的收盘价当作当前样本的标签
                                     
print(df.shape)
(611, 14)
# 丢弃 'label', 'price_change', 'p_change', 不需要它们做预测
Data = df.drop(['label', 'price_change', 'p_change'],axis=1)
Data.tail()
openhighcloselowvolumema5ma10ma20v_ma5v_ma10v_ma20
date
2019-05-2412.3512.4512.3512.31495526.1912.39612.49812.928637251.61781466.471046943.98
2019-05-2712.2112.4212.3711.931048426.0012.39412.50512.824689649.77812117.301001879.10
2019-05-2812.3112.5512.4912.26880703.1212.38012.50512.742719548.29781927.80990340.43
2019-05-2912.3612.5912.4012.26666411.5012.38012.45312.673751584.45738170.10973189.95
2019-05-3012.3212.3812.2212.11646284.6212.36612.39012.579747470.29739308.42953969.39
X = Data.values
# 去掉最后5行,因为没有Y的值
X = X[:-num]
# 将特征进行归一化
X = preprocessing.scale(X)
# 去掉标签为null的最后5行
df.dropna(inplace=True)
Target = df.label
y = Target.values

print(np.shape(X), np.shape(y))
(606, 11) (606,)
# 将数据分为训练数据和测试数据
X_train, y_train = X[0:550, :], y[0:550]
X_test, y_test = X[550:, -51:], y[550:606]
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
(550, 11)
(550,)
(56, 11)
(56,)
lr = LinearRegression()
lr.fit(X_train, y_train)
lr.score(X_test, y_test) # 使用绝对系数 R^2 评估模型
0.04930040648385525
# 做预测 :取最后5行数据,预测5天后的股票价格
X_Predict = X[-num:]
Forecast = lr.predict(X_Predict)
print(Forecast)
print(y[-num:])
[12.5019651  12.45069629 12.56248765 12.3172638  12.27070154]
[12.35 12.37 12.49 12.4  12.22]
# 查看模型的各个特征参数的系数值
for idx, col_name in enumerate(['open', 'high', 'close', 'low', 'volume', 'ma5', 'ma10', 'ma20', 'v_ma5', 'v_ma10', 'v_ma20']):
    print("The coefficient for {} is {}".format(col_name, lr.coef_[idx]))
The coefficient for open is -0.7623399996475224
The coefficient for high is 0.8321435171405448
The coefficient for close is 0.24463705375238926
The coefficient for low is 1.091415550493547
The coefficient for volume is 0.0043807937569128675
The coefficient for ma5 is -0.30717535019465575
The coefficient for ma10 is 0.1935431079947582
The coefficient for ma20 is 0.24902077484698157
The coefficient for v_ma5 is 0.17472336466033722
The coefficient for v_ma10 is 0.08873934447969857
The coefficient for v_ma20 is -0.27910702694420775

3.绘制预测结果

# 预测 2019-05-13 到 2019-05-17 , 一共 5 天的收盘价 
trange = pd.date_range('2019-05-13', periods=num, freq='d')
trange
DatetimeIndex(['2019-05-13', '2019-05-14', '2019-05-15', '2019-05-16',
               '2019-05-17'],
              dtype='datetime64[ns]', freq='D')
# 产生预测值dataframe
Predict_df = pd.DataFrame(Forecast, index=trange)
Predict_df.columns = ['forecast']
Predict_df
forecast
2019-05-1312.501965
2019-05-1412.450696
2019-05-1512.562488
2019-05-1612.317264
2019-05-1712.270702
# 将预测值添加到原始dataframe
df = pd.read_csv('./000001.csv') 
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
# 按照时间升序排列
df.sort_values(by=['date'], inplace=True, ascending=True)
df_concat = pd.concat([df, Predict_df], axis=1)

df_concat = df_concat[df_concat.index.isin(Predict_df.index)]
df_concat.tail(num)
openhighcloselowvolumeprice_changep_changema5ma10ma20v_ma5v_ma10v_ma20forecast
2019-05-1312.3312.5412.3012.23741917.75-0.38-3.0012.53813.14313.6371107915.511191640.891211461.6112.501965
2019-05-1412.2012.7512.4912.161182598.120.191.5412.44612.97913.5851129903.461198753.071237823.6912.450696
2019-05-1512.5813.1112.9212.571103988.500.433.4412.51012.89213.5601155611.001208209.791254306.8812.562488
2019-05-1612.9312.9912.8512.78634901.44-0.07-0.5412.64812.76713.518971160.961168630.361209357.4212.317264
2019-05-1712.9212.9312.4412.36965000.88-0.41-3.1912.60012.62613.411925681.341153473.431138638.7012.270702
# 画预测值和实际值
df_concat['close'].plot(color='green', linewidth=1)
df_concat['forecast'].plot(color='orange', linewidth=3)
plt.xlabel('Time')
plt.ylabel('Price')
plt.show()

在这里插入图片描述

如果文章对你有帮助,感谢点赞+关注!

关注下方GZH:阿旭算法与机器学习,回复:“ML31”即可获取本文数据集、源码与项目文档,欢迎共同学习交流

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿_旭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值