Advertisement
mjaniec

Sharpe Ratio and Information Ratio in R

Jul 22nd, 2012
819
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.81 KB | None | 0 0
  1. # MORE INFO: http://www.reakkt.com/2012/07/calculating-sharpe-ratio-and.html
  2.  
  3. SharpeRatio <- function(x,rf=0.05,fq=1,annualized=FALSE,visualize=FALSE) {
  4. # x  - returns
  5. # rf - risk free or constant benchmark interest rate
  6. # fq - frequency of x per day; 1 - daily  
  7. # reference: http://en.wikipedia.org/wiki/Sharpe_ratio
  8.  
  9.   n <- length(x)
  10.  
  11.   rft <- (1+rf)^(1/(252*fq))-1
  12.  
  13.   xrf <- -rft+x # -rep(rft,n)  
  14.  
  15.   xrf.m  <- mean(xrf) # mean
  16.   xrf.sd <- sd(xrf)   # standard deviation
  17.  
  18.   sharpe.ratio <- xrf.m / xrf.sd
  19.  
  20.   if (annualized) sharpe.ratio <- sqrt(252*fq)*sharpe.ratio
  21.  
  22.   if (visualize) {
  23.  
  24.     matplot(cbind(cumprod(1+x),cumprod(rep(1+rft,n))),type="l",main="Sharpe Ratio",ylab="")
  25.     mtext(paste("value =",format(sharpe.ratio,digits=4),
  26.                 ifelse(annualized,"annualized,",""),
  27.                 "excess mean =",format(xrf.m,digits=4)),line=0.5)
  28.  
  29.   }
  30.  
  31.   return( sharpe.ratio )
  32.  
  33. }
  34.  
  35. InformationRatio <- function(x, rb, fq=1, annualized=FALSE, visualize=FALSE) {
  36.  
  37.   n <- length(x)
  38.  
  39.   xrb <- x-rb
  40.  
  41.   xrb.m  <- mean(xrb)
  42.   xrb.sd <- sd(xrb)
  43.  
  44.   information.ratio <- xrb.m / xrb.sd
  45.  
  46.   if (annualized) information.ratio <- sqrt(252*fq)*information.ratio
  47.  
  48.   if (visualize) {
  49.    
  50.     matplot(cbind(cumprod(1+x),cumprod(1+y)),type="l",main="Information Ratio",ylab="")
  51.     mtext(paste("ratio =",format(information.ratio,digits=4),
  52.                 ifelse(annualized,"annualized,",""),
  53.                 "excess mean  =",format(xrb.m,digits=4)),line=0.5)
  54.  
  55.   }
  56.    
  57.   return( information.ratio )
  58.  
  59. }
  60.  
  61. # example:
  62.  
  63. x <- rnorm(252,mean=0.5,sd=2)/100 # 0.1/100 -> 0.1%
  64. y <- rnorm(252,mean=0.2,sd=1)/100
  65.  
  66. summary(x)
  67. tail(cumprod(1+x),1)
  68.  
  69. SharpeRatio(x,rf=0.05,fq=1,annualized=TRUE,visualize=TRUE)
  70. InformationRatio(x,y,fq=1,annualized=FALSE,visualize=TRUE)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement