From 1efaed9ef527f0e6316d135612c20d7f37e60dcb Mon Sep 17 00:00:00 2001 From: friedeggs Date: Sat, 17 Sep 2016 15:29:32 -0400 Subject: [PATCH 1/2] Initial implementation --- your_return_calculator.rb | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/your_return_calculator.rb b/your_return_calculator.rb index 3b43174..7a07c29 100644 --- a/your_return_calculator.rb +++ b/your_return_calculator.rb @@ -2,14 +2,22 @@ class YourReturnCalculator < ReturnCalculator def calculate! - # Write your code here. - # You have access to the `snapshots` variable. - # - # You can access the following properties of a snapshot: - # snapshot.date - # snapshot.cash_flow - # snapshot.market_value - - BigDecimal.new(0) + + case snapshots.length + when 0 # Edge case: if there is only one day, return 0 + 0 + else # Otherwise: + + time_weighted_return = BigDecimal.new(1) # Better accuracy with floating point operations + + prev_snapshot = snapshots[0].market_value # Set prev_snapshot + + for snapshot in snapshots[1..-1] do # Loop starting from second day + time_weighted_return *= (snapshot.market_value - snapshot.cash_flow)/prev_snapshot + prev_snapshot = snapshot.market_value + end + + time_weighted_return - 1 # return the compounded return + end end end From e318998b563579aa21c355acf06a84d0314582f9 Mon Sep 17 00:00:00 2001 From: friedeggs Date: Sat, 17 Sep 2016 15:32:34 -0400 Subject: [PATCH 2/2] Edge cases --- your_return_calculator.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/your_return_calculator.rb b/your_return_calculator.rb index 7a07c29..640a749 100644 --- a/your_return_calculator.rb +++ b/your_return_calculator.rb @@ -13,8 +13,11 @@ def calculate! prev_snapshot = snapshots[0].market_value # Set prev_snapshot for snapshot in snapshots[1..-1] do # Loop starting from second day - time_weighted_return *= (snapshot.market_value - snapshot.cash_flow)/prev_snapshot - prev_snapshot = snapshot.market_value + + unless prev_snapshot == 0 then # Skip days where the market value is 0 + time_weighted_return *= (snapshot.market_value - snapshot.cash_flow)/prev_snapshot + prev_snapshot = snapshot.market_value + end end time_weighted_return - 1 # return the compounded return