Last active
April 16, 2018 05:40
-
-
Save martynscn/b6c06e984a7585f4b1efd96b2369ee0b to your computer and use it in GitHub Desktop.
ShinyCode_20180415
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load packages ---- | |
library(shiny) | |
library(quantmod) | |
# Source helpers ---- | |
# source("helpers.R") | |
if (!exists(".inflation")) { | |
.inflation <- getSymbols('CPIAUCNS', src = 'FRED', | |
auto.assign = FALSE) | |
} | |
# adjusts Google finance data with the monthly consumer price index | |
# values provided by the Federal Reserve of St. Louis | |
# historical prices are returned in present values | |
adjust <- function(data) { | |
latestcpi <- last(.inflation)[[1]] | |
inf.latest <- time(last(.inflation)) | |
months <- split(data) | |
adjust_month <- function(month) { | |
date <- substr(min(time(month[1]), inf.latest), 1, 7) | |
coredata(month) * latestcpi / .inflation[date][[1]] | |
} | |
adjs <- lapply(months, adjust_month) | |
adj <- do.call("rbind", adjs) | |
axts <- xts(adj, order.by = time(data)) | |
axts[ , 5] <- Vo(data) | |
axts | |
} | |
# User interface ---- | |
ui <- fluidPage( | |
titlePanel("stockVis"), | |
sidebarLayout( | |
sidebarPanel( | |
helpText("Select a stock to examine. | |
Information will be collected from Google finance."), | |
textInput("symb", "Symbol", "SPY"), | |
dateRangeInput("dates", | |
"Date range", | |
start = "2013-01-01", | |
end = as.character(Sys.Date())), | |
br(), | |
br(), | |
checkboxInput("log", "Plot y axis on log scale", | |
value = FALSE), | |
checkboxInput("adjust", | |
"Adjust prices for inflation", value = FALSE) | |
), | |
mainPanel(plotOutput("plot")) | |
) | |
) | |
# Server logic | |
server <- function(input, output) { | |
dataInput <- reactive({ | |
getSymbols(input$symb, src = "yahoo", | |
from = input$dates[1], | |
to = input$dates[2], | |
auto.assign = FALSE) | |
}) | |
finalInput <- reactive({ | |
if(!input$adjust) return(dataInput()) | |
adjust(dataInput()) | |
}) | |
output$plot <- renderPlot({ | |
chartSeries(finalInput(), theme = chartTheme("white"), | |
type = "line", log.scale = input$log, TA = NULL) | |
}) | |
} | |
# Run the app | |
shinyApp(ui, server) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment