如何在此图中绘制线性回归线? [英] How can I draw a linear regression line in this graph?

查看:102
本文介绍了如何在此图中绘制线性回归线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处输入图像描述如何在此图中绘制线性回归线?

enter image description hereHow can I draw a linear regression line in this graph?

这是我的代码:

import numpy as np
import pandas_datareader.data as web
import pandas as pd
import datetime
import matplotlib.pyplot as plt
#get adjusted close price of Tencent from yahoo
start = datetime.datetime(2007, 1, 1)
end = datetime.datetime(2017, 12, 27)
tencent = pd.DataFrame()
tencent = web.DataReader('0700.hk', 'yahoo', start, end)['Adj Close']
nomalized_return=np.log(tencent/tencent.iloc[0])
nomalized_return.plot()
plt.show()

图片1木星笔记本

图2我的木星笔记本

推荐答案

您可以使用scikit-learn计算线性回归.

You can use scikit-learn to compute linear regression.

在文件底部添加以下内容:

Add the following to the bottom of your file:

# Create dataframe
df = pd.DataFrame(data=nomalized_return)

# Resample by day
# This needs to be done otherwise your x-axis for linear regression will be incorrectly scaled since you have missing days.
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()

# Fit linear regression model using scikit-learn
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X=df['x'].values[:, np.newaxis], y=df['y'].values[:, np.newaxis])

# 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])

# Plot 'y' and 'y_pred' vs 'x'
df[['y', 'y_pred', 'x']].plot(x='x')  # Remember 'y' is 'Adj Close'

# Plot 'y' and 'y_pred' vs 'DateTimeIndex`
df[['y', 'y_pred']].plot()

这篇关于如何在此图中绘制线性回归线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆