我有一些数据用 matplotlib 绘制为 250 点长的线。我可以拟合整个数据集。但是,我希望使用最小二乘法将回归线拟合并绘制到最后 50 个数据点。最好的方法是什么?(我的情节代码如下。)
j = 0
for line, rank in sortedSymbols:
series = getattr(self, line)["CLOSE"]
dates = pd.to_datetime(getattr(self, line)["DATE"]).dt.date
ax.plot(dates.iloc[-250:], series.iloc[-250:]/series.iloc[-250] * (40+j), label = line)
j += 10
有很多不同的方法可以做到这一点。但是如果没有关于您的数据结构的更多信息以及您正在寻找什么,这是可以完成的一种方式。np.polyfit()
(此处的文档)对列表或数组中的顺序数据使用 OLS 回归。
import numpy as np
j = 0
for line, rank in sortedSymbols:
series = getattr(self, line)["CLOSE"]
dates = pd.to_datetime(getattr(self, line)["DATE"]).dt.date
#Calculate the slope and intercept of fitted curve based on last 50 datapoint using the values
#you plotted before with 1 specified for a linear best fit line
slope, intercept = np.polyfit(dates.iloc[-50:].index,series.iloc[-50:]/series.iloc[-250] * (40+j),1)
#plot the trend line
ax.plot(dates.iloc[-50:],slope*dates.iloc[-50:].index+intercept,label=line)
j += 10
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句