程式

將 pandas 日期時間轉換為 QuantLib 日期:為什麼只需要將輸入轉換為 int 幾次?看起來很隨意

  • February 6, 2021

我正在嘗試將 QuantLib 庫與 Python 一起使用。

在下面的範例中,我創建了一個帶有一些日期和一些現金流的 pandas 數據框,將日期從 pandas 格式轉換為 QuantLib 格式,並使用 QuantLib 計算天數(這對於 act/365 來說是平庸的,但 QuantLib 對於其他30/360 等情況)。可能有空間讓它更有效(以某種方式矢量化它?)但它有效。

然後我嘗試製作一個將 pandas 日期時間轉換為 QuantLib 日期的函式,但它不起作用,即使程式碼完全相同!

TypeError: Wrong number or type of arguments for overloaded function 'new_Date'.

這是相同的數據框應用語句。但是,如果我通過int(x['day'])而不是 just x['day'],那麼它可以工作。

為什麼會這樣?pd.DatetimeIndex 返回一個整數,而不是浮點數。為什麼 apply 語句在函式外部執行時不需要將輸入轉換為整數,但如果在函式內執行則需要它?我不明白!

import QuantLib as ql
import pandas as pd
from datetime import date
import numpy as np

# I create a dataframe with
# investment in which we pay 100 in the first month, then get 2 each month for the next 59 months

d0 = pd.to_datetime(date(2010,1,1))
df = pd.DataFrame()

df['month #'] = np.arange(0,60)
df['dates'] = df.apply( lambda x: d0 + pd.DateOffset(months = x['month #']) , axis = 1 )
df['cf'] = 0
df.iloc[0,2] = -100
df.iloc[1:,2] = 2

df['year'] = pd.DatetimeIndex(df['dates']).year
df['month'] = pd.DatetimeIndex(df['dates']).month
df['day'] = pd.DatetimeIndex(df['dates']).day

# Now I use pandas apply to add a column which contains the same dates, but in qlib format
df['qldate'] = df.apply( lambda x:   ql.Date(x['day'], x['month'], x['year'] )       , axis = 1)

#now I use qlib to calculate the day count
# NB: actual 365 is easy to calculate manually, but qlib comes in handy for other daycount conventions
# so we don't reinvent the wheel
df['dayc act 365'] = df.apply( lambda x: ql.Actual365Fixed().dayCount(df['qldate'][0], x['qldate'])   , axis =1 )


def date_pd_to_ql(pdate):
   df = pd.DataFrame()
   df['year'] = pd.DatetimeIndex(pdate).year
   df['month'] = pd.DatetimeIndex(pdate).month
   df['day'] = pd.DatetimeIndex(pdate).day
   
   # this works:
   out = df.apply( lambda x: ql.Date(int(x['day']), int(x['month']), int(x['year']) )     , axis = 1  )
   
   # but this doesn't:
   out = df.apply( lambda x: ql.Date(x['day'], x['month'], x['year'] )     , axis = 1  )
   
   return out

out = date_pd_to_ql(df['dates'])

您可以使用該ql.Date().from_date方法。

例子:

d0 = pd.to_datetime(date(2010,1,1))
df = pd.DataFrame()

df['month #'] = np.arange(0,60)
df['dates'] = df.apply( lambda x: d0 + pd.DateOffset(months = x['month #']) , axis = 1 )
df['cf'] = 0
df.iloc[0,2] = -100
df.iloc[1:,2] = 2

df['qldate'] = df.dates.apply(ql.Date().from_date)
df['dayc act 365'] = df.apply( lambda x: ql.Actual365Fixed().dayCount(df['qldate'][0], x['qldate'])   , axis =1 )

df.head()

在此處輸入圖像描述

引用自:https://quant.stackexchange.com/questions/60991