如何在R中回测对交易策略

时间:2016-07-14 11:51:33

标签: r trading quantitative-finance performanceanalytics back-testing

我正在尝试了解配对交易策略,我正在使用此pseudo code来编写我的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))

在上面的代码中,创建信号很容易,但是对于交易对,我应该使用什么逻辑来创建信号并返回信号?

0 个答案:

没有答案