Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: order.by requires an appropriate time-based object PerformanceAnalytics

Tags:

r

time-series

xts

'sI am new to R and even more to ts objects. I try to use the package PerformanceAnalytics on a vector from a dataframe (df).

I have the following data frame:

    row.names   Date    PnL
1   22  1992-01-02  -1.751133e-02
2   23  1992-01-03  -1.586737e-02
3   24  1992-01-06  -2.898982e-02

I tried:

  TestS=SharpeRatio.annualized(df[,"PnL"],Rf=0,scale=252)
  TestS=SharpeRatio.annualized(as.ts(df[,"PnL"]),Rf=0,scale=252)

It returns respectively the error in the object and:

Error in checkData(R, method = "xts") : The data cannot be converted into a time series. If you are trying to pass in names from a data object with one column, you should use the form 'data[rows, columns, drop = FALSE]'. Rownames should have standard date formats, such as '1985-03-15'

dput(df[,"PnL")=0.00994504296273811, 0.00156467225423175, 0.00976137048829638, etc.
dputdf[,"Date")=8036, 8037, 8040, 8041,etc.

The package's help says the function works on vector. I don't have any NA, and therefore I don't see why it does not work.

like image 569
VincentH Avatar asked Dec 20 '22 19:12

VincentH


2 Answers

First, you need to convert your data frame to an xts object:

dfx = xts(df$PnL, order.by=as.Date(df$Date))

Then you can do:

TestS = SharpeRatio.annualized(dfx, Rf=0, scale=252)

Or whatever else you need to do.

like image 155
A5C1D2H2I1M1N2O1R2T1 Avatar answered Dec 28 '22 06:12

A5C1D2H2I1M1N2O1R2T1


PerformanceAnalytics attempts to convert your data into a form that is easier to work with internally. To make this work with a data.frame, the data.frame has to have rownames that are formatted like Dates. So, this would work

rownames(df) <- df[, 2]
(TestS=SharpeRatio.annualized(df[, "PnL", drop=FALSE], Rf=0, scale=252))
#                                      PnL
#Annualized Sharpe Ratio (Rf=0%) -8.767439

Although PerformanceAnalytics claims to work on many data types, the authors use xts extensively. Therefore, they may have missed a few places where the code doesn't quite work right without using xts, such as passing a vector to this function.

I think the problem in SharpeRatio.annualized is that it calls Return.excess and Return.excess tries to turn your vector into an xts with this line

xR = coredata(as.xts(R) - as.xts(Rf))

However, a vector cannot be converted to xts without adding a time index. (Also, the next line uses apply, which isn't meant for vectors)

like image 40
GSee Avatar answered Dec 28 '22 06:12

GSee