R/Method-AssetClassTimeWeightedReturns.R

#'Methods for all Asset Class-level returns calculator


##Method to calculate the TWR-----------------------------------------------------
setGeneric(name = "AssetClassTimeWeightedReturns",
           def = function(object){
             standardGeneric("AssetClassTimeWeightedReturns")
           })

setMethod(f="AssetClassTimeWeightedReturns",
          signature = "AssetClass",
          definition = function(object){
            #Data
            Data<-data.frame(AssetClass = object@AssetClass,OpeningMarketValue = object@OpeningMarketValue,Debit = object@Debit,
                             Credit = object@Credit,ClosingMarketValue = object@ClosingMarketValue, FixedIncome = object@FixedIncome,
                             Weight = object@Weight, Benchmark = object@Benchmark , BenchmarkWeight =object@BenchmarkWeight)


            ###---------Function to sum weights
            WeightSumFunc<-function(Data){
              weightsum<-sum(Data$Weight)
              weightsum
            }

            ###---------Function To calculate Time Weighted returns
            Returnfunc<-function(data){
              HPR<-((data$ClosingMarketValue/(data$OpeningMarketValue + (data$Credit + data$Debit)))-1)

              #TWR
              returns=1
              for(i in 1:length(HPR)){
                returns=returns*(1+HPR[[i]])
              }
              returns=(returns-1)*100
              as.numeric( returns)
            }

            #Aggregate returns as per asset library( dplyr )
            result <- Data %>%group_by(AssetClass,Benchmark,BenchmarkWeight,FixedIncome) %>% do( Returns = Returnfunc(.),Weight= WeightSumFunc(.) ) %>%data.frame
            #result$Returns<-as.numeric(result$) ###TO DO **--- Change returns and weights output format from list to numeric
            result
          }
)
CarlvinJerry/InnovaPerformanceAttribution documentation built on May 16, 2019, 7:26 a.m.