2017-12-27 29 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

あなたは、あなたの質問に 'tencent.head()'の出力に含まを追加してもらえ? – grovina

+0

PIC –

+0

の計算方法、描画方法、またはその両方を尋ねていますか?どちらの場合でも、スタック交換時のPythonの線形回帰に関する多くの既に回答のある質問があります。同様に、線を描くためにmatplotlibを使用することに関する多くの答えの質問があります –

答えて

1

あなたは線形回帰を計算するために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

+0

わかりやすく、明確な説明のあるコード!!!ありがとうございました。 –

+0

ようこそ。場合は、それは正しい答えとしてそれを選択することを検討してください:) – Nitred

関連する問題