【问题标题】:Looping functions over dates - Python在日期上循环函数 - Python
【发布时间】:2021-03-31 15:02:02
【问题描述】:

我不是最精通 Python 的,所以对任何可怕的代码表示歉意。

我有一个 csv 文件,其中包含不同期限的不同 libor 曲线的每日即期汇率。我有两个函数,第一个函数在一个日期获取一条 libor 曲线的即期利率,第二个函数从第一个函数中获取这些利率并计算远期利率:

def importdata (fileloc, date, name, max_maturity=None):
    'Imports data from a given location, date and name'
    data = pd.read_csv(fileloc) # file location 
    data = data[ (data['date']) == date] # getting the date of the curve
    data =  data.loc[:, data.columns.str.startswith(name)] # getting the curve wanted at the date
    data = data.T # Transposing the data
    data = data.reset_index()
    data.columns = ['maturity','spot rate'] # renaming columns
    data['maturity'] = data.maturity.str.rsplit(n=1).str[-1]
    if max_maturity:
        data = data.iloc[:data.loc[data.maturity.str.contains(max_maturity,na=False)].index[0]+1]
    return data


def interpolate (dataframe, TENOR, freq):

    'Gets the forward rates from given tenors (X) and corresponding spot rates (Y)'
    
    terms= dataframe["maturity"].tolist()
    rates= dataframe['spot rate'].tolist() 
    
    dc = ql.Actual360()
    settlement_days = 0
    if Curve =='3M USD' or Curve == '6M EUR' or Curve == '6M GBP': 
        
        helpers = []

        for term, r in zip(terms, rates):
            if Curve == '3M USD': 
                swapIndex = ql.UsdLiborSwapIsdaFixAm(ql.Period((term)))
                helpers.append(ql.SwapRateHelper(r/100, swapIndex))
            elif Curve == '6M EUR':
                swapIndex = ql.EuriborSwapIsdaFixB(ql.Period((term)))
                helpers.append(ql.SwapRateHelper(r/100, swapIndex))
            elif Curve == '6M GBP': 
                #swapIndex = ql.SwapIndex('GBP Libor', ql.Period(term), settlement_days, ql.GBPCurrency(), ql.UnitedKingdom(), ql.Period('6M'), ql.Following, dc, ql.GBPLibor)
                swapIndex = ql.GbpLiborSwapIsdaFix(ql.Period((term)))
                helpers.append(ql.SwapRateHelper(r/100, swapIndex))
            
    elif Curve == 'EONIA' or Curve =='SONIA' or Curve =='FF':
       
        OIS_helpers = []
        
        if Curve == 'EONIA': 
            calendar = ql.TARGET()
            EONIA = ql.OvernightIndex("EONIA", settlement_days, ql.EURCurrency(), calendar, dc)
           
            for i in range(len(terms)):
                tenor = ql.Period(terms[i])
                rate = rates[i]
                OIS_helpers.append(ql.OISRateHelper(settlement_days, tenor, ql.QuoteHandle(ql.SimpleQuote(rate/100)), EONIA)) 
           
        elif Curve =='SONIA': 
            calendar = ql.UnitedKingdom()
            SONIA = ql.OvernightIndex("SONIA", settlement_days, ql.GBPCurrency(), calendar, dc)
            
            for i in range(len(terms)):
                tenor = ql.Period(terms[i])
                rate = rates[i]
                OIS_helpers.append(ql.OISRateHelper(settlement_days, tenor, ql.QuoteHandle(ql.SimpleQuote(rate/100)), SONIA)) 
                    
        elif Curve == 'FF': 
            calendar = ql.UnitedStates()
            FedF = ql.OvernightIndex("FedF", settlement_days, ql.USDCurrency(), calendar, dc)
            
            for i in range(len(terms)):
                tenor = ql.Period(terms[i])
                rate = rates[i]
                OIS_helpers.append(ql.OISRateHelper(settlement_days, tenor, ql.QuoteHandle(ql.SimpleQuote(rate/100)), FedF)) 
         
        helpers = OIS_helpers
    
    curve = ql.PiecewiseSplineCubicDiscount(0, ql.TARGET(), helpers, dc)
    curve.enableExtrapolation()                                                                           
    
    days = ql.MakeSchedule(curve.referenceDate(), curve.maxDate() , ql.Period(freq)) #Frequency
    
    if Curve == '3M USD' or Curve =='FF':
        fwds = [
            curve.forwardRate(d, ql.UnitedStates().advance(d,ql.Period(TENOR)), dc, ql.Simple).rate()*100
            for d in days
        ]
   
    elif Curve =='6M EUR' or Curve == 'EONIA': 
        fwds = [
            curve.forwardRate(d, ql.TARGET().advance(d,ql.Period(TENOR)), dc, ql.Simple).rate()*100 
            for d in days
        ]
    
    elif Curve =='6M GBP' or Curve == 'SONIA':
        fwds = [
            curve.forwardRate(d, ql.UnitedKingdom().advance(d,ql.Period(TENOR)), dc, ql.Simple).rate()*100
            for d in days
        ]
  
    fwdsdic = {Date:fwds}
    fwdcomp = pd.DataFrame(fwdsdic)
 
    ALL_FWD = fwdcomp.to_csv('1y1y.csv', header = '1y1y')     
    
    return fwdcomp;

data 的示例,它被用作interpolate 的输入:

    maturity    spot rate
0   1Y  0.105
1   18M 0.19
2   2Y  0.265
3   3Y  0.41100000000000003
4   4Y  0.542
5   5Y  0.655
6   6Y  0.7509999999999999
7   7Y  0.833
8   8Y  0.904
9   9Y  0.966
10  10Y 1.021
11  12Y 1.093
12  15Y 1.157
13  20Y 1.182
14  25Y 1.18
15  30Y 1.162
16  40Y 1.073
17  50Y 1.01

我想做的是为一条曲线计算这些远期汇率,但针对 CSV 文件中的所有日期,然后将这些汇率保存到一个新的 csv 文件中。到目前为止,我所做的是将整个 CSV 文件导入 pandas,然后为所有日期创建一个 for 循环:

AllDate = all_data['date']
for dt in AllDate.iteritems():
    data = importdata(locationAll, dt, Curve)
    interpolate(data, '1y', '1y')

我收到此错误:

ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements

我不确定我哪里出错了,非常感谢任何帮助。

编辑:

我已将 for 循环更改为:

AllDate = all_data['date']
for dt in AllDate.iterrows():
    data = importdata(location, dt, Curve)
    interpolate(data, '1y', '1y')

我收到此错误消息:

AttributeError: 'Series' 对象没有属性 'iterrows'

如果有帮助,这是我的输入文件的图片:

enter image description here

【问题讨论】:

    标签: python pandas loops


    【解决方案1】:

    你得到的错误说明出了什么问题。 pandas.DataFrame.interitems() 返回两个值(标签和内容),但您只给了它一个变量 dt 来写入。

    你可以阅读docs here作为例子。

    【讨论】:

    • 我编辑了我的问题,我意识到 interitems() 是用于列,而我的数据集是在行中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2018-07-09
    • 2017-01-20
    • 2015-04-22
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多