Python线性回归线与股票数据一起得到yAxis上的收盘价

2024-06-02 12:15:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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=tencent)替换df = pd.DataFrame(data=nomalized_return),那么它可以工作。我得到了y轴上的价格,但是回归线最终是错误的。 无论如何,下面的图片显示了我从上面的代码中得到了什么,它显示了问题所在

chart if IBM with a regression line


Tags: andimportdataframedfdatadatetimereturnas
1条回答
网友
1楼 · 发布于 2024-06-02 12:15:06

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

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()

enter image description here

相关问题 更多 >