[R-SIG-Finance] Generating Monthly Returns from a ton of daily data

Cedrick Johnson cedrick at cedrickjohnson.com
Fri Jun 5 05:24:09 CEST 2009


Here's a quick and dirty solution (rife with errors, but based on spot 
checks it looks like i'm in the right ballpark) that I came up with 
after doing a bit more investigation. I'm fairly close, I recall in one 
help file I was reading there was a way to properly get the first and 
last trading days of the month... I'm forsaking previous pub time due to 
my R addiction, so I'll pick this up tomorrow AM, particularly I believe 
a starting point for me to investigate should be the from and to dates 
in the example below (and how to deal with timeseries/xts/zoo and dates, 
etc.).

I ran CalculateReturns before on a mirror object that I created (x) and 
extracted the daily returns for column 3 and did the sum of returns..

 > ts = as.timeSeries(x[,3])
 > head(ts)
GMT
                  TS.1
2009-05-27 0.016053309
2009-05-26 0.005035229
2009-05-22 0.011481779
2009-05-21 0.008237344
2009-05-20 0.002171932
2009-05-19 0.004968058

 > from  = timeSequence(from="2008-05-01", length.out=13, by ="month")
 > to = from + 4*6*24*3600
 > from
GMT
 [1] [2008-05-01] [2008-06-01] [2008-07-01] [2008-08-01] [2008-09-01] 
[2008-10-01] [2008-11-01] [2008-12-01] [2009-01-01] [2009-02-01] 
[2009-03-01] [2009-04-01] [2009-05-01]

 > to
GMT
 [1] [2008-05-25] [2008-06-25] [2008-07-25] [2008-08-25] [2008-09-25] 
[2008-10-25] [2008-11-25] [2008-12-25] [2009-01-25] [2009-02-25] 
[2009-03-25] [2009-04-25] [2009-05-25]

 > test = applySeries(ts, from, to, FUN=sum)
 > timeSeries(test, to)
GMT
                  TS.1
2008-05-25  0.18501584
2008-06-25  0.17309887
2008-07-25  0.09630221
2008-08-25  0.04597184
2008-09-25  0.10668020
2008-10-25  0.14313745
2008-11-25  0.10458655
2008-12-25 -0.04078307
2009-01-25 -0.04049024
2009-02-25  0.12576100
2009-03-25  0.13219515
2009-04-25  0.03148875
2009-05-25  0.02194375

 > ts1 = timeSeries(test, to)
 > table.CalendarReturns(ts1)
     Jan  Feb  Mar Apr  May  Jun Jul Aug  Sep  Oct  Nov  Dec  TS.1
2008  NA   NA   NA  NA 18.5 17.3 9.6 4.6 10.7 14.3 10.5 -4.1 113.7
2009  -4 12.6 13.2 3.1  2.2   NA  NA  NA   NA   NA   NA   NA  28.9


PS: Dirk, just saw the reply in my inbox.. thanks, i'll investigate that 
method as well

-c



More information about the R-SIG-Finance mailing list