my_api_key <- ‘2KQlSWTEhYhZZ39VPYOLp3BWyfoQwwWe’ library(PerformanceAnalytics) library(dygraphs) library(bslib) library(simfinR) library(dplyr) library(ggplot2) library(lubridate) library(shiny) library(shinythemes) library(shinyWidgets) library(DT) library(scales) library(ggridges) library(gridExtra) library(curl) library(tidyquant) library(quantmod) library(purrr) library(tidyverse) library(plotly)

df_info_companies <- simfinR_get_available_companies(my_api_key)

check it

glimpse(df_info_companies)

id_companies <- c(56317,1016068,858327,825113,125620,825112,249937,1202766,104458,996264) type_statements <- ‘pl’ periods = c(‘FY’) years = 2009:2021 df_fin_FY <- simfinR_get_fin_statements( id_companies, type_statements = type_statements, periods = periods, years = years, api_key = my_api_key) glimpse(df_fin_FY) df_fin_FY <- na.omit(df_fin_FY) NI <- df_fin_FY %>% filter(acc_name==“Net Income”,company_name == “Tesla”) %>% select(acc_value,year) df_tesla <- filter(df_fin_FY,company_name == “Tesla”) df_tesla <- select(df_fin_FY,acc_value,year,acc_name) NI_dt <- datatable(df_tesla)

tickers = c(“BMWYY”, “F”, “DDAIF”, “GM”, “PII”, “RACE”,“TSLA”, “VWAPY”)

getSymbols(tickers, from = “2015-10-21”, to = “2021-12-31”) stck_prc1 <- map(tickers,function(x) Ad(get(x))) stck_prc1 <- reduce(stck_prc1,merge) colnames(stck_prc1) <- tickers

names(stck_prc1)[names(stck_prc1) == “BMWYY”] <- “BMW-Group” names(stck_prc1)[names(stck_prc1) == “DDAIF”] <- “Daimler-AG” names(stck_prc1)[names(stck_prc1) == “F”] <- “Ford-Motors” names(stck_prc1)[names(stck_prc1) == “GM”] <- “General-Motors” names(stck_prc1)[names(stck_prc1) == “PII”] <- “Polaris-Industries” names(stck_prc1)[names(stck_prc1) == “RACE”] <- “Ferrari-NV” names(stck_prc1)[names(stck_prc1) == “TSLA”] <- “Tesla” names(stck_prc1)[names(stck_prc1) == “VWAPY”] <- “Volksvagen”

dt <- as.data.frame(colnames(stck_prc1)) mln <- as.data.frame(stck_prc1)

stck_prc <- datatable(mln)

prices_monthly <- to.monthly(stck_prc1, indexAt = “last”, OHLC = FALSE) # indexAt = ‘endof’

monthly.ret <- na.omit(Return.calculate(prices_monthly, method = “discrete”))

names(monthly.ret)[names(monthly.ret) == “BMWYY”] <- “BMW-Group” names(monthly.ret)[names(monthly.ret) == “DDAIF”] <- “Daimler-AG” names(monthly.ret)[names(monthly.ret) == “F”] <- “Ford-Motors” names(monthly.ret)[names(monthly.ret) == “GM”] <- “General-Motors” names(monthly.ret)[names(monthly.ret) == “PII”] <- “Polaris-Industries” names(monthly.ret)[names(monthly.ret) == “RACE”] <- “Ferrari-NV” names(monthly.ret)[names(monthly.ret) == “TSLA”] <- “Tesla” names(monthly.ret)[names(monthly.ret) == “VWAPY”] <- “Volksvagen”

daily.ret <- na.omit(Return.calculate(stck_prc1, method = “discrete”))

names(daily.ret)[names(daily.ret) == “BMWYY”] <- “BMW-Group” names(daily.ret)[names(daily.ret) == “DDAIF”] <- “Daimler-AG” names(daily.ret)[names(daily.ret) == “F”] <- “Ford-Motors” names(daily.ret)[names(daily.ret) == “GM”] <- “General-Motors” names(daily.ret)[names(daily.ret) == “PII”] <- “Polaris-Industries” names(daily.ret)[names(daily.ret) == “RACE”] <- “Ferrari-NV” names(daily.ret)[names(daily.ret) == “TSLA”] <- “Tesla” names(daily.ret)[names(daily.ret) == “VWAPY”] <- “Volksvagen”

stock_list_tbl <- c(“BMWYY”, “F”, “DDAIF”, “GM”, “PII”, “RACE”,“TSLA”, “VWAPY”) ############### stock_list_table <- as.data.frame(stock_list_tbl) ########### names(stock_list_table)[names(stock_list_table) == “stock_list_tbl”] <- “Label” ##############3

#question3 tickersss <- c(“BMWYY”, “F”, “DDAIF”, “GM”, “PII”, “RACE”,“TSLA”, “VWAPY”) benchmarks <- c(“NDX”,”GSPC”) # Nasdaq100 and SP500 prices <- tq_get(tickersss, get = “stock.prices”, from = “2015-10-21”, to = “2021-12-31”, complete_cases = F) %>% select(symbol,date,close) bench <- tq_get(benchmarks, get = “stock.prices”, from = “2015-10-21”, to = “2021-12-31”) %>% select(symbol,date,close) ############### ui <- navbarPage( #theme = shinytheme(‘flatly’), theme = bs_theme(version = 4, bootswatch = “cosmo”),

title = div(img(src=“jane.png”,width = 108, height = 108),img(src=“headshot.jpg”,width = 108, height = 108),HTML(“Tran Viet Hung - 110035102
              Jane-108039004”)), # App Title #################################### #question3 #############################3 tabPanel(“Stock trends”, # Title titlePanel(“My Tech Stock Portfolio”),

       # Sidebar 
       sidebarLayout(
         sidebarPanel(width = 3,
                      
                      # Let user pick stocks
                      pickerInput(
                        inputId = "stocks",
                        label = h4("Stocks"),
                        choices = c(
                          "BMW-Group"       = tickersss[1], 
                          "Ford-Motors"   = tickersss[2],
                          "Daimler-AG"      = tickersss[3],
                          "General-Motors"         = tickersss[4],
                          "Polaris-Industries"    = tickersss[5],
                          "Ferrari-NV"     = tickersss[6],
                          "Tesla"       = tickersss[7],
                          "Volksvagen" = tickersss[8]),
                        selected = tickersss,   
                        options = list(actions-box = TRUE), 
                        multiple = T
                      ),# Pick time period
                      radioButtons("period", label = h4("Period"),
                                   choices = list("1 month" = 1, "3 months" = 2, "6 months" = 3, "12 months" = 4, "YTD" = 5), 
                                   selected = 4
                      ),
                      
                      # Pick benchmark
                      radioButtons("benchmark", label = h4("Benchmark"),
                                   choices = list("SP500" = 1, "Nasdaq100" = 2,"None" = 3),
                                   selected = 3)
         ),
         
         # Plot results
         mainPanel(
           plotlyOutput("plot",height=800)
         )
       )

), ############### tabPanel(“Net income Graph”, fluidRow( column(9, wellPanel(style = “background-color: #fff; border-color: #2c3e50; height: 720px;”, plotOutput(“NI_graph”, height = 680,click = “plot_click”)), verbatimTextOutput(“info”)), column(3, fluidRow(column(12, wellPanel(style = “background-color: #fff; border-color: #2c3e50;width : 100%; height: 100%;”, p(tags$b(“Income statement:”, style = “font-size: 102%”)), fluidRow(column(12, align = ‘right’, DTOutput(“tbl_tsla”))))))

         ))),

tabPanel(“About”, fluidRow( column(12, wellPanel(style = “background-color: #fff; border-color: #2c3e50;”, includeHTML(“https://www.slickcharts.com/sp500”))))), tabPanel(“Competitor Detail”, fluidRow( column(7, fluidRow(column(12, wellPanel(style = “background-color: #fff; border-color: #2c3e50; height: 100px;”, fluidRow(style = ‘margin-top: 18px’, column(4, style = ‘margin-top: 7px’, align = ‘right’, p(“Select a company:”)), column(8, align = “left”, selectizeInput(inputId = “competitors”, label = NULL, choices = colnames(daily.ret), selected = “Tesla”, multiple = F, options = list(maxOptions = 1500))))))), fluidRow(column(12, wellPanel(style = “background-color: #fff; border-color: #2c3e50;width: 100%; height: 100%;”, DTOutput(“compet_tbl”))))), column(5, # Error Message Appearance tags\(head(tags\)style(HTML(“.shiny-output-error-validation { font-style: italic; font-size: 125%; }”))), wellPanel(style = “background-color: #fff; border-color: #2c3e50; height: 800px;”, fluidRow(column(12, p(“Selected company’s net income graph”), plotOutput(“com_ni”, height = 340), verbatimTextOutput(“det”))), fluidRow(column(12, p(“Selected company’s revenue graph”), plotOutput(“com_sales”, height = 340) )))))), tabPanel(“Stock prices”, fluidRow( column(8,

                fluidRow(column(12, 
                                wellPanel(style = "background-color: #fff; border-color: #2c3e50;width: 100%; height: 100%;",
                                          DTOutput("stock_price"))))),
         column(4,
                # Error Message Appearance
                tags$head(tags$style(HTML(".shiny-output-error-validation { font-style: italic; font-size: 125%; }"))),
                wellPanel(style = "background-color: #fff; border-color: #2c3e50; height: 800px;",
                          fluidRow(column(12, p("Daily return"),
                                          dygraphOutput("daily_ret_gr", height = 340),
                          )),
                          fluidRow(column(12, p("Monthly return"),
                                          dygraphOutput("monthly_ret_gr", height = 340)
                          )))))),

)

server <- function(input, output, session) {

output\(NI_graph <- renderPlot({ NI %>% ggplot(aes(x = NI\)year, y = NI\(acc_value))+ geom_bar(stat = 'identity')+ labs(x = 'year', y = 'Net Income')}) output\)info <- renderPrint({ req(input\(plot_click) x <- round(input\)plot_click\(x, 2) y <- round(input\)plot_click$y, 2) cat(“[”, x, ”, ”, y, ”]”, sep = ““)

}) output\(tbl_tsla <- renderDataTable(NI_dt, options = list(pageLenght = 5)) df_fin_FY <- select(df_fin_FY,company_name,company_sector,year,acc_name,acc_value,period) df_fin_FY_dt <- datatable(df_fin_FY) output\)compet_tbl <- renderDataTable(df_fin_FY_dt)

output\(com_ni <- renderPlot({ NI_all <- df_fin_FY %>% filter(acc_name=="Net Income",company_name == input\)competitors) %>% select(acc_value,year) NI_all %>% ggplot(aes(x = year, y = acc_value))+ geom_bar(stat = ‘identity’)+ labs(x = ‘year’, y = ‘Net Income’) }) output\(com_sales <- renderPlot({ NI_all <- df_fin_FY %>% filter(acc_name=="Revenue",company_name == input\)competitors) %>% select(acc_value,year) NI_all %>% ggplot(aes(x = year, y = acc_value))+ geom_bar(stat = ‘identity’)+ labs(x = ‘year’, y = ‘Net Income’) }) max(daily.ret) min(daily.ret) output\(stock_price <- renderDataTable(stck_prc) output\)daily_ret_gr <- renderDygraph({ dygraph(daily.ret) %>% dyAxis(“y”, label = “Returns”,valueRange = c(-2,2)) %>% dyRangeSelector() } ) max(monthly.ret) min(monthly.ret) output$monthly_ret_gr <- renderDygraph({ dygraph(monthly.ret) %>% dyAxis(“y”, label = “Returns”,valueRange = c(-2,2)) %>% dyRangeSelector() }

) ###################################

#question 3 ############ # server logic based on user input observeEvent(c(input\(period,input\)stocks,input$benchmark), {

prices <- prices %>%
  filter(symbol %in% input$stocks)

if (input$period == 1) {
  prices <- prices %>%
    filter(
      date >= today()-months(1)) }

if (input$period == 2) {
  prices <- prices %>%
    filter(date >= today()-months(3)) }

if (input$period == 3) {
  prices <- prices %>%
    filter(date >= today()-months(6)) }

if (input$period == 5) {
  prices <- prices %>%
    filter(year(date) == year(today())) }

if (input$benchmark == 1) {
  bench <- bench %>%
    filter(symbol=="^GSPC",
           date >= min(prices$date))
  prices <- rbind(prices,bench) }

if (input$benchmark == 2) {
  bench <- bench %>%
    filter(symbol=="^NDX",
           date >= min(prices$date))
  prices <- rbind(prices,bench) }

# Create plot
output$plot <- renderPlotly({
  print(
    ggplotly(prices %>%
               group_by(symbol) %>%
               mutate(init_close = if_else(date == min(date),close,NA_real_)) %>%
               mutate(value = round(100 * close / sum(init_close,na.rm=T),1)) %>%
               ungroup() %>%
               ggplot(aes(date, value,colour = symbol)) +
               geom_line(size = 1, alpha = .9) +
               # uncomment the line below to show area under curves
               #geom_area(aes(fill=symbol),position="identity",alpha=.2) +
               theme_minimal(base_size=16) +
               theme(axis.title=element_blank(),
                     plot.background = element_rect(fill = "black"),
                     panel.background = element_rect(fill="black"),
                     panel.grid = element_blank(),
                     legend.text = element_text(colour="white"))
    )
  )
})

}) } shinyApp(ui, server)