[R-SIG-Finance] portfolio rebalancing
Fuchs Ira
irafuchs at gmail.com
Fri May 22 02:41:14 CEST 2009
I'm trying (so far unsuccessfully) to figure out how I might write a
function (or more likely a set of functions) to backtest a few
rebalancing algorithms. for example, starting with some amount of
capital I want to equal weight purchase a set of equities and then
rebalance in a variety of frequencies (daily, weekly, monthly, and
perhaps based on % change from equal weights). Getting the prices
with getSymbols is easy enough but things kind of go downhill from
there. I know this should be easy for anyone familiar with R but my
background is APL and whenever I try to do something that I think
should work, it doesn't. I know this is just because I don't have
enough R experience but if anyone can suggest any functions that I
could reuse for this purpose, that would be much appreciated.
As an example of my bad R intuition:
Let's say I want the prices of stock tickers MSFT, IBM, ORCL:
I say
getSymbols(c("MSFT","IBM","ORCL"))
Now I have 3 data frames which I think would be easier to deal with as
one so I say
prices=merge(ORCL[,6],merge(MSFT[,6],IBM[,6]))
so far so good.
Now I have a dataframe with 3 columns each with the adjusted prices of
a stock.
I can calculate the number of shares for the equal weight purchase for
a specific date (2009-01-02] by saying:
shares=(capital/3)/prices["2009-01-02"] #determine shares
but now I'd like to do this calculation each day, or week, or month
and after each calculation determine the new total value and redo the
equal weighting (or for that matter a more complex weighting).
functions like to.weekly won;t work because the dataframe is not OHLC.
Are there other similar functions that will just give me the rows for
some set of periodic dates?
Here's where my R intuition starts to break down...I try
sum(shares*prices["2009-02-02"]) #calculate total share value on
2009-02-02
I get:
[1] 0
not quite what I expected..so guessing that multiplying data.frames is
not good form, I try:
capital=sum(shares*as.numeric(prices["2009-02-02"]))
which works:
> capital
[1] 945462
OK, so now I have a new starting capital value and I can repeat as
above but with the following day's or week's or month's prices.
shares=(capital/3)/prices["2009-02-02"] # gives me the number of
shares to own on 2009-02-02
but what if I want shares (and the capital values) to be a time series
so I can see the share and capital amounts by date...I tried
shares[,2]=(capital/3)/prices["2009-02-02"] gives:
Error in NextMethod(.Generic) :
number of items to replace is not a multiple of replacement length
No doubt this is simple to do...right?
Of course, the real goal is to have a set of functions that would
permit easy changes to the frequencies, the threshold for rebalancing
and so on but maybe some kind soul could put me on the right R way to
think about this.
Thanks.
More information about the R-SIG-Finance
mailing list