[This article was first published on The Average Investor's Blog » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Often I like to see the performance of a trading strategy summarized annually, quarterly or by month. In R, we start off with the summary function:
aggregateReturns = function( xx, leverage=1 ) { return( tail( cumprod( 1 + xx*leverage ), 1 ) ) }
Given a series xx, usually a chunk of the original, this function returns the accumulative returns for the period. The leverage is useful to somewhat simulate leveraged ETFs.
The rest is to call this function for various periods:
summarizeDailyReturns = function( ss, indicator, returns="closeToClose", period="annually", leverage=1 ) { stopifnot( length( index( ss ) ) == length( index( indicator ) ) ) stopifnot( is.xts( ss ) ) stopifnot( is.xts( indicator ) ) if( tolower( returns ) == "opentoclose" ) { stopifnot( has.Op( ss ) && has.Cl( ss ) ) rets = Cl( ss ) / Op( ss ) - 1 } else { stopifnot( has.Ad( ss ) || has.Cl( ss ) ) if( has.Ad( ss ) ) { rets = Ad( ss ) / lag( Ad( ss ) ) - 1 } else { rets = Cl( ss ) / lag( Cl( ss ) ) - 1 } } rets[as.character(head( index( ss ), 1 ))] = 0 rets = as.xts( indicator * coredata( rets ) ) if( tolower( period ) == "annually" ) { yy = as.numeric( format( index( rets ), "%Y" ) ) rets = aggregate( rets, yy, aggregateReturns, leverage ) } else if( tolower( period ) == "quarterly" ) { rets = aggregate( rets, as.yearqtr, aggregateReturns, leverage ) } else if( tolower( period ) == "monthly" ) { rets = aggregate( rets, as.yearmon, aggregateReturns, leverage ) } return( round( rets, 4 ) ) }
I will finish the post with an illustration how to use this function (assuming the two functions reside in returns.R from the current directory):
library(quantmod) source("returns.R") getSymbols("^GSPC", from="1900-01-01") # The indicator - buy and hold: 1 every day ind = xts(rep(1, length(index(GSPC))), order.by=index(GSPC)) summarizeDailyReturns(GSPC, ind, returns="OpenToClose") summarizeDailyReturns(GSPC, ind, leverage=2, period="quarterly") summarizeDailyReturns(GSPC, ind, leverage=2, period="daily")
The last call computes the compound growth on a daily basis.
The final version of the function is available from the quntscript project.
To leave a comment for the author, please follow the link and comment on their blog: The Average Investor's Blog » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.