首页 > 解决方案 > 带有股票数据的 Python 线性回归线 - 获取 y 轴上的收盘价

问题描述

我在 stackoverflow 上使用了以前的线程,以达到我发现自己的目的。我想制作一个显示最佳拟合线的股票图表。除了一个问题,我大部分时间都在工作。y 轴显示 -0.10 到 0.25 的标准化比例,而不是股票价格。我希望股票的价格显示在 y 轴上。

#!/usr/bin/env python3

import numpy as np
import pandas_datareader.data as web
import pandas as pd
import datetime
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import statistics as stat

#get adjusted close price of Tencent from yahoo
start = datetime.datetime(2020, 5, 21)
end = datetime.datetime(2021, 5, 21)
tencent = pd.DataFrame()
tencent = web.DataReader('IBM', 'yahoo', start, end)['Adj Close']

nomalized_return=np.log(tencent/tencent.iloc[0])

df = pd.DataFrame(data=nomalized_return)

df = df.resample('D').asfreq()

# Create a 'x' and 'y' column for convenience
df['y'] = df['Adj Close']     # create a new y-col (optional)
df['x'] = np.arange(len(df))  # create x-col of continuous integers


# Drop the rows that contain missing days
df = df.dropna()

X=df['x'].values[:, np.newaxis]
y=df['y'].values[:, np.newaxis]

# Fit linear regression model using scikit-learn
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Make predictions w.r.t. 'x' and store it in a column called 'y_pred'
df['y_pred'] = lin_reg.predict(df['x'].values[:, np.newaxis])

df['above']= y + np.std(y)
df['below']= y - np.std(y)
# Plot 'y' and 'y_pred' vs 'DateTimeIndex`
df[['y', 'y_pred']].plot()


plt.show()

问题在于这些行

nomalized_return=np.log(tencent/tencent.iloc[0])

df = pd.DataFrame(data=nomalized_return)

如果我替换df = pd.DataFrame(data=nomalized_return)df = pd.DataFrame(data=tencent)然后它工作。我得到了 y 轴上的价格,但回归线最终是错误的。无论如何,下图显示了我使用上面的代码得到的结果,它显示了问题。

带有回归线的 IBM 图表

标签: pythonregressionlinestock

解决方案


您可以将响应缩放回取指数并乘以第一个值:

df['y_pred'] = lin_reg.predict(df['x'].values[:, np.newaxis])
df['y_unscaled'] = tencent
df['y_pred_unscaled'] = np.exp(df['y_pred']) * tencent.iloc[0]

df[['y_unscaled', 'y_pred_unscaled']].plot()

在此处输入图像描述


推荐阅读