我试图使用线性回归模型在python中预测股票价格。我使用train_testrongplit拆分数据,所以据我所知,我的测试数据不应该在我的训练数据中,所以我不明白为什么模型给出100%的准确率。
下面是我的代码:X = RMV.drop('Close', axis=1)
y = RMV['Close']`
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(X_train, y_train)
reg_preds = reg.predict(X_test)
当我使用这段代码运行交叉验证以测试准确性时,我得到的值为1.00。
scores = model_selection.cross_val_score(reg, X_test, y_test, cv=10)
print ("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() / 2))
作为参考,以下是我使用的数据示例:
Close SMA EMA MACD Upper Band Middle Band Lower Band RSI
Date
2010-02-18 60.900002 57.335715 57.419887 2.099073 64.842238 55.4075 45.972762 60.517959
2010-02-19 61.000000 57.967857 57.897236 2.215288 65.422290 55.9000 46.377710 60.672590
2010-02-22 62.099998 58.560714 58.457604 2.368843 66.047128 56.4675 46.887872 62.416318
2010-02-23 61.200001 59.117857 58.823257 2.390360 66.386746 57.0000 47.613254 60.069541
2010-02-24 60.900002 58.539286 59.100156 2.356046 66.504379 57.5425 48.580621 59.269579
我哪里错了?
更新:准确性似乎是错误的指标,所以我已经切换到使用MSE的答复建议:
print('Mean Squared Error: ', metrics.mean_squared_error(y_true=y_test, y_pred=lm_preds))
print('Coefficient of determination: %.2f' % metrics.r2_score(y_true=y_test, y_pred=lm_preds))
这给了我大约MSE = 13-15取决于运行和R2 = 0.999,这仍然是非常高的。MSE实际上并没有看起来那么高,因为平均股价在600左右。这个模型似乎仍然表现得很好。
我使用的是Rightmove 2010-2020年的股票数据。我刚刚从2010-2020年和2019-2020年切换到使用波动性更大的股票(PMO.L),我还删除了我使用的5/7个指标。
对于2010-2020年,模型给出的MSE为69(与股票价格相比相对较低)和0.999 R2。然而,对于2019-2020年,该模型似乎有点糟糕,MSE为15.5,R2为0.82,明显低于之前。然而,考虑到这只是一年的数据,它似乎仍然表现得太好了。
以下是用于训练新股票模型的特征数据样本:
2010 - 2020:
SMA EMA
Date
2010-02-18 266.214286 266.857731
2010-02-19 266.910714 268.110034
2010-02-22 267.303571 269.428696
2010-02-23 267.589286 269.838203
2010-02-24 264.660714 270.659776
2011 - 2020:
SMA EMA
Date
2019-02-18 73.425000 73.791397
2019-02-19 73.632143 74.052544
2019-02-20 73.785715 74.325538
2019-02-21 73.953572 74.335466
2019-02-22 73.928572 74.330738
当你这样做的时候:
scores = model_selection.cross_val_score(lm, X_test, y_test, cv=10)
我假设您在lm
之前定义(我看不到它)。你需要知道你在用cross_val_score
做什么。您将创建10个不同的模型,每个X_test
拆分,然后使用各自的y_test
进行尝试。所以你不能说你用x_train
和y_train
训练的reg
模型是过拟合的,因为你没有评估它。无论如何,这表明你可能也会在你训练的模型中过度拟合。
查看您的reg模型是否过拟合,使用X_test
对其进行评估,如下所示:
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
test_prediction = reg.predict(x_test)
print('Mean Squared Error: ', mean_squared_error(y_true=y_test, y_pred=test_prediction))
print('Coefficient of determination: %.2f'
% r2_score(y_true=y_test, y_pred=test_prediction))
如果您想继续进行交叉验证,请使用完整的X和Y(不分割训练和测试):
scores = model_selection.cross_val_score(lm, X, y, cv=10) # Note I changed values of X and y
print ("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() / 2))
最后,你必须意识到你处于时间序列问题(你有约会)。而线性回归并不是处理数据的好模型。如果你想继续使用线性回归,我建议放弃这个功能。如果您想保留它,请使用ARMA或ARIMA模型,因为它们更适合处理时间序列数据