I am new to Python and I am trying to define a simple class with attributes and one method.
import scipy.optimize as optimize
class BondPricing:
def __init__(self, price = 95.0428,par = 100,T = 1.5,freq = 2,coup_perc = 5.75,dy = 0.01,guess = 0.05):
self.price = price
self.par = par
self.T = T
self.freq = freq
self.coup_perc = coup_perc
self.dy = dy
self.guess = guess
def ytm(self):
freq = float(self.freq) #cast frequency as float data type
periods = self.T*freq #calculate number of cash flow periods
coupon = self.coup_perc/100.*self.par/freq #calculate actual periodic coupon level
dt = [(i 1)/freq for i in range(int(periods))] #calculate time steps in bond maturity
#write down ytm function from bond pricing formula
ytm_func = lambda y:sum([coupon/(1 y/self.freq)**(self.freq*t) for t in dt]) self.par/(1 y/self.freq)**(self.freq*self.T)-self.price
return optimize.newton(ytm_func, self.guess) #find root of ytm function via Newton-Raphson
bond1 = BondPricing()
When I try to call the method of the class with bond1.ytm(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2)
, I get the following error:
TypeError: ytm() got an unexpected keyword argument 'price'
or when I try:
bond1.ymt()
I get this error:
AttributeError: 'BondPricing' object has no attribute 'ymt'
Can anyone kindly explain me what am I doing wrong?
Many thanks in advance!
CodePudding user response:
When I try to call the method of the class with
bond1.ytm(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2)
, I get the following error:
TypeError: ytm() got an unexpected keyword argument 'price'
The error is because the ytm method does not accept any arguments. You should be passing the arguments when you intialize the class. Example:
bond1 = BondPricing(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2)
# now call ytm method on the object
bond1.ytm()
or when I try:
bond1.ymt()
I get this error:
AttributeError: 'BondPricing' object has no attribute 'ymt'
You have defined the method name as ytm. You should be calling it as
bond1.ytm() # not bond1.ymt()