Sha256: 9ca44d8751a0cae4b217243d365f50843cdc25a4583f557699a32e3da9454d8e

Contents?: true

Size: 1.75 KB

Versions: 15

Compression:

Stored size: 1.75 KB

Contents

require "work_day"
require "active_support"
require "active_support/core_ext/date"

module ROI
  class FinancialResult
    attr_reader :start_date, :end_date, :rentabilities

    def initialize(rentabilities, start_date, end_date)
      @rentabilities = rentabilities
      @start_date = start_date
      @end_date = end_date
    end

    def current_month
      scope_start = WorkDay.next_after(end_date.beginning_of_month, 0)
      format_financial(scope_start, end_date)
    end

    def months(amount)
      scope_start = (end_date - amount.months + 1.month).beginning_of_month
      check_gaps_and_format(scope_start, end_date)
    end

    def current_year
      scope_start = WorkDay.next_after(end_date.beginning_of_year, 0)
      format_financial(scope_start, end_date)
    end

    def years_ago(amount)
      scope_end = (end_date - amount.year).end_of_year
      scope_start = scope_end.beginning_of_year
      format_financial(scope_start, scope_end)
    end

    def portfolio
      format_financial(start_date, end_date)
    end

    private
    def scoped_rentabilities(scope_start, scope_end)
      rentabilities.values.select.each do |line|
        line.date.between?(scope_start, scope_end)
      end
    end

    def format_financial(scope_start, scope_end)
      return unless scope_start && scope_end
      total = scoped_rentabilities(scope_start, scope_end).sum do |line|
        line.try(:daily_result) || 0
      end.round(2)
      total != 0 ? total : nil
    end

    def check_gaps_and_format(scope_start, scope_end)
      if scope_start >= start_date
        scoped_rentabilities(scope_start, scope_end).each do |line|
          return if line.try(:have_position) == false
        end
        format_financial(scope_start, scope_end)
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
roi_calculator-0.3.7 lib/roi/financial_result.rb
roi_calculator-0.3.6 lib/roi/financial_result.rb
roi_calculator-0.3.5 lib/roi/financial_result.rb
roi_calculator-0.3.4 lib/roi/financial_result.rb
roi_calculator-0.3.3 lib/roi/financial_result.rb
roi_calculator-0.3.2 lib/roi/financial_result.rb
roi_calculator-0.3.1 lib/roi/financial_result.rb
roi_calculator-0.3.0 lib/roi/financial_result.rb
roi_calculator-1.0.0 lib/roi/financial_result.rb
roi_calculator-0.2.0 lib/roi/financial_result.rb
roi_calculator-0.1.6 lib/roi/financial_result.rb
roi_calculator-0.1.5 lib/roi/financial_result.rb
roi_calculator-0.1.4 lib/roi/financial_result.rb
roi_calculator-0.1.3 lib/roi/financial_result.rb
roi_calculator-0.1.2 lib/roi/financial_result.rb