我有以下简单的交易策略:
进入信号:当IBM的价格高于布林带上限时。
关闭信号:当IBM的价格低于布林带下限时。
以下是布林带:
require(quantmod)
# load IBM data
tickers = c("IBM")
myEnv = new.env()
getSymbols(tickers, from="2012-01-03", to="2014-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("IBM")
# extract the upper and lower bollinger band with TTR's BBands function
bb.up = BBands(close.prices, n=20, maType = SMA)[,3]
bb.dn = BBands(close.prices, n=20, maType = SMA)[,1]
现在棘手的部分是,只有当IBM的价格在重新分配日期低于布林带下限时才会平仓。否则我们将最后一个时段的信号滚动到下一个时段期。 要完成每周重新分配:
# apply the startpoints function to pick the week's first trading day for
# re-allocating the portfolio
startpoints = function (x, on = "weeks", k = 1) {
head(endpoints(x, on, k) + 1, -1)
}
sig.bb.up = ifelse(close.prices > bb.up, 1, 0)
sig.bb.up = sig.bb.up[startpoints(bb.up),]
sig.bb.dn = ifelse(close.prices < bb.dn, 1, 0)
sig.bb.dn = sig.bb.dn[startpoints(bb.dn),]
现在的问题是如何定义一个包含&#34; 1&#34;的正确编码信号函数 sig.bb 。一旦价格在重新分配日期高于其上限布林带,然后持有该股票,直到价格在任何后续重新分配日期低于其下布林带。
我所尝试的是捕获frist观察结果,然后基于sig.bb向量的第一个条目滚动所有以下观察结果
sig.bb = ifelse(index(close.prices[1,1]) == "2012-01-03", sig.bb.up,
ifelse(close.prices > bb.up, 1,
ifelse(close.prices < bb.dn, 0, lag(sig.bb))))
返回&#34; NA&#34; ...
在获得 sig.bb 之后,如何继续(对于对此主题感兴趣的人)可以在此处找到: Equally Weighted Reallocation of Stock Portfolio at Specific Dates According to a Signal
答案 0 :(得分:4)
我不确定你想要的输出是什么,但看看它是否接近
m <- merge(close.prices, BBands(close.prices, n=20, maType="SMA"))
m$sig[with(m, IBM > up) & index(m) %in% index(m)[startpoints(m, on="weeks")]] <- 1
m$sig[with(m, IBM < dn) & index(m) %in% index(m)[startpoints(m, on="weeks")]] <- 0
m$sig[1] <- 0
na.locf(m)