r - 基于符号排名的Quantstrat中的头寸规模?
问题描述
我正在尝试创建一种基于相对排名进行交易的算法。即,如果 Google 排名第一,则在本周开始时买入 100,000 美元并在结束时卖出。如果谷歌排名第二,开始时买入 50,000 美元,最后卖出。
我已经想出了如何让系统每周交易,但我不知道如何设置动态头寸规模。我已将 $ position 值附加到我的 XTS 文件中,因此系统需要在正确的日期/周内查找这些值。
关于如何做到这一点的任何建议?谢谢!
我目前的功能如下。“symbol[timestamp,26]”试图在给定特定时间戳的情况下引用第 26 列的符号 XTS 对象。但是,我收到一条错误消息,显示“维度数不正确”。
"osMaxDollar" <- function(data, timestamp, orderqty, ordertype, orderside,
portfolio, symbol, prefer="Open", tradeSize,
maxSize, integerQty=TRUE,
...) {
pos <- getPosQty(portfolio, symbol, timestamp)
if(prefer=="Close") {
price <- as.numeric(Cl(mktdata[timestamp,]))
} else {
price <- as.numeric(Op(mktdata[timestamp,]))
}
posVal <- pos*price
if (orderside=="short") {
dollarsToTransact = symbol[timestamp,26]
#If our position is profitable, we don't want to cover needlessly.
# if(dollarsToTransact > 0) {dollarsToTransact=0}
} else {
dollarsToTransact <- -symbol[timestamp,26]
#If our position is profitable, we don't want to sell needlessly.
# if(dollarsToTransact < 0) {dollarsToTransact=0}
}
qty <- dollarsToTransact/price
if(integerQty) {
qty <- trunc(qty)
}
return(qty)
}
编辑:这是我对任何好奇的人的最终解决方案
"osMaxDollar" <- function(data, timestamp, orderqty, ordertype, orderside,
portfolio, symbol, prefer="Open", tradeSize,
maxSize, integerQty=TRUE,
...) {
pos <- getPosQty(portfolio, symbol, timestamp)
if(prefer=="Close") {
price <- as.numeric(Cl(mktdata[timestamp,]))
} else {
price <- as.numeric(Op(mktdata[timestamp,]))
}
posVal <- pos*price
#Negative mktdata due to buy bot sell top
dollarsToTransact = mktdata[timestamp,26]
qty <- dollarsToTransact/price
if(integerQty) {
qty <- trunc(qty)
}
return(qty)