浮点精度问题Python

时间:2018-04-04 16:32:59

标签: python precision

我对Python很陌生,我遇到的是我在Python(Jupyter)中使用数字操作的精度问题。我计算投资组合到期时的利润(期权的收益 - 期权的收盘价)。最后我应该在我的字典中只得到一个值,但似乎存在一些差异,我无法理解为什么。

以下是我使用的代码:

import pandas as pd
do = {'Underlying': ['AMZN','AMZN','AMZN','AMZN','FB','FB'], 'Qty': [-31, -42, 31, 42,92,-92], 'Type': ['Call','Call','Put','Put','Call','Put'], 'Strike': [1450,1480,1450,1480,160,160], 'Close Price': [55.4, 42.7,72.3,87.1,3,10.8]}
dfoption = pd.DataFrame(data=do)
ds = {'Symbol': ['AMZN','FB'], 'Qty': [7300, -9200], 'Close Price': [1447, 160]}
dfstock = pd.DataFrame(data=ds)


def optionpnl(row,stress) :
    stockprice = dfstock.loc[dfstock['Symbol'] == row['Underlying']]['Close Price'] 
    if row['Type'] == 'Call' :
        return 100*row['Qty'] * (max(float(stress*stockprice - row['Strike']),0) - row['Close Price'])
    if row['Type'] == 'Put' :
        return 100*row['Qty'] * (max(float(row['Strike'] - stress*stockprice),0) - row['Close Price'])

def stockpnl(row,stress) :
    return row['Qty'] * (stress*row['Close Price'] - row['Close Price'])


dicpnl = {}

for i in (pd.Series(range(70,131,5))) :
    dfoption['PnL'+str(i-100)] = dfoption.apply(lambda row: optionpnl(row,i/100), axis=1)
    dfstock['PnL'+str(i-100)] = dfstock.apply(lambda row: stockpnl(row,i/100), axis=1)
    dicpnl[str(i-100) + "%"] = sum(dfoption['PnL'+str(i-100)]) + sum(dfstock['PnL'+str(i-100)])

输出:

{'-10%': -19209.999999999884,
 '-15%': -19210.000000000233,
 '-20%': -19210.0,
 '-25%': -19210.0,
 '-30%': -19210.0,
 '-5%': -19210.00000000006,
 '0%': -19209.99999999997,
 '10%': -19210.0,
 '15%': -19210.0,
 '20%': -19210.0,
 '25%': -19210.0,
 '30%': -19210.0,
 '5%': -19209.999999999884}

0 个答案:

没有答案