QUANTSTRAT - 如何在某个资产上构建策略并在另一个资产上使用它?

时间:2016-04-05 11:09:20

标签: r trading quantstrat

我正在撰写我的理学硕士论文,我一直试图用quantstrat包开发一个交易策略。我想做的是交易SPY查看由VIX构建的MACD生成的信号。

我很难在VIX上开发策略,然后在SPY上使用它。 我想拿VIX并计算一个MACD。当VIX的MACD向下穿过信号线时,我希望算法买入SPY。当VIX的MACD向上越过信号线时,我希望算法关闭前一个位置。

这是我现在直到的代码:

# MACD strategy on VIX and SPY (SPDR S&P500 FUND)
#
# I will use MACD as trend indicator.
#
# This is the main idea. 
#
# I want to make prediction on SPY's returns. Due to the EMH, returns are not predictable. 
# Otherwise, the volatility clustering effect allows us to forecast volatility.
# The VIX is the S&P500's implied volatility index. I can make previsions about it and use them
# to forecast the SPY returns. This is because S&P500 and VIX have a strong negative correlation.
# 
# This strategy consists of buying/selling the SPY when the VIX's MACD generates sell/buy signal
#
# Author: Matteo Cavaggioni, 2016
######################################################################################################################
require(quantstrat)

ttz <- Sys.getenv('TZ')
Sys.setenv(TZ = 'UTC')

#startDate <- '2000-01-01'
initDate <- '2004-01-02'
endDate <- '2015-12-31'
initEq <- 1e6

fastMA <- 12
slowMA <- 26
signalMA <- 9
maType <- "EMA"

symb1 <- '^VIX'
symb2 <- 'SPY'

portfolio1.st <- "vmacd"
portfolio2.st <- "smacd"
account.st <- "vsmacd"

getSymbols(c(symb1, symb2), from = initDate, to = endDate, adjust = TRUE, index.class = c("POSIXt", "POSIXct"))
symb1 <- 'VIX'

currency("USD")
stock(symb1, currency = "USD", multiplier = 1)
stock(symb2, currency = "USD", multiplier = 1)

volStrat <- 'volStrat'

rm.strat(volStrat)

initPortf(name = portfolio1.st, symbols = symb1, initDate = initDate) # portafoglio contenente il VIX
initPortf(name = portfolio2.st, symbols = symb2, initDate = initDate) # portafoglio contenente lo SPY
initAcct(name = account.st, portfolios = c(portfolio1.st, portfolio2.st), initEq = initEq, initDate = initDate)
initOrders(portfolio = portfolio2.st, initDate = initDate)

volStrat <- strategy('volStrat', store = TRUE, assets = symb1)

volStrat <- add.indicator(strategy = volStrat, name = "MACD",
                          arguments = list(x = quote(Ad(mktdata)),
                                           nFast = fastMA,
                                           nSlow = slowMA,
                                           nSig = signalMA,
                                           maType = maType), 
                          label = 'macd.out')
#####
volStrat <- add.signal(strategy = volStrat, name = "sigCrossover",
                       arguments = list(columns = c("macd.macd.out", "signal.macd.out"),
                                        relationship = "gt"),
                       label = "macd.gt.signal")
volStrat <- add.signal(strategy = volStrat, name = "sigCrossover",
                       arguments = list(columns = c("macd.macd.out", "signal.macd.out"),
                                        relationship = "lt"),
                       label = "macd.lt.signal")

# go long when macd < signal
volStrat <- add.rule(strategy = volStrat, name = "ruleSignal",
                     arguments = list(sigcol = "macd.lt.signal", sigval = TRUE,
                                      orderqty = 1000,
                                      ordertype = "market",
                                      orderside = "long"),
                     type = "enter")

# exit long when macd > signal
volStrat <- add.rule(strategy = volStrat, name = "ruleSignal",
                     arguments = list(sigcol = "macd.gt.signal", sigval = TRUE,
                                      orderqty = "all",
                                      ordertype = "market",
                                      orderside = "long"),
                     type = "exit")

#####

start_t <- Sys.time()
out <- applyStrategy(strategy = volStrat, portfolios = portfolio2.st,
                     parameters = list(nFast = fastMA, nSlow = slowMA, nSig = signalMA, maType = maType), verbose = T)
end_t <- Sys.time()
print(end_t - start_t)

start_t<-Sys.time()
updatePortf(Portfolio='smacd',Dates=paste('::',as.Date(Sys.time()),sep=''))
updateAcct(account.st)
updateEndEq(account.st)
end_t<-Sys.time()
print(end_t-start_t)

book    = getOrderBook('smacd')
stats   = tradeStats('smacd')
ptstats = perTradeStats('smacd')
rets    = PortfReturns(account.st)
txns    = getTxns('smacd', symb2)

chart.Posn(Portfolio = 'smacd',Symbol = symb2)
plot(add_MACD(fast = fastMA, slow = slowMA, signal = signalMA, maType = "EMA"))

# COMPARING STRATEGY WITH SPY
instRets <- PortfReturns(account.st)

portfRets <- xts(rowMeans(instRets) * ncol(instRets), order.by = index(instRets))
portfRets <- portfRets[!is.na(portfRets)]
cumPortfRets <- cumprod(1 + portfRets)
firstNonZeroDay <- as.character(index(portfRets)[min(which(portfRets != 0))])

getSymbols("SPY", from = firstNonZeroDay, to = endDate)
SPYrets <- diff(log(Cl(SPY)))[-1]
cumSPYrets <- cumprod(1 + SPYrets)
comparison <- cbind(cumPortfRets, cumSPYrets)
colnames(comparison) <- c("strategy", "SPY")
chart.TimeSeries(comparison, legend.loc = "topleft", colors = c("green", "red"))
#

Sys.setenv(TZ=ttz)

任何人都可以帮我弄清楚它有什么问题吗?

非常感谢你。

1 个答案:

答案 0 :(得分:2)

这很有趣,我出于好奇而随机点击了你的问题。我目前正在对VIX索引进行大量研究。

利用MACD利用负相关......它可以起作用,但技术分析对随机序列无效。如果你对VIX进行随机性测试,它就不会拒绝这个假设。

此外,VIX具有随机盘中峰值,这些峰值未反映在收盘价中(由getSybmols产生 - 不是研究的可靠来源)。在现实生活中,您可能会在数据集实际代表它之前停止或达到您的价格目标。您可以通过使用更高频率来避免这种情况,这在此非常值得推荐

以下是2篇你应该阅读的论文:

VIX期货基础:证据和交易策略 - David P.Simon(2013)

上述策略与下一篇论文中的收益策略相同: 轻松波动投资 - 托尼库珀(2013)

最后一篇论文除了收益率1之外还有4个其他策略。

与代码相关,因为你几乎没有帖子,值得一提的是,不太可能有人检查你的整个代码。除非你可能付钱给他们,你仍然会相信你的计算陌生人吗?

佐罗是一种很容易实现这样的策略并与R集成的方法。

  You're using a very complex package for something very simple. I haven't looked at yoru code but if I were you i would try something like this: 
        1. calculate MACD for VIX
        2. Create a trade signal - Make new column by SPY with 1s for periods where VIX MACD >0 and zeros for VIX MACD <0 
        3. Simply add up SPY returns for rows that contain either 0s or 1s in the $MACD column / multiply by -1 if you want to go short..


P.S. use the xts package - helps u keep track of dates and not missmatch data  
祝你好运,我也在做我的论文,而不是这个。