Equally Weighted Reallocation of Stock Portfolio at Specific Dates According to a Signal

*爱你&永不变心* 提交于 2019-12-06 04:29:33
Joshua Ulrich

How I would have coded your example:

require(quantmod)
tickers <- c("ABI.BR","AI.PA","AIR.PA","ALV.DE","ASML.AS")
myEnv <- new.env()
getSymbols(tickers, from="2012-01-01", to="2013-12-01", env=myEnv)

close.prices <- do.call(merge, eapply(myEnv, Cl))
close.prices <- close.prices[,pmatch(tickers,colnames(close.prices))]
colnames(close.prices) <- c("Anheuser-Busch InBev",
  "L'Air Liquide","AIRBUS GROUP","Allianz","ASML HLDG")

assets.ret <- ROC(close.prices,type="discrete")[-1]

rsi.fct <- function(x) RSI(x, n=20, maType = SMA) 
rsi <- xts(apply(close.prices, 2, rsi.fct), index(close.prices))

Now, to answer your question, use GSee's startpoints function to get the first RSI value for each month. startpoints allows you to choose any number of weeks, months, quarters, etc as the rebalancing period.

startpoints <- function (x, on = "months", k = 1) {
  head(endpoints(x, on, k) + 1, -1)
}
# get the signal at the beginning of each month
rsi.signal <- lag(ifelse(rsi < 30, 1, 0))[startpoints(rsi),]
# rsi.signal is monthly; we need a daily series where each day has the
# value from the first day of the month, so we merge with an empty xts
# object that has the daily index and use na.locf to fill the gaps
rsi.signal <- merge(rsi.signal, xts(,index(rsi)), fill=na.locf)
# now calculate returns
rsi.ret <- rsi.signal * assets.ret
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!