我不是最精通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文件导入到熊猫中,然后为所有日期创建一个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:“串联”对象没有属性“迭代行”
这是我的输入文件的图片,如果有帮助的话:
发布于 2021-03-31 07:09:22
你所犯的错误说明出了什么问题。pandas.DataFrame.interitems()
返回两个值(label和content),但是您只给它一个变量dt
来写入它。
您可以阅读医生来了作为一个示例。
https://stackoverflow.com/questions/66890358
复制相似问题