股票价格预测:使用线性回归模型进行预测
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error
读取数据集
data = pd.read_excel('E:\pythonProject5\深度学习\新建 XLS 工作表.xls')
选择特征和目标变量
features = data[['开盘', '涨跌额', '涨跌幅', '最低', '最高', '成交量', '成交金额']] target = data['收盘']
划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
训练模型
model = LinearRegression() model.fit(X_train, y_train)
预测股票价格
predictions = model.predict(X_test)
对比实际价格进行验证
mse = mean_squared_error(y_test, predictions) print('均方误差(MSE):', mse)
输出预测结果和实际价格
result = pd.DataFrame({'预测价格': predictions, '实际价格': y_test}) print(result) import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定使用SimHei字体 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
绘制预测价格和实际价格的图像
plt.plot(result.index, result['预测价格'], label='预测价格') plt.plot(result.index, result['实际价格'], label='实际价格') plt.xlabel('样本编号') plt.ylabel('股票价格') plt.title('预测价格 vs 实际价格') plt.legend() plt.show() 第一列的结果按照从大到小的顺序排序 代码结果内容:均方误差(MSE): 0.003564937055201937 预测价格 实际价格 0 13.142269 13.15 1 14.878596 14.89 2 14.879956 14.88 3 13.139995 13.14 4 14.880230 14.88 5 13.139995 13.14 6 14.879956 14.88 7 13.139995 13.14 8 13.139995 13.14 9 13.139995 13.14 10 13.139995 13.14 11 14.879956 14.88 12 13.139995 13.14 13 13.139995 13.14 14 13.139995 13.14 15 13.139995 13.14 16 13.139995 13.14 17 14.879956 14.88 18 14.879956 14.88 19 14.879956 14.88 20 14.879956 14.88 21 13.139995 13.14 22 13.139995 13.14 23 14.879956 14.88 24 13.139995 13.14 25 14.879956 14.88 26 13.139995 13.14 27 13.139995 13.14 28 14.879956 14.88 29 14.879956 14.88 30 13.139995 13.14 31 14.879956 14.88 32 13.139995 13.14 33 14.879956 14.88 34 13.139995 13.14 35 14.879956 14.88 36 13.139995 13.14 37 14.879956 14.88 38 14.879956 14.88 39 14.879956 14.88 40 14.879956 14.88 41 13.139995 13.14 42 14.879956 14.88 43 13.139995 13.14 44 14.879956 14.88 45 14.879956 14.88 46 13.139995 13.14 47 13.139995 13.14 48 13.139995 13.14 49 14.879956 14.88 50 14.879956 14.88 51 14.879956 14.88 52 13.139995 13.14 53 14.879956 14.88 54 14.879956 14.88 55 14.879956 14.88 56 14.879956 14.88 57 14.879956 14.88 58 13.139995 13.14 59 14.879956 14.88
原文地址: https://www.cveoy.top/t/topic/f3Fz 著作权归作者所有。请勿转载和采集!