可重复的代码:
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订单正常工作。即使我复制演示代码(并根据我的目的略微修改它),有时它也不起作用而且我没有理解为什么。上面是&#34;动态&#34;的一个例子。止损价格,但在我的订单簿中,即使我使用固定值(如quote(0.001)
),我也看不到止损订单。尽管如此,orderset
,parent
和type
似乎没问题。
请你解释一下我错过了什么?
这是我的getOrderBook(portfolio = name)
:
Order.Qty Order.Price Order.Type Order.Side Order.Threshold Order.Status Order.StatusTime Prefer Order.Set Txn.Fees Rule Time.In.Force
2002-08-15 "3487" "86.02" "market" "long" NA "closed" "2002-08-16 00:00:00" "" NA "0" "wpr.buy.enter" ""
2002-09-06 "3430" "87.46" "market" "long" NA "closed" "2002-09-09 00:00:00" "" NA "0" "wpr.buy.enter" ""
2002-09-25 "3348" "89.58" "market" "long" NA "closed" "2002-09-26 00:00:00" "" NA "0" "wpr.buy.enter" ""
2002-10-01 "3373" "88.94" "market" "long" NA "closed" "2002-10-02 00:00:00" "" NA "0" "wpr.buy.enter" ""
2002-11-14 "3457" "86.76" "market" "long" NA "closed" "2002-11-15 00:00:00" "" NA "0" "wpr.buy.enter" ""
2002-12-13 "3467" "86.53" "market" "long" NA "closed" "2002-12-16 00:00:00" "" NA "0" "wpr.buy.enter" ""
2002-12-31 "3387" "88.57" "market" "long" NA "closed" "2003-01-02 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-01-27 "3422" "87.65" "market" "long" NA "closed" "2003-01-28 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-02-05 "3428" "87.51" "market" "long" NA "closed" "2003-02-06 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-02-10 "3416" "87.8" "market" "long" NA "closed" "2003-02-11 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-02-21 "3397" "88.3" "market" "long" NA "closed" "2003-02-24 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-03-13 "3351" "89.52" "market" "long" NA "closed" "2003-03-14 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-05-02 "3396" "88.32" "market" "long" NA "closed" "2003-05-05 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-05-27 "3187" "94.12" "market" "long" NA "closed" "2003-05-28 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-06-11 "3132" "95.78" "market" "long" NA "closed" "2003-06-12 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-06-16 "3116" "96.26" "market" "long" NA "closed" "2003-06-17 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-09-02 "3655" "82.06" "market" "long" NA "closed" "2003-09-03 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-09-08 "3605" "83.2" "market" "long" NA "closed" "2003-09-09 00:00:00" "" NA "0" "wpr.buy.enter" ""
2003-09-11 "3567" "84.1" "market" "long" NA "closed" "2003-09-12 00:00:00" "" NA "0" "wpr.buy.enter" ""
如您所见,根本没有限制令。
答案 0 :(得分:4)
我怀疑只需在脚本顶部添加Sys.setenv(TZ ="UTC")
即可解决您的问题(许多每日数据的量子演示都会这样做)。当您在quantstrat中处理每日数据时,有时会发生这种情况。
ruleSignal
quantstrat发生的事情是在市场订单被填满时正确获得chain.price
,以及何时无法找到链条价格,它忽略了创造止损。
如果您有点好奇并希望说服自己,请尝试在填充止损的情况下在ruleSignal
中设置调试器(您可以创建自己的ruleSignal函数,与{{1}非常相似并在ruleSignal
add.rule
参数中为stoplimit规则提供该函数的名称。
如果您将调试器设置为在第一个订单填充时暂停(在name
或触发链停止限制规则时等效),您将看到:
ruleSignal
为了使事情正常工作,第一个txn时间戳应为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
。
为{limit}提供给2007-01-26
的{{1}}是一个空的xts对象,这是因为在quantstrat的函数chain.price
中,这些行在切换链中ruleSignal
1}}案例不能正确处理每日数据:
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)
参数不会传入有效的parameter
。在ruleProc
中,chain.price
提供了applyRules
和getTxns
,(交易在2007-01-26填写,输入信号在2007-01-25)在&#34; 2007-01-25 19:00:00&#34;之后,所以Dates = timestamp
是一个空的xts对象。为什么这一天的交易&#34; 2007-01-26&#34;时间戳为&#34; 2007-01-25 19:00:00&#34;?因为在我的R系统环境中,时区对应于纽约时间的UTC午夜。
简而言之,这是一个错误(如果您没有为每日数据集设置UTC的时区),但由于作者和量身定制的最严重用户可能不会与之合作每日酒吧,它可能不是一个重要的优先事项。在处理具有timestamp = "2007-01-26"
时间索引而非txns
类型的xts对象时,请务必将时区设置为UTC
。