本文将从以下几个方面对如何利用Python对股票进行线性预测进行详细的阐述:爬虫获取数据、数据预处理、线性回归模型建立、模型评价与预测。
一、爬虫获取数据
在进行股票预测之前,我们需要先获得相应的数据。网上有很多免费的股票数据获取接口,但是他们的数据时间跨度较小,只有几天或几个月的数据,这样显然不能满足我们的需求。因此我们可以利用Python爬虫技术从同花顺等网站获取更为全面的数据。
具体的步骤如下:
import requests
import pandas as pd
from bs4 import BeautifulSoup
# 构造url
def get_url(stock_code, start_date, end_date):
url = 'http://q.stock.sohu.com/hisHq?code=cn_{0}&start={1}&end={2}&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp'.format(stock_code, start_date, end_date)
return url
# 获取数据
def get_data(stock_code, start_date, end_date):
url = get_url(stock_code, start_date, end_date)
r = requests.get(url)
data = r.text
data = data.split('[')[1].split(']')[0]
data = '[' + data + ']'
data = eval(data)
df = pd.DataFrame(data)
df.columns = ['date', 'open_price', 'close_price', 'rise_fall', 'amount', 'turnover_rate']
return df
代码说明:
- get_url函数:构造url,用于获取股票数据
- get_data函数:利用requests库向服务器发送请求,获得HTML文本;使用BeautifulSoup库解析HTML文本,将数据转化为DataFrame格式,以便后续处理。
- date:日期
- open_price:股票开盘价
- close_price:收盘价
- rise_fall:涨跌幅
- amount:成交量
- turnover_rate:换手率
二、数据预处理
在进行股票预测之前,我们需要对数据进行处理和检验,确保其准确性。具体的步骤如下:
1、删除重复值:
df = df.drop_duplicates(['date'])
2、缺失值处理:
df = df.dropna()
3、数据类型转换:
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df['open_price'] = pd.to_numeric(df['open_price'])
df['close_price'] = pd.to_numeric(df['close_price'])
三、线性回归模型建立
我们使用sklearn.linear_model中的LinearRegression实现线性回归模型的建立。代码如下:
import numpy as np
from sklearn.linear_model import LinearRegression
# 获取训练数据
def get_train_data(df):
df = df.sort_values('date', ascending=True)
df = df[['open_price']]
X_train = []
y_train = []
for i in range(30, df.shape[0]):
X_train.append(np.array(df.iloc[i-30:i]))
y_train.append(np.array(df.iloc[i:i+1]))
X_train = np.array(X_train)
y_train = np.array(y_train)
return(X_train, y_train)
# 建立模型
def model_fit(X_train, y_train):
lr = LinearRegression()
lr.fit(X_train.reshape(X_train.shape[0], X_train.shape[1]), y_train)
return lr
函数说明:
get_train_data函数:按照时间顺序将数据排序后,每30条数据作为一组特征值,每组数据的下一条数据作为其对应的目标值。
model_fit函数:调用sklearn.linear_model的LinearRegression函数进行模型拟合。
四、模型评价与预测
在进行模型预测之前,我们需要对模型进行评价,并确定最优的特征组合。具体的步骤如下:
1、分离训练集和测试集:
train_size = int(len(X_train) * 0.7)
X_train_, X_test = X_train[:train_size], X_train[train_size:]
y_train_, y_test = y_train[:train_size], y_train[train_size:]
2、模型评价:
y_pred_train = lr.predict(X_train_.reshape(X_train_.shape[0], X_train_.shape[1]))
y_pred_test = lr.predict(X_test.reshape(X_test.shape[0], X_test.shape[1]))
print('Training Score: ', lr.score(X_train_.reshape(X_train_.shape[0], X_train_.shape[1]), y_train_))
print('Testing Score: ', lr.score(X_test.reshape(X_test.shape[0], X_test.shape[1]), y_test))
3、模型预测:
df_predict = df[-30:].copy()
for i in range(30):
X_predict = np.array(df_predict.iloc[-30:])
y_predict = lr.predict(X_predict.reshape(1, X_predict.shape[0]))
df_predict.loc[df_predict.index[-1]+datetime.timedelta(days=1), 'open_price'] = y_predict[0][0]
代码说明:
- train_test_split函数:用于将数组或矩阵分为训练集和测试集,便于对模型的性能进行评价。
- score函数:用于计算预测得分。
总结
本文介绍了如何利用Python对股票进行线性预测,主要分为了爬虫获取数据、数据预处理、线性回归模型建立、模型评价与预测四个方面。通过对这些方面的说明,我们可以了解到Python实现股票线性预测的基本流程。