我正在尝试了解配对交易策略,并且我正在使用这个伪代码来编写我的 R 程序。
if X and Y are cointegrated:
calculate Beta between X and Y
calculate spread as X - Beta * Y
calculate z-score of spread
# entering trade (spread is away from mean by two sigmas):
if z-score > 2:
sell spread (sell 1000 of X, buy 1000 * Beta of Y)
if z-score < -2:
buy spread (buy 1000 of X, sell 1000 * Beta of Y)
# exiting trade (spread converged close to mean):
if we're short spread and z-score < 1:
close the trades
if we're long spread and z-score > -1:
close the trades
# repeat above on each new bar, recalculating rolling Beta and spread etc.
我目前正在使用Systematic Investor Toolbox (SIT)
技术分析进行回测,但我不知道如何使用 SIT 进行回测配对交易策略。
#data downloading
library(quantmod)
#downloading cointegrated pepsi and coca cola time series data from yahoo
pep<-getSymbols("PEP",start="2010-01-01",auto.assign=F)
ko<-getSymbols("KO",start="2010-01-01",auto.assign=F)
#close price of pepsi and coca cola
pepc<-Cl(pep)
koc<-Cl(ko)
#rolling regression of close price of pepsi vs coca cola
reg= rollSFM(pepc,koc , 50)
#calculating spread
spread=pepc-reg$beta*koc
#mean of the spread
avg=mean(spread)
#standard deviation of spread
std=sd(spread)
#z-score
z=(spread-avg)/std
#pair trading longing and shorting
if(z> 2){
sell spread()
t=1
} else if(z<-2) {
buy spread()
t=2
}
else if(z<1&t=1) {
close the short trade
}else if(z>-1&t=2) {
close the long trade
}
当前的问题是如何在 SIT 中模拟交易对的买卖。如果 SIT 无法进行配对交易策略回测,那么我应该如何执行配对交易策略,尤其是进入和退出。我应该使用什么逻辑?
编辑
PerformanceAnalytics
经过一段时间的搜索,我知道我们可以使用;从头开始制作回测器。但在回测之前,我们必须创建信号和返回值。下面是一个示例代码
library(quantmod)
library(PerformanceAnalytics)
s <- get(getSymbols('SPY'))["2016::"]
s$sma20 <- SMA(Cl(s) , 20)
s$signal <- ifelse(Cl(s) > s$sma20 , 1 , -1)
myReturn <- lag(s$signal) * dailyReturn(s)
charts.PerformanceSummary(cbind(dailyReturn(s),myReturn))
在上面的代码中,创建信号很容易,但是对于交易对,我应该使用什么逻辑来创建信号并返回该信号?