Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions your_return_calculator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,25 @@

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
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you mean to write when 1?

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

unless prev_snapshot == 0 then # Skip days where the market value is 0
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you prev_snapshot = 0, then it will always stay 0 because you never set it again.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    if prev_snapshot == 0
      prev_snapshot = snapshot.market_value
    else
      time_weighted_return *= (snapshot.market_value - snapshot.cash_flow)/prev_snapshot
      prev_snapshot = snapshot.market_value
    end

This will work.

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