Trading on the Sharpe Ratio using quantstrat

The sharpe ratio can be viewed as a signal to noise ratio (when rf = 0), and this is a quick strategy to execute on “momentum” when the signal to noise ratio is appropriate, it appears to be profitable on the backtest.

Here is quick example using the sharpe ratio to trade on.

This is not investment advice.

As always credit to the authors of all the packages used, especially Brian Peterson, Joshua Ulrich and Jan Humme, for the work on the various packages they have done and their contributions to the community.

#clear workspace (for testing)
rm(list = ls())

#load libraries
require(quantmod)
require(PerformanceAnalytics)
require(blotter)
require(FinancialInstrument)
require(quantstrat)
require(forecast)
require(foreach)

#clear portfolio and acct not needed due to the clearing workspace but here incase you don't use it.
suppressWarnings(rm("account.stocky","portfolio.stocky",pos=.blotter))
suppressWarnings(rm("order_book.stocky",pos=.strategy))
suppressWarnings(rm(stocky))

#if your stock is different you need to change (initdate,initportf,addposlimit, chart.posn)
symbol = "SPY"

#Set up currencies
currency("USD")

#define stock change spy to your stock of choice
stock(symbol, currency="USD", multiplier = 1)

####################################################### Get Data #################################################
getSymbols(symbol,src="yahoo",from = "2000-01-01" )

#Set Initial Date and Equity, note change SPY to your stock of choice.
initDate = start(SPY)
initEq = 10000

########################## Set up portfolio orders and Acct #######################################
#change SPY to your stock choice

initPortf(name="stocky","SPY",initPosQty=0,initDate=initDate,currency="USD")
initAcct("stocky",portfolios="stocky",initDate=initDate,initEq=initEq)
initOrders("stocky",symbols=symbol,initDate=initDate)

#position limits
#change "SPY" to your stock choice
addPosLimit("stocky","SPY",timestamp=initDate,maxpos=100, minpos=0)

#Set up Strategy
stratstocky<-strategy("stocky")

##############################FUNCTIONS#################################


ret2sharpe = function(x)
{

  returns = ROC(x)
  returns = returns[2:length(returns)] 
  sra = SharpeRatio.annualized(returns)

  return(sra)

}

rollingsharpe = function(x,window)
{
  x = Cl(x)
  ans = rollapply(x,window,ret2sharpe)
  return(ans)

}

########################indicators#############################

stratstocky<-add.indicator(
  strategy  =	stratstocky, 
  name		=	"rollingsharpe", 
  arguments	=	list(
    x		=	quote(mktdata),
    window = 90 ),
  label		=	"rs")

################################################ Signals #############################

stratstocky<-add.signal(
  strategy			= stratstocky,
  name				= "sigThreshold",
  arguments			= list(
    threshold		= -1,
    column			= "rs",
    relationship	= "lte",
    cross			= TRUE),
  label				= "Selltime")

stratstocky<-add.signal(
  strategy			= stratstocky,
  name				= "sigThreshold",
  arguments			= list(
    threshold		= 1,
    column			= "rs",
    relationship	= "lt",
    cross			= TRUE),
  label				= "cashtime")

stratstocky<-add.signal(
  strategy  		= stratstocky,
  name				= "sigThreshold",
  arguments			= list(
    threshold		= -1,
    column			= "rs",
    relationship	= "gt",
    cross			= TRUE),
  label				= "cashtime")

stratstocky<-add.signal(
  strategy  		= stratstocky,
  name				= "sigThreshold",
  arguments			= list(
    threshold		= 1,
    column			= "rs",
    relationship	= "gte",
    cross			= TRUE),
  label				= "Buytime")

######################################## Rules #################################################

#Entry Rule Long
stratstocky<- add.rule(stratstocky,
                       name				=	"ruleSignal",
                       arguments			=	list(
                         sigcol			=	"Buytime",
                         sigval			=	TRUE,
                         orderqty		=	100,
                         ordertype		=	"market",
                         orderside		=	"long",
                         pricemethod		=	"market",
                         replace			=	TRUE,
                         TxnFees				=	-1,
                         osFUN				=	osMaxPos), 
                       type				=	"enter",
                       path.dep			=	TRUE,
                       label				=	"Entry")

#Entry Rule Short

stratstocky<- add.rule(stratstocky,
                       name  			=	"ruleSignal",
                       arguments			=	list(
                         sigcol			=	"Selltime",
                         sigval			=	TRUE,
                         orderqty		=	100,
                         ordertype		=	"market",
                         orderside		=	"short",
                         pricemethod		=	"market",
                         replace			=	TRUE,
                         TxnFees				=	-1,
                         osFUN				=	osMaxPos), 
                       type				=	"enter",
                       path.dep			=	TRUE,
                       label				=	"Entry")

#Exit Rules

#Exit 
stratstocky <- add.rule(stratstocky,
                        name				=	"ruleSignal",
                        arguments			=	list(
                          sigcol				=	"cashtime", 
                          sigval			=	TRUE, 
                          orderqty		=	"all", 
                          ordertype		=	"market",
                          orderside		=	"long", 
                          pricemethod		=	"market",
                          replace			=	TRUE,
                          TxnFees			=	-1),
                        type			=	"exit",
                        path.dep			=	TRUE,
                        label				=	"Exit")

##############################    Apply Strategy ##############################################

out <- applyStrategy(strategy=stratstocky, portfolios="stocky")
updatePortf("stocky")

############################# Portfolio Return Characterics ################################
#get portfolio data
portRet <- PortfReturns("stocky")
portRet$Total <- rowSums(portRet, na.rm=TRUE)
charts.PerformanceSummary(portRet$Total)
#tradeStats("stocky")[,c("Symbol","Num.Trades","Net.Trading.PL","maxDrawdown")]
#change SPY to your stock choice
chart.Posn("stocky","SPY")
results1<-getTxns("stocky","SPY")
#plot(results1$Net.Txn.Realized.PL)

Created by Pretty R at inside-R.org

results

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: