R 双移动平均每月

R 双移动平均每月,r,moving-average,back-testing,R,Moving Average,Back Testing,我正在建立一个简单的交易策略,每月使用双移动平均线交叉。我使用的是简单的2个月MA和10个月MA。如果2Ma高于10Ma,则买入,如果低于10Ma,则卖出。问题是我的权益曲线不正确。为了得到每月的移动平均数,我将每日价格转换为每月价格。这在计算移动平均值时似乎很有效,但当我在回溯测试环境中将信号应用于价格时,它似乎考虑了每日数据,因此信号与日期不匹配 我得到这个警告: > data$weight[] = ifelse(as.integer(SMA_2>SMA_10)==1,1,0)

我正在建立一个简单的交易策略,每月使用双移动平均线交叉。我使用的是简单的2个月MA和10个月MA。如果2Ma高于10Ma,则买入,如果低于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")
###简单双移动平均交叉
#加载所需的包
load.packages('quantmod')
需要(RCurl)
sit=getURLContent('https://github.com/systematicinvestor/SIT/raw/master/sit.gz,binary=TRUE,followlocation=TRUE,ssl.verifypeer=FALSE)
con=gzcon(rawConnection(sit,'rb'))
资料来源(con)
关闭(con)
数据