首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在此图中绘制线性回归线?

如何在此图中绘制线性回归线?
EN

Stack Overflow用户
提问于 2017-12-28 00:18:20
回答 1查看 3.2K关注 0票数 2

enter image description here如何在此图中绘制线性回归线?

下面是我的代码:

代码语言:javascript
复制
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()

Pic 1 Jupiter Notebook

Pic 2 my Jupiter Notebook

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-28 00:54:26

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

将以下内容添加到文件的底部:

代码语言:javascript
复制
# 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'

代码语言:javascript
复制
# Plot 'y' and 'y_pred' vs 'DateTimeIndex`
df[['y', 'y_pred']].plot()

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47995356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档