gpt4 book ai didi

r - R中的布林带

转载 作者:行者123 更新时间:2023-12-02 07:34:22 25 4
gpt4 key购买 nike

我在 R 中回测布林带策略时遇到问题。逻辑是,如果收盘价大于上带,我想做空头寸,然后在它穿过平均线时平仓。如果收盘价低于 Lower Band,我还想做多头寸,并在它穿过平均线时平仓。到目前为止,这就是我所拥有的:

bbands <- BBands(stock$Close, n=20,sd=2)

sig1 <- Lag(ifelse((stock$Close >bbands$up),-1,0))

sig2 <- Lag(ifelse((stock$Close <bbands$dn),1,0))

sig3 <- Lag(ifelse((stock$Close > bbands$mavg),1,-1))

sig <- sig1 + sig2

... 这就是我卡住的地方,我该如何使用 sig3得到想要的结果?

最佳答案

library(quantmod)

getSymbols("SPY", src="yahoo", from="2013-01-01", to="2013-08-01")
x <- na.omit(merge(SPY, BBands(Cl(SPY))))

x$sig <- NA

# Flat where Close crossed the mavg
x$sig[c(FALSE, diff(sign(Cl(x) - x$mavg), na.pad=FALSE) != 0)] <- 0
x$sig[Cl(x) > x$up] <- -1 # short when Close is above up
x$sig[Cl(x) < x$dn] <- 1 # long when Close is below dn
x$sig[1] <- 0 # flat on the first day
x$sig[nrow(x)] <- 0 # flat on the last day

# Fill in the signal for other times
x$sig <- na.locf(x$sig) # wherever sig is NA, copy previous value to next row

# Now Lag your signal to reflect that you can't trade on the same bar that
# your signal fires
x$sig <- Lag(x$sig)
x$sig[1] <- 0 # replace NA with zero position on first row

现在,sig 是您的位置。如果您有头寸,您可以计算其他内容,例如交易次数、PnL 等。

sum(abs(diff(x$sig, na.pad=FALSE))) # number of trades

sum(diff(Cl(x)) * x$sig, na.rm=TRUE) # PnL of 1 share
cumsum(diff(Cl(x), na.pad=FALSE) * x$sig[-1]) # equity over time

sum(ROC(Cl(x)) * x$sig, na.rm=TRUE) # Return of fully invested account
cumsum(ROC(Cl(x), na.pad=FALSE) * x$sig[-1]) # cumulative return

关于r - R中的布林带,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com