Quantcast

tradeStats vs table.AnnualizedReturns discrepancy

classic Classic list List threaded Threaded
3 messages Options
SW
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

tradeStats vs table.AnnualizedReturns discrepancy

SW
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
       // \\     [hidden email]
      /(   )\
       ^`~'^
======================
======================

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

_______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions should go.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: tradeStats vs table.AnnualizedReturns discrepancy

braverock
On Mon, 2012-04-23 at 20:50 -0700, SW wrote:

> 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.

You've run into the difference between geometric and simple returns.

> table.AnnualizedReturns(rets,geometric=FALSE)
                            GSPC
Annualized Return         0.0005
Annualized Std Dev        0.1076
Annualized Sharpe (Rf=0%) 0.0042
> 680/initEq
[1] 0.0004791972


So, this looks correct...

Regards,

   - Brian

--
Brian G. Peterson
http://braverock.com/brian/
Ph: 773-459-4973
IM: bgpbraverock

_______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions should go.
SW
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: tradeStats vs table.AnnualizedReturns discrepancy

SW
Thanks, Brian;
Makes perfect sense.

Best Regards,
Sergey

>
> You've run into the difference between geometric and simple
> returns.
>
> > table.AnnualizedReturns(rets,geometric=FALSE)
>                
>             GSPC
> Annualized Return     
>    0.0005
> Annualized Std Dev        0.1076
> Annualized Sharpe (Rf=0%) 0.0042
> > 680/initEq
> [1] 0.0004791972
>
>
> So, this looks correct...
>
> Regards,
>
>    - Brian
>
> --
> Brian G. Peterson
> http://braverock.com/brian/
> Ph: 773-459-4973
> IM: bgpbraverock
>
>

_______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions should go.
Loading...