Python中的异常处理,无需使用except语句堆

时间:2019-01-31 05:32:11

标签: python pandas

我正在运行一个try循环,该循环会附加一个数据帧。有时在df中添加元素会失败,我不介意,但我希望它被忽略,并在try循环中继续进行其他所有操作。我当前正在使用except: pass,但这意味着在try循环中其他所有操作都无法完成。

例如,如果它在df['putiv'].loc[i]=put.implied_volatility处失败,那么该行以下的所有内容都会传递到我不希望出现的位置,我只是希望putiv被忽略并继续前进。

代码:

import pandas as pd 
import numpy as np 
import wallstreet as ws 
from openpyxl import load_workbook 
import datetime

def day(string_date): 
    return(int(i[0][0]+i[0][1]))

def month(string_date): 
    return(int(i[0][3]+i[0][4]))

def year(string_date): 
    return(int(i[0][6]+i[0][7]+i[0][8]+i[0][9]))

c=ws.Call('AAPL', source='yahoo') 
lst=[(i,j) for i in c.expirations[: 1] for j in c.strikes[25: 30]] 
index=pd.MultiIndex.from_tuples(lst, names=['Expiry', 'Strike']) 


df=pd.DataFrame(index=index, columns=['expDate', 'strike', 'callBid', 'callAsk','callPrice', 'iv', 'delta', 'gamma', 'vega', 'theta', 'rho',\
                                      'putBid', 'putAsk', 'putExp', 'putStrike', 'putiv', 'putDelta', 'putGamma', 'putVega', 'putTheta', 'putRho'])  

for i in df.index: 
   # print('d: ', day(i), 'm: ', month(i), 'y: ', year(i)) 

    try: 
        call=ws.Call('AAPL', source='yahoo', d=day(i), m=month(i), y= year(i)) 
        call.set_strike(i[1])
        put=ws.Put('AAPL', source='yahoo', d=day(i), m=month(i), y= year(i))  
        put.set_strike(i[1]) 

        df['expDate'].loc[i]=call.expiration 
        df['strike'].loc[i]=call.strike 
        df['callBid'].loc[i]=call.bid 
        df['callAsk'].loc[i]=call.ask 
        df['iv'].loc[i]=call.implied_volatility()
        df['callPrice'].loc[i]=call.price 
        df['delta'].loc[i]=call.delta() 
        df['gamma'].loc[i]=call.gamma() 
        df['vega'].loc[i]=call.vega() 
        df['theta'].loc[i]=call.theta()
        df['rho'].loc[i]=call.rho()


        df['putExp'].loc[i]=put.expiration 
        df['putStrike'].loc[i]=put.strike 
        df['putBid'].loc[i]=put.bid 
        df['putAsk'].loc[i]=put.ask 
        df['putPrice'].loc[i]=put.price 
        df['putiv'].loc[i]=put.implied_volatility() 
        df['putDelta'].loc[i]=put.delta() 
        df['putGamma'].loc[i]=put.gamma() 
        df['putVega'].loc[i]=put.vega() 
        df['putTheta'].loc[i]=put.theta()
        df['putRho'].loc[i]=put.rho()

    except KeyboardInterrupt: break
    except: 
        print(i, 'error') 
        pass 

2 个答案:

答案 0 :(得分:4)

这里的一般技巧是翻译:

df['expDate'].loc[i] = call.expiration 

进入包装try / except块的函数调用:

def set_value(i, col, attr):
    try:
        val = getattr(call, attr)
        # tweak thanks to @cullzie (to ensure it's called if necessary)
        val = val() if callable(val) else val
        df[col].loc[i] = val
    except KeyboardInterrupt:
        raise
    except:
        pass

因此:

df['expDate'].loc[i] = call.expiration 
# becomes
set_value(i, 'expDate', 'expiration')

答案 1 :(得分:1)

以下代码应执行所需的操作,并说明被调用的put / call对象的属性或方法。目前的默认返回值为 None ,但您可以根据需要进行处理。

def get_value(obj, attr):
    result = None
    try:
        attribute = getattr(obj, attr) 
        result = attribute() if callable(attribute) else attribute 
    except Exception as e:
        print(str(e))

    return result

样品用量:

    df['iv'].loc[i] = get_value(call, 'implied_volatility')
    df['callPrice'].loc[i] = get_value(call, 'price') 

我用来测试的伪调用类:

class Call(object):
    def __init__(self):
        self.price = 100

    def implied_volatility(self):
        return 0.001