5
votes

Consider we have daily time series of stock prices (let's say the FTSE Index). We want to calculate daily, monthly and yearly returns.

In order to compute monthly and yearly returns we have to aggregate time series data into months and years. In package "zoo" we have the aggregate function whoch can help us aggregating data to a monthly frequency. Below the code lines using the as.yearmon class:

# Computing simple returns
FTSERet = diff(FTSE)/lag(FTSE,k=-1)

# Monthly simple returns
MonRet <- aggregate(FTSERet+1, as.yearmon, prod)-1

# Quarterly simple returns
QuartRet <- aggregate(FTSERet+1, as.yearqtr, prod)-1

I have not found an equivalent class as as.yearmon for monthly data or as.yearqtr for quarterly data for aggregating to year data. Do you have any hint about that stuff?

3

3 Answers

4
votes

"yearmon" and "yearqtr" classes represent dates as year + fraction so:

as.year <- function(x) as.integer(as.yearmon(x))

Also note this construct: diff(x, arithmetic = FALSE) - 1

0
votes

Check out the time series package here and look for 'seasonality' options somewhere in the documentation. I guess for quarterly data you are looking in time series with seasonality of 4, if you look in monthly data - you are looking in time series with seasonality of 12.

0
votes

You might want to look at the allReturns function in the quantmod package.

library(quantmod)
getSymbols("^FTSE")
allRet <- allReturns(FTSE)

To calculate yearly returns using aggregate.zoo, just extract the year from the index.

YearRet <- aggregate(FTSERet+1, as.integer(format(index(FTSERet),"%Y")), prod)-1