---
title: "Stocks dashboard"
Author: "Venkata Surya Vadrevu, Raavi Anvesh"
output:
flexdashboard::flex_dashboard:
orientation: rows
social: menu
source_code: embed
---
```{r setup, include=FALSE}
library(quantmod)
library(flexdashboard)
library(dygraphs)
library(xts)
library(tidyverse)
library(TTR)
library(DT)
yahooTickerSymbols = c("PYPL", "SQ", "V", "BABA", "^GSPC", "^DJI")
oneYear = Sys.Date() - 365
getSymbols(yahooTickerSymbols, src = 'yahoo', auto.assign = TRUE, warnings = FALSE, from = oneYear)
SP500 = GSPC
rm(GSPC)
tempColnames = gsub("GSPC", "SP500", colnames(SP500))
colnames(SP500) = tempColnames
tickers = c("PYPL", "SQ", "V", "BABA", "SP500", "DJI")
colnames(PYPL) = c("Open", "High", "Low", "Close", "Volume.in.Million", "Adjusted")
colnames(SQ) = c("Open", "High", "Low", "Close", "Volume.in.Million", "Adjusted")
colnames(V) = c("Open", "High", "Low", "Close", "Volume.in.Million", "Adjusted")
colnames(BABA) = c("Open", "High", "Low", "Close", "Volume.in.Million", "Adjusted")
colnames(DJI) = c("Open", "High", "Low", "Close", "Volume.in.Million", "Adjusted")
colnames(SP500) = c("Open", "High", "Low", "Close", "Volume.in.Million", "Adjusted")
PYPL$`Volume.in.Million` = PYPL$`Volume.in.Million`/1000000
SQ$`Volume.in.Million` = SQ$`Volume.in.Million`/1000000
V$`Volume.in.Million` = V$`Volume.in.Million`/1000000
BABA$`Volume.in.Million` = BABA$`Volume.in.Million`/1000000
SP500$`Volume.in.Million` = SP500$`Volume.in.Million`/1000000
DJI$`Volume.in.Million` = DJI$`Volume.in.Million`/1000000
PYPL = cbind(PYPL[,-5],PYPL[,5])
SQ = cbind(SQ[,-5],SQ[,5])
V = cbind(V[,-5],V[,5])
BABA = cbind(BABA[,-5],BABA[,5])
SP500 = cbind(SP500[,-5],SP500[,5])
DJI = cbind(DJI[,-5],DJI[,5])
# get combined data
openPrice = do.call(merge, lapply(tickers, function(x) Op(get(x))))
closePrice = do.call(merge, lapply(tickers, function(x) Cl(get(x))))
lowPrice = do.call(merge, lapply(tickers, function(x) Lo(get(x))))
highPrice = do.call(merge, lapply(tickers, function(x) Hi(get(x))))
volume = do.call(merge, lapply(tickers, function(x) Vo(get(x))))
openClosePercentageChange = do.call(merge, lapply(tickers, function(x) OpCl(get(x))*100))
closeClosePercentageChange = do.call(merge, lapply(tickers, function(x) ClCl(get(x))*100))
closeClosePercentageChange = closeClosePercentageChange[-1,]
colnames(openPrice) = tickers
colnames(closePrice) = tickers
colnames(lowPrice) = tickers
colnames(highPrice) = tickers
colnames(volume) = tickers
colnames(openClosePercentageChange) = tickers
colnames(closeClosePercentageChange) = tickers
mov.avgs<-function(stock.close){
x<-data.frame(stock.close, SMA(stock.close, 50), SMA(stock.close, 25))
colnames(x)<-c(names(stock.close), 'sma_50','sma_25')
#x<-x[complete.cases(x$sma_50),]
return(x)
}
closePriceWithMA<-lapply(closePrice, mov.avgs)
buyOrSell <- "function(rawData) {
var ribbonData = [];
var sma_50_index = 2;
var sma_25_index = 3;
for (var i = 0; i < rawData.length; i++) {
var row = rawData[i];
var sma_50 = row[sma_50_index];
var sma_25 = row[sma_25_index];
if (sma_50 < sma_25) {
ribbonData.push(1);
} else {
ribbonData.push(0);
}
}
return ribbonData;
}"
PaypalCandleStick = cbind(PYPL[,-6], closePriceWithMA$PYPL$sma_50, closePriceWithMA$PYPL$sma_25)
colnames(PaypalCandleStick)[6] = "sma_50"
colnames(PaypalCandleStick)[7] = "sma_25"
SquareCandleStick = cbind(SQ[,-6], closePriceWithMA$SQ$sma_50, closePriceWithMA$SQ$sma_25)
colnames(SquareCandleStick)[6] = "sma_50"
colnames(SquareCandleStick)[7] = "sma_25"
VisaCandleStick = cbind(V[,-6], closePriceWithMA$V$sma_50, closePriceWithMA$V$sma_25)
colnames(VisaCandleStick)[6] = "sma_50"
colnames(VisaCandleStick)[7] = "sma_25"
AlibabaCandleStick = cbind(BABA[,-6], closePriceWithMA$BABA$sma_50, closePriceWithMA$BABA$sma_25)
colnames(AlibabaCandleStick)[6] = "sma_50"
colnames(AlibabaCandleStick)[7] = "sma_25"
SP500CandleStick = cbind(SP500[,-6], closePriceWithMA$SP500$sma_50, closePriceWithMA$SP500$sma_25)
colnames(SP500CandleStick)[6] = "sma_50"
colnames(SP500CandleStick)[7] = "sma_25"
DJICandleStick = cbind(DJI[,-6], closePriceWithMA$DJI$sma_50, closePriceWithMA$DJI$sma_25)
colnames(DJICandleStick)[6] = "sma_50"
colnames(DJICandleStick)[7] = "sma_25"
Volume = volume[,1:4]
what_metrics <- yahooQF(c("P/E Ratio",
"Price/EPS Estimate Next Year",
"200-day Moving Average",
"Market Capitalization",
"Percent Change From 200-day Moving Average",
"52-week High",
"52-week Low"
))
tickers <- c("PYPL", "SQ","V", "BABA")
metrics <- getQuote(paste(tickers, sep="", collapse=";"),what=what_metrics)
metrics = data.frame(metrics)
metrics = metrics[,-1]
metrics$Market.Capitalization = metrics$Market.Cap/1000000000
metrics$Market.Capitalization = round(metrics$Market.Cap, digits = 2)
colnames(metrics) = c("PE.Ratio", "EPS.Estimate.Next.Year", "Market.Cap.In.Billions",
"200.Day.MA", "Percentage.Change.From.200.Day.MA", "52.Week.High", "52.Week.Low")
closePrice.df = data.frame(closePrice)
endIndex = length(closePrice.df$PYPL)
Paypal_KPI = round((closePrice.df$PYPL[endIndex] - closePrice.df$PYPL[1])*100/closePrice.df$PYPL[1], digits = 2)
Square_KPI = round((closePrice.df$SQ[endIndex] - closePrice.df$SQ[1])*100/closePrice.df$SQ[1], digits = 2)
Visa_KPI = round((closePrice.df$V[endIndex] - closePrice.df$V[1])*100/closePrice.df$V[1], digits = 2)
Alibaba_KPI = round((closePrice.df$BABA[endIndex] - closePrice.df$BABA[1])*100/closePrice.df$BABA[1], digits = 2)
SP500_KPI = round((closePrice.df$SP500[endIndex] - closePrice.df$SP500[1])*100/closePrice.df$SP500[1], digits = 2)
DJI_KPI = round((closePrice.df$DJI[endIndex] - closePrice.df$DJI[1])*100/closePrice.df$DJI[1], digits = 2)
get.color = function(metric){
retColor = ""
if (metric > 100) {
retColor = "success"
}else if (metric > 50) {
retColor = "primary"
}else if (metric <= 50 & metric > 25) {
retColor = "warning"
}else {
retColor = "danger"
}
return(retColor)
}
get.icon = function(metric){
retIcon = ""
if (metric >= 100) {
retIcon = "fa-battery-full"
}else if (75 >= metric & metric > 50){
retIcon = "fa-battery-three-quarters"
}else if (50 >= metric & metric > 25){
retIcon = "fa-battery-half"
}else if (25 >= metric & metric > 0){
retIcon = "fa-battery-quarter"
}else{
retIcon = "fa-battery-empty"
}
return(retIcon)
}
convert.kpis = function(vector){
vectorString = c()
for (i in 1: length(vector)){
if (vector[i] > 0){
vectorString[i] = paste("+", toString(vector[i]), "%", sep = "")
}else{
vectorString[i] = paste("-", toString(vector[i]), "%", sep = "")
}
}
return(vectorString)
}
KPIS = c(Paypal_KPI, Square_KPI, Visa_KPI, Alibaba_KPI, SP500_KPI, DJI_KPI)
StringKPIS = convert.kpis(KPIS)
```
Candlestick Charts and KPI's {data-orientation=rows}
==========================================================================
Sidebar {.sidebar}
-----------------------------------------------------------------------
### Payment Stocks Analyses
This dashboard looks into the stock prices of 4 payment companies : Paypal (PYPL), Square (SQ), Visa (V) and Alibaba (BABA) over a period of 1 year. We also compare the 4 stocks against standard stock market indices such as S&P 500 and Dow Jones Index to see if they outperformed the overall stock market.
Row {data-height=200}
-----------------------------------------------------------------------
### Square
```{r}
valueBox(value = StringKPIS[2],
icon = get.icon(Square_KPI),
color = get.color(Square_KPI))
```
### Paypal
```{r}
valueBox(value = StringKPIS[1],
icon = get.icon(Paypal_KPI),
color = get.color(Paypal_KPI))
```
### Visa
```{r}
valueBox(value = StringKPIS[3],
icon = get.icon(Visa_KPI),
color = get.color(Visa_KPI))
```
### Alibaba
```{r}
valueBox(value = StringKPIS[4],
icon = get.icon(Alibaba_KPI),
color = get.color(Alibaba_KPI))
```
### Dow Jones Index
```{r}
valueBox(value = StringKPIS[6],
icon = get.icon(DJI_KPI),
color = get.color(DJI_KPI))
```
### S&P 500 Index
```{r}
valueBox(value = StringKPIS[5],
icon = get.icon(SP500_KPI),
color = get.color(SP500_KPI))
```
Row {.tabset .tabset-fade}
-----------------------------------------------------------------------
### Paypal Stock price - PYPL
```{r}
dygraph(PaypalCandleStick, main = "Paypal") %>%
dyUnzoom() %>%
dyAxis("y", label="Price") %>%
dyCandlestick() %>%
dyOptions(colors= c(RColorBrewer::brewer.pal(5, "Set2"), "red", "blue")) %>%
dyHighlight(highlightCircleSize = 2, highlightSeriesOpts = list(strokeWidth = 2)) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
### Square Stock Price - SQ
```{r}
dygraph(SquareCandleStick, main = "Square") %>%
dyUnzoom() %>%
dyCandlestick() %>%
dyAxis("y", label="Price") %>%
dyOptions(colors= c(RColorBrewer::brewer.pal(5, "Set2"), "red", "blue")) %>%
dyHighlight(highlightCircleSize = 2, highlightSeriesOpts = list(strokeWidth = 2)) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
### Visa Stock Price - V
```{r}
dygraph(VisaCandleStick, main = "Visa") %>%
dyUnzoom() %>%
dyCandlestick() %>%
dyAxis("y", label="Price") %>%
dyOptions(colors= c(RColorBrewer::brewer.pal(5, "Set2"), "red", "blue")) %>%
dyHighlight(highlightCircleSize = 2, highlightSeriesOpts = list(strokeWidth = 2)) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
### Alibaba Stock Price - BABA
```{r}
dygraph(AlibabaCandleStick, main = "Alibaba") %>%
dyUnzoom() %>%
dyCandlestick() %>%
dyAxis("y", label="Price") %>%
dyOptions(colors= c(RColorBrewer::brewer.pal(5, "Set2"), "red", "blue")) %>%
dyHighlight(highlightCircleSize = 2, highlightSeriesOpts = list(strokeWidth = 2)) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
### S&P 500 Index
```{r}
dygraph(SP500CandleStick, main = " S&P 500 Index") %>%
dyUnzoom() %>%
dyCandlestick() %>%
dyOptions(colors= c(RColorBrewer::brewer.pal(5, "Set2"), "red", "blue")) %>%
dyHighlight(highlightCircleSize = 2, highlightSeriesOpts = list(strokeWidth = 2)) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
### Dow Jones Industrial Average Index
```{r}
dygraph(DJICandleStick, main = "Dow Jones Index") %>%
dyUnzoom() %>%
dyCandlestick() %>%
dyOptions(colors= c(RColorBrewer::brewer.pal(5, "Set2"), "red", "blue")) %>%
dyHighlight(highlightCircleSize = 2, highlightSeriesOpts = list(strokeWidth = 2)) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
Row {data-height=400}
-----------------------------------------------------------------------
### Metrics
```{r}
datatable(metrics) %>%
formatStyle(
'Market.Cap.In.Billions',
background = styleColorBar(metrics$Market.Cap.In.Billions, 'lightpink'),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center'
) %>%
formatStyle(
'Percentage.Change.From.200.Day.MA',
background = styleColorBar(metrics$Percentage.Change.From.200.Day.MA, 'lightblue'),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = "center"
) %>%
formatStyle(
'EPS.Estimate.Next.Year',
background = styleColorBar(metrics$EPS.Estimate.Next.Year, 'lightgreen'),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center'
)
```
Comparison Charts {data-orientation=columns}
==========================================================================
Sidebar {.sidebar}
-----------------------------------------------------------------------
### Comparison Graphs
Here we compare the closing prices, % change in stock price over time, stock volume per day, % change in stock price in a single trading day.
Column {data-width=400}
------------------------------------------------------------------------------
### Closing Prices
```{r}
dygraph(closePrice[,1:4], main = "Closing Price") %>%
dyUnzoom() %>%
dyAxis("y", label="Price in $") %>%
dyOptions(colors = RColorBrewer::brewer.pal(6, "Set2")) %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
dyRangeSelector(height = 25)
```
### Percent Change Comparison
```{r}
dygraph(closePrice, main = "% Change in Price") %>%
dyUnzoom() %>%
dyRebase(percent = TRUE) %>%
dyOptions(colors = RColorBrewer::brewer.pal(6, "Set2")) %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
dyRangeSelector(height = 25)
```
Column {data-width=400}
-------------------------------------
### Volume comparison
```{r}
dygraph(Volume, main = "Volume") %>%
dyUnzoom() %>%
dyAxis("y", label="Stock Volume in Millions") %>%
dyStackedRibbonGroup(name = c("PYPL", "SQ", "V", "BABA")) %>%
dyOptions(colors= RColorBrewer::brewer.pal(4, "Set2")) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
### Intra Day % Change comparison
```{r}
dygraph(openClosePercentageChange, main = "Percentage Change From Open to Close") %>%
dyUnzoom() %>%
dyAxis("y", label="Intraday % Change") %>%
dyGroup(c("SP500", "DJI"), color = c("red", "black"), strokeWidth = 2, fillGraph = FALSE)%>%
dyGroup(c("PYPL", "SQ", "V", "BABA"), color = RColorBrewer::brewer.pal(4, "Set2"), strokeWidth = 1, fillGraph = "TRUE") %>%
dyOptions(stepPlot = FALSE, fillAlpha = 0.2) %>%
dyRangeSelector(height = 25) %>%
dyLegend(show = "onmouseover")
```
Moving Average Buy/Sell Time Charts {data-orientation=rows}
==========================================================================
Sidebar {.sidebar}
-----------------------------------------------------------------------
### Moving Average based buy/sell signals
In this dashboard we look at the 50-day simple moving average (sma 50) and 25-day simple moving average (sma 25) of the stock prices. If (sma 25) > (sma 50), then we shade the graph "green", indicating a buy/hold signal based on current trend. If (sma 25) <= (sma 50), then we shade the graph "red", indicating a sell signal.
Row {.tabset .tabset-fade}
-----------------------------------------------------------------------
### Paypal
```{r}
dygraph(closePriceWithMA$PYPL,main = 'Paypal Moving Averages') %>%
dyUnzoom() %>%
dySeries('PYPL', label = 'closing price') %>%
dySeries('sma_25', label = 'sma 25') %>%
dySeries('sma_50', label = 'sma 50') %>%
dyOptions(colors = c("black", "green", "red")) %>%
dyRibbon(parser = buyOrSell,
palette = c('#CCEBD6', '#FFE6E6')) %>%
dyRangeSelector(height = 25)
```
### Square
```{r}
dygraph(closePriceWithMA$SQ,main = 'Square Moving Averages') %>%
dyUnzoom() %>%
dySeries('SQ', label = 'closing price') %>%
dySeries('sma_25', label = 'sma 25') %>%
dySeries('sma_50', label = 'sma 50') %>%
dyOptions(colors = c("black", "green", "red")) %>%
dyRibbon(parser = buyOrSell,
palette = c('#CCEBD6', '#FFE6E6')) %>%
dyRangeSelector(height = 25)
```
### Visa
```{r}
dygraph(closePriceWithMA$V,main = 'Visa Moving Averages') %>%
dyUnzoom() %>%
dySeries('V', label = 'closing price') %>%
dySeries('sma_25', label = 'sma 25') %>%
dySeries('sma_50', label = 'sma 50') %>%
dyOptions(colors = c("black", "green", "red")) %>%
dyRibbon(parser = buyOrSell,
palette = c('#CCEBD6', '#FFE6E6')) %>%
dyRangeSelector(height = 25)
```
### Alibaba
```{r}
dygraph(closePriceWithMA$BABA, main = 'Alibaba Moving Averages') %>%
dyUnzoom() %>%
dySeries('BABA', label = 'closing price') %>%
dySeries('sma_25', label = 'sma 25') %>%
dySeries('sma_50', label = 'sma 50') %>%
dyOptions(colors = c("black", "green", "red")) %>%
dyRibbon(parser = buyOrSell,
palette = c('#CCEBD6', '#FFE6E6')) %>%
dyRangeSelector(height = 25)
```