无法使stoplimit订单在quantstrat中工作
可复制代码:无法使stoplimit订单在quantstrat中工作,r,quantstrat,R,Quantstrat,可复制代码: package <- c("compiler", "quantmod", "dygraphs", "plyr", "devtools", "PerformanceAnalytics", "doParallel") lapply(X = package, FUN = function(this.package)
package <- c("compiler",
"quantmod",
"dygraphs",
"plyr",
"devtools",
"PerformanceAnalytics",
"doParallel")
lapply(X = package,
FUN = function(this.package){
if (!require(package = this.package,
character.only = TRUE))
{
install.packages(pkgs = this.package,
repos = "https://cloud.r-project.org")
library(package = this.package,
character.only = TRUE)
} else {
library(package = this.package,
character.only = TRUE)
}
})
install_github("braverock/FinancialInstrument")
install_github("braverock/blotter")
install_github("braverock/quantstrat")
install_github("braverock/PerformanceAnalytics")
require(quantstrat)
# +------------------------------------------------------------------
# | The registerDoParallel() function is used to register the
# | parallel backend with the foreach package. detectCores() attempts
# | to detect the number of CPU cores on the current host.
# +------------------------------------------------------------------
registerDoParallel(detectCores())
# +------------------------------------------------------------------
# | Get data.
# +------------------------------------------------------------------
symbols <- c('SPY', 'TLT', 'GLD')
getSymbols(Symbols = symbols)
# +------------------------------------------------------------------
# | osTotEq() is an order sizing function which should return the
# | maximum amount of purchasable securities as for current equity
# | available (assuming you're not invested at the moment of
# | calculation).
# +------------------------------------------------------------------
osTotEq <- function(timestamp, orderqty, portfolio, symbol, ruletype, ...)
{
if (orderqty == "all" && !(ruletype %in% c("exit", "risk")) ||
orderqty == "trigger" && ruletype != "chain")
{
stop(paste("orderqty 'all'/'trigger' would produce nonsense, maybe use osMaxPos instead?\n",
"Order Details:\n", "Timestamp:", timestamp, "Qty:",
orderqty, "Symbol:", symbol))
}
endEq <- getEndEq(Account = portfolio,
Date = timestamp)
refPrice <- Cl(mktdata[, 1:4])[timestamp, ]
orderqty <- floor(endEq / refPrice)
return(orderqty)
}
# +------------------------------------------------------------------+ #
# +------------------------------------------------------------------+ #
# | Main: William's %R | #
# +------------------------------------------------------------------+ #
# +------------------------------------------------------------------+ #
# +------------------------------------------------------------------
# | Parameters
# +------------------------------------------------------------------
name <- 'WPR'
currency <- 'USD'
initEq <- 300000
# +------------------------------------------------------------------
# | Initialization
# +------------------------------------------------------------------
rm.strat(name = name)
currency(currency)
for (symbol in symbols)
{
stock(primary_id = symbol,
currency = currency,
multiplier = 1)
}
initPortf(name = name,
symbols = symbols,
currency = currency)
initAcct(name = name,
portfolios = name,
initEq = initEq)
initOrders(portfolio = name)
strategy(name = name,
store = TRUE)
# +------------------------------------------------------------------
# | Indicators
# +------------------------------------------------------------------
add.indicator(strategy = name,
name = 'volatility',
arguments = list(OHLC = quote(OHLC(mktdata)),
n = 5,
calc = 'yang.zhang',
N = 1),
label = 'sigma',
store = TRUE)
add.indicator(strategy = name,
name = 'WPR',
arguments = list(HLC = quote(HLC(mktdata)),
n = 14),
label = 'wpr',
store = TRUE)
# +------------------------------------------------------------------
# | Signals
# +------------------------------------------------------------------
add.signal(strategy = name,
name = 'sigThreshold',
arguments = list(column = 'wpr',
threshold = .2,
relationship = 'gt',
cross = TRUE),
label = 'wpr.buy')
add.signal(strategy = name,
name = 'sigThreshold',
arguments = list(column = 'wpr',
threshold = .8,
relationship = 'lt',
cross = TRUE),
label = 'wpr.sell')
# +------------------------------------------------------------------
# | Rules
# +------------------------------------------------------------------
add.rule(strategy = name,
name = 'ruleSignal',
arguments = list(sigcol = 'wpr.buy',
sigval = TRUE,
orderqty = 1,
ordertype = 'market',
orderside = 'long',
osFUN = osTotEq),
type = 'enter',
label = 'wpr.buy.enter',
store = TRUE)
add.rule(strategy = name,
name = 'ruleSignal',
arguments = list(sigcol = 'wpr.buy',
sigval = TRUE,
orderqty = 'all',
ordertype = 'stoplimit',
orderside = 'long',
tmult = TRUE,
threshold = quote(mktdata[timestamp, 'X1.sigma']),
orderset = 'stop.loss'),
parent = 'wpr.buy.enter',
type = 'chain',
label = 'wpr.buy.chain',
store = TRUE)
# add.rule(strategy = name,
# name = 'ruleSignal',
# arguments = list(sigcol = 'wpr.sell',
# sigval = TRUE,
# orderqty = 'all',
# ordertype = 'market',
# orderside = 'long',
# pricemethod = 'market',
# replace = TRUE,
# osFUN = osNoOp),
# path.dep = TRUE,
# type = 'exit',
# label = 'wpr.buy.exit',
# store = TRUE)
# +------------------------------------------------------------------
# | Strategy backtest
# +------------------------------------------------------------------
try(applyStrategy(strategy = name,
portfolios = name))
updatePortf(Portfolio = name,
Dates = paste('::',as.Date(Sys.time()), sep = ''))
updateAcct(name = name)
updateEndEq(Account = name)
# +------------------------------------------------------------------
# | Performance analysis
# +------------------------------------------------------------------
for (symbol in symbols)
{
dev.new()
chart.Posn(Portfolio = name,
Symbol = symbol)
}
dev.new()
R <- PortfReturns(Account = name)
R$total.DailyEqPl <- rowSums(R)
charts.PerformanceSummary(R = R,
ylog = TRUE,
main = "Smoothing spline performance",
geometric = TRUE)
getOrderBook(portfolio = name)
如您所见,根本不存在stoplimit订单。我怀疑您的问题可以通过简单地在脚本顶部添加
Sys.setenv(TZ=“UTC”)
来解决(许多quantstrat每日数据演示都会这样做)。在quantstrat中处理日常数据时,有时会发生这种情况
发生在ruleSignal
quantstrat中的情况是,在填写市场订单时,quantstrat没有正确获取链。价格
,当它找不到链价格时,它会忽略创建止损
如果您感到好奇并想说服自己,请尝试将ruleSignal
中的调试器设置为stoploss正在填充的条件(您可以创建非常类似于ruleSignal
的自己的ruleSignal函数,并在stoplimit规则的add.rule
name
参数中提供该函数的名称
如果将调试器设置为在第一次填充时暂停(当触发链停止限制规则时,在ruleSignal
或等效项中),您将看到以下内容:
getTxns(portfolio, "SPY")
Txn.Qty Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL
1950-01-01 00:00:00 0 0.00 0 0.0 0.00 0
2007-01-25 19:00:00 2108 142.13 0 299610.1 142.13 0
为了使事情正常运行,第一个txn时间戳应该是2007-01-26
为stoplimit提供给ruleSignal
的chain.price
是一个空的xts对象,这是因为在quantstrat的函数applyRules
中,开关链chain
案例中的这些行在日常数据上无法正常工作:
txns <- getTxns(Portfolio=portfolio, Symbol=symbol, Dates=timestamp)
txn.price <- last(txns$Txn.Price)
ruleProc(rules[j], timestamp=timestamp, path.dep=path.dep, mktdata=mktdata, portfolio=portfolio, symbol=symbol, ruletype=type, mktinstr=mktinstr, parameters=list(chain.price=txn.price), curIndex=curIndex)
txns太棒了!这就是问题所在!根据您的经验,这个bug是否会对stoptrailing
订单产生不切实际的结果?如果您将stoptrailing
替换为stoptrailing
,我的脚本就是这样的。如果您将时区设置为UTC
,并保留它,它就不再是bug了(对于每日条形图数据集)。我认为,您使用stoptrailing观察到的情况与此无关
txns <- getTxns(Portfolio=portfolio, Symbol=symbol, Dates=timestamp)
txn.price <- last(txns$Txn.Price)
ruleProc(rules[j], timestamp=timestamp, path.dep=path.dep, mktdata=mktdata, portfolio=portfolio, symbol=symbol, ruletype=type, mktinstr=mktinstr, parameters=list(chain.price=txn.price), curIndex=curIndex)