Skip to content

Instantly share code, notes, and snippets.

@fauxvalue
Last active March 31, 2019 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fauxvalue/35d3f577ac038acea4c2dc941e9cea0f to your computer and use it in GitHub Desktop.
Save fauxvalue/35d3f577ac038acea4c2dc941e9cea0f to your computer and use it in GitHub Desktop.
example of R's optimize function: weighting us 2x10 curve to have zero correlation to usdjpy
library(fredr)
require(xts)
# note you'll need an API key
fredr_set_key("123YourFREDAPIKey321")
# helper function to convert tib to xts
xtsT <- function(TIB) xts(TIB$value, TIB$date)
# helper function to remove rows that have NA values
rmNA <- function(X) X[complete.cases(X), ]
# get data
us2yr <- xtsT(fredr("DGS2", observation_start=as.Date('2016-01-01')))
us10yr <- xtsT(fredr("DGS10", observation_start=as.Date('2016-01-01')))
usdjpy <- xtsT(fredr("DEXJPUS", observation_start=as.Date('2016-01-01')))
# create portfolio: % returns for USDJPY and bps changes for 2x10 curve
portfolio <- rmNA(cbind(usdjpy, us2yr, us10yr))
portfolio_diff <- rmNA(100 * cbind(diff(portfolio[, 1], log=T),
diff(portfolio[, 2:3])))
# embed problem in a function
corFun <- function(b, targetCor = 0) {
spread <- portfolio_diff[, 'us10yr'] - b * portfolio_diff[, 'us2yr']
abs(cor(spread, portfolio_diff[, 'usdjpy']) - targetCor)
}
# optimise the function
optWeight <- optimize(corFun, lower = 0, upper = 2)
# plot the range of results
plot(sapply(seq(0, 2, 0.01), corFun), x = seq(0, 2, 0.01),
main = "Correlation of weighted US 2x10 curve trade with USDJPY",
xlab = "weighting on 2yr",
ylab = "Correlation with USDJPY")
abline(v = 1, col=8, lty=2, lwd=1)
abline(h = 0, col=2, lty=2, lwd=1)
points(optWeight$minimum, 0, pch=17, col=2, type='p')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment