I'm new with this trying to add a custom indicator to Shiny/R quantmod app.
The below code in R script works well.
library(quantmod)
getSymbols('SBUX')
barChart(SBUX)
# create new TA function
myInd <- function(x) {
return(WMA(Cl(x)))
}
addMyInd <- newTA(FUN = myInd)
addMyInd()
The equivalent in shiny
library(shiny)
library(quantmod)
myInd <- function(x) {
return(WMA(Cl(x)))
}
addMyInd <- newTA(FUN = myInd)
shinyServer(function(input, output,session) {
observe({
query <- parseQueryString(session$clientData$url_search)
dataInput <- reactive({ as.xts(getSymbols('SBUX', auto.assign = FALSE)) })
output$chart <- renderPlot({ chartSeries(dataInput(), name = 'SBUX', TA = c(addMyInd()) ) })
})
})
fails with the Error: could not find function "myInd".
Whereas replacing "addMyInd" with any of the inbuilt function works well.
output$chart <- renderPlot({ chartSeries(dataInput(), name = 'SBUX', TA = c(addWMA()) )
Any idea how to make Shiny find the "myInd" function?
For anyone who might face a similar issue.
the trick is to put the two functions for the custom indicator inside another file and include it in server.R.
helper.R
library(quantmod)
myInd <- function(x) {
return(WMA(Cl(x)))
}
addMyInd <- newTA(FUN = myInd)
and server.R just reads
library(shiny)
library(quantmod)
source("helper.R");
shinyServer(function(input, output,session) {
observe({
query <- parseQueryString(session$clientData$url_search)
dataInput <- reactive({ as.xts(getSymbols('SBUX', auto.assign = FALSE)) })
output$chart <- renderPlot({
chartSeries(dataInput(), name = 'SBUX', TA = c(addMyInd()) )
})
})
})