【问题标题】:How to get current "symbol" inside custom function when applyIndicators or applyStrategy in quantstrat在 quantstrat 中 applyIndi​​cators 或 applyStrategy 时如何在自定义函数中获取当前“符号”
【发布时间】:2017-11-12 04:21:50
【问题描述】:

我想在我的自定义指标函数中访问当前的符号字符串,例如“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)

【问题讨论】:

    标签: r quantstrat financialinstrument


    【解决方案1】:

    好问题。

    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 保存正在计算指标的当前符号。

    这显然允许您从全局环境或其他环境中提取外部数据,如果您想使用更多的数据进行更高级的指标构造,而不仅仅是传递给 @ 的当前符号的 mktdata 对象中的数据987654330@.

    (更简单的方法也是从 OHLC 列名中提取符号名,如果列名包含符号标签,则可能存在于 testfun 内的 x 对象中。)

    【讨论】:

    • 谢谢!是的,实际上我正在运行 applyStrategy() 函数。自定义指标使用符号对数据框进行查找,这就是我需要符号代码的原因。
    • 抱歉,我刚刚标记为已回答,再次感谢
    • 看起来像个杂牌?如果可以将它作为sym = quote(symbol) 传递到参数中会更好,其中test_fun 将有第二个参数sym
    • 是的,它是,但它对我有用:) 上次我查看源代码,iirc,指标和信号不通过符号参数。实际上有一些注释代码涉及传递符号,但我猜没有解决它。更新代码以反映这种变化很容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2022-01-03
    • 2019-05-29
    • 1970-01-01
    相关资源
    最近更新 更多