require "work_day" module ROI module RentabilityPeriods def days(days_amount = 1) scoped_start = WorkDay.last_until(end_date - days_amount) format(scoped_start, end_date) end def current_month scoped_start = WorkDay.last_until((end_date - 1.month).end_of_month) check_gaps_and_format(adjust_start_date(scoped_start), end_date) end def months(amount, date = end_date) return current_month if amount == 1 && date == end_date scoped_start = WorkDay.last_until((date - (amount+1).month).end_of_month) scoped_end = adjust_end_date((date - 1.month).end_of_month) check_gaps_and_format(scoped_start, scoped_end) end def current_year scoped_start = WorkDay.last_until((end_date - 1.year).end_of_year) format(adjust_start_date(scoped_start), end_date) end def years_ago(amount) scoped_end = WorkDay.last_until((end_date - amount.year).end_of_year) scoped_start = WorkDay.last_until((scoped_end - 1.year).end_of_year) format(adjust_start_date(scoped_start), scoped_end) end def portfolio format(start_date, end_date) end private def adjust_start_date(date) [start_date, date].compact.max end def adjust_end_date(date) WorkDay.last_until(date.strftime("%Y-%m") == end_date.strftime("%Y-%m") ? end_date : date.end_of_month) end def format(start_date, end_date) scoped_start, scoped_end = rentabilities.values_at(start_date, end_date) if scoped_start && scoped_end ((scoped_end.share / scoped_start.share - 1) * 100).round(8) end end def check_gaps_and_format(scoped_start, scoped_end) _start, _end = rentabilities.values_at(scoped_start, scoped_end) return unless _start && _end if skip_on_gap rentabilities.each_value do |line| return if line.date.between?(_start.date, _end.date) && !line.have_position end end format(scoped_start, scoped_end) end end end