2017-12-27 4 views
2

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

+0

:

은 파일의 맨 아래에 다음을 추가 ? – grovina

+0

PIC –

+0

계산 방법, 그리기 방법 또는 둘 다를 묻는 것이 있습니까? 두 경우 모두, 스택 교환시 파이썬에서 선형 회귀에 대한 많은 질문이 이미 있습니다. 마찬가지로, 줄을 그릴 때 matplotlib를 사용하는 것에 대한 많은 대답이 있습니다 –

답변

1

당신은 선형 회귀를 계산 scikit-learn를 사용할 수 있습니다

여기 내 코드입니다. 당신이 당신의 질문에 tencent.head`의 OUPUT을()`추가 시겠어요

# 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

+0

와우, 환상적인 코드와 명확한 설명 !!! 고맙습니다. –

+0

반갑습니다. 경우 작동, 제발 대답을 선택하여 그것을 고려하십시오 :) – Nitred

관련 문제