我提出了一个新问题,因为原始帖子已经太长了,而我得出的解决方案几乎否定了该帖子。
以下是我发现的添加与您的数据不同的周期性指标的解决方法。该解决方案是基于Brian Peterson 在 R-SIG-Finance 邮件列表上的这篇文章构建的。
代码有两个主要问题。
1) 尽管生成了信号,但该策略不占用任何位置(mktdata
运行该策略后存在相应的列)
2)奇怪的是,如果indMerge()
没有将 SMA 列显式重命名为"SPY.SMA"
并使用,add.signal(columns = c("SPY.Close", SPY.SMA"))
则会引发以下错误(也就是说我无法传入:columns = c("Close", "SMA")
add.signal
Warning message:
In match.names(columns, colnames(data)) :
all columns not located in Close SMA for SPY.Open SPY.High SPY.Low SPY.Close
SPY.Volume SPY.Adjusted SMA Cl.gt.SMA
由于我发现解决此错误的唯一方法是下面的代码,因此下面的解决方案在具有多个符号的投资组合中实际上是无用的。无论如何,这是代码:
require(quantstrat)
require(quantmod)
require(FinancialInstrument)
symbols = "SPY"
initDate="2000-01-01"
from="2003-01-01"
to="2016-12-31"
options(width=70)
options("getSymbols.warning4.0"=FALSE)
#set account currency and system timezone
currency('USD')
stock("SPY",currency="USD",multiplier=1)
Sys.setenv(TZ="UTC")
#trade sizing and initial equity settings
tradeSize <- 1e6
initEq <- tradeSize*length(symbols)
#Brians code
#>> http://r.789695.n4.nabble.com/R-Quantstrat-package-question-td3772989.html
indMerge <- function(x, period, k, SMAlength, maType){
mktdata <- getSymbols(x, auto.assign = FALSE)
xW = to.period(mktdata, period = period, k = k, indexAt = "startof")
smaW = wSMA = SMA(Cl(xW), n = SMAlength, maType = maType)
x <- cbind(mktdata, smaW[paste(first(index(mktdata)) ,
last(index(mktdata)) , sep='/')])
colnames(x)[ncol(x)] = paste("SPY", ".", "SMA", sep = "")
x <- na.locf(x)
x
}
#get the data
getSymbols(symbols, from=from, to=to, src="yahoo", adjust=TRUE)
#apply the weekly SMA to the data without the use of add.indicator
SPY = indMerge(x = symbols, period = "weeks", k = 1, SMAlength = 14, maType = "SMA")
#set up the portfolio, account and strategy
strategy.st <- portfolio.st <- account.st <- "mtf.strat"
rm.strat(strategy.st)
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate,
currency='USD',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)
#add signals
add.signal(strategy.st, name = "sigComparison", arguments = list(columns =
c("SPY.Close", "SPY.SMA"), relationship = "gt"), label = "Cl.gt.SMA")
add.signal(strategy.st, name = "sigComparison", arguments = list(columns =
c("SPY.Close", "SPY.SMA"), relationship = "lt"), label = "Cl.lt.SMA")
#test = applySignals(strategy.st, mktdata = SPY)
#add.rules
add.rule(strategy.st, name = "ruleSignal", arguments = list(sigCol = "Cl.gt.SMA",
sigval = 1, orderqty = 900, ordertype = "market", orderside = "long"),
type = "enter")
add.rule(strategy.st, name = "ruleSignal", arguments = list(sigCol = "Cl.lt.SMA",
sigval = 1, orderqty = "all", ordertype = "market", orderside = "long"),
type = "exit")
strat = getStrategy(strategy.st)
summary(strat)
#apply the strategy and get the transactions
applyStrategy(strategy = strategy.st, portfolios = portfolio.st)
getTxns(Portfolio = portfolio.st, Symbol = "SPY")