Pandas 股票回归图

0 投票
1 回答
650 浏览
提问于 2025-04-18 06:26

我想要创建一个简单的线性回归图,就像在Excel里那样。希望能用最简单的方法来实现。

用pandas的.plot功能,绘制一个带有回归线的股票收益图,最简单的方法是什么呢?

1 个回答

1

使用 statsmodels 会非常简单。

import statsmodels.api as sm
mod = sm.OLS.from_formula('y ~ x', data=df)  # y and x are column names in the DataFrame
res = mod.fit()
fig, ax = plt.subplots()
sm.graphics.abline_plot(model_results=res, ax=ax)
df.plot(kind='scatter', x='x', y='y', ax=ax)

撰写回答