[R-SIG-Finance] tradeStats vs table.AnnualizedReturns discrepancy

SW kryp33 at yahoo.com
Tue Apr 24 05:50:28 CEST 2012


Hello All,

I am wondering if anybody can help me to understand why I have a strange discrepancy between tradeStats and AnnulaizedReturns output for my strategy.
Here is what I have. I made a simple quantstrat model and as result I've got an array of trades which I feed to  tradeStrats function like this:
tstats <- tradeStats(Portfolio=port.name, Symbol=ticker)
and printout output for tstats shows "Net Profit = 680" positive and probably correct number. Then, I run the following 
rets <- PortfReturns(acct.name)
table.AnnualizedReturns(rets)
As result I have "Annualized Return = -0.0053" and it is negative...

So here is the dilemma: PnL positive, Return negative

In strategy there is only one account with one ticker and commission is not set. No open positions in the end.  (Full code below runs at 04/23/2012 in case you want to rerun it. change the total_hist.end variable at the top of file to the appropriate date.)
I would be much obliged for any suggestions.

Thanks,
Sergey 


======================
        .~.      
        /v\      Sergey W. Andreyev
       // \\     kryp33 at yahoo.com
      /(   )\
       ^`~'^
======================
======================

rm(list=ls(all=T))

#clean subspaces
unloadNamespace("quantstrat")
unloadNamespace("blotter")


library(zoo)
library(tseries)
library(quantmod)
library(blotter)
library(quantstrat)
library(PerformanceAnalytics)


#####################   INSTRUMENT INITIALIZATION   #######################
ticker="GSPC"
tickerY="^GSPC"
total_hist.start = as.Date("2011-04-02")
total_hist.end   = Sys.Date()
total_hist = total_hist.end - total_hist.start

currency("USD")
stock(ticker,currency="USD",multiplier=1)

getSymbols(tickerY,from=total_hist.start,to=total_hist.end,to.assign=TRUE)


####################   INIT PORTFOLIO AND ACCTS  ########################
init.date = initDate=total_hist.start-1
strat.name<- "MyStrat"
port.name <- "MyPort"
acct.name <- "MyAcct"

TradeSize = 1000
initEq=as.numeric( TradeSize*max(Ad(get(ticker)) ) )

port <- initPortf(port.name,ticker,initDate=init.date)
acct <- initAcct(acct.name,portfolios=port.name, initDate=init.date, initEq=initEq)
ords <- initOrders(portfolio=port.name,initDate=init.date)
strat<- strategy(strat.name)

#################  CREATE INDICATORS            ##########################
strat<-add.indicator(strategy = strat,name ="SMA",arguments=list(x = quote(Ad(mktdata)), n=50), label="SMA50")
# summary(strat)
# out <- applyIndicators(strat,mktdata=get(ticker))
# tail(out)
###########################################################################

#################  CREATE SIGNALS            ##############################
strat <- add.signal(strat,name="sigCrossover",arguments = list(columns=c("Adjusted","SMA50"),relationship="gt"),label="px.gt.SMA50")
strat <- add.signal(strat,name="sigCrossover",arguments = list(columns=c("Adjusted","SMA50"),relationship="lt"),label="px.lt.SMA50")
#out   <- applySignals(strat,mktdata=mktdata)
#head(out)


#################  CREATE RULES            ##########################
# go long when px > MA50
strat <- add.rule(strategy = strat, name='ruleSignal', arguments = list(sigcol="px.gt.SMA50", sigval=TRUE, orderqty=TradeSize, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE ) 
#exit when px<SMA50
strat <- add.rule(strategy = strat, name='ruleSignal', arguments = list(sigcol="px.lt.SMA50", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market'), type='exit', path.dep=TRUE) 
#out<-applyRules(port.name, ticker, strat, mktdata = px)
#head(out,100)

out<-try(applyStrategy(strategy=strat, portfolios=port.name))

updatePortf(Portfolio=port.name,Dates=paste("::",as.Date(Sys.time()),sep=''))
updateAcct(acct.name,Dates=paste(total_hist.start,total_hist.end,sep="::")) 
updateEndEq(acct.name,Dates=paste(total_hist.start,total_hist.end,sep="::"))
getEndEq(acct.name,Sys.time())

chart.Posn(Portfolio=port.name,Symbol=ticker)
plot(add_SMA(n=50,col=4, on=1, lwd=2))

rets <- PortfReturns(acct.name)
charts.PerformanceSummary(rets,geometric=FALSE,wealth.index=TRUE,colorset = bluefocus)

PA1.tab <- table.Arbitrary(rets, metrics=c("Return.cumulative","Return.annualized",   "SharpeRatio.annualized", "CalmarRatio"),metricsNames=c("Cumulative Return", "Annualized Return","Annualized Sharpe Ratio", "Calmar Ratio"))
PA2.tab <- table.Arbitrary(rets, metrics=c("StdDev.annualized", "maxDrawdown","VaR", "ES"),metricsNames=c("Annualized StdDev", "Max DrawDown","Value-at-Risk", "Conditional VaR"))
tab1 <- data.frame(rownames(PA1.tab),PA1.tab[,1],rownames(PA2.tab),PA2.tab[,1])
tab1

tstats <- tradeStats(Portfolio=port.name, Symbol=ticker)
res.tab1 <- cbind(c("Trades","Win Percent","Loss Percent","W/L Ratio"),c((tstats[,"Num.Trades"]-1)/2,tstats[,c("Percent.Positive","Percent.Negative")],  tstats[,"Percent.Positive"]/tstats[,"Percent.Negative"]))
res.tab2 <- cbind(c("Net Profit","Gross Profits","Gross Losses","Profit Factor"),c(tstats[,c("Net.Trading.PL","Gross.Profits","Gross.Losses","Profit.Factor")]))
res.tab3 <- cbind(c("Avg Trade","Avg Win","Avg Loss","Avg W/L Ratio"),c(tstats[,c("Avg.Trade.PL","Avg.Win.Trade","Avg.Losing.Trade","Avg.WinLoss.Ratio")]))
tab2 <- data.frame(res.tab1,res.tab2,res.tab3)
tab2

tab3 <- table.AnnualizedReturns(rets)
tab1
tab2
tab3



More information about the R-SIG-Finance mailing list