loan_creator 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: ce94717f0c667263653597ea2037844157e6cebe
4
+ data.tar.gz: e498fe9069ca0ff9c3d765083a182f28ddc3ca22
5
+ SHA512:
6
+ metadata.gz: da8108111a04280719eba3143444bd2ceac35abaade6521c2e9a5a3297266037c7d8e194156c3a373602fe766bbce49c23ebe515a2db1b64e1a35ac67a4aff06
7
+ data.tar.gz: 5e49dd7114a25fc67e9230ea0d6120b7a12bb83b6b6c50d28eecbfb7c92cc7bbd68da4ca26d0bf7dffe0b7b1fc2a7ec9acbbbb9369bf2cdfb1eb6837625dd2be
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
@@ -0,0 +1,11 @@
1
+ rspec:
2
+ image: "ruby:2.3"
3
+ before_script:
4
+ # COMMANDS
5
+ - ruby -v
6
+ - which ruby
7
+ # BUNDLER
8
+ - gem install bundler --no-ri --no-rdoc
9
+ - bundle install --jobs $(nproc) "${FLAGS[@]}"
10
+ script:
11
+ - bundle exec rspec --color --format documentation
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --color
2
+ --require spec_helper
3
+ --format documentation
@@ -0,0 +1,37 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.3
3
+ Exclude:
4
+ - 'db/**/*'
5
+ - 'vendor/**/*'
6
+ DisplayCopNames: true
7
+
8
+ Documentation:
9
+ Enabled: false
10
+
11
+ Metrics/BlockLength:
12
+ Exclude:
13
+ - spec/**/*
14
+
15
+ Metrics/LineLength:
16
+ Max: 120
17
+
18
+ Metrics/MethodLength:
19
+ Max: 20
20
+
21
+ Style/FrozenStringLiteralComment:
22
+ Enabled: false
23
+
24
+ Style/ClassAndModuleChildren:
25
+ Enabled: false
26
+
27
+ Style/Lambda:
28
+ EnforcedStyle: literal
29
+
30
+ Style/NumericPredicate:
31
+ EnforcedStyle: comparison
32
+
33
+ Naming/VariableNumber:
34
+ EnforcedStyle: snake_case
35
+
36
+ Lint/UnifiedInteger:
37
+ Enabled: false
@@ -0,0 +1 @@
1
+ loan_creator
@@ -0,0 +1 @@
1
+ ruby-2.3.7
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.1
5
+ before_install: gem install bundler -v 1.13.6
Binary file
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in loan_creator.gemspec
4
+ gemspec
5
+
6
+ gem 'activesupport'
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 thibaulth
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,175 @@
1
+ # LoanCreator
2
+
3
+ `loan_creator` gem intends to provide a set of methods to allow automatic generation of loan timetables, for simulation, from a lender point of view and from a borrower point of view, regarding financial rounding differences. As of today, the gem makes the borrower support any rounding issue. In a later work, an option should be provided to decide who supports such issues.
4
+
5
+ Link to Loan_Creator excel simulator [Click here] (Excel)
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'loan_creator'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install loan_creator
22
+
23
+ ## Usage
24
+
25
+ Parent module
26
+
27
+ ```ruby
28
+ module LoanCreator
29
+ ```
30
+
31
+ There are four types of loans. All inherit from a `LoanCreator::Common` class.
32
+
33
+ ```ruby
34
+ LoanCreator::Standard
35
+ LoanCreator::Linear
36
+ LoanCreator::InFine
37
+ LoanCreator::Bullet
38
+ ```
39
+
40
+ Each instance of one of the previous classes has the following attributes:
41
+
42
+ ```ruby
43
+ :period
44
+ :amount
45
+ :annual_interests_rate
46
+ :starts_at
47
+ :duration_in_periods
48
+ :deferred_in_periods (default to zero)
49
+ :interests_start_date (optional)
50
+ ```
51
+
52
+ There is also a `LoanCreator::Timetable` class dedicated to record the data of the loans' terms. Each instance of `LoanCreator::Timetable` represents an array of `LoanCreator::Term` records, each having the following attributes:
53
+
54
+ ```ruby
55
+ # Term number (starts at 1)
56
+ :index
57
+
58
+ # Term date
59
+ :due_on
60
+
61
+ # Remaining due capital at the beginning of the term
62
+ :crd_beginning_of_period
63
+
64
+ # Remaining due capital at the end of the term
65
+ :crd_end_of_period
66
+
67
+ # Theoricaly due interests
68
+ :period_theoric_interests
69
+
70
+ # Difference between theorical and real (rounded) due interests
71
+ :delta_interests
72
+
73
+ # Accrued interests' delta
74
+ :accrued_delta_interests
75
+
76
+ # Adjustment of -0.01 0 or +0.01 cent depending on accrued_delta_interests
77
+ :amount_to_add
78
+
79
+ # Interests to pay this term
80
+ :period_interests
81
+
82
+ # Capital to pay this term
83
+ :period_capital
84
+
85
+ # Total capital paid so far (including current term)
86
+ :total_paid_capital_end_of_period
87
+
88
+ # Total interests paid so far (including current term)
89
+ :total_paid_interests_end_of_period
90
+
91
+ # Amount to pay this term
92
+ :period_amount_to_pay
93
+ ```
94
+
95
+ `#periodic_interests_rate` renders a precise calculation of the loan's periodic interests rate based on two inputs: `#annual_interests_rate` and `#period`.
96
+
97
+ `#lender_timetable` shall be defined in each loan class. It renders an instance of `LoanCreator::Timetable` which contains an ascending order array of `LoanCreator::Term`. It takes into account financial rounding differences and makes the borrower
98
+ support all those differences.
99
+
100
+ `.borrower_timetable(*lenders_timetables)` (class method) intends to sum each attribute of each provided `lender_timetable` on each term and thus to provide an ascending order array of `LoanCreator::Term`. It should be used for the borrower of a loan, once all lenders and their lending amounts
101
+ are known. It makes the borrower support all financial rounding differences.
102
+
103
+ ## Example
104
+
105
+ ```ruby
106
+ loan_creator = LoanCreator::Standard.new(
107
+ period: :year,
108
+ amount: 42_000,
109
+ annual_interests_rate: 4,
110
+ starts_on: '2019-03-01',
111
+ duration_in_periods: 5,
112
+ deferred_in_periods: 1,
113
+ interests_start_date: '2019-02-10'
114
+ )
115
+ loan_creator.lender_timetable
116
+ # => #<LoanCreator::Timetable:0x0000000003198bd0 @terms=[...] ...>
117
+ loan_creator.lender_timetable.terms.first
118
+ # => #<LoanCreator::Term:0x00000000030f1a88 @crd_beginning_of_period=0.42e5,
119
+ # [...] @period_amount_to_pay=0.8745e2, @index=0, @due_on=Sun, 10 Feb 2019>
120
+ ````
121
+
122
+ ## Explanation
123
+
124
+ ### Classes
125
+
126
+ `Standard` loan generates terms with constant payments.
127
+
128
+ `Linear` loan generates terms with constant capital share payment.
129
+
130
+ `Standard` and `Linear` loans may be capital-deferred, i.e. capital repayment is delayed.\
131
+ Interests are to be payed normally during this period.
132
+
133
+ `InFine` loan generates terms where terms' payments are composed by interests only.\
134
+ Capital share shall be repaid in full at loan's end.
135
+
136
+ `Bullet` loan generates terms where terms' payments are zero. \
137
+ Interests are capitalized, i.e. added to the borrowed capital on each term.\
138
+ Capital share shall be repaid in full and all interests paid at loan's end.
139
+
140
+ There is no deferred time for `InFine` and `Bullet` loans as it would be equivalent to increasing loan's duration.
141
+
142
+ ### Attributes
143
+
144
+ `period`: A `Symbol`. `:month`, `:quarter`, `:semester` or `:year`.
145
+
146
+ `duration_in_periods`: An `Integer`.
147
+
148
+ `amount`: Any number that can be converted to `BigDecimal`.
149
+
150
+ `annual_interests_rate`: In percentage. Any number that can be converted to `BigDecimal`.
151
+
152
+ `starts_at`: A `Date`, or a `String` that can be parsed.
153
+
154
+ `deferred_in_periods`: Optional. An `Integer`, smaller than `duration_in_periods`. Number of periods during which no
155
+ capital is refunded, only interest. Only relevant for `Standard` and `Linear` loans.
156
+
157
+ `interests_start_date`: Optional. To be used when the loan starts before the first full term date. This then compute an
158
+ additional term with only interests for the time difference.
159
+ For example, with a `start_at` in january 2020 and a `interests_start_date` in october 2019, the timetable will include a
160
+ first term corresponding to 3 months of interests.
161
+
162
+ ## Development
163
+
164
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
165
+
166
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
167
+
168
+ ## Contributing
169
+
170
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/loan_creator.
171
+
172
+
173
+ ## License
174
+
175
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task default: :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "loan_creator"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,19 @@
1
+ require 'active_support/all'
2
+ require 'bigdecimal'
3
+
4
+ require 'loan_creator/initialize_bigdecimal'
5
+ require 'loan_creator/version'
6
+
7
+ module LoanCreator
8
+ BIG_DECIMAL_DIGITS = 14
9
+
10
+ autoload :ExcelFormulas, 'loan_creator/excel_formulas'
11
+ autoload :BorrowerTimetable, 'loan_creator/borrower_timetable'
12
+ autoload :Common, 'loan_creator/common'
13
+ autoload :Standard, 'loan_creator/standard'
14
+ autoload :Linear, 'loan_creator/linear'
15
+ autoload :InFine, 'loan_creator/in_fine'
16
+ autoload :Bullet, 'loan_creator/bullet'
17
+ autoload :Timetable, 'loan_creator/timetable'
18
+ autoload :Term, 'loan_creator/term'
19
+ end
@@ -0,0 +1,42 @@
1
+ module LoanCreator
2
+ module BorrowerTimetable
3
+ BORROWER_FINANCIAL_ATTRIBUTES = [
4
+ :crd_beginning_of_period,
5
+ :crd_end_of_period,
6
+ :period_interests,
7
+ :period_capital,
8
+ :total_paid_capital_end_of_period,
9
+ :total_paid_interests_end_of_period,
10
+ :period_amount_to_pay
11
+ ].freeze
12
+
13
+ def borrower_timetable(*lenders_timetables)
14
+ raise ArgumentError.new('Array of LoanCreator::Timetable expected') unless Array === lenders_timetables
15
+ raise ArgumentError.new('At least one LoanCreator::Timetable expected') unless lenders_timetables.length > 0
16
+ lenders_timetables.each do |lender_timetable|
17
+ raise ArgumentError.new('Array of LoanCreator::Timetable expected') unless LoanCreator::Timetable === lender_timetable
18
+ end
19
+
20
+ borrower_timetable = LoanCreator::Timetable.new(
21
+ starts_on: lenders_timetables.first.starts_on,
22
+ period: lenders_timetables.first.period
23
+ )
24
+
25
+ # Borrower timetable is not concerned with computation-related value (delta, etc.),
26
+ # thus we start with all values to zero, then we override only BORROWER_FINANCIAL_ATTRIBUTES.
27
+ all_zero = LoanCreator::Term::ARGUMENTS.each_with_object({}) { |k, h| h[k] = bigd('0') }
28
+
29
+ # Group lenders' terms by index
30
+ transposed_terms = lenders_timetables.map(&:terms).transpose
31
+ # For each term, sum each required element
32
+ # First borrower's term contains the sums of lenders' first terms' elements (LoanCreator::Term::ARGUMENT), etc.
33
+ transposed_terms.each do |arr|
34
+ term = BORROWER_FINANCIAL_ATTRIBUTES.each_with_object({}) do |k, h|
35
+ h[k] = arr.inject(bigd('0')) { |sum, tt| sum + tt.send(k) }
36
+ end
37
+ borrower_timetable << LoanCreator::Term.new(all_zero.merge(term))
38
+ end
39
+ borrower_timetable
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,40 @@
1
+ module LoanCreator
2
+ class Bullet < LoanCreator::Common
3
+ def lender_timetable
4
+ raise ArgumentError.new(:deferred_in_periods) unless deferred_in_periods == 0
5
+ raise ArgumentError.new(:interests_start_date) unless interests_start_date.nil?
6
+ timetable = new_timetable
7
+ reset_current_term
8
+ @crd_beginning_of_period = amount
9
+ @crd_end_of_period = amount
10
+ (duration_in_periods - 1).times { timetable << current_term }
11
+ compute_last_term
12
+ timetable << current_term
13
+ timetable
14
+ end
15
+
16
+ private
17
+
18
+ def compute_last_term
19
+ @crd_end_of_period = bigd('0')
20
+ @period_interests = total_interests
21
+ @period_capital = @crd_beginning_of_period
22
+ @total_paid_capital_end_of_period = @period_capital
23
+ @total_paid_interests_end_of_period = @period_interests
24
+ @period_amount_to_pay = @period_capital + @period_interests
25
+ end
26
+
27
+ # Capital * (periodic_interests_rate ^(total_terms))
28
+ #
29
+ def total_payment
30
+ amount.mult(
31
+ (bigd(1) + periodic_interests_rate) ** bigd(duration_in_periods),
32
+ BIG_DECIMAL_DIGITS
33
+ )
34
+ end
35
+
36
+ def total_interests
37
+ total_payment - amount
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,163 @@
1
+ module LoanCreator
2
+ class Common
3
+ extend BorrowerTimetable
4
+
5
+ PERIODS_IN_MONTHS = {
6
+ month: 1,
7
+ quarter: 3,
8
+ semester: 6,
9
+ year: 12
10
+ }.freeze
11
+
12
+ REQUIRED_ATTRIBUTES = [
13
+ :period,
14
+ :amount,
15
+ :annual_interests_rate,
16
+ :starts_on,
17
+ :duration_in_periods
18
+ ].freeze
19
+
20
+ OPTIONAL_ATTRIBUTES = {
21
+ # attribute: default_value
22
+ deferred_in_periods: 0,
23
+ interests_start_date: nil,
24
+ }.freeze
25
+
26
+ attr_reader *REQUIRED_ATTRIBUTES
27
+ attr_reader *OPTIONAL_ATTRIBUTES.keys
28
+
29
+ def initialize(**options)
30
+ @options = options
31
+ require_attributes
32
+ reinterpret_attributes
33
+ set_attributes
34
+ validate_attributes
35
+ end
36
+
37
+ def periodic_interests_rate_percentage
38
+ @periodic_interests_rate_percentage ||=
39
+ annual_interests_rate.div(12 / PERIODS_IN_MONTHS[period], BIG_DECIMAL_DIGITS)
40
+ end
41
+
42
+ def periodic_interests_rate
43
+ @periodic_interests_rate ||=
44
+ periodic_interests_rate_percentage.div(100, BIG_DECIMAL_DIGITS)
45
+ end
46
+
47
+ def lender_timetable
48
+ raise NotImplementedError
49
+ end
50
+
51
+ def self.bigd(value)
52
+ BigDecimal(value, BIG_DECIMAL_DIGITS)
53
+ end
54
+
55
+ def bigd(value)
56
+ self.class.bigd(value)
57
+ end
58
+
59
+ private
60
+
61
+ def require_attributes
62
+ REQUIRED_ATTRIBUTES.each { |k| raise ArgumentError.new(k) unless @options.fetch(k, nil) }
63
+ end
64
+
65
+ def reinterpret_attributes
66
+ @options[:period] = @options[:period].to_sym
67
+ @options[:amount] = bigd(@options[:amount])
68
+ @options[:annual_interests_rate] = bigd(@options[:annual_interests_rate])
69
+ @options[:starts_on] = Date.parse(@options[:starts_on]) if @options[:starts_on].is_a?(String)
70
+ @options[:interests_start_date] = Date.parse(@options[:interests_start_date]) if @options[:interests_start_date].is_a?(String)
71
+ end
72
+
73
+ def set_attributes
74
+ REQUIRED_ATTRIBUTES.each { |k| instance_variable_set(:"@#{k}", @options.fetch(k)) }
75
+ OPTIONAL_ATTRIBUTES.each { |k,v| instance_variable_set(:"@#{k}", @options.fetch(k, v)) }
76
+ end
77
+
78
+ def validate(key, &block)
79
+ raise unless block.call(instance_variable_get(:"@#{key}"))
80
+ rescue
81
+ raise ArgumentError.new(key)
82
+ end
83
+
84
+ def validate_attributes
85
+ validate(:period) { |v| PERIODS_IN_MONTHS.keys.include?(v) }
86
+ validate(:amount) { |v| v.is_a?(BigDecimal) && v > 0 }
87
+ validate(:annual_interests_rate) { |v| v.is_a?(BigDecimal) && v >= 0 }
88
+ validate(:starts_on) { |v| v.is_a?(Date) }
89
+ validate(:duration_in_periods) { |v| v.is_a?(Integer) && v > 0 }
90
+ validate(:deferred_in_periods) { |v| v.is_a?(Integer) && v >= 0 && v < duration_in_periods }
91
+ end
92
+
93
+ def reset_current_term
94
+ @crd_beginning_of_period = bigd('0')
95
+ @crd_end_of_period = bigd('0')
96
+ @period_theoric_interests = bigd('0')
97
+ @delta_interests = bigd('0')
98
+ @accrued_delta_interests = bigd('0')
99
+ @amount_to_add = bigd('0')
100
+ @period_interests = bigd('0')
101
+ @period_capital = bigd('0')
102
+ @total_paid_capital_end_of_period = bigd('0')
103
+ @total_paid_interests_end_of_period = bigd('0')
104
+ @period_amount_to_pay = bigd('0')
105
+ @due_on = nil
106
+ @index = nil
107
+ end
108
+
109
+ def current_term
110
+ LoanCreator::Term.new(
111
+ crd_beginning_of_period: @crd_beginning_of_period,
112
+ crd_end_of_period: @crd_end_of_period,
113
+ period_theoric_interests: @period_theoric_interests,
114
+ delta_interests: @delta_interests,
115
+ accrued_delta_interests: @accrued_delta_interests,
116
+ amount_to_add: @amount_to_add,
117
+ period_interests: @period_interests,
118
+ period_capital: @period_capital,
119
+ total_paid_capital_end_of_period: @total_paid_capital_end_of_period,
120
+ total_paid_interests_end_of_period: @total_paid_interests_end_of_period,
121
+ period_amount_to_pay: @period_amount_to_pay,
122
+ due_on: @due_on,
123
+ index: @index
124
+ )
125
+ end
126
+
127
+ def new_timetable
128
+ LoanCreator::Timetable.new(starts_on: starts_on, period: period, interests_start_date: interests_start_date)
129
+ end
130
+
131
+ def compute_term_zero
132
+ @crd_beginning_of_period = @crd_end_of_period
133
+ @period_theoric_interests = term_zero_interests
134
+ @delta_interests = @period_theoric_interests - @period_theoric_interests.round(2)
135
+ @accrued_delta_interests += @delta_interests
136
+ @period_interests = @period_theoric_interests.round(2)
137
+ @total_paid_interests_end_of_period += @period_interests
138
+ @period_amount_to_pay = @period_interests
139
+ @index = 0
140
+ end
141
+
142
+ def term_zero_interests
143
+ @crd_beginning_of_period * term_zero_interests_rate
144
+ end
145
+
146
+ def term_zero_interests_rate
147
+ term_zero_interests_rate_percentage = (annual_interests_rate * term_zero_duration).div(365, BIG_DECIMAL_DIGITS)
148
+ term_zero_interests_rate_percentage.div(100, BIG_DECIMAL_DIGITS)
149
+ end
150
+
151
+ def term_zero_duration
152
+ (term_zero_date - interests_start_date).to_i
153
+ end
154
+
155
+ def term_zero_date
156
+ starts_on.advance(months: -PERIODS_IN_MONTHS.fetch(@period))
157
+ end
158
+
159
+ def term_zero?
160
+ interests_start_date && interests_start_date < term_zero_date
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,41 @@
1
+ # Source: https://gist.github.com/mattetti/1015948
2
+
3
+ module LoanCreator::ExcelFormulas
4
+ # Returns the interest payment
5
+ # for a given period for an investment based on periodic, constant payments and a constant interest rate.
6
+ def ipmt(rate, per, nper, pv, fv=0, type=0)
7
+ p = _pmt(rate, nper, pv, fv, 0);
8
+ ip = -(pv * _pow1p(rate, per - 1) * rate + p * _pow1pm1(rate, per - 1))
9
+ (type == 0) ? ip : ip / (1 + rate)
10
+ end
11
+
12
+ # Returns the payment on the principal
13
+ # for a given period for an investment based on periodic, constant payments and a constant interest rate.
14
+ def ppmt(rate, per, nper, pv, fv=0, type=0)
15
+ p = _pmt(rate, nper, pv, fv, type)
16
+ ip = ipmt(rate, per, nper, pv, fv, type)
17
+ p - ip
18
+ end
19
+
20
+ protected
21
+
22
+ def _pmt(rate, nper, pv, fv=0, type=0)
23
+ ((-pv * _pvif(rate, nper) - fv ) / ((bigd('1.0') + rate * type) * _fvifa(rate, nper)))
24
+ end
25
+
26
+ def _pow1pm1(x, y)
27
+ (x <= -1) ? ((1 + x) ** y) - 1 : Math.exp(y * Math.log(bigd('1.0') + x)) - 1
28
+ end
29
+
30
+ def _pow1p(x, y)
31
+ (x.abs > bigd('0.5')) ? ((1 + x) ** y) : Math.exp(y * Math.log(bigd('1.0') + x))
32
+ end
33
+
34
+ def _pvif(rate, nper)
35
+ _pow1p(rate, nper)
36
+ end
37
+
38
+ def _fvifa(rate, nper)
39
+ (rate == 0) ? nper : _pow1pm1(rate, nper) / rate
40
+ end
41
+ end
@@ -0,0 +1,10 @@
1
+ module LoanCreator
2
+ class InFine < LoanCreator::Common
3
+ # InFine is the same as a Linear loan with (duration - 1) deferred periods.
4
+ # Thus we're generating a Linear loan instead of rewriting already existing code.
5
+ def lender_timetable
6
+ options = @options.merge(deferred_in_periods: duration_in_periods - 1)
7
+ LoanCreator::Linear.new(options).lender_timetable
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,6 @@
1
+ # Round towards the nearest neighbor, unless both neighbors are
2
+ # equidistant, in which case round towards the even neighbor
3
+ # (Bank rounding)
4
+ # usage of BigDecimal method: div(value, digits)
5
+ # usage of BigDecimal method: mult(value, digits)
6
+ BigDecimal.mode(BigDecimal::ROUND_HALF_EVEN, true)
@@ -0,0 +1,65 @@
1
+ # coding: utf-8
2
+ module LoanCreator
3
+ class Linear < LoanCreator::Common
4
+ def lender_timetable
5
+ timetable = new_timetable
6
+ reset_current_term
7
+ @crd_end_of_period = amount
8
+
9
+ if term_zero?
10
+ compute_term_zero
11
+ timetable << current_term
12
+ end
13
+
14
+ duration_in_periods.times do |idx|
15
+ @last_period = last_period?(idx)
16
+ @deferred_period = idx < deferred_in_periods
17
+ compute_current_term(idx)
18
+ timetable << current_term
19
+ end
20
+ timetable
21
+ end
22
+
23
+ private
24
+
25
+ def last_period?(idx)
26
+ idx == (duration_in_periods - 1)
27
+ end
28
+
29
+ def compute_current_term(idx)
30
+ # Reminder: CRD beginning of period = CRD end of period **of previous period**
31
+ @crd_beginning_of_period = @crd_end_of_period
32
+ @period_theoric_interests = @crd_beginning_of_period * periodic_interests_rate
33
+ @delta_interests = @period_theoric_interests - @period_theoric_interests.round(2)
34
+ @accrued_delta_interests += @delta_interests
35
+ @amount_to_add = bigd(
36
+ if @accrued_delta_interests >= bigd('0.01')
37
+ '0.01'
38
+ elsif @accrued_delta_interests <= bigd('-0.01')
39
+ '-0.01'
40
+ else
41
+ '0'
42
+ end
43
+ )
44
+ @accrued_delta_interests -= @amount_to_add
45
+ @period_interests = @period_theoric_interests.round(2) + @amount_to_add
46
+ @period_capital = period_capital
47
+ @total_paid_capital_end_of_period += @period_capital
48
+ @total_paid_interests_end_of_period += @period_interests
49
+ @period_amount_to_pay = @period_interests + @period_capital
50
+ @crd_end_of_period -= @period_capital
51
+ @due_on = nil
52
+ @index = idx + 1
53
+ end
54
+
55
+ def period_capital
56
+ if @last_period
57
+ @crd_beginning_of_period
58
+ elsif @deferred_period
59
+ bigd(0)
60
+ else
61
+ (amount / (duration_in_periods - deferred_in_periods)).round(2)
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,83 @@
1
+ module LoanCreator
2
+ class Standard < LoanCreator::Common
3
+ include LoanCreator::ExcelFormulas
4
+
5
+ def lender_timetable
6
+ timetable = new_timetable
7
+ reset_current_term
8
+ @crd_end_of_period = amount
9
+
10
+ if term_zero?
11
+ compute_term_zero
12
+ timetable << current_term
13
+ end
14
+
15
+ duration_in_periods.times do |idx|
16
+ @last_period = last_period?(idx)
17
+ @deferred_period = idx < deferred_in_periods
18
+ compute_current_term(idx)
19
+ timetable << current_term
20
+ end
21
+ timetable
22
+ end
23
+
24
+ private
25
+
26
+ def last_period?(idx)
27
+ idx == (duration_in_periods - 1)
28
+ end
29
+
30
+ def compute_current_term(idx)
31
+ @crd_beginning_of_period = @crd_end_of_period
32
+ @period_theoric_interests = period_theoric_interests(idx)
33
+ @delta_interests = @period_theoric_interests - @period_theoric_interests.round(2)
34
+ @accrued_delta_interests += @delta_interests
35
+ @amount_to_add = bigd(
36
+ if @accrued_delta_interests >= bigd('0.01')
37
+ '0.01'
38
+ elsif @accrued_delta_interests <= bigd('-0.01')
39
+ '-0.01'
40
+ else
41
+ '0'
42
+ end
43
+ )
44
+ @accrued_delta_interests -= @amount_to_add
45
+ @period_interests = @period_theoric_interests.round(2) + @amount_to_add
46
+ @period_capital = period_capital(idx)
47
+ @total_paid_capital_end_of_period += @period_capital
48
+ @total_paid_interests_end_of_period += @period_interests
49
+ @period_amount_to_pay = @period_interests + @period_capital
50
+ @crd_end_of_period -= @period_capital
51
+ @due_on = nil
52
+ @index = idx + 1
53
+ end
54
+
55
+ def period_theoric_interests(idx)
56
+ if @deferred_period
57
+ @crd_beginning_of_period * periodic_interests_rate
58
+ else
59
+ -ipmt(
60
+ periodic_interests_rate,
61
+ (idx + 1) - deferred_in_periods,
62
+ duration_in_periods - deferred_in_periods,
63
+ amount
64
+ )
65
+ end
66
+ end
67
+
68
+ def period_capital(idx)
69
+ if @last_period
70
+ @crd_beginning_of_period
71
+ elsif @deferred_period
72
+ bigd(0)
73
+ else
74
+ -ppmt(
75
+ periodic_interests_rate,
76
+ (idx + 1) - deferred_in_periods,
77
+ duration_in_periods - deferred_in_periods,
78
+ amount
79
+ ).round(2)
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,70 @@
1
+ module LoanCreator
2
+ class Term
3
+
4
+ ARGUMENTS = [
5
+ # Remaining due capital at the beginning of the term
6
+ :crd_beginning_of_period,
7
+
8
+ # Remaining due capital at the end of the term
9
+ :crd_end_of_period,
10
+
11
+ # Theoricaly due interests
12
+ :period_theoric_interests,
13
+
14
+ # Difference between theorical and real (rounded) due interests
15
+ :delta_interests,
16
+
17
+ # Accrued interests' delta
18
+ :accrued_delta_interests,
19
+
20
+ # Adjustment of -0.01, 0 or +0.01 cent depending on accrued_delta_interests
21
+ :amount_to_add,
22
+
23
+ # Interests to pay this term
24
+ :period_interests,
25
+
26
+ # Capital to pay this term
27
+ :period_capital,
28
+
29
+ # Total capital paid so far (including current term)
30
+ :total_paid_capital_end_of_period,
31
+
32
+ # Total interests paid so far (including current term)
33
+ :total_paid_interests_end_of_period,
34
+
35
+ # Amount to pay this term
36
+ :period_amount_to_pay
37
+ ].freeze
38
+
39
+ OPTIONAL_ARGUMENTS = [
40
+ # Term number (starts at 1)
41
+ # This value is to be set by Timetable
42
+ :index,
43
+
44
+ # Term date
45
+ # This value is to be set by Timetable
46
+ :due_on,
47
+ ]
48
+
49
+ ATTRIBUTES = (ARGUMENTS + OPTIONAL_ARGUMENTS).freeze
50
+
51
+ attr_accessor *ATTRIBUTES
52
+
53
+ def initialize(**options)
54
+ ARGUMENTS.each { |k| instance_variable_set(:"@#{k}", options.fetch(k)) }
55
+ OPTIONAL_ARGUMENTS.each { |k| instance_variable_set(:"@#{k}", options.fetch(k, nil)) }
56
+ end
57
+
58
+ def to_csv
59
+ ATTRIBUTES.map { |k| instance_variable_get(:"@#{k}") }.join(',')
60
+ end
61
+
62
+ def to_s
63
+ to_csv
64
+ end
65
+
66
+ def to_h
67
+ ATTRIBUTES.each_with_object({}) { |k, h| h[k] = instance_variable_get(:"@#{k}") }
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,70 @@
1
+ # coding: utf-8
2
+ module LoanCreator
3
+ class Timetable
4
+ # Used to calculate next term's date (see ActiveSupport#advance)
5
+ PERIODS = {
6
+ month: {months: 1},
7
+ quarter: {months: 3},
8
+ semester: {months: 6},
9
+ year: {years: 1}
10
+ }
11
+
12
+ attr_reader :terms, :starts_on, :period #, :interests_start_date
13
+
14
+ def initialize(starts_on:, period:, interests_start_date: nil)
15
+ raise ArgumentError.new(:period) unless PERIODS.keys.include?(period)
16
+
17
+ @terms = []
18
+ @starts_on = (starts_on.is_a?(Date) ? starts_on : Date.parse(starts_on))
19
+ @period = period
20
+
21
+ if interests_start_date
22
+ @interests_start_date = (interests_start_date.is_a?(Date) ? interests_start_date : Date.parse(interests_start_date))
23
+ end
24
+ end
25
+
26
+ def <<(term)
27
+ raise ArgumentError.new('LoanCreator::Term expected') unless term.is_a?(LoanCreator::Term)
28
+ term.index ||= autoincrement_index
29
+ term.due_on ||= date_for(term.index)
30
+ @terms << term
31
+ self
32
+ end
33
+
34
+ def to_csv(header: true)
35
+ output = []
36
+ output << terms.first.to_h.keys.join(',') if header
37
+ terms.each { |t| output << t.to_csv }
38
+ output
39
+ end
40
+
41
+ def term(index)
42
+ @terms.find { |term| term.index == index }
43
+ end
44
+
45
+ private
46
+
47
+ def autoincrement_index
48
+ @current_index = @current_index.nil? ? 1 : @current_index + 1
49
+ end
50
+
51
+ def date_for(index)
52
+ @_dates ||= Hash.new do |dates, index|
53
+ dates[index] =
54
+ if index < 1
55
+ dates[index + 1].advance(PERIODS.fetch(period).transform_values {|n| -n})
56
+ elsif index == 1
57
+ starts_on
58
+ else
59
+ dates[index - 1].advance(PERIODS.fetch(period))
60
+ end
61
+ end
62
+
63
+ @_dates[index]
64
+ end
65
+
66
+ def reset_dates
67
+ @_dates = nil
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,3 @@
1
+ module LoanCreator
2
+ VERSION = '0.5.0'.freeze
3
+ end
@@ -0,0 +1,30 @@
1
+ lib = File.expand_path('../lib', __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'loan_creator/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'loan_creator'
7
+ spec.version = LoanCreator::VERSION
8
+ spec.authors = %w[thibaulth nicob younes.serraj]
9
+ spec.email = ['thibault@capsens.eu', 'nicolas.besnard@capsens.eu', 'younes.serraj@gmail.com']
10
+
11
+ spec.summary = 'Create and update timetables from input data'
12
+ spec.homepage = 'https://capsens.githost.io/capsens/loan-creator'
13
+ spec.license = 'MIT'
14
+
15
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
16
+ f.match(%r{^(test|spec|features)/})
17
+ end
18
+ spec.bindir = 'exe'
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.add_development_dependency 'bundler', '~> 1.13'
23
+ spec.add_development_dependency 'rake', '~> 10.0'
24
+ spec.add_development_dependency 'rspec', '~> 3.0'
25
+ spec.add_development_dependency 'simplecov', '~> 0.16'
26
+ spec.add_development_dependency 'byebug', '~> 11.0'
27
+
28
+ spec.add_runtime_dependency 'bigdecimal'
29
+ spec.add_runtime_dependency 'activesupport'
30
+ end
metadata ADDED
@@ -0,0 +1,173 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: loan_creator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.5.0
5
+ platform: ruby
6
+ authors:
7
+ - thibaulth
8
+ - nicob
9
+ - younes.serraj
10
+ autorequire:
11
+ bindir: exe
12
+ cert_chain: []
13
+ date: 2020-09-16 00:00:00.000000000 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: bundler
17
+ requirement: !ruby/object:Gem::Requirement
18
+ requirements:
19
+ - - "~>"
20
+ - !ruby/object:Gem::Version
21
+ version: '1.13'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: '1.13'
29
+ - !ruby/object:Gem::Dependency
30
+ name: rake
31
+ requirement: !ruby/object:Gem::Requirement
32
+ requirements:
33
+ - - "~>"
34
+ - !ruby/object:Gem::Version
35
+ version: '10.0'
36
+ type: :development
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - "~>"
41
+ - !ruby/object:Gem::Version
42
+ version: '10.0'
43
+ - !ruby/object:Gem::Dependency
44
+ name: rspec
45
+ requirement: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - "~>"
48
+ - !ruby/object:Gem::Version
49
+ version: '3.0'
50
+ type: :development
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - "~>"
55
+ - !ruby/object:Gem::Version
56
+ version: '3.0'
57
+ - !ruby/object:Gem::Dependency
58
+ name: simplecov
59
+ requirement: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - "~>"
62
+ - !ruby/object:Gem::Version
63
+ version: '0.16'
64
+ type: :development
65
+ prerelease: false
66
+ version_requirements: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - "~>"
69
+ - !ruby/object:Gem::Version
70
+ version: '0.16'
71
+ - !ruby/object:Gem::Dependency
72
+ name: byebug
73
+ requirement: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - "~>"
76
+ - !ruby/object:Gem::Version
77
+ version: '11.0'
78
+ type: :development
79
+ prerelease: false
80
+ version_requirements: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - "~>"
83
+ - !ruby/object:Gem::Version
84
+ version: '11.0'
85
+ - !ruby/object:Gem::Dependency
86
+ name: bigdecimal
87
+ requirement: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: '0'
92
+ type: :runtime
93
+ prerelease: false
94
+ version_requirements: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ - !ruby/object:Gem::Dependency
100
+ name: activesupport
101
+ requirement: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ type: :runtime
107
+ prerelease: false
108
+ version_requirements: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ description:
114
+ email:
115
+ - thibault@capsens.eu
116
+ - nicolas.besnard@capsens.eu
117
+ - younes.serraj@gmail.com
118
+ executables: []
119
+ extensions: []
120
+ extra_rdoc_files: []
121
+ files:
122
+ - ".gitignore"
123
+ - ".gitlab-ci.yml"
124
+ - ".rspec"
125
+ - ".rubocop.yml"
126
+ - ".ruby-gemset"
127
+ - ".ruby-version"
128
+ - ".travis.yml"
129
+ - CapSens_Loan.xlsx
130
+ - Gemfile
131
+ - LICENSE.txt
132
+ - README.md
133
+ - Rakefile
134
+ - bin/console
135
+ - bin/setup
136
+ - lib/loan_creator.rb
137
+ - lib/loan_creator/borrower_timetable.rb
138
+ - lib/loan_creator/bullet.rb
139
+ - lib/loan_creator/common.rb
140
+ - lib/loan_creator/excel_formulas.rb
141
+ - lib/loan_creator/in_fine.rb
142
+ - lib/loan_creator/initialize_bigdecimal.rb
143
+ - lib/loan_creator/linear.rb
144
+ - lib/loan_creator/standard.rb
145
+ - lib/loan_creator/term.rb
146
+ - lib/loan_creator/timetable.rb
147
+ - lib/loan_creator/version.rb
148
+ - loan_creator.gemspec
149
+ homepage: https://capsens.githost.io/capsens/loan-creator
150
+ licenses:
151
+ - MIT
152
+ metadata: {}
153
+ post_install_message:
154
+ rdoc_options: []
155
+ require_paths:
156
+ - lib
157
+ required_ruby_version: !ruby/object:Gem::Requirement
158
+ requirements:
159
+ - - ">="
160
+ - !ruby/object:Gem::Version
161
+ version: '0'
162
+ required_rubygems_version: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ requirements: []
168
+ rubyforge_project:
169
+ rubygems_version: 2.5.2.3
170
+ signing_key:
171
+ specification_version: 4
172
+ summary: Create and update timetables from input data
173
+ test_files: []