我想访问我的自定义指示器函数中的当前符号字符串,例如"GOOG"。这是我能做的最基本的例子。
require(quantstrat)
Sys.setenv(TZ="UTC")
symbols <- c("GOOG", "AAPL")
getSymbols(symbols, src="yahoo")
strategy.st <- "test"
strategy(strategy.st, store=TRUE)
test_fun <- function(x){
print(symbol) ##### i want to access the current symbol eg "GOOG"
return(x)
}
add.indicator(strategy = strategy.st,
name = "test_fun",
arguments = list(x = quote(Cl(mktdata))),
label = "test_ind")
mktdata <- applyIndicators(strategy = strategy.st, GOOG)
Error in print(symbol) : object 'symbol' not found
Called from: print(symbol)
好问题。
将applyIndicator
函数中的符号作为独立函数调用并没有多大意义,因为mktdata = GOOG
参数已经包含了所需的数据。我怀疑你想在applyIndicator
调用中获得符号,但当你工作时,当你调用applyStrategy
时。。。
你可以这样做:
require(quantstrat)
Sys.setenv(TZ="UTC")
symbols <- c("GOOG", "AAPL")
getSymbols(symbols, src="yahoo")
currency("USD")
stock(c("GOOG", "AAPL"), "USD")
strategy.st <- "test"
portfolio.st <- "test"
rm.strat(strategy.st)
initPortf(portfolio.st, symbols = symbols)
strategy(strategy.st, store=TRUE)
account.st <- "test"
initAcct(account.st, portfolios = portfolio.st, initEq = 1000)
initOrders(portfolio.st)
test_fun <- function(x){
symbol <- parent.frame(n = 2)$symbol
print(symbol) ##### i want to access the current symbol eg "GOOG"
return(x)
}
add.indicator(strategy = strategy.st,
name = "test_fun",
arguments = list(x = quote(Cl(mktdata))),
label = "test_ind")
applyStrategy(strategy.st, portfolio.st)
这适用于applyStrategy
,因为上级环境在符号循环(每次迭代调用applyIndicators
)周围循环几个级别,symbol
保存正在计算其指示符的当前符号。
如果您希望使用传递给applyIndicators
的currenct符号的mktdata
对象中的数据以外的数据进行更高级的指标构建,那么这显然允许您从全局环境或其他环境中提取外部数据。
(一种更简单的方法是简单地从OHLC列名中提取符号名称,如果列名包含符号标签,则OHLC列名可能存在于testfun
内的x
对象中。)