【问题标题】:Bollinger Strategy in R with Entry and Exit Signals at Re-allocation DatesR 中的布林线策略,在重新分配日期具有进入和退出信号
【发布时间】:2014-12-16 13:50:52
【问题描述】:

我有以下简单的交易策略:

入场信号:当 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),]

现在的整个问题是如何定义一个正确编码的信号函数sig.bb,一旦价格高于其上布林带,它就包含一个“1”在重新分配日期,然后持有该股票,直到价格低于下一个重新分配日期的布林带下限。

我尝试的是捕捉第一个观察结果,然后根据 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))))

返回“NA”...

获取sig.bb后如何进行(对本主题感兴趣的人)可以在这里找到: Equally Weighted Reallocation of Stock Portfolio at Specific Dates According to a Signal

【问题讨论】:

    标签: r quantmod portfolio trading algorithmic-trading


    【解决方案1】:

    我不确定你想要输出什么,但看看这是否接近

    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)
    

    【讨论】:

    • 这是该示例的正确解决方案。感谢您的快速回答和您的起点功能!我不知道 '& index(m) %in%' 表达式,因此必须了解更多信息。您是否还有建议如何将您的解决方案应用于股票投资组合,而无需单独运行每个资产的代码?例如在上面的例子中假设ticters = c('IBM','GOOG')。
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2018-05-07
    相关资源
    最近更新 更多