# [R-SIG-Finance] Stock Total Returns?

SW kryp33 at yahoo.com
Sat Feb 18 23:20:41 CET 2012

```Hello All,

I am relatively new to R and I am still not very comfortable with syntactic and libraries. Is there are any nice way to calculate and plot total returns for stocks which I would define as change in price and paid dividends? I made a code to do that but the loop that constructs prices+dividends looks ugly(see code below). Any suggestions to do it more efficiently? Thanks. Sergey

##############  CODE  ##################################
library(quantmod)
library(PerformanceAnalytics)

#Time frame
dt.end = "2010-01-01"
dt.start =  "2007-01-01"

tickers = c('SPY',
'XLY',
'XLP',
'XLE',
'XLF',
'XLV',
'XLI',
'XLB',
'XLK',
'XLU')
tickers.desc = c('SNP500',
'ConsumerCyclicals',
'ConsumerStaples',
'Energy',
'Financials',
'HealthCare',
'Industrials',
'Materials',
'Technology',
'Utilities')

############              Get prices        ###############################
setDefaults(getSymbols, warnings=FALSE,auto.assign=FALSE)
fnPx <- function(i) { return(Ad(getSymbols(tickers[i], from=dt.start,to=dt.end))) }
ts = lapply(1:length(tickers), fnPx)
###########################################################################

############              Get Dividends     ################################
fnDiv<- function(i) { return(getDividends(tickers[i], from=dt.start,to=dt.end,auto.assign=FALSE)) }
div = lapply(1:length(tickers), fnDiv)
###########################################################################

###########    Create Prices + Dividends (UGLY !!!!)  #####################
fnTotPx <- function(i)
{
ret = ts[[i]]
for(j in 1:length(div[[i]]))
{
row  = div[[i]][j,]
tm   = time(row)
val  = as.double(row[1,1])
iFwd = paste(tm,"::",sep='')
iBk  = paste("::",tm-1,sep='')
unch = ret[iBk]
chg  = ret[iFwd]+val
ret = rbind(unch,chg)
}
return(ret)
}
totPx = lapply(1:length(tickers), fnTotPx)
############################################################################

################          Calc Total Returns     ##########################
fnRet <- function(i) { return(periodReturn(totPx[[i]],period='daily')) }
ts.ret = lapply(1:length(tickers), fnRet)

################          Plot Total Returns     ##########################
ts.ret.df = as.data.frame(ts.ret)
colnames(ts.ret.df)=tickers.desc
chart.CumReturns(ts.ret.df, main="Cumulative Returns",geometric=FALSE,legend.loc="bottomleft")
############################################################################

```