All the brilliant people on this incredibly useful platform. I have spent over 12 hours trying to get this to work (yes, I am not smart). Please help me.
I want to loop over the 'text input' values (users can input as many tickers as they want) and pass them to my getSymbols.yahoo() to be able to calculate my portfolio returns. I also want the date in the 'from' argument in getSymbols.yahoo() to be input dynamically. Please someone help me.
Here is my code:
library(quantmod)
library(PerformanceAnalytics)
library(imputeTS)
library(PortfolioAnalytics)
library(shiny)
ui<-fluidPage(
textInput("x","Enter tickers"),
dateInput("dt", "Select a date:"),
plotOutput("myplot")
)
server <- function(input, output){
p <- reactive({
portfolioPrices <- NULL
for(ticker in 1:input$x) {
portfolioPrices <- cbind(portfolioPrices,
getSymbols.yahoo(ticker,
from=input$dt, periodicity = 'daily', auto.assign=FALSE)[,4])
}
})
portfolioReturns <- na.omit(ROC(p))
Outside of shiny this code would look something like
library(quantmod)
library(PerformanceAnalytics)
library(imputeTS)
library(PortfolioAnalytics)
tickers <- c("FB", "AAPL", "AMZN", "NFLX", "GOOGL")
portfolioPrices <- NULL
for(ticker in tickers) {
portfolioPrices <- cbind(portfolioPrices,
getSymbols.yahoo(ticker, from='2016-01-03', periodicity = 'daily', auto.assign=FALSE)[,4])
}
portfolioReturns <- na.omit(ROC(portfolioPrices))
Once again, I will be eternally grateful if someone could please help me with this.
PS: I need to do this inside shiny. The 'outside shiny' code above is just to present a gist of what I am trying to do.
CodePudding user response:
You can loop through the comma-separated text input in R using strsplit
function as foloows:
p <- as.character(unlist(strsplit(input$x, ",")))
After that, you can loop over p and access every element inside that vector.
for (i in p) {
df <- cbind(df, getSymbols.yahoo(i, from = input$dt, periodicity = "daily", auto.assign = F)[,4])
}
Here' the code that I've modified based on your requirements:
library(quantmod)
library(PerformanceAnalytics)
library(imputeTS)
library(PortfolioAnalytics)
library(shiny)
library(DT)
ui<-fluidPage(
textInput("x","Enter tickers"),
dateInput("dt", "Select a date:"),
actionButton("GO","GO"),
DT::dataTableOutput("table"),
plotOutput("myplot")
)
server <- function(input, output){
df <- NULL
data <- eventReactive(input$GO, {
req(input$dt)
p <- as.character(unlist(strsplit(input$x, ",")))
for (i in p) {
df <- cbind(df, getSymbols.yahoo(i, from = input$dt, periodicity = "daily", auto.assign = F)[,4])
}
return(df)
})
output$table <- DT::renderDataTable({
data()
})
}
shinyApp(ui = ui, server = server)
P.s: Please note that when you use strsplit
it doesn't consider any spaces between two values. You have to pass the input text without spaces in between them.
For e.g: amzn,aapl,fb
and not amzn, aapl, fb