How can I draw a linear regression line in this graph?

python datetime matplotlib linear-regression

2272 观看


13 作者的声誉

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

here is my code:

import numpy as np
import 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('', 'yahoo', start, end)['Adj Close']

Pic 1 Jupiter Notebook

Pic 2 my Jupiter Notebook

作者: Ken LAM 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


2225 作者的声誉


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()['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

作者: nitred 发布者: 27.12.2017 04:54