Skip to content

Instantly share code, notes, and snippets.

@ilovejs
Forked from wch/server.r
Created May 3, 2013 02:37
Show Gist options
  • Save ilovejs/5506844 to your computer and use it in GitHub Desktop.
Save ilovejs/5506844 to your computer and use it in GitHub Desktop.
if (!require(quantmod)) {
stop("This app requires the quantmod package. To install it, run 'install.packages(\"quantmod\")'.\n")
}
# Download data for a stock if needed, and return the data
require_symbol <- function(symbol, envir = parent.frame()) {
if (is.null(envir[[symbol]])) {
envir[[symbol]] <- getSymbols(symbol, auto.assign = FALSE)
}
envir[[symbol]]
}
shinyServer(function(input, output) {
# Create an environment for storing data
symbol_env <- new.env()
# Make a chart for a symbol, with the settings from the inputs
make_chart <- function(symbol) {
symbol_data <- require_symbol(symbol, symbol_env)
chartSeries(symbol_data,
name = symbol,
type = input$chart_type,
subset = paste("last", input$time_num, input$time_unit),
log.scale = input$log_y,
theme = "white")
}
output$plot_aapl <- renderPlot({ make_chart("AAPL") })
output$plot_msft <- renderPlot({ make_chart("MSFT") })
output$plot_ibm <- renderPlot({ make_chart("IBM") })
output$plot_goog <- renderPlot({ make_chart("GOOG") })
output$plot_yhoo <- renderPlot({ make_chart("YHOO") })
})
shinyUI(pageWithSidebar(
headerPanel("Stocks"),
sidebarPanel(
wellPanel(
p(strong("Stocks")),
checkboxInput(inputId = "stock_aapl", label = "Apple (AAPL)", value = TRUE),
checkboxInput(inputId = "stock_msft", label = "Microsoft (MSFT)", value = FALSE),
checkboxInput(inputId = "stock_ibm", label = "IBM (IBM)", value = FALSE),
checkboxInput(inputId = "stock_goog", label = "Google (GOOG)", value = TRUE),
checkboxInput(inputId = "stock_yhoo", label = "Yahoo (YHOO)", value = FALSE)
),
selectInput(inputId = "chart_type",
label = "Chart type",
choices = c("Candlestick" = "candlesticks",
"Matchstick" = "matchsticks",
"Bar" = "bars",
"Line" = "line")
),
wellPanel(
p(strong("Date range (back from present)")),
sliderInput(inputId = "time_num",
label = "Time number",
min = 1, max = 24, step = 1, value = 6),
selectInput(inputId = "time_unit",
label = "Time unit",
choices = c("Days" = "days",
"Weeks" = "weeks",
"Months" = "months",
"Years" = "years"),
selected = "Months")
),
checkboxInput(inputId = "log_y", label = "log y axis", value = FALSE)
),
mainPanel(
conditionalPanel(condition = "input.stock_aapl",
br(),
div(plotOutput(outputId = "plot_aapl"))),
conditionalPanel(condition = "input.stock_msft",
br(),
div(plotOutput(outputId = "plot_msft"))),
conditionalPanel(condition = "input.stock_ibm",
br(),
div(plotOutput(outputId = "plot_ibm"))),
conditionalPanel(condition = "input.stock_goog",
br(),
div(plotOutput(outputId = "plot_goog"))),
conditionalPanel(condition = "input.stock_yhoo",
br(),
plotOutput(outputId = "plot_yhoo"))
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment