我正在建立一个简单的交易策略,每月使用双移动平均线交叉。我使用简单的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")
不确定我是否做错其他但我感谢你的帮助。
谢谢, 玛利亚