2017-11-12 9 views
1

사용자 정의 표시기 함수 내에서 현재 기호 문자열 (예 : "GOOG")에 액세스하고 싶습니다. 여기에 내가 할 수있는 가장 기본적인 예제가 있습니다.사용자 정의 함수 내에서 현재 기호를 얻는 방법 quantstrat에서 applyIndicators 또는 applyStrategy를 적용하는 방법

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) 

답변

1

좋은 질문입니다.

applyIndicator 함수의 기호를 독립 실행 형 함수 호출로 가져 오는 것은 실제로 의미가 없습니다. mktdata = GOOG 인수에 이미 원하는 데이터가 포함되어 있기 때문입니다. 나는

당신은이 작업을 수행 할 수 있습니다 ... 당신이 생각 applyStrategy를 호출 할 때 당신이 일을 할 때 비록 applyIndicator 통화 기호를 얻고 싶은 생각 :

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 개체의 데이터 이상으로 고급 표시기를 구성하려는 경우이 작업을 통해 분명히 전역 환경이나 다른 환경에서 외부 데이터를 가져올 수 있습니다.

+0

감사합니다 (더 쉬운 방법은 단순히 열 이름은 기호 레이블을 포함합니다., testfun 내부의 x 개체에 존재할 수있는의 OHLC 열 이름에서 심볼 이름을 추출 할 수도있다)! 네, 사실 applyStrategy() 함수를 실행하고 있습니다. 사용자 정의 인디케이터는 심볼을 사용하여 데이터 프레임에서 조회를 수행하므로 심볼 코드가 필요합니다. –

+0

사과 죄송합니다 답변을 드렸습니다. 다시 한 번 감사드립니다. –