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

标签 python datetime matplotlib linear-regression

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

这是我的代码:

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

最佳答案

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

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

# 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'

The linear regression fit using integers as the x-axis

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

The linear regression fit using DateTimeIndex as the x-axis

关于python - 如何在此图中绘制线性回归线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47995356/

相关文章:

python - 尽管添加到 INSTALLED_APPS,但找不到 Django 应用程序?

python - 评估 TensorFlow 张量时执行卡住

Python 类型提示,可索引对象

c# - 日期时间偏移错误 : UTC offset of local dateTime does not match the offset argument

ruby-on-rails - 将标准 rails/ruby 时间转换为美国格式 - 日期混淆

python - 未找到 matplotlib 字体

sql - 如何在 MS SQL SERVER 2008 R2 中将 nvarchar 列转换为日期时间类型

python - Matplotlib imshow 反转二维 IFFT 数组的颜色

matplotlib - matplotlib radviz 中的关键字参数

python - 如何旋转 matplotlib map ?