使用线性回归模型预测股票价格
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.family'] = 'SimHei' # 设置字体为SimHei
绘制预测价格和实际价格的图像
plt.plot(result.index, result['预测价格'], label='预测价格') plt.plot(result.index, result['实际价格'], label='实际价格') plt.xlabel('样本编号') plt.ylabel('股票价格') plt.title('预测价格 vs 实际价格') plt.legend() plt.show()
原文地址: https://www.cveoy.top/t/topic/f3EM 著作权归作者所有。请勿转载和采集!