#stock prices app
#install.packages("shiny")
#install.packages("quantmod")
#load packages
library(shiny)
library(quantmod)
library(dplyr)
ret <- function(buy,sell){ #create a function that returns a return given buy price and sell price
round(((sell-buy)/buy)*100,2)
}
ui <- fluidPage(# main argument for ui
titlePanel("Stock Price Analysis"), #top panel
sidebarLayout( #for side and main panel
sidebarPanel(# creates side bar panel
h3("Instructions"),
h5("Please Read Carefully"),
h6("Enjoy your trading"),
helpText("Select a stock to examine.
Select dates of interest for the graph and return calculation.
Information will be collected from Yahoo Finance."), #generate help text
textInput(inputId = "symb", label = "Ticker Symbol", "SPY"), #label symbol, defaul is SPY
dateRangeInput("dates", #input ID for function that receives two dates and generates a vector across the range
"Date range to view",
start = "2013-01-01",
end = as.character(Sys.Date())),
dateInput("dateBought", #input ID
"Date stock is bought",
value = "2015-01-02"),
dateInput("dateSold", #input ID
"Date stock is sold",
value = "2015-01-10"),
), #close sidebarPanel
mainPanel(#main panel
img(src = "rstudio.png", height = 40, width = 100),##Includes the R studio image
h6("minimum"),
h2(htmlOutput("minprice")),
h6("maximum"),
h2(htmlOutput("maxprice")),
textOutput("text"), #output Text
plotOutput("plot") #output plot
) #close main panel
) #end sidebarLayout
) #end fluidPage
server <- function(input,output) {
stockPrices <- reactive({
getSymbols(input$symb, src = "yahoo",
from = input$dates[1],
to = input$dates[2],
auto.assign = FALSE)
})
output$text <- renderText({
buyPrice <-
getSymbols(input$symb, src = "yahoo",
from = input$dateBought,
to = as.Date(input$dateBought)+5,
auto.assign = FALSE)
sellPrice <-
getSymbols(input$symb, src = "yahoo",
from = input$dateSold,
to = as.Date(input$dateSold)+5,
auto.assign = FALSE)
paste("Your return is",paste0(ret(as.numeric(buyPrice[1,1]),as.numeric(sellPrice[1,1])),"%"))
})
output$plot <- renderPlot({
chartSeries(stockPrices(), theme = chartTheme("white"),
type = "line", TA = NULL, name = paste(input$symb, "Prices"))
output$minprice <- renderText(
paste('Price : $', min(stockPrices[,2]), '<br>Date :', rownames(stockPrices)[which.min(stockPrices$Price)] )
)
output$maxprice <- renderText(
paste('Price : $', max(stockPrices[,2]), '<br>Date :', rownames(stockPrices)[which.max(stockPrices$Price)] )
)
})
}
shinyApp(ui, server) #run app