2017-04-20 76 views
1

爲什麼此代碼會給出以下錯誤?如何將數據框傳遞給對象的方法?

TypeError: simple_returns() takes 1 positional argument but 2 were given

import datetime as dt 
import math 
from matplotlib import style 
import numpy as np 
import pandas as pd 
import pandas_datareader.data as web 

start = dt.datetime(2000, 1, 1) 
end = dt.datetime(2016, 12, 31) 

df = web.DataReader('TSLA', 'yahoo', start, end) 


class CalcReturns: 
    def simple_returns(self): 
     simple_ret = self.pct_change() 
     return simple_ret 

    def log_returns(self): 
     simple_ret = self.pct_change() 
     log_ret = np.log(1 + simple_ret) 
     return log_ret 


myRet = CalcReturns() 
c = df['Adj Close'] 
sim_ret = myRet.simple_returns(c) 
print(sim_ret) 

回答

0

只需添加到類的方法的參數來接收pandas.Series並確保應用pct_change()方法的系列而不是類對象self

class CalcReturns: 
    def simple_returns(self, ser): 
     simple_ret = ser.pct_change() 
     return simple_ret 

    def log_returns(self, ser): 
     simple_ret = ser.pct_change() 
     log_ret = np.log(1 + simple_ret) 
     return log_ret 


myRet = CalcReturns() 
c = df['Adj Close'] 
sim_ret = myRet.simple_returns(c) 
print(sim_ret) 

# Date 
# 2010-06-29   NaN 
# 2010-06-30 -0.002511 
# 2010-07-01 -0.078473 
# 2010-07-02 -0.125683 
# 2010-07-06 -0.160937 
# 2010-07-07 -0.019243 
# 2010-07-08 0.105063 
# 2010-07-09 -0.003436 
# 2010-07-12 -0.020115 
+0

謝謝Parfait。你是對的。偉大的圖標! – Leigh

0

線:

sim_ret = myRet.simple_returns(c) 

呼叫CalcReturns.simple_returns()並且似乎僅傳遞一個參數。但是python類的方法是特殊的,因爲python也傳遞對象本身。它在第一個參數中執行此操作。這就是你看到這個模式的原因:

class MyClass(): 

    def my_method(self): 
     """ a method with no parameters, but is passed the object itself """ 

self名爲自按照慣例提醒我們,它是對象。所以,如果你想通過你的數據框,您將需要更改方法簽名的樣子:

def simple_returns(self, a_df): 
+0

謝謝。這hleps – Leigh