python - calling function with dataframe data gives error (cannot convert the series to <class 'float'>) -


i have option pricing model (very simple black scholes) works fine data in fashion:

in [18]: bs2(100.,100.,1.,.001,.3)  out[18]: 11.96762435837207 

the function here:

black sholes function  def bs2(s,x,t,r,v):     d1 = (log(s/x)+(.001+v*v/2)*t)/(v*sqrt(t))     d2 = d1-v*sqrt(t)     return (s*cnd(d1)-x*exp(-.001*t)*cnd(d2)) 

i not think matters question, bs2 calls this:

cumulative normal distribution function  def cnd(x):     (a1,a2,a3,a4,a5) = (0.31938153, -0.356563782, 1.781477937,       -1.821255978, 1.330274429)     l = abs(x)     k = 1.0 / (1.0 + 0.2316419 * l)     w = 1.0 - 1.0 / sqrt(2*pi)*exp(-l*l/2.) * (a1*k + a2*k*k + a3*pow(k,3) +     a4*pow(k,4) + a5*pow(k,5))     if x<0:         w = 1.0-w     return w 

i tried modify working bs function accept data df seem have done wrong:

def bs(df):     d1 = (log(s/x)+(.001+v*v/2)*t)/(v*sqrt(t))     d2 = d1-v*sqrt(t)     return pd.series((s*cnd(d1)-x*exp(-.001*t)*cnd(d2))) 

my data straight forward:

in [13]: df  out[13]:     s    x   t    r    v 0  100  100  1  0.001  0.3 1   50   50  1  0.001  0.3 

and float64

in [14]:  df.dtypes out[14]: s    float64 x    float64 t    float64 r    float64 v    float64 dtype: object 

i aslo tried assigning df variables name before sending bs2 (i did way , without assignment:

s=df['s'] x=df['x'] t=df['t'] r=df['r'] v=df['v'] 

at risk of sending info, here error message:

in [18]:  bs(df) --------------------------------------------------------------------------- typeerror                                 traceback (most recent call last) <ipython-input-18-745e7dd0eb2c> in <module>() ----> 1 bs(df)  <ipython-input-17-b666a39cd530> in bs(df)   3 def bs(df):   4     callputflag='c' ----> 5     d1 = (log(s/x)+(.001+v*v/2)*t)/(v*sqrt(t))   6     d2 = d1-v*sqrt(t)   7     cp = ((s*cnd(d1)-x*exp(-.001*t)*cnd(d2)))  c:\users\camcompco\appdata\roaming\python\python34\site-   packages\pandas\core\series.py in wrapper(self)  74             return converter(self.iloc[0])  75         raise typeerror( ---> 76             "cannot convert series {0}".format(str(converter)))  77     return wrapper  78   typeerror: cannot convert series <class 'float'> 

any assistance appreciated.

john

i think easier use dataframe.apply()

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.dataframe.apply.html

then syntax df.apply(func, axis = 1) apply function func each row.

the answer question similar:

apply function each row of pandas dataframe create 2 new columns


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -