I am able to convert daily H,L,C data to monthly H, L, C data:
library(xts)
data(sample_matrix)
samplexts <- as.xts(sample_matrix)
to.monthly(sample xts)
But how can I easily obtain the monthly averages from the daily data?
There are 2 ways of doing this with xts
Simple way: using the apply.x
functions (where x is the period) . In this case apply.monthly
:
apply.monthly(samplexts, mean)
Open High Low Close
2007-01-31 50.21140 50.31528 50.12072 50.22791
2007-02-28 50.78427 50.88091 50.69639 50.79533
2007-03-31 49.53185 49.61232 49.40435 49.48246
2007-04-30 49.62687 49.71287 49.53189 49.62978
2007-05-31 48.31942 48.41694 48.18960 48.26699
2007-06-30 47.47717 47.57592 47.38255 47.46899
Or the more complicated way using period.apply
which is used in the call to apply.monthly
and other apply.x functions. This can give you a more finely tuned control if there is a missing period for the apply.x functions.
period.apply(samplexts, INDEX = endpoints(samplexts, on = "months"), FUN = mean)
Open High Low Close
2007-01-31 50.21140 50.31528 50.12072 50.22791
2007-02-28 50.78427 50.88091 50.69639 50.79533
2007-03-31 49.53185 49.61232 49.40435 49.48246
2007-04-30 49.62687 49.71287 49.53189 49.62978
2007-05-31 48.31942 48.41694 48.18960 48.26699
2007-06-30 47.47717 47.57592 47.38255 47.46899