Converting QuantLib Periods to Approximate Years in Python
Summary
The document addresses how to express a QuantLib-Python Period in years when the C++ years function is not exposed through the Python interface. The proposed workaround reads the period's length and unit separately, then divides by a unit-specific convention: days by 365, weeks by 52, and months by 12. The example represents a period of one year and three months as fifteen months, yielding 1.25 years under that conversion.
This is an approximate conversion, not a universal calendar-time rule. The result depends on the chosen day-count convention and on whether the period is measured in calendar units or for a particular financial calculation. The response notes that the unit is available as an integer and that QuantLib constants identify the units. It does not give a complete implementation for every possible unit or discuss calendar adjustments, so users must adapt the mapping to their specific use case.
Key ideas
- The Python interface may not expose the C++ Period-to-years helper described in the question.
- A workaround uses a Period's length and unit to compute an approximate year fraction.
- The suggested denominators are 365 for days, 52 for weeks, and 12 for months.
- Unit-based division may not match the day-count convention required by a pricing calculation.
Tags
Full text
# QuantLib-Python: where is the function to take Period to years?
# QuantLib-Python: where is the function to take Period to years?
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?
## Answer by byouness (score 3, accepted)
https://quant.stackexchange.com/a/54751
It is not swigged AFAIK. As a workaround, you can retrieve this information by using `p.units()` and `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
For example:
```
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
```Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.