Question

I would like to create a simple linear regression chart just like in excel. With the shortest way possible.

Which is the easiest way to to plot a stock returns chart with a regression line using the pandas .plot ?

Was it helpful?

Solution

It would be pretty simple with 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top