cashflow_sim 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 15ea823bf47ada32f48f9afa7f9b103b434712498e5aadc4c53ca825d8bb2468
4
+ data.tar.gz: 051c79a1a8ddfbcdef7ec9cd7f13ef96e53e4d56cf2c431da15f89fdbe6cfb4b
5
+ SHA512:
6
+ metadata.gz: 42fd8ee7a2d64c36fbc7119fe3d3789e9b679afe59c4f8cbe3bf009595482257f9d7a969617a74d85942efac8b4d411c684802b7612247a214a093ddc0a4f5e4
7
+ data.tar.gz: c85d2c9ca179873cd7cbe85bef99a9b2aa3b0bb54a58fc04eba414068e61faaf4fae2fedc6ad1c65008e87380a53cada74c2a6ff9f252e1c208fda03269d6e27
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-09-11
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 篠原亮太
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.
data/README.md ADDED
@@ -0,0 +1,46 @@
1
+ ## Installation
2
+
3
+ Add this line to your application's Gemfile:
4
+
5
+ ```ruby
6
+ gem "cashflow_sim"
7
+ ```
8
+
9
+ And then execute:
10
+
11
+ ```bash
12
+ bundle install
13
+ ```
14
+
15
+ Or install it yourself:
16
+
17
+ ```bash
18
+ gem install cashflow_sim
19
+ ```
20
+
21
+ ## CLI
22
+
23
+ ```bash
24
+ # 固定金利(年次)
25
+ cashflow_sim --principal 1000000 --years 5 --rate 1.5 --yearly
26
+
27
+ # 線形に変動(1年目0.7%→30年目2.0%へ、以降据え置き)
28
+ cashflow_sim --principal 45000000 --years 40 --start-rate 0.7 --end-rate 2.0 --end-year 30 --format csv > schedule.csv
29
+
30
+ # ヘルプ
31
+ cashflow_sim --help
32
+ ```
33
+
34
+ ## Library (Ruby)
35
+
36
+ ```ruby
37
+ require "cashflow_sim"
38
+
39
+ am = CashflowSim::Amortization.new(
40
+ principal: 1_000_000,
41
+ years: 5,
42
+ rate_schedule: 1.5,
43
+ frequency: :yearly
44
+ )
45
+ rows = am.schedule
46
+ ```
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/exe/cashflow_sim ADDED
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "optparse"
5
+ require "json"
6
+ require "csv"
7
+ require_relative "../lib/cashflow_sim"
8
+
9
+ # ---- オプション定義(デフォルト値)----
10
+ options = {
11
+ principal: 45_000_000,
12
+ years: 40,
13
+ # 固定金利か、線形に変動する金利かを選べる
14
+ rate: nil, # 単一の年利%(例: 1.5)を与えたら固定金利として使用
15
+ start_rate: 0.7, # 変動開始年利%
16
+ end_rate: 2.0, # 変動終了年利%
17
+ end_year: 30, # end_rate に到達する年(以降は据え置き)
18
+ frequency: :monthly,
19
+ format: "json"
20
+ }
21
+
22
+ # ---- OptionParser で引数を解析 ----
23
+ # Ruby標準の optparse は「-」「--」のフラグを宣言し、ブロックで値を受け取る仕組み
24
+ parser = OptionParser.new do |o|
25
+ o.banner = "Usage: cashflow_sim [options]"
26
+
27
+ o.on("--principal N", Integer, "元本(例: 45000000)") { |v| options[:principal] = v }
28
+ o.on("--years N", Integer, "返済年数(例: 40)") { |v| options[:years] = v }
29
+
30
+ # 固定金利(--rate)か、線形変動金利(--start-rate/--end-rate/--end-year)かを選択
31
+ o.on("--rate F", Float, "固定の年利%(例: 1.5)") { |v| options[:rate] = v }
32
+ o.on("--start-rate F", Float, "変動スタート年利%(例: 0.7)") { |v| options[:start_rate] = v }
33
+ o.on("--end-rate F", Float, "変動終了年利%(例: 2.0)") { |v| options[:end_rate] = v }
34
+ o.on("--end-year N", Integer, "end_rate に到達する年(例: 30)") { |v| options[:end_year] = v }
35
+
36
+ o.on("--yearly", "年次計算にする(既定は月次)") { options[:frequency] = :yearly }
37
+ o.on("--monthly", "月次計算にする(デフォルト)") { options[:frequency] = :monthly }
38
+
39
+ o.on("--format FORMAT", %w[json csv], "出力形式:json | csv(default: json)") { |v| options[:format] = v }
40
+
41
+ o.on("-h", "--help", "ヘルプを表示") do
42
+ puts o
43
+ exit
44
+ end
45
+ end
46
+
47
+ begin
48
+ parser.parse!
49
+ rescue OptionParser::ParseError => e
50
+ warn e.message
51
+ warn parser
52
+ exit 1
53
+ end
54
+
55
+ # ---- 金利スケジュールを決定 ----
56
+ # Amortization.new の rate_schedule 引数には、
57
+ # - Proc(年を受けて年利%を返す) か
58
+ # - Array(年ごとの年利%)
59
+ # - Numeric(単一の年利%)
60
+ # のいずれかを渡せる実装になっている。
61
+ rate_schedule =
62
+ if options[:rate]
63
+ # 固定金利:Numeric を渡す
64
+ options[:rate]
65
+ else
66
+ # 線形変動金利:Proc を渡す
67
+ start_rate = options[:start_rate].to_f
68
+ end_rate = options[:end_rate].to_f
69
+ end_year = [options[:end_year].to_i, 1].max
70
+
71
+ # year=1 で start_rate、year=end_year で end_rate、その後は据え置き
72
+ lambda do |year|
73
+ y = [[year, 1].max, end_year].min
74
+ t = (y - 1).to_f / (end_year - 1) # 0..1 に正規化(end_year==1 の場合は下で補正)
75
+ t = 0.0 if end_year == 1
76
+ start_rate + (end_rate - start_rate) * t
77
+ end
78
+ end
79
+
80
+ # ---- 計算本体 ----
81
+ am = CashflowSim::Amortization.new(
82
+ principal: options[:principal],
83
+ years: options[:years],
84
+ rate_schedule: rate_schedule,
85
+ frequency: options[:frequency]
86
+ )
87
+
88
+ rows = am.schedule
89
+
90
+ # ---- 出力 ----
91
+ case options[:format]
92
+ when "json"
93
+ puts JSON.pretty_generate(rows.map(&:to_h))
94
+ when "csv"
95
+ CSV($stdout) do |csv|
96
+ csv << %w[year month rate payment interest principal_paid balance]
97
+ rows.each { |r| csv << [r.year, r.month, r.rate, r.payment, r.interest, r.principal_paid, r.balance] }
98
+ end
99
+ else
100
+ warn "unknown format: #{options[:format]}"
101
+ exit 1
102
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CashflowSim
4
+ # 返済スケジュールを生成するクラス
5
+ # - principal: 元本
6
+ # - years: 返済年数
7
+ # - rate_schedule: 年ごとの「年利(%)」を返す Proc / 配列 / 数値
8
+ # - frequency: :monthly or :yearly
9
+ class Amortization
10
+ Period = Struct.new(:year, :month, :rate, :payment, :interest, :principal_paid, :balance, keyword_init: true)
11
+
12
+ def initialize(principal:, years:, rate_schedule:, frequency: :monthly)
13
+ @principal = principal.to_f
14
+ @years = years.to_i
15
+ @rate_fn = to_rate_fn(rate_schedule)
16
+ @freq = frequency
17
+ end
18
+
19
+ def schedule
20
+ periods = []
21
+ balance = @principal
22
+ total = (@freq == :monthly ? (@years * 12) : @years)
23
+
24
+ (1..total).each do |i|
25
+ y = year_of(i)
26
+ m = month_of(i)
27
+ annual_percent = @rate_fn.call(y)
28
+ r = period_rate(annual_percent)
29
+
30
+ # 残期間(いまの期も含める)
31
+ n_left = total - i + 1
32
+ # 残期間が0にならないようガード
33
+ n_left = 1 if n_left < 1
34
+
35
+ pmt = annuity_payment(balance, r, n_left)
36
+
37
+ interest = balance * r
38
+ principal_paid = [pmt - interest, balance].min
39
+ balance = (balance - principal_paid).clamp(0.0, Float::INFINITY)
40
+
41
+ periods << Period.new(
42
+ year: y,
43
+ month: m,
44
+ rate: r.round(8),
45
+ payment: pmt.round(2),
46
+ interest: interest.round(2),
47
+ principal_paid: principal_paid.round(2),
48
+ balance: balance.round(2)
49
+ )
50
+
51
+ break if balance <= 0.0
52
+ end
53
+
54
+ periods
55
+ end
56
+
57
+ private
58
+
59
+ def to_rate_fn(obj)
60
+ case obj
61
+ when Proc
62
+ obj
63
+ when Array
64
+ # yが配列長を超えたら最終年の利率を継続
65
+ ->(y) { obj[[y - 1, obj.length - 1].min] }
66
+ when Numeric
67
+ ->(_y) { obj }
68
+ else
69
+ raise ArgumentError, "rate_schedule must be Proc, Array, or Numeric"
70
+ end
71
+ end
72
+
73
+ def year_of(i)
74
+ @freq == :monthly ? ((i - 1) / 12 + 1) : i
75
+ end
76
+
77
+ def month_of(i)
78
+ @freq == :monthly ? (((i - 1) % 12) + 1) : 1
79
+ end
80
+
81
+ def period_rate(annual_percent)
82
+ annual = annual_percent.to_f / 100.0
83
+ @freq == :monthly ? (annual / 12.0) : annual
84
+ end
85
+
86
+ # 元利均等の期間支払額(r==0 にも対応)
87
+ def annuity_payment(balance, r, n)
88
+ return balance / n if r.zero?
89
+
90
+ balance * r / (1 - (1 + r)**(-n))
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CashflowSim
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "cashflow_sim/version"
4
+ require_relative "cashflow_sim/amortization"
5
+
6
+ module CashflowSim
7
+ class Error < StandardError; end
8
+ # Your code goes here...
9
+ end
@@ -0,0 +1,4 @@
1
+ module CashflowSim
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,56 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cashflow_sim
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - 篠原亮太
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Generate schedules with variable interest rates, CSV/JSON output, and
13
+ an extensible API.
14
+ email:
15
+ - your.email@example.com
16
+ executables:
17
+ - cashflow_sim
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - CODE_OF_CONDUCT.md
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - exe/cashflow_sim
27
+ - lib/cashflow_sim.rb
28
+ - lib/cashflow_sim/amortization.rb
29
+ - lib/cashflow_sim/version.rb
30
+ - sig/cashflow_sim.rbs
31
+ homepage: https://github.com/ryota1119/cashflow_sim
32
+ licenses:
33
+ - MIT
34
+ metadata:
35
+ allowed_push_host: https://rubygems.org
36
+ homepage_uri: https://github.com/ryota1119/cashflow_sim
37
+ source_code_uri: https://github.com/ryota1119/cashflow_sim
38
+ changelog_uri: https://github.com/ryota1119/cashflow_sim/blob/main/CHANGELOG.md
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: 3.1.0
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 3.7.1
54
+ specification_version: 4
55
+ summary: Simple amortization & cashflow simulator for loans/investments.
56
+ test_files: []