PerformanceAnalytics Numbers to Percent %

点点圈 提交于 2019-12-09 03:46:11

问题


I want to know if it is possible to make the table output in this R package a % instead of a numeric.

table.AnnualizedReturns(indOver, Rf=0)

                          SP500  
Annualized Return         0.0732
Annualized Std Dev        0.1951
Annualized Sharpe (Rf=0%) 0.3752

So the 1st one 0.0732 I would like to see as 0.07%


回答1:


The return value from that function is a data frame, so the question is how to make a column of a data frame print with a percentage sign.

Reproducible example follows.

> require(PerformanceAnalytics)
> data(managers)
> tb =      table.AnnualizedReturns(managers[,1],Rf=0)
> tb
                            HAM1
Annualized Return         0.1375
Annualized Std Dev        0.0888
Annualized Sharpe (Rf=0%) 1.5491

Now we define a new class and a format function that displays with a percent sign:

> format.pc = function(x,...){sprintf('%0.2f%%',x)}
> class(tb[,1])="pc"

And now, as if by magic:

> tb
                           HAM1
Annualized Return         0.14%
Annualized Std Dev        0.09%
Annualized Sharpe (Rf=0%) 1.55%

The underlying values have not been changed:

> tb[,1]
[1] 0.1375 0.0888 1.5491
attr(,"class")
[1] "pc"

they are just in a vector of this new class.




回答2:


One way formatting the string correctly is:

sprintf('%0.2f%%', 0.0567)    # Note I use %% to get a percent sign in the output
[1] "0.06%"

Getting this to work in table.AnnualizedReturns will mean editing the code. You could make a copy, and edit the code according to your wishes. Alternatively, you could contact the writer of the package that contains this function and propose the change.



来源:https://stackoverflow.com/questions/27013290/performanceanalytics-numbers-to-percent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!