Skip to content

Instantly share code, notes, and snippets.

@laineyliu0901

laineyliu0901/global.R

Last active Feb 5, 2018
Embed
What would you like to do?
Shiny Project 1
library("quantmod")
library("PerformanceAnalytics")
library ("timeSeries")
library ("timeDate")
library("shiny")
library("dplyr")
library("tibble")
library(DT)
library('data.table')
library('xts')
library("BatchGetSymbols")
tic <- read.csv("sp500.csv",header = FALSE, col.names = c('tic'))
row <- function(...) {
tags$div(class="row", ...)
}
col <- function(width, ...) {
tags$div(class=paste0("span", width), ...)
}
nameOfStrategy <- "Moving Average Strategy"
#source("portfolio1.R")
#Specify dates for downloading data, training models and running simulation
StartDate=as.Date("1989-01-01")
EndDate= as.Date("2018-01-02")
trainingStartDate = as.Date("1989-01-01")
trainingEndDate = as.Date("2018-01-02")
outofSampleStartDate = as.Date("2009-01-01")
outofSampleEndDate = as.Date("2018-01-02")
symbolData <- new.env()
getSymbols("^GSPC", env = symbolData, src = "yahoo", from = StartDate)
getSymbols("^DJI", env = symbolData, src = "yahoo", from = StartDate)
getSymbols("^IXIC", env = symbolData, src = "yahoo", from = StartDate)
Data_GSPC <- window(symbolData$GSPC, start = StartDate, end =EndDate)
Data_DJI <- window(symbolData$DJI, start = StartDate, end =EndDate)
Data_IXIC <- window(symbolData$IXIC, start = StartDate, end =EndDate)
RawData <- cbind(Data_GSPC, Data_DJI, Data_IXIC)
testData_GSPC <- window(symbolData$GSPC, start = outofSampleStartDate, end = outofSampleEndDate)
testData_DJI <- window(symbolData$DJI, start = outofSampleStartDate, end = outofSampleEndDate)
testData_IXIC <- window(symbolData$IXIC, start = outofSampleStartDate, end = outofSampleEndDate)
testData <- cbind(testData_GSPC, testData_GSPC, testData_IXIC)
indexReturns <- cbind(Delt(Cl(window(symbolData$GSPC, start = trainingStartDate))),
Delt(Cl(window(symbolData$DJI, start = trainingStartDate))),
Delt(Cl(window(symbolData$IXIC, start = trainingStartDate))))
colnames(indexReturns) <- c("GSPC Buy&Hold","DJI Buy&Hold", "IXIC Buy&Hold")
#########################################################################################
#
# setting up functions for calculation
#
#########################################################################################
TradingStrategy_MA <- function(mktdata,mavga_period,mavgb_period){
#Check moving averages at start of the day and use as the direciton signal
#Enter trade at the start of the day and exit at the close
#Lets print the name of whats running
runName <- paste(substr(colnames(mktdata)[1],1,nchar(colnames(mktdata)[1])-5),mavga_period,"SMA","and",mavgb_period,"SMA",sep=" ")
print(paste("Running Strategy: ",runName))
#Calculate the Open Close return
returns <- (Cl(mktdata)/Op(mktdata))-1
#Calculate the moving averages
mavga <- SMA(Op(mktdata),n=mavga_period)
mavgb <- SMA(Op(mktdata),n=mavgb_period)
# emavga <- EMA(Op(mktdata), n = mavga_period, wilder = FALSE, ratio = NULL)
# emavgb <- EMA(Op(mktdata), n = emavga_period, wilder = FALSE, ratio = NULL)
signal <- mavga / mavgb
#If mavga > mavgb go long
signal <- apply(signal,1,function (x) { if(is.na(x)){ return (0) } else { if(x>1){return (1)} else {return (-1)}}})
tradingreturns <- signal * returns
colnames(tradingreturns) <- runName
return (tradingreturns)
}
RunIterativeStrategy <- function(mktdata){
#This function will run the TradingStrategy
#It will iterate over a given set of input variables
#In this case we try lots of different periods for the moving average
firstRun <- TRUE
for(a in seq(from = 20, to = 80, by=10)){
for(b in seq(from = 100, to= 360, by=40)){
runResult <- TradingStrategy_MA(mktdata,a,b)
if(firstRun){
firstRun <- FALSE
results <- runResult
} else {
results <- cbind(results,runResult)
}
}
}
return(results)
}
CalculatePerformanceMetric <- function(returns,metric){
#Get given some returns in columns
#Apply the function metric to the data
print (paste("Calculating Performance Metric:",metric))
metricFunction <- match.fun(metric)
metricData <- as.matrix(metricFunction(returns))
#Some functions return the data the wrong way round
#Hence cant label columns to need to check and transpose it
if(nrow(metricData) == 1){
metricData <- t(metricData)
}
colnames(metricData) <- metric
return (metricData)
}
PerformanceTable <- function(returns){
pMetric <- CalculatePerformanceMetric(returns,"colSums")
pMetric <- cbind(pMetric,CalculatePerformanceMetric(returns,"SharpeRatio.annualized"))
pMetric <- cbind(pMetric,CalculatePerformanceMetric(returns,"maxDrawdown"))
colnames(pMetric) <- c("Profit","SharpeRatio","MaxDrawDown")
print("Performance Table")
print(pMetric)
return (pMetric)
}
OrderPerformanceTable <- function(performanceTable,metric){
return (performanceTable[order(performanceTable[,metric],decreasing=TRUE),])
}
SelectTopNStrategies <- function(returns,performanceTable,metric,n){
#Metric is the name of the function to apply to the column to select the Top N
#n is the number of strategies to select
pTab <- OrderPerformanceTable(performanceTable,metric)
if(n > ncol(returns)){
n <- ncol(returns)
}
strategyNames <- rownames(pTab)[1:n]
topNMetrics <- returns[,strategyNames]
return (topNMetrics)
}
FindOptimumStrategy <- function(trainingData_GSPC){
#Optimise the strategy
trainingReturns <- RunIterativeStrategy(trainingData_GSPC)
pTab <- PerformanceTable(trainingReturns)
toptrainingReturns <- SelectTopNStrategies(trainingReturns,pTab,"SharpeRatio",5)
OpPlot1 <- charts.PerformanceSummary(toptrainingReturns,main=paste(nameOfStrategy,"- Training"),geometric=FALSE)
return (pTab)
}
#########################################################################################
#
# functions ends
#
#########################################################################################
# blackscholes <- function(S, X, rf, T, sigma) {
# values <- c(2)
#
# d1 <- (log(S/X)+(rf+sigma^2/2)*T)/(sigma*sqrt(T))
# d2 <- d1 - sigma * sqrt(T)
#
# values[1] <- S*pnorm(d1) - X*exp(-rf*T)*pnorm(d2)
# values[2] <- X*exp(-rf*T) * pnorm(-d2) - S*pnorm(-d1)
#
# values}
#
#
# cal_Option <- function(tsfile,vec, r, T, sig){
# tsfile$call_atm = tsfile$vec *
# pnorm((log(1)+(r+sig^2/2)*T)/(sig*sqrt(T)))-
# tsfile$vec *
# pnorm(((log(1)+(r+sig^2/2)*T)/(sig*sqrt(T)))-sig*sqrt(T))*exp(-r*T)
# lag <- lag(tsfile$vec, k = -1)
# tsfile$call_new <- tsfile$vec *
# pnorm((log(tsfile$vec/lag)+(r+sig^2/2)*Tn)/(sig*sqrt(Tn)))-
# lag*pnorm(((log(tsfile$vec/lag)+(r+sig^2/2)*Tn)/(sig*sqrt(Tn)))-sig *sqrt(Tn))*exp(-r*Tn)
# tsfile$abreturn= tsfile$call_new - lag(tsfile$call_atm, k = -1)
# }
#########################################################################################
#
#Original R code
#
#########################################################################################
library("quantmod")
library("PerformanceAnalytics")
library ("timeSeries")
library ("timeDate")
library("BatchGetSymbols", quietly = T)
library("shiny")
library("dplyr")
library("tibble")
library('data.table')
nameOfStrategy <- "Moving Average Strategy"
#########################################################################################
#
#Download the data from Yahoo
#
#########################################################################################
#Specify dates for downloading data, training models and running simulation
StartDate=as.Date("1989-01-01")
EndDate= as.Date("2018-01-02")
trainingStartDate = as.Date("1989-01-01")
trainingEndDate = as.Date("2018-01-02")
outofSampleStartDate = as.Date("2009-01-01")
outofSampleEndDate = as.Date("2018-01-02")
symbolData <- new.env()
getSymbols("^GSPC", env = symbolData, src = "yahoo", from = StartDate)
getSymbols("^DJI", env = symbolData, src = "yahoo", from = StartDate)
getSymbols("^IXIC", env = symbolData, src = "yahoo", from = StartDate)
#HOW TO FUCKING SPECIFY THE START AND END WITH UI!!!!!
Data_GSPC <- window(symbolData$GSPC, start = StartDate, end =EndDate)
Data_DJI <- window(symbolData$DJI, start = StartDate, end =EndDate)
Data_IXIC <- window(symbolData$IXIC, start = StartDate, end =EndDate)
RawData <- cbind(Data_GSPC, Data_DJI, Data_IXIC)
testData_GSPC <- window(symbolData$GSPC, start = outofSampleStartDate, end = outofSampleEndDate)
testData_DJI <- window(symbolData$DJI, start = outofSampleStartDate, end = outofSampleEndDate)
testData_IXIC <- window(symbolData$IXIC, start = outofSampleStartDate, end = outofSampleEndDate)
testData <- cbind(testData_GSPC, testData_GSPC, testData_IXIC)
#########################################################################################
#
# Calculate the benchmark - basic buy and hold strategy
#
#########################################################################################
indexReturns <- cbind(Delt(Cl(window(symbolData$GSPC, start = outofSampleStartDate))),
Delt(Cl(window(symbolData$DJI, start = outofSampleStartDate))),
Delt(Cl(window(symbolData$IXIC, start = outofSampleStartDate))))
colnames(indexReturns) <- c("GSPC Buy&Hold","DJI Buy&Hold", "IXIC Buy&Hold")
#########################################################################################
#
# setting up functions for calculation
#
#########################################################################################
TradingStrategy_MA <- function(mktdata,mavga_period,mavgb_period){
#Check moving averages at start of the day and use as the direciton signal
#Enter trade at the start of the day and exit at the close
#Lets print the name of whats running
runName <- paste("MA _",mavga_period," OVER _",mavgb_period,sep="")
print(paste("Running Strategy: ",runName))
#Calculate the Open Close return
returns <- (Cl(mktdata)/Op(mktdata))-1
#Calculate the moving averages
mavga <- SMA(Op(mktdata),n=mavga_period)
mavgb <- SMA(Op(mktdata),n=mavgb_period)
# emavga <- EMA(Op(mktdata), n = mavga_period, wilder = FALSE, ratio = NULL)
# emavgb <- EMA(Op(mktdata), n = emavga_period, wilder = FALSE, ratio = NULL)
signal <- mavga / mavgb
#If mavga > mavgb go long
signal <- apply(signal,1,function (x) { if(is.na(x)){ return (0) } else { if(x>1){return (1)} else {return (-1)}}})
tradingreturns <- signal * returns
colnames(tradingreturns) <- runName
return (tradingreturns)
}
RunIterativeStrategy <- function(mktdata){
#This function will run the TradingStrategy
#It will iterate over a given set of input variables
#In this case we try lots of different periods for the moving average
firstRun <- TRUE
for(a in seq(from = 20, to = 120, by=20)){
for(b in seq(from = 120, to= 280, by=40)){
runResult <- TradingStrategy_MA(mktdata,a,b)
if(firstRun){
firstRun <- FALSE
results <- runResult
} else {
results <- cbind(results,runResult)
}
}
}
return(results)
}
CalculatePerformanceMetric <- function(returns,metric){
#Get given some returns in columns
#Apply the function metric to the data
print (paste("Calculating Performance Metric:",metric))
metricFunction <- match.fun(metric)
metricData <- as.matrix(metricFunction(returns))
#Some functions return the data the wrong way round
#Hence cant label columns to need to check and transpose it
if(nrow(metricData) == 1){
metricData <- t(metricData)
}
colnames(metricData) <- metric
return (metricData)
}
PerformanceTable <- function(returns){
pMetric <- CalculatePerformanceMetric(returns,"colSums")
pMetric <- cbind(pMetric,CalculatePerformanceMetric(returns,"SharpeRatio.annualized"))
pMetric <- cbind(pMetric,CalculatePerformanceMetric(returns,"maxDrawdown"))
colnames(pMetric) <- c("Profit","SharpeRatio","MaxDrawDown")
print("Performance Table")
print(pMetric)
return (pMetric)
}
OrderPerformanceTable <- function(performanceTable,metric){
return (performanceTable[order(performanceTable[,metric],decreasing=TRUE),])
}
SelectTopNStrategies <- function(returns,performanceTable,metric,n){
#Metric is the name of the function to apply to the column to select the Top N
#n is the number of strategies to select
pTab <- OrderPerformanceTable(performanceTable,metric)
if(n > ncol(returns)){
n <- ncol(returns)
}
strategyNames <- rownames(pTab)[1:n]
topNMetrics <- returns[,strategyNames]
return (topNMetrics)
}
FindOptimumStrategy <- function(trainingData_GSPC){
#Optimise the strategy
trainingReturns <- RunIterativeStrategy(trainingData_GSPC)
pTab <- PerformanceTable(trainingReturns)
toptrainingReturns <- SelectTopNStrategies(trainingReturns,pTab,"SharpeRatio",5)
charts.PerformanceSummary(toptrainingReturns,main=paste(nameOfStrategy,"- Training"),geometric=FALSE)
return (pTab)
}
pTab <- FindOptimumStrategy(Data_GSPC) #pTab is the performance table of the various parameters tested
#Test out of sample
dev.new()
#Manually specify the parameter that we want to trade here, just because a strategy is at the top of
#pTab it might not be good (maybe due to overfit)
outOfSampleReturns <- TradingStrategy_MA(testData_GSPC,mavga_period=60,mavgb_period=120)
finalReturns <- cbind(outOfSampleReturns,indexReturns)
charts.PerformanceSummary(finalReturns,main=paste(nameOfStrategy,"- Out of Sample"),geometric=FALSE)
shinyServer(function(input, output){
# x=c("Open", "High", "Low", "Close", "Volume")
# for (i in input$index[1:n]){
# y=paste(input$index[i],x,sep =".")
#
# sumy=paste(y,sum)
# }
#########################################################################################
#
# one function that needs user input, MA range
#
#########################################################################################
# Reactive Training Data set
TrainIndexSelected <- reactive({
RawData[paste(input$TrainingDateRange[1],input$TrainingDateRange[2], sep = "/") ,
paste(rep(input$index,each=6),
c("Open", "High", "Low", "Close", "Volume", "Adjusted"), sep = ".") ,
drop = FALSE]
})
# Reactive Testing Data set
TestIndexSelected <- reactive({
RawData[paste(input$TestingDateRange[1],input$TestingDateRange[2], sep = "/") ,
paste(rep(input$index,each=6),
c("Open", "High", "Low", "Close", "Volume", "Adjusted"), sep = ".") ,
drop = FALSE]
})
# Reactive training data optimi, pick top 3
OpSMA <- reactive({
trainingReturns <- RunIterativeStrategy(TrainIndexSelected())
pTab <- PerformanceTable(trainingReturns)
toptrainingReturns <- SelectTopNStrategies(trainingReturns,pTab,"SharpeRatio",3)
})
# Reactive training op data set
SelectTickerTrain<- reactive({
v= gsub(" ", "", input$ticName, fixed = TRUE)
total<- data.frame()
for (i in v){
addon= getSymbols(i, env = NULL, src = "yahoo", from = StartDate, to = EndDate)
total=merge(addon, total)
}
total[paste(input$TrainingDateRange[1],input$TrainingDateRange[2], sep = "/") ,
paste(rep(v,each=6),
c("Open", "High", "Low", "Close", "Volume", "Adjusted"), sep = ".") ,
drop = FALSE]
})
SelectTickerTest<- reactive({
v= gsub(" ", "", input$ticName, fixed = TRUE)
total<- data.frame()
for (i in v){
addon= getSymbols(i, env = NULL, src = "yahoo", from = StartDate, to = EndDate)
total=merge(addon, total)
}
total[paste(input$TestingDateRange[1],input$TestingDateRange[2], sep = "/") ,
paste(rep(v,each=6),
c("Open", "High", "Low", "Close", "Volume", "Adjusted"), sep = ".") ,
drop = FALSE]
})
output$SelectedStock <- renderPlot({
total[paste(input$TrainingDateRange[1],input$TrainingDateRange[2], sep = "/") ,
paste(rep(v,each=6),
c("Open", "High", "Low", "Close", "Volume", "Adjusted"), sep = ".") ,
drop = FALSE]
j = "Close"
plotticker = paste(v,j,sep=".")
plot(total[,plotticker])
})
#Tab: Training Data
#Type: DataTable
output$RawDataTable1 <- DT::renderDataTable(
as.data.table(TrainIndexSelected(), keep.rownames = TRUE)
,
options = list(scrollX = TRUE))
#Tab: Testing Data
#Type: DataTable
output$RawDataTable2 <- DT:: renderDataTable(
as.data.table(TestIndexSelected(), keep.rownames = TRUE)
, options = list(scrollX = TRUE)
)
#Tab: Training Data
#Type: Time Series Plot
output$RawDataPlot1 <- renderPlot({
j = "Close"
plotticker = paste(input$index,j,sep=".")
plot(TrainIndexSelected()[,plotticker])
})
Selected <- reactive({
v= gsub(" ", "", input$ticName, fixed = TRUE)
TradingStrategyMAGROUP <- xts()
for (i in v){
ma = TradingStrategy_MA(SelectTickerTrain()[,grep(x = colnames(SelectTickerTrain()), pattern = i)],
as.numeric(input$SMAlower),
as.numeric(input$SMAupper))
TradingStrategyMAGROUP= cbind(TradingStrategyMAGROUP, ma )
}
SelectedResult = cbind(TradingStrategy_MA(TrainIndexSelected(),
as.numeric(input$SMAlower),
as.numeric(input$SMAupper)),
TradingStrategyMAGROUP,
indexReturns[paste(input$TrainingDateRange[1],
input$TrainingDateRange[2],
sep = "/"),])
})
Testfinal <- reactive({
v= gsub(" ", "", input$ticName, fixed = TRUE)
TradingStrategyMAGROUP <- xts()
for (i in v){
ma = TradingStrategy_MA(SelectTickerTest()[,grep(x = colnames(SelectTickerTest()), pattern = i)],
as.numeric(input$SMAlower),
as.numeric(input$SMAupper))
TradingStrategyMAGROUP= cbind(TradingStrategyMAGROUP, ma )
}
SelectedResult <- cbind(TradingStrategy_MA(TestIndexSelected(),
as.numeric(input$SMAlower),
as.numeric(input$SMAupper)),
TradingStrategyMAGROUP,
indexReturns[paste(input$TestingDateRange[1],
input$TestingDateRange[2],
sep = "/"),])
})
#Tab: SMA trading
#Type: Result table
output$SelectedSMAtable <- renderTable({
tttab <- PerformanceTable(Selected())
#as.data.table(tttab, keep.rownames = TRUE)
},width = "300px", rownames = TRUE)
#Tab: SMA trading
#Type: Cumulative Return Plot
output$SMA_CumR_Plot <- renderPlot({
chart.CumReturns(Selected(),colorset = rich6equal,legend.loc = "topleft",main="Cumulative Returns")
},width = 900, height = 450)
#Tab: SMA trading
#Type: Max DrawDown Plot
output$SMA_Max_Plot <- renderPlot({
chart.Drawdown(Selected(),main="Drawdown from Peak Equity Attained",colorset = tim8equal[-1],legend.loc = "bottom")
},width = 900, height = 450)
#Tab: SMA trading
#Type: boxplot
output$SMA_Box_Plot <- renderPlot({
chart.Boxplot(Selected(), main = "Trailing Returns")
},width = 900, height = 450)
#Tab: Optimize
#Type: Optimize table
output$OpTable <- renderTable({
per_table <- PerformanceTable(OpSMA())
as.data.table(per_table, keep.rownames = TRUE)
})
#Tab: Optimize
#Type: Optimize Plot
output$OpPlot <- renderPlot({
charts.PerformanceSummary(OpSMA(),main=paste(nameOfStrategy,"- Training"),
geometric=FALSE,
colorset= tim8equal[-1])
},width = 1200, height = 600)
# output$TestPlot <- renderPlot({
#
# charts.PerformanceSummary(Testfinal(),colorset = tim8equal[-1])
#
# },width = 1200, height = 600)
#Tab: back testing
#Type: Cumulative Return Plot
output$BT_CumR_Plot <- renderPlot({
chart.CumReturns(Testfinal(),colorset = rich6equal,legend.loc = "topleft",main="Cumulative Returns")
},width = 900, height = 450)
#Tab: back testing
#Type: Max DrawDown Plot
output$BT_Max_Plot <- renderPlot({
chart.Drawdown(Testfinal(),main="Drawdown from Peak Equity Attained",colorset = tim8equal[-1],legend.loc = "bottom")
},width = 900, height = 450)
#Tab: back testing
#Type: boxplot
output$BT_Box_Plot <- renderPlot({
chart.Boxplot(Testfinal(), main = "Trailing Returns")
},width = 900, height = 450)
output$TestTable <- renderTable({
testptab = PerformanceTable(Testfinal())
as.data.table(testptab, keep.rownames = TRUE)
})
output$pdfviewer <- renderText({
return(paste('<iframe style="height:600px; width:100%" src="IAQF.pdf"', input$pdfurl, '"></iframe>', sep = ""))
})
})
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
MMM
ABT
ABBV
ACN
ATVI
AYI
ADBE
AAP
AMD
AES
AET
AMG
AFL
A
APD
AKAM
ALK
ALB
ARE
ALXN
ALGN
ALLE
AGN
ADS
LNT
ALL
GOOGL
MO
AMZN
AEE
AAL
AEP
AXP
AIG
AMT
AWK
AMP
ABC
AME
AMGN
APH
APC
ADI
ANDV
ANSS
ANTM
AOS
AON
APA
AIV
AAPL
AMAT
ADM
ARNC
AJG
AIZ
T
ADP
AZO
AVB
AVY
BHGE
BLL
BAC
BK
BAX
BBT
BDX
BRK/A
BIIB
BLK
BA
BWA
BXP
BSX
BHF
BMY
AVGO
COG
CDNS
CPB
COF
CAH
CCL
CAT
CBOE
CBG
CBS
CELG
CNC
CNP
CTL
CERN
CF
CHRW
SCHW
CHTR
CHK
CVX
CMG
CB
CHD
CI
XEC
CINF
CSCO
C
CFG
CTXS
CLX
CME
CMS
KO
CTSH
CL
CMCSA
CMA
CXO
COP
ED
COO
GLW
COST
COTY
BCR
CCI
CSX
CMI
CVS
DHR
DVA
DE
DLPH
DAL
XRAY
DVN
DLR
DFS
DISCA
DISH
D
DOV
DHI
DPS
DTE
DUK
DRE
ETFC
EMN
ETN
EBAY
ECL
EIX
EW
LLY
EMR
ETR
EVHC
EOG
EQT
EFX
EQIX
EQR
ESS
EL
RE
ES
EXC
EXPE
EXPD
ESRX
EXR
XOM
FFIV
FB
FAST
FRT
FIS
FITB
FE
FISV
FLIR
FLS
FLR
FMC
F
FTV
FBHS
BEN
FCX
GRMN
IT
GD
GE
GM
GPC
GGP
GILD
GPN
GS
GT
HAL
HBI
HOG
HRS
HIG
HAS
HCA
HCP
HP
HSIC
HSY
HES
HPE
HLT
HOLX
HON
HRL
HST
HPQ
HUM
HBAN
IDXX
INFO
ITW
ILMN
INCY
IR
INTC
ICE
IBM
IFF
IP
IPG
INTU
ISRG
IVZ
IQV
IRM
JEC
JBHT
JNJ
JCI
JPM
JNPR
KSU
K
KEY
KMB
KIM
KMI
KLAC
KHC
LLL
LH
LRCX
LEG
LEN
LUK
LNC
LKQ
LMT
L
LYB
MTB
MAC
MRO
MPC
MAR
MMC
MLM
MAS
MA
MAT
MKC
MCD
MRK
MET
MTD
MGM
MU
MSFT
MAA
MHK
TAP
MDLZ
MON
MNST
MCO
MS
MOS
MSI
MYL
NDAQ
NOV
NAVI
NFLX
NWL
NFX
NEM
NWSA
NEE
NLSN
NI
NBL
NSC
NTRS
NOC
NCLH
NRG
NUE
ORLY
OXY
OMC
OKE
PCAR
PKG
PH
PYPL
PNR
PBCT
PEP
PKI
PRGO
PFE
PCG
PM
PSX
PNW
PXD
PNC
PPG
PPL
PX
PCLN
PFG
PG
PGR
PLD
PRU
PEG
PSA
PHM
QCOM
PWR
DGX
RRC
RJF
RTN
O
REG
REGN
RF
RSG
RMD
RHI
ROK
COL
ROP
RCL
SPGI
SBAC
SCG
SLB
SNI
STX
SEE
SRE
SHW
SPG
SWKS
SLG
SNA
SO
LUV
SWK
SBUX
STT
SRCL
SYK
STI
SYF
SNPS
SYY
TROW
TPR
TEL
FTI
TXN
TXT
TMO
TWX
TMK
TSS
TSCO
TDG
TRV
TRIP
FOXA
TSN
UDR
UAA
UNP
UAL
UPS
URI
UTX
UNH
UHS
UNM
USB
VLO
VAR
VTR
VRSN
VRSK
VZ
VRTX
VFC
VIAB
V
VNO
VMC
WBA
DIS
WM
WAT
WEC
WFC
HCN
WDC
WU
WRK
WY
WHR
WMB
WLTW
GWW
WYN
WYNN
XEL
XRX
XL
XYL
YUM
ZBH
ZION
ZTS
library(shinydashboard)
shinyUI(dashboardPage(
skin="black",
dashboardHeader(title = "Moving Average",titleWidth = 200),
#########################################################################################
#
#SIDE BAR START
#
#########################################################################################
dashboardSidebar(
width = 200,
sidebarUserPanel("MENU"),
sidebarMenu(
menuItem("Home", tabName = "home", icon = icon("home")),
# menuItem("Team", tabName = "team", icon = icon("group")),
menuItem("Portfolio",
tabName = "p",
icon = icon("database"),
menuItem("Portfolio", tabName = "p1", icon = icon("line-chart"))
# menuItem("Portfolio #2", tabName = "p2", icon = icon("line-chart")),
# menuItem("Portfolio #3", tabName = "p3", icon = icon("line-chart")),
# menuItem("Portfolio #4", tabName = "p4", icon = icon("line-chart"))),
# menuItem("Enhancement", tabName = "en", icon = icon("lightbulb-o")),
# menuItem("Competition Problem ", tabName = "pro", icon = icon("mortar-board")),
# menuItem("Reference", tabName = "refer", icon = icon("book")))
))),
#########################################################################################
#
#BODY STARTS
#
#########################################################################################
dashboardBody(
tabItems(
tabItem(tabName = "home",
mainPanel(
HTML(
paste(
h2("Moving Average Trading\n\n"),'<br/>',
h3("This app simulates Moving Average Trading based on three index:
S&P500, Dow Jones and Nasdaq. Also all the stocks from S&P500
can be added on.\n\n"),'<br/>',
# h4("Since this app more focus on the theory side, reference paper will be provided in the end \n\n"),'<br/>',
# h4("At the same time this app is designed for a competition hosted by IAQF(International Association of Quantitative Finance) \n\n"),'<br/>',
# h4("Background and details given by IAQF are in the IAQF 2018 tab "),'<br/>',
h4("Thank you for using the app!")
)
)
)),
#tabItem(tabName = "team","to be replaced with team info"),
#########################################################################################
#
#portfolio 1
#
#########################################################################################
tabItem(tabName = "p1",
fluidPage(
sidebarLayout(
sidebarPanel(
# Let user choose which index to look at (S&P500, Dow Jones, Nasdaq)
fluidRow(
column(width = 4,
conditionalPanel(
#include tabs name here
'input.dataset === "Training Data",
"Testing Data","SMA trading","Optimize",
"Back Testing"',
radioButtons("index",
"Columns in index data to show:",
choiceNames = list("S&P500",
"Dow Jones",
"Nasdaq"),
choiceValues = list("GSPC", "DJI", "IXIC"),
selected = list("GSPC")
),
# textInput("ticName",
# "Enter stock ticker: ",
# value = "")
selectizeInput(inputId = "ticName",
label = "Enter stock ticker:",
choices = tic$tic,
multiple = TRUE)
)),
column(width = 4,
# Let user choose Training Date
dateRangeInput(inputId = "TrainingDateRange",
label = "CHOOSE TRAINING DATE: ",
format = "yyyy-mm-dd",
start = "2001-01-01",
end = "2010-01-01",
min = "1990-01-01",
max = "2017-12-31"
),
# Let user choose Testing Date
dateRangeInput(inputId = "TestingDateRange",
label = "CHOOSE TESTING DATE: ",
format = "yyyy-mm-dd",
start = "2011-01-01",
end = "2015-01-01",
min = "1990-01-01",
max = "2017-12-31"
)),
column(width = 4,
# Let user choose SMA lower Bound:
selectizeInput(inputId = "SMAlower",
label = "CHOOSE LOWER BOUND SMA : ",
choices = seq(from = 20, to = 80, by=10),
selected = 60
),
# Let user choose SMA upper Bound:
selectizeInput(inputId = "SMAupper",
label = "CHOOSE UPPER BOUND SMA : ",
choices = seq(from = 100, to= 360, by=40)
))
# actionButton("OpButton", "Optimize"),
# width = 3
), width = 8),
mainPanel(
tabsetPanel(id = 'dataset',
#include tabs name here
tabPanel("SMA trading",tableOutput("SelectedSMAtable"),
plotOutput("SMA_CumR_Plot",height = "600px"),
plotOutput("SMA_Max_Plot", height = "600px"),
plotOutput("SMA_Box_Plot", height = "600px")),
tabPanel("Optimize",tableOutput("OpTable"),
plotOutput("OpPlot",height = "600px")),
tabPanel("Back Testing",tableOutput("TestTable"),
plotOutput("BT_CumR_Plot",height = "600px"),
plotOutput("BT_Max_Plot", height = "600px"),
plotOutput("BT_Box_Plot", height = "600px")),
tabPanel("Training Data", DT::dataTableOutput("RawDataTable1"),
plotOutput("RawDataPlot1")),
tabPanel("Testing Data", DT::dataTableOutput("RawDataTable2"))
)
)
)
)
),
#########################################################################################
#
#portfolio 2
#
#########################################################################################
tabItem(tabName = "p2","to be replaced with portfolio 2"),
tabItem(tabName = "p3","to be replaced with portfolio 3"),
tabItem(tabName = "p4","to be replaced with portfolio 4"),
tabItem(tabName = "en","to be replaced with enhancement")
)
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.