python - 带有股票数据的 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 轴上的价格,但回归线最终是错误的。无论如何,下图显示了我使用上面的代码得到的结果,它显示了问题。
解决方案
推荐阅读
- sql - 针对数据集在表中运行多个 SQL 查询
- javascript - 角度的电子邮件验证
- ios - 在 Safari Web Extension (iOS 15) 中将消息从应用程序 (popup.js) 发送到 JS (content.js)
- c# - MSBuild 如何解析参考项?
- hazelcast - Hazelcast Node 运行多个节点时出现多个错误
- checkmarx - Checkmarx 报告漏洞 - “未加密的 Web 配置文件”,即使代码没有任何敏感数据
- wordpress - 计算 WooCommerce 购物车中的自定义分类术语并将运费乘以数字
- salt-stack - 盐栈顶文件执行
- java - OutputStreamWriter 仅将一项写入文件
- sql-server - 使用等效的 SET STATISTICS 监控 SSIS 数据流