2

我正在构建一个简单的交易策略,每月使用双移动平均线交叉。我正在使用简单的 2 个月 MA 和 10 个月 MA。如果 2Ma 上穿 10Ma,则买入,如果下穿,则卖出。问题是我的资产曲线不正确。为了获得每月移动平均线,我将每日价格转换为每月价格。这在计算移动平均线时似乎效果很好,但是当我在回测环境中将信号应用于我的价格时,它看起来像是考虑了每日数据,因此信号与日期不匹配。

我收到了这个警告:

> data$weight[] = ifelse(as.integer(SMA_2>SMA_10)==1,1,0)  #If price of SPY is above the SMA then buy
Warning message:
 In NextMethod(.Generic) :
 number of items to replace is not a multiple of replacement length

接着:

> models$dmac2_10 = bt.run.share(data, trade.summary=T)
Error in which(tstart[, i]) : argument to 'which' is not logical
Called from: which(tstart[, i])
Browse[1]>

这是代码:

### Simple Dual Moving Average Crossover

#Load the required packages
load.packages('quantmod')
require(RCurl)
sit = getURLContent('https://github.com/systematicinvestor/SIT/raw/master/sit.gz', binary=TRUE, followlocation = TRUE, ssl.verifypeer = FALSE)
con = gzcon(rawConnection(sit, 'rb'))
source(con)
close(con)
data <- new.env()

# Load historical data and adjusts for splits and dividends
tickers = spl('^GSPC')
getSymbols(tickers, src = 'yahoo', from = '2000-01-01', env = data, auto.assign = T)
for(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T) 


#Sets backtesting environment and convert to monthly prices
bt.prep(data, align='remove.na', fill.gaps = T) 
prices = data$prices  
prices = prices[ endpoints(prices, on="months", k=1), ]


#Create a empty list for attaching the models to at a later stage
models = list()


#Calculate the moving averages- not considered: lag them one day to prevent lookback bias
SMA_2 <- SMA(prices,2)
SMA_10 <- SMA(prices,10)  


#Specify the weights to be used in the backtest
data$weight[] = NA #Zero out any weights from previous
data$weight[] = ifelse(as.integer(SMA_2>SMA_10)==1,1,0)  #If price of 2SMA is above the 10SMA then buy

#Call the function to run the backtest given the data, which contains the prices and weights.
#models$dmac2_10 = bt.run.share(data, trade.summary=T)
models$dmac2_10 = bt.run.share(data, clean.signal=T)


#Plot equity curve 
plot(models$dmac2_10$equity, main="Equity Curve")

不确定我是否做错了其他事情,但我很感激你的帮助。

谢谢,玛丽亚

4

0 回答 0