【问题标题】:alpha & beta (for linear regression) calculations output nan?alpha & beta(用于线性回归)计算输出 nan?
【发布时间】: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 的第一行。您需要量化这些值以获得回归系数。 xPltyPlt中分别有3个Nans
  • 做到了,谢谢 - 将以下行添加到我的 compute_daily_returns(df) 函数解决了问题:daily_returns.ix[0, :] = 0
  • 但在xPltyPlt 中,您仍然有2 个Nans。您还需要删除这些,以便回归线与散点一起显示。处理Nans的方法有很多种,比如ffillbfill,甚至可以使用sklearn的Imputer方法。

标签: python pandas numpy linear-regression


【解决方案1】:

试图对此进行调查,但这让我有点困惑。另外,我无法在当前机器上重现从 yahoo 提取的数据,因此无法按原样运行您的代码。

这里有几个问题和想法:

  • 不应将变量命名为 close,因为 Python 使用了这个词。有时(如您的示例)它仍然有效,但这不是一个好习惯。
  • 你能单独绘制你的数据xPltyPlt,而不用别的吗?我怀疑错误就在那里。
  • 您使用包含两个值的数组调用DataReader,并将输出保存在instrument 中。然后你给close分配一列(按名称选择),但实际上会有两列命名为Adj close,对吧?

长话短说:您应该尝试逐步构建代码,在每一步之后添加一些printplot 命令,以查看保存在变量中的数据的样子。

【讨论】:

    【解决方案2】:

    我也无法检索数据。

    我的最佳猜测:检索到的数据中有nans 或重复点。

    【讨论】:

      【解决方案3】:
      def compute_daily_returns(df):
          daily_returns = (df / df.shift(1)) - 1
          daily_returns.ix[0, :] = 0  
          return daily_returns
      

      添加 daily_returns.ix[0, :] = 0 解决了这个问题,感谢 Nickil Maveli

      【讨论】:

        猜你喜欢
        • 2019-04-12
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 2016-02-28
        • 1970-01-01
        • 2017-12-16
        • 2020-06-10
        • 1970-01-01
        相关资源
        最近更新 更多