Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rterbush/73f038bfd93f450f23f2 to your computer and use it in GitHub Desktop.

Select an option

Save rterbush/73f038bfd93f450f23f2 to your computer and use it in GitHub Desktop.
###################################
# Server functions
#
# [email protected] - June 2014
###################################
shinyServer(function(input, output) {
getData <- function(inputPath=inputPath,inputFile=inputFile,keepColumns=keepColumns){
data <- read.csv(paste(inputPath,inputFile,sep=""),sep=",")
keepColumns <- keepColumns
dataDaily <- data[,keepColumns]
colnames(dataDaily) <- c("date","rtn")
days <- as.Date(dataDaily[,"date"],"%m/%d/%Y")
dailyRtn <- as.numeric(substring(dataDaily[,"rtn"],1,nchar(as.character(dataDaily[,"rtn"]))-1)) ##
return(list(date=days,rtn=dailyRtn))
}
data <- reactive({
### ETF
if (input$strategy == "ETF"){
dt <- getData(inputPath="yourPath1",
inputFile="yourFile1.csv",
keepColumns=c("date","rtn"))
}
### EQUITY BOND ALLOCATION
if (input$strategy == "Equity Bond Allocation"){
dt <- getData(inputPath="yourPath2",
inputFile="yourFile2.csv",
keepColumns=c("date","rtn"))
}
### EQUITY LONG SHORT
if (input$strategy == "Equity Index"){
dt <- getData(inputPath="yourPath3",
inputFile="yourFile3.csv",
keepColumns=c("date","rtn"))
}
return(dt)
})
output$plot1 <- renderPlot({
data <- data()
pos <- min(which(as.Date(data$date,format="%Y-%m-%d") >= as.Date(input$startDate,format="%Y-%m-%d")))
x <- data$date[pos:length(data$date)]
y <- data$rtn[pos:length(data$rtn)]
xDD <- as.vector(Drawdowns(y/100))
par(mfrow=c(2,1),cex=0.9,mex=0.4)
plot(x,cumsum(y),
type="l",
main=" Equity Curve (%)",
xlab="",
ylab="",
col="royal blue",
lwd=1.5)
grid(col="dark grey")
plot(x,100*xDD,
type="l",
xlab="",
ylab="",
main="DrawDowns (%)",
col="royal blue",
lwd=1.5)
grid(col="dark grey")
})
output$tablePerformance <- renderTable({
data <- data()
pos <- min(which(as.Date(data$date,format="%Y-%m-%d") >= as.Date(input$startDate,format="%Y-%m-%d")))
x <- data$date[pos:length(data$date)]
y <- data$rtn[pos:length(data$rtn)]
dailyDD <- as.vector(Drawdowns(y/100))
nbDays <- length(x)
nbYears <- nbDays/252
totalReturn <- sum(y)
annualizedReturn <- round(totalReturn/nbYears,2)
annualizedVolatility <- round(sd(y)*sqrt(252),2)
sharpeRatio <- round(annualizedReturn/annualizedVolatility,2)
profitFactor <- round(sum(y[y > 0])/abs(sum(y[y < 0])),2)
rtnTable <- rbind(paste(annualizedReturn,"%",sep=""),paste(annualizedVolatility,"%",sep=""),sharpeRatio,profitFactor)
rownames(rtnTable) <- c("Ann.Return","Ann.Volatility","Sharpe Ratio","Profit Factor")
colnames(rtnTable) <- c("Performance")
rtnTable
})
output$tableRisk <- renderTable({
data <- data()
pos <- min(which(as.Date(data$date,format="%Y-%m-%d") >= as.Date(input$startDate,format="%Y-%m-%d")))
x <- data$date[pos:length(data$date)]
y <- data$rtn[pos:length(data$rtn)]
dailyDD <- as.vector(Drawdowns(y/100))
maxDD <- 100*round(min(dailyDD),3)
recoveryTime <- round(min(which(dailyDD[match(min(dailyDD),dailyDD):length(dailyDD)] == 0)),0)
painIndex <- round(PainIndex(y),2)
timeInMarket <- 100*round(length(which(y != 0))/length(y),2)
riskTable <- rbind(paste(maxDD,"%",sep=""),paste(recoveryTime," days",sep=""),painIndex,paste(timeInMarket,"%",sep=""))
rownames(riskTable) <- c("Max.DD","Recovery Time","Pain Index","% Time Invested")
colnames(riskTable) <- c("Risk")
riskTable
})
output$tableDaily <- renderTable({
data <- data()
pos <- min(which(as.Date(data$date,format="%Y-%m-%d") >= as.Date(input$startDate,format="%Y-%m-%d")))
x <- data$date[pos:length(data$date)]
y <- data$rtn[pos:length(data$rtn)]
avRtn <- round(mean(y,na.rm=TRUE),2)
avRtnPos <- round(mean(y[y >0],na.rm=TRUE),2)
avRtnNeg <- round(mean(y[y <0],na.rm=TRUE),2)
hitRatio <- 100*round(length(which(y > 0))/length(which(y != 0)),2)
worstDay <- round(min(y),2)
bestDay <- round(max(y),2)
dailyTable <- rbind(paste(avRtn,"%",sep=""),paste(avRtnPos,"%",sep=""),paste(avRtnNeg,"%",sep=""),paste(hitRatio,"%",sep=""),paste(worstDay,"%",sep=""),paste(bestDay,"%",sep=""))
rownames(dailyTable) <- c("Av. Rtn","Av. Rtn > 0","Av. Rtn < 0","Hit Ratio","Worst Day","Best Day")
colnames(dailyTable) <- c("Daily")
dailyTable
})
output$tableMonthly <- renderTable({
data <- data()
pos <- min(which(as.Date(data$date,format="%Y-%m-%d") >= as.Date(input$startDate,format="%Y-%m-%d")))
x <- data$date[pos:length(data$date)]
y <- data$rtn[pos:length(data$rtn)]
months <- sort(unique(substring(x,1,7)))
monthlyRtn <- aggregate(y,by=list(substring(x,1,7)),sum)[,2]
monthlyHitRate <- 100*round(length(which(monthlyRtn > 0))/length(monthlyRtn),2)
monthlyRtnAverage <- round(mean(monthlyRtn),2)
monthlyRtnPositive <- round(mean(monthlyRtn[which(monthlyRtn > 0)]),2)
monthlyRtnNegative <- round(mean(monthlyRtn[which(monthlyRtn < 0)]) ,2)
worstMonth <- round(min(monthlyRtn),2)
bestMonth <- round(max(monthlyRtn),2)
monthlyTable <- rbind(paste(monthlyRtnAverage,"%",sep=""),paste(monthlyRtnPositive,"%",sep=""),paste(monthlyRtnNegative,"%",sep=""),paste(monthlyHitRate,"%",sep=""),paste(worstMonth,"%",sep=""),paste(bestMonth,"%",sep=""))
rownames(monthlyTable) <- c("Av. Rtn","Av. Rtn > 0","Av. Rtn < 0","Hit Ratio","Worst Month","Best Month")
colnames(monthlyTable) <- c("Monthly")
monthlyTable
})
})
###############################################################################
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# Please visit: <http://www.gnu.org/licenses/>.
###############################################################################
# Copyright (C) 2014 The R Trader
#
# For more information please visit my blog at www.thertrader.com
# or you can reach me at: TheRTrader at gmail
###############################################################################
###################################
# Launch Shiny App
#
# [email protected] - June 2014
###################################
library(PerformanceAnalytics)
library(shiny)
library(xts)
runApp("D:\\daily\\shinyApps")
###################################
# UI functions
#
# [email protected] - June 2014
###################################
shinyUI(
fluidPage(
headerPanel(""),
sidebarPanel(
selectInput("strategy",
"Strategy:",
choices = c("ETF","Equity Bond Allocation","Equity Index")),
selectInput("startDate",
"Starting Date:",
choices = seq(as.Date("2000-01-01"),Sys.Date(),by="months")),
div(HTML("<br>This app was created by the R Trader.
<br><a href='http://thertrader.com' target='_blank'>www.thertrader.com</a>"))
),
mainPanel(
tabsetPanel(
tabPanel("Overview", plotOutput("plot1",height = 550, width = 550)),
tabPanel("Trading Statistics",
fixedRow(
column(8,
fixedRow(column(4,tableOutput("tablePerformance")),
column(4,tableOutput("tableRisk"))),
fixedRow(column(4,tableOutput("tableDaily")),
column(4,tableOutput("tableMonthly"))))
)
),
tabPanel("About",
HTML("<div> This Shiny application is the first version of an app designed to help analysing trading strategies. I will certainly improve it in the future.</div>
<p>The code used to create this app is available on <a href='https://gist.github.com/thertrader/8e777452b8e0e10320ee' target='_blank'>Github</a>. There are essentially 3 files.</p>
<li><i>ui.R</i>: controls the layout and appearance of the app</li>
<li><i>server.R</i>: contains the instructions needed to build the app. You can load as much strategies as you want as long as they have the right format.</li>
<li><i>shinyStrategyGeneral.R</i>: loads the required packages and launches the app</li>"))
)
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment