QUANTSTRAT - 如何针对某项资产制定策略并将其用于另一项资产?

QUANTSTRAT - How to build a strategy on a certain asset and use it on another one?

我正在写我的 MSc 期末论文,我一直在尝试使用 quantstrat 包开发交易策略。我想做的是通过观察基于 VIX 的 MACD 生成的信号来交易 SPY。

我很难在 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)

任何人都可以帮我找出问题所在吗?

非常感谢。

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

利用 MACD 的负相关性...它可以工作,但技术分析对随机序列毫无用处。如果您对 VIX 执行随机性测试,它不会拒绝假设。

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

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

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

以上策略与下一篇论文中的yield策略相同: 简单的波动性投资 - Tony Cooper (2013)

上一篇论文除了 yield 之外还有 4 种其他策略。

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

Zorro 是实现此类策略并与 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  

祝你好运,我也在做我的论文 atm,但不是在这个。