【发布时间】:2016-08-26 00:03:14
【问题描述】:
我是 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
知道我为什么要让 Nan 来这里吗?我很茫然,非常感谢任何帮助。
【问题讨论】:
-
当您向下执行
shift操作时,它是具有Nans的第一行。您需要量化这些值以获得回归系数。xPlt和yPlt中分别有3个Nans。 -
做到了,谢谢 - 将以下行添加到我的 compute_daily_returns(df) 函数解决了问题:daily_returns.ix[0, :] = 0
-
但在
xPlt和yPlt中,您仍然有2 个Nans。您还需要删除这些,以便回归线与散点一起显示。处理Nans的方法有很多种,比如ffill、bfill,甚至可以使用sklearn的Imputer方法。
标签: python pandas numpy linear-regression