The C++ version of QuantLib has a function called years:
Real years(const &Period p);
I don't see this in QuantLib-Python version 1.18. Is it supposed to be there or was it not SWIGed?
Quantitative Finance Stack Exchange is a question and answer site for finance professionals and academics. It only takes a minute to sign up.Sign up to join this community
It is not swigged AFAIK.
As a workaround, you can retrieve this information by using
p.length() that are available (if.
p is your period):
p.length() returns the length of the period
p.units() will return an integer giving you the unit (0 for days, 1 for weeks, 2 for months, etc.), according to: https://github.com/lballabio/QuantLib-SWIG/blob/ab15e33d7feb23b5f204037e16b64c6d1ea7a05f/SWIG/date.i#L135-L136
p = ql.Period("1Y3M") p.units() # returns 2 (i.e. ql.Months) p.length() # returns 15
Your function will look something like:
def ql_period_in_years(period): units = period.units() if units == ql.Days: denominator = 365 elif units == ql.Weeks: denominator = 52 elif units == ql.Months: denominator = 12 ... return period.length() / denominator
For the example above:
ql_period_in_years(p) # returns 1.25