I am trying to make a function to replace weird looking maturities into numbers:
For a reproducable example: the following block contains the data.
dict <- c("ON","TN","1W","1M","2M","3M","6M","9M","1Y","1Y3M","1Y6M","1Y9M","2Y","2Y3M", "2Y6M","2Y9M","3Y","3Y3M","3Y6M","3Y9M","4Y","4Y3M","4Y6M","4Y9M","5Y","5Y3M","5Y6M","5Y9M","6Y","6Y3M","6Y6M","6Y9M","7Y","7Y3M","7Y6M","7Y9M","8Y","8Y3M","8Y6M","8Y9M","9Y","9Y3M","9Y6M","9Y9M","10Y","11Y","12Y","13Y","14Y","15Y","20Y","25Y","30Y","40Y","50Y")
I tried to think about it as follows:
- make a
sub()
function for the months (extract everything before M and after Y). Divide by 12. - Then add this value to another sub that I call to extract the years.
- And then I guess a similar one for 0N (overnight so =
0
) & TN (tomorrow next, so1/365
) although I would work with an if function for those? What do you think is most handy?
I was running this code. It correctly extracts the values after Y. Although it does not work for 10Y 11Y 12Y 13Y 14Y 15Y 20Y 25Y
... Anyone that can provide support?
sub("*.Y", "", dict)
CodePudding user response:
We could replace the substring with str_replace_all
and then eval
uate
library(stringr)
setNames(sapply(trimws(str_replace_all(dict, c("ON" = "0",
"TN" = "1/365", "W" = "*1/52", "M"="*1/12", "Y" = "*1 ")),
whitespace = "\\ "), function(x) eval(parse(text = x))), dict)
-output
ON TN 1W 1M 2M 3M 6M 9M 1Y 1Y3M
0.000000000 0.002739726 0.019230769 0.083333333 0.166666667 0.250000000 0.500000000 0.750000000 1.000000000 1.250000000
1Y6M 1Y9M 2Y 2Y3M 2Y6M 2Y9M 3Y 3Y3M 3Y6M 3Y9M
1.500000000 1.750000000 2.000000000 2.250000000 2.500000000 2.750000000 3.000000000 3.250000000 3.500000000 3.750000000
4Y 4Y3M 4Y6M 4Y9M 5Y 5Y3M 5Y6M 5Y9M 6Y 6Y3M
4.000000000 4.250000000 4.500000000 4.750000000 5.000000000 5.250000000 5.500000000 5.750000000 6.000000000 6.250000000
6Y6M 6Y9M 7Y 7Y3M 7Y6M 7Y9M 8Y 8Y3M 8Y6M 8Y9M
6.500000000 6.750000000 7.000000000 7.250000000 7.500000000 7.750000000 8.000000000 8.250000000 8.500000000 8.750000000
9Y 9Y3M 9Y6M 9Y9M 10Y 11Y 12Y 13Y 14Y 15Y
9.000000000 9.250000000 9.500000000 9.750000000 10.000000000 11.000000000 12.000000000 13.000000000 14.000000000 15.000000000
20Y 25Y 30Y 40Y 50Y
20.000000000 25.000000000 30.000000000 40.000000000 50.000000000