[英]alpha & beta (for linear regression) calculations output nan?
我是Python的新手,一直在嘗試計算兩種證券的線性回歸/ Beta / Alpha,但是我的代碼同時輸出Beta和Alpha的Nan,因此我無法繪制回歸線。
這是有問題的代碼:
#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
這是完整的腳本:
from pandas.io.data import DataReader
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
#inputs
symbols = ['EUR=X', 'JPY=X']
startDate = datetime(2011,1,1)
endDate = datetime(2016,12,31)
#get data from yahoo
instrument = DataReader(symbols, 'yahoo', startDate, endDate)
#isolate column
close = instrument['Adj Close']
#calculate daily returns
def compute_daily_returns(df):
daily_returns = (df / df.shift(1)) - 1
return daily_returns
dlyRtns = compute_daily_returns(close)
xPlt = dlyRtns[symbols[0]]
yPlt = dlyRtns[symbols[1]]
#draw "scatter plot" - using "o" workaround
dlyRtns.plot(x=symbols[0], y=symbols[1], marker='o', linewidth=0)
#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
# Calculate correlation coefficient
print "Correlation", dlyRtns.corr(method='pearson')
plt.show()
這是輸出:
C:\Python27\python.exe C:/Users/Us/Desktop/untitled3/scatterPlot.py
Y Beta nan
Y Alpha nan
Correlation EUR=X JPY=X
EUR=X 1.000000 0.228223
JPY=X 0.228223 1.000000
Process finished with exit code 0
有什么想法讓我來南嗎? 我很茫然,非常感謝您的幫助。
試圖研究這個問題,但這讓我有些困惑。 另外,我無法在當前計算機上從yahoo復制數據,因此我無法按原樣運行您的代碼。
這里有一些問題和想法:
close
,因為Python使用了這個詞。 有時(如您的示例所示)仍然可以工作,但這不是一個好習慣。 xPlt
和yPlt
,而無需其他任何操作? 我懷疑錯誤在那里。 DataReader
,並將輸出保存在instrument
。 然后,您分配一列(按名稱選擇)來close
,但是實際上,會有兩列名為Adj close
,對嗎? 簡而言之:您應該嘗試逐步構建代碼,在每一步之后添加一些print
和plot
命令,以查看保存在變量中的數據的外觀。
我也無法檢索數據。
我最好的猜測:檢索到的數據中存在nan
或重復點。
def compute_daily_returns(df):
daily_returns = (df / df.shift(1)) - 1
daily_returns.ix[0, :] = 0
return daily_returns
由於Nickil Maveli,添加daily_returns.ix[0, :] = 0
,: daily_returns.ix[0, :] = 0
解決了該問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.