SlideShare a Scribd company logo
R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows"
Copyright (C) 2012 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[R.app GUI 1.52 (6188) x86_64-apple-darwin9.8.0]

[History restored from /Users/ananthraj/.Rapp.history]

> library("quantmod")
library("PerformanceAnalytics")


nameOfStrategy <- "GSPC Moving Average Strategy"

#Specify dates for downloading data, training models and running simulation
trainingStartDate = as.Date("2000-01-01")
trainingEndDate = as.Date("2010-01-01")
outofSampleStartDate = as.Date("2010-01-02")


#Download the data
symbolData <- new.env() #Make a new environment for quantmod to store data in
getSymbols("^GSPC", env = symbolData, src = "yahoo", from = trainingStartDate)
trainingData <- window(symbolData$GSPC, start = trainingStartDate, end =
trainingEndDate)
testData <- window(symbolData$GSPC, start = outofSampleStartDate)
indexReturns <- Delt(Cl(window(symbolData$GSPC, start = outofSampleStartDate)))
colnames(indexReturns) <- "GSPC Buy&Hold"

TradingStrategy <- function(mktdata,mavga_period,mavgb_period){
  #This is where we define the trading strategy
  #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("MAVGa",mavga_period,".b",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)

  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 1:10) {
            for(b in 1:10) {

                 runResult <- TradingStrategy(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){
  #Optimise the strategy
  trainingReturns <- RunIterativeStrategy(trainingData)
  pTab <- PerformanceTable(trainingReturns)
  toptrainingReturns <-
SelectTopNStrategies(trainingReturns,pTab,"SharpeRatio",5)
  charts.PerformanceSummary(toptrainingReturns,main=paste(nameOfStrategy,"-
Training"),geometric=FALSE)
  return (pTab)
}

pTab <- FindOptimumStrategy(trainingData) #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(testData,mavga_period=9,mavgb_period=6)
finalReturns <- cbind(outOfSampleReturns,indexReturns)
charts.PerformanceSummary(finalReturns,main=paste(nameOfStrategy,"- Out of
Sample"),geometric=FALSE)

More Related Content

What's hot (20)

PDF
Gearman, from the worker's perspective
Brian Aker
 
PDF
The Ring programming language version 1.3 book - Part 47 of 88
Mahmoud Samir Fayed
 
PDF
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Sean May
 
PPTX
R: Apply Functions
DataminingTools Inc
 
PDF
The Ring programming language version 1.5.4 book - Part 64 of 185
Mahmoud Samir Fayed
 
PPTX
Mapfilterreducepresentation
ManjuKumara GH
 
PDF
Austin Bingham. Transducers in Python. PyCon Belarus
Alina Dolgikh
 
DOCX
Implementasi Pemodelan Sistem Ke TeeChart
Lusiana Diyan
 
PDF
The Ring programming language version 1.2 book - Part 45 of 84
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.3 book - Part 25 of 88
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.4.1 book - Part 17 of 31
Mahmoud Samir Fayed
 
PDF
[ShaderX5] 8 1 Postprocessing Effects In Design
종빈 오
 
PPT
Chap1 1 4
Hemo Chella
 
PDF
Functional Programming in Java 8
Omar Bashir
 
PPTX
Function composition in Javascript
Anand Kumar
 
PDF
The Ring programming language version 1.8 book - Part 71 of 202
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.4 book - Part 65 of 185
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.7 book - Part 25 of 196
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.3 book - Part 8 of 184
Mahmoud Samir Fayed
 
PDF
Introduction to Data Science With R Lab Record
Lakshmi Sarvani Videla
 
Gearman, from the worker's perspective
Brian Aker
 
The Ring programming language version 1.3 book - Part 47 of 88
Mahmoud Samir Fayed
 
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Sean May
 
R: Apply Functions
DataminingTools Inc
 
The Ring programming language version 1.5.4 book - Part 64 of 185
Mahmoud Samir Fayed
 
Mapfilterreducepresentation
ManjuKumara GH
 
Austin Bingham. Transducers in Python. PyCon Belarus
Alina Dolgikh
 
Implementasi Pemodelan Sistem Ke TeeChart
Lusiana Diyan
 
The Ring programming language version 1.2 book - Part 45 of 84
Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 25 of 88
Mahmoud Samir Fayed
 
The Ring programming language version 1.4.1 book - Part 17 of 31
Mahmoud Samir Fayed
 
[ShaderX5] 8 1 Postprocessing Effects In Design
종빈 오
 
Chap1 1 4
Hemo Chella
 
Functional Programming in Java 8
Omar Bashir
 
Function composition in Javascript
Anand Kumar
 
The Ring programming language version 1.8 book - Part 71 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 65 of 185
Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 25 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 8 of 184
Mahmoud Samir Fayed
 
Introduction to Data Science With R Lab Record
Lakshmi Sarvani Videla
 

Viewers also liked (20)

PDF
Aviso publicacion pavimento voragine
Ramiro Cisneros
 
PPTX
Biografías
Nat_00
 
PDF
Esp016
sindicatocormup
 
DOC
Dossier de presse
lenac72
 
PPTX
Mandriva
Fitria Muhammad
 
PPTX
Xp
SandraGomezz
 
PPT
Presentation1a
95veritymaywalker
 
PDF
03
Haber48
 
PDF
Cpl Capability Interactive Brochure
Saïd C
 
PPT
Zeytinburnu Protherm Lynx Kombi Servisi 0212 472 722 3---0541 872 72 23
mamamm
 
PPT
Меморандум о дальнейшем развитии Ассоциации новаторских городов
Елена Киреева (Енютина)
 
PPTX
Proyecto productivo de tecnologia
danielmestra17
 
PPT
Federación de consejos regionales
Gonzalo Robles
 
PPS
Enciendelaluz
MIS AMIGOS
 
PPTX
Html
omaryessi
 
PPT
Aulkien jokoa
fernando larraiotz perez
 
DOCX
Martha cecilia gomez es considerada una autoridad mundial en clonación.
Paola Rodriguez
 
PDF
Todas las chicas besan con los ojos cerrados
Amanda Exposito
 
PPT
Como se elabora_un_pp_12-13
ArantxaMF87
 
Aviso publicacion pavimento voragine
Ramiro Cisneros
 
Biografías
Nat_00
 
Dossier de presse
lenac72
 
Mandriva
Fitria Muhammad
 
Presentation1a
95veritymaywalker
 
Cpl Capability Interactive Brochure
Saïd C
 
Zeytinburnu Protherm Lynx Kombi Servisi 0212 472 722 3---0541 872 72 23
mamamm
 
Меморандум о дальнейшем развитии Ассоциации новаторских городов
Елена Киреева (Енютина)
 
Proyecto productivo de tecnologia
danielmestra17
 
Federación de consejos regionales
Gonzalo Robles
 
Enciendelaluz
MIS AMIGOS
 
Html
omaryessi
 
Martha cecilia gomez es considerada una autoridad mundial en clonación.
Paola Rodriguez
 
Todas las chicas besan con los ojos cerrados
Amanda Exposito
 
Como se elabora_un_pp_12-13
ArantxaMF87
 
Ad

Similar to R console (20)

PPT
Basic concept of MATLAB.ppt
aliraza2732
 
PDF
Data mining with caret package
Vivian S. Zhang
 
PDF
R Programming: Mathematical Functions In R
Rsquared Academy
 
PPT
Adding Statistical Functionality to the DATA Step with PROC FCMP
Jacques Rioux
 
PPTX
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
Craig Chao
 
PDF
RxJava applied [JavaDay Kyiv 2016]
Igor Lozynskyi
 
DOCX
R (Shiny Package) - Server Side Code for Decision Support System
Maithreya Chakravarthula
 
PPTX
A brief introduction to apply functions
NIKET CHAURASIA
 
PPTX
Where the wild things are - Benchmarking and Micro-Optimisations
Matt Warren
 
PDF
Oct.22nd.Presentation.Final
Andrey Skripnikov
 
PDF
Recompacting your react application
Greg Bergé
 
PDF
Pumps, Compressors and Turbine Fault Frequency Analysis
University of Illinois,Chicago
 
PDF
SQL Functions and Operators
Mohan Kumar.R
 
PDF
The Ring programming language version 1.9 book - Part 93 of 210
Mahmoud Samir Fayed
 
DOCX
Pumps, Compressors and Turbine Fault Frequency Analysis
University of Illinois,Chicago
 
PDF
Interactively querying Google Analytics reports from R using ganalytics
Johann de Boer
 
PPTX
Reactive programming every day
Vadym Khondar
 
PDF
R code for data manipulation
Avjinder (Avi) Kaler
 
PDF
R code for data manipulation
Avjinder (Avi) Kaler
 
PDF
Map reduce: beyond word count
Jeff Patti
 
Basic concept of MATLAB.ppt
aliraza2732
 
Data mining with caret package
Vivian S. Zhang
 
R Programming: Mathematical Functions In R
Rsquared Academy
 
Adding Statistical Functionality to the DATA Step with PROC FCMP
Jacques Rioux
 
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
Craig Chao
 
RxJava applied [JavaDay Kyiv 2016]
Igor Lozynskyi
 
R (Shiny Package) - Server Side Code for Decision Support System
Maithreya Chakravarthula
 
A brief introduction to apply functions
NIKET CHAURASIA
 
Where the wild things are - Benchmarking and Micro-Optimisations
Matt Warren
 
Oct.22nd.Presentation.Final
Andrey Skripnikov
 
Recompacting your react application
Greg Bergé
 
Pumps, Compressors and Turbine Fault Frequency Analysis
University of Illinois,Chicago
 
SQL Functions and Operators
Mohan Kumar.R
 
The Ring programming language version 1.9 book - Part 93 of 210
Mahmoud Samir Fayed
 
Pumps, Compressors and Turbine Fault Frequency Analysis
University of Illinois,Chicago
 
Interactively querying Google Analytics reports from R using ganalytics
Johann de Boer
 
Reactive programming every day
Vadym Khondar
 
R code for data manipulation
Avjinder (Avi) Kaler
 
R code for data manipulation
Avjinder (Avi) Kaler
 
Map reduce: beyond word count
Jeff Patti
 
Ad

R console

  • 1. R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows" Copyright (C) 2012 The R Foundation for Statistical Computing ISBN 3-900051-07-0 Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. [R.app GUI 1.52 (6188) x86_64-apple-darwin9.8.0] [History restored from /Users/ananthraj/.Rapp.history] > library("quantmod") library("PerformanceAnalytics") nameOfStrategy <- "GSPC Moving Average Strategy" #Specify dates for downloading data, training models and running simulation trainingStartDate = as.Date("2000-01-01") trainingEndDate = as.Date("2010-01-01") outofSampleStartDate = as.Date("2010-01-02") #Download the data symbolData <- new.env() #Make a new environment for quantmod to store data in getSymbols("^GSPC", env = symbolData, src = "yahoo", from = trainingStartDate) trainingData <- window(symbolData$GSPC, start = trainingStartDate, end = trainingEndDate) testData <- window(symbolData$GSPC, start = outofSampleStartDate) indexReturns <- Delt(Cl(window(symbolData$GSPC, start = outofSampleStartDate))) colnames(indexReturns) <- "GSPC Buy&Hold" TradingStrategy <- function(mktdata,mavga_period,mavgb_period){ #This is where we define the trading strategy #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("MAVGa",mavga_period,".b",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) signal <- mavga / mavgb #If mavga > mavgb go long signal <- apply(signal,1,function (x) { if(is.na(x)){ return (0) } else
  • 2. { 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 1:10) { for(b in 1:10) { runResult <- TradingStrategy(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),])
  • 3. } 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){ #Optimise the strategy trainingReturns <- RunIterativeStrategy(trainingData) pTab <- PerformanceTable(trainingReturns) toptrainingReturns <- SelectTopNStrategies(trainingReturns,pTab,"SharpeRatio",5) charts.PerformanceSummary(toptrainingReturns,main=paste(nameOfStrategy,"- Training"),geometric=FALSE) return (pTab) } pTab <- FindOptimumStrategy(trainingData) #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(testData,mavga_period=9,mavgb_period=6) finalReturns <- cbind(outOfSampleReturns,indexReturns) charts.PerformanceSummary(finalReturns,main=paste(nameOfStrategy,"- Out of Sample"),geometric=FALSE)