lifecycle-allocation 0.1.0__tar.gz

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.
Files changed (35) hide show
  1. lifecycle_allocation-0.1.0/LICENSE +21 -0
  2. lifecycle_allocation-0.1.0/PKG-INFO +203 -0
  3. lifecycle_allocation-0.1.0/README.md +162 -0
  4. lifecycle_allocation-0.1.0/lifecycle_allocation/__init__.py +34 -0
  5. lifecycle_allocation-0.1.0/lifecycle_allocation/cli/__init__.py +0 -0
  6. lifecycle_allocation-0.1.0/lifecycle_allocation/cli/main.py +141 -0
  7. lifecycle_allocation-0.1.0/lifecycle_allocation/core/__init__.py +0 -0
  8. lifecycle_allocation-0.1.0/lifecycle_allocation/core/allocation.py +131 -0
  9. lifecycle_allocation-0.1.0/lifecycle_allocation/core/discounting.py +21 -0
  10. lifecycle_allocation-0.1.0/lifecycle_allocation/core/explain.py +83 -0
  11. lifecycle_allocation-0.1.0/lifecycle_allocation/core/human_capital.py +69 -0
  12. lifecycle_allocation-0.1.0/lifecycle_allocation/core/income_models.py +76 -0
  13. lifecycle_allocation-0.1.0/lifecycle_allocation/core/models.py +160 -0
  14. lifecycle_allocation-0.1.0/lifecycle_allocation/core/mortality.py +19 -0
  15. lifecycle_allocation-0.1.0/lifecycle_allocation/core/strategies.py +88 -0
  16. lifecycle_allocation-0.1.0/lifecycle_allocation/io/__init__.py +0 -0
  17. lifecycle_allocation-0.1.0/lifecycle_allocation/io/loaders.py +97 -0
  18. lifecycle_allocation-0.1.0/lifecycle_allocation/viz/__init__.py +0 -0
  19. lifecycle_allocation-0.1.0/lifecycle_allocation/viz/charts.py +131 -0
  20. lifecycle_allocation-0.1.0/lifecycle_allocation/viz/themes.py +36 -0
  21. lifecycle_allocation-0.1.0/lifecycle_allocation.egg-info/PKG-INFO +203 -0
  22. lifecycle_allocation-0.1.0/lifecycle_allocation.egg-info/SOURCES.txt +33 -0
  23. lifecycle_allocation-0.1.0/lifecycle_allocation.egg-info/dependency_links.txt +1 -0
  24. lifecycle_allocation-0.1.0/lifecycle_allocation.egg-info/entry_points.txt +2 -0
  25. lifecycle_allocation-0.1.0/lifecycle_allocation.egg-info/requires.txt +18 -0
  26. lifecycle_allocation-0.1.0/lifecycle_allocation.egg-info/top_level.txt +1 -0
  27. lifecycle_allocation-0.1.0/pyproject.toml +80 -0
  28. lifecycle_allocation-0.1.0/setup.cfg +4 -0
  29. lifecycle_allocation-0.1.0/tests/test_allocation.py +173 -0
  30. lifecycle_allocation-0.1.0/tests/test_cli.py +125 -0
  31. lifecycle_allocation-0.1.0/tests/test_human_capital.py +221 -0
  32. lifecycle_allocation-0.1.0/tests/test_io.py +69 -0
  33. lifecycle_allocation-0.1.0/tests/test_models.py +135 -0
  34. lifecycle_allocation-0.1.0/tests/test_strategies.py +99 -0
  35. lifecycle_allocation-0.1.0/tests/test_viz_smoke.py +90 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Engineer Investor
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.4
2
+ Name: lifecycle-allocation
3
+ Version: 0.1.0
4
+ Summary: Lifecycle portfolio allocation framework inspired by Choi et al.
5
+ Author-email: Engineer Investor <egr.investor@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/engineerinvestor/lifecycle-allocation
8
+ Project-URL: Repository, https://github.com/engineerinvestor/lifecycle-allocation
9
+ Project-URL: Documentation, https://engineerinvestor.github.io/lifecycle-allocation
10
+ Project-URL: Issues, https://github.com/engineerinvestor/lifecycle-allocation/issues
11
+ Project-URL: Changelog, https://github.com/engineerinvestor/lifecycle-allocation/blob/main/CHANGELOG.md
12
+ Keywords: finance,portfolio,allocation,lifecycle,human-capital,investment
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Education
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Office/Business :: Financial
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: pandas>=2.0
26
+ Requires-Dist: matplotlib>=3.7
27
+ Requires-Dist: pyyaml>=6.0
28
+ Requires-Dist: click>=8.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
32
+ Requires-Dist: ruff>=0.1; extra == "dev"
33
+ Requires-Dist: black>=23.0; extra == "dev"
34
+ Requires-Dist: mypy>=1.0; extra == "dev"
35
+ Requires-Dist: types-PyYAML>=6.0; extra == "dev"
36
+ Requires-Dist: pandas-stubs>=2.0; extra == "dev"
37
+ Provides-Extra: docs
38
+ Requires-Dist: mkdocs>=1.5; extra == "docs"
39
+ Requires-Dist: mkdocs-material>=9.0; extra == "docs"
40
+ Dynamic: license-file
41
+
42
+ # lifecycle-allocation
43
+
44
+ A Python library implementing a practical lifecycle portfolio choice framework inspired by [Choi et al.](https://www.nber.org/papers/w34166) It combines human capital analysis with visual analytics to produce data-driven stock/bond allocation recommendations.
45
+
46
+ [![CI](https://github.com/engineerinvestor/lifecycle-allocation/actions/workflows/ci.yml/badge.svg)](https://github.com/engineerinvestor/lifecycle-allocation/actions/workflows/ci.yml)
47
+ [![PyPI](https://img.shields.io/pypi/v/lifecycle-allocation)](https://pypi.org/project/lifecycle-allocation/)
48
+ [![Python](https://img.shields.io/pypi/pyversions/lifecycle-allocation)](https://pypi.org/project/lifecycle-allocation/)
49
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
50
+ [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://engineerinvestor.github.io/lifecycle-allocation)
51
+
52
+ ## Why This Matters
53
+
54
+ Most portfolio allocation "rules" are single-variable heuristics: 60/40, 100-minus-age, target-date funds. They ignore the biggest asset most people own -- their future earning power. A 30-year-old software engineer with $100k in savings and 35 years of income ahead is in a fundamentally different position than a 30-year-old retiree with the same $100k.
55
+
56
+ This library takes a **balance-sheet** view of your finances. Your investable portfolio is only part of your total wealth. Future earnings (human capital) act like a bond-like asset, and accounting for them changes how much stock risk you should take. The result is a theoretically grounded, personalized allocation that evolves naturally over your lifecycle -- no arbitrary rules required.
57
+
58
+ ## Features
59
+
60
+ - **Core allocation engine** -- Merton-style optimal risky share adjusted for human capital
61
+ - **4 income models** -- flat, constant-growth, age-profile, and CSV-based
62
+ - **Strategy comparison** -- benchmark against 60/40, 100-minus-age, and target-date funds
63
+ - **Visualization suite** -- balance sheet waterfall, glide paths, sensitivity tornado, heatmaps
64
+ - **CLI interface** -- generate full reports from YAML/JSON profiles
65
+ - **YAML/JSON profiles** -- declarative investor configuration
66
+ - **Leverage support** -- two-tier borrowing rate model with configurable constraints
67
+ - **Mortality adjustment** -- survival probability discounting for human capital
68
+
69
+ ## Install
70
+
71
+ ```bash
72
+ pip install lifecycle-allocation
73
+ ```
74
+
75
+ For development:
76
+
77
+ ```bash
78
+ git clone https://github.com/engineerinvestor/lifecycle-allocation.git
79
+ cd lifecycle-allocation
80
+ pip install -e ".[dev]"
81
+ ```
82
+
83
+ Requires Python 3.10+.
84
+
85
+ ## Quick Start (Python)
86
+
87
+ ```python
88
+ from lifecycle_allocation import (
89
+ InvestorProfile,
90
+ MarketAssumptions,
91
+ recommended_stock_share,
92
+ compare_strategies,
93
+ )
94
+
95
+ profile = InvestorProfile(
96
+ age=30,
97
+ retirement_age=67,
98
+ investable_wealth=100_000,
99
+ after_tax_income=70_000,
100
+ risk_tolerance=5,
101
+ )
102
+ market = MarketAssumptions(mu=0.05, r=0.02, sigma=0.18)
103
+
104
+ result = recommended_stock_share(profile, market)
105
+ print(f"Recommended stock allocation: {result.alpha_recommended:.1%}")
106
+ print(f"Human capital: ${result.human_capital:,.0f}")
107
+ print(result.explain)
108
+
109
+ # Compare against heuristic strategies
110
+ df = compare_strategies(profile, market)
111
+ print(df.to_string(index=False))
112
+ ```
113
+
114
+ ## Quick Start (CLI)
115
+
116
+ ```bash
117
+ lifecycle-allocation alloc \
118
+ --profile examples/profiles/young_saver.yaml \
119
+ --out ./output \
120
+ --report
121
+ ```
122
+
123
+ This produces `allocation.json`, `summary.md`, and charts in `output/charts/`.
124
+
125
+ ## How It Works
126
+
127
+ 1. Compute a **baseline risky share** (Merton-style): `alpha* = (mu - r) / (gamma * sigma^2)`
128
+ 2. Estimate **human capital** H as the present value of future earnings + retirement benefits, discounted by survival probability and a term structure
129
+ 3. Adjust: `alpha = alpha* x (1 + H/W)`, clamped to [0, 1] (or [0, L_max] with leverage)
130
+
131
+ Young workers with high H/W ratios get higher equity allocations. As you age and accumulate financial wealth, H shrinks relative to W and the allocation naturally declines -- producing a lifecycle glide path from first principles rather than arbitrary rules.
132
+
133
+ ## Example Output
134
+
135
+ | Archetype | Age | Income | Wealth | H/W Ratio | Recommended Equity |
136
+ |---|---|---|---|---|---|
137
+ | Young saver | 30 | $70k | $100k | ~15x | ~90%+ |
138
+ | Mid-career | 45 | $120k | $500k | ~4x | ~65% |
139
+ | Near-retirement | 60 | $90k | $1.2M | ~0.5x | ~40% |
140
+
141
+ *Values depend on market assumptions and risk tolerance. These are illustrative.*
142
+
143
+ ## Tutorial
144
+
145
+ Explore the interactive tutorial notebook for a guided walkthrough:
146
+
147
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/engineerinvestor/lifecycle-allocation/blob/main/examples/notebooks/tutorial.ipynb)
148
+
149
+ Or run locally:
150
+
151
+ ```bash
152
+ jupyter notebook examples/notebooks/tutorial.ipynb
153
+ ```
154
+
155
+ ## Documentation
156
+
157
+ Full documentation is available at [engineerinvestor.github.io/lifecycle-allocation](https://engineerinvestor.github.io/lifecycle-allocation).
158
+
159
+ ## Roadmap
160
+
161
+ | Version | Milestone |
162
+ |---|---|
163
+ | **v0.1** | Core allocation engine, CLI, YAML profiles, strategy comparison, charts |
164
+ | **v0.5** | Monte Carlo simulation, CRRA utility evaluation, Social Security modeling |
165
+ | **v1.0** | Full documentation, tax-aware optimization, couples modeling |
166
+
167
+ ## Contributing
168
+
169
+ Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, code style, and PR guidelines.
170
+
171
+ ## Citation
172
+
173
+ If you use this library in academic work, please cite both the underlying research and the software:
174
+
175
+ ```bibtex
176
+ @techreport{choi2025practical,
177
+ title={Practical Finance: An Approximate Solution to Lifecycle Portfolio Choice},
178
+ author={Choi, James J. and Liu, Canyao and Liu, Pengcheng},
179
+ year={2025},
180
+ institution={National Bureau of Economic Research},
181
+ type={Working Paper},
182
+ number={34166},
183
+ doi={10.3386/w34166},
184
+ url={https://www.nber.org/papers/w34166}
185
+ }
186
+
187
+ @software{engineerinvestor2025lifecycle,
188
+ title={lifecycle-allocation: A Lifecycle Portfolio Choice Framework},
189
+ author={{Engineer Investor}},
190
+ year={2025},
191
+ url={https://github.com/engineerinvestor/lifecycle-allocation},
192
+ version={0.1.0},
193
+ license={MIT}
194
+ }
195
+ ```
196
+
197
+ ## Disclaimer
198
+
199
+ **This library is for education and research purposes only. It is not investment advice.** The authors are not financial advisors. Consult a qualified professional before making investment decisions. Past performance and model outputs do not guarantee future results.
200
+
201
+ ## License
202
+
203
+ [MIT](LICENSE)
@@ -0,0 +1,162 @@
1
+ # lifecycle-allocation
2
+
3
+ A Python library implementing a practical lifecycle portfolio choice framework inspired by [Choi et al.](https://www.nber.org/papers/w34166) It combines human capital analysis with visual analytics to produce data-driven stock/bond allocation recommendations.
4
+
5
+ [![CI](https://github.com/engineerinvestor/lifecycle-allocation/actions/workflows/ci.yml/badge.svg)](https://github.com/engineerinvestor/lifecycle-allocation/actions/workflows/ci.yml)
6
+ [![PyPI](https://img.shields.io/pypi/v/lifecycle-allocation)](https://pypi.org/project/lifecycle-allocation/)
7
+ [![Python](https://img.shields.io/pypi/pyversions/lifecycle-allocation)](https://pypi.org/project/lifecycle-allocation/)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
9
+ [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://engineerinvestor.github.io/lifecycle-allocation)
10
+
11
+ ## Why This Matters
12
+
13
+ Most portfolio allocation "rules" are single-variable heuristics: 60/40, 100-minus-age, target-date funds. They ignore the biggest asset most people own -- their future earning power. A 30-year-old software engineer with $100k in savings and 35 years of income ahead is in a fundamentally different position than a 30-year-old retiree with the same $100k.
14
+
15
+ This library takes a **balance-sheet** view of your finances. Your investable portfolio is only part of your total wealth. Future earnings (human capital) act like a bond-like asset, and accounting for them changes how much stock risk you should take. The result is a theoretically grounded, personalized allocation that evolves naturally over your lifecycle -- no arbitrary rules required.
16
+
17
+ ## Features
18
+
19
+ - **Core allocation engine** -- Merton-style optimal risky share adjusted for human capital
20
+ - **4 income models** -- flat, constant-growth, age-profile, and CSV-based
21
+ - **Strategy comparison** -- benchmark against 60/40, 100-minus-age, and target-date funds
22
+ - **Visualization suite** -- balance sheet waterfall, glide paths, sensitivity tornado, heatmaps
23
+ - **CLI interface** -- generate full reports from YAML/JSON profiles
24
+ - **YAML/JSON profiles** -- declarative investor configuration
25
+ - **Leverage support** -- two-tier borrowing rate model with configurable constraints
26
+ - **Mortality adjustment** -- survival probability discounting for human capital
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install lifecycle-allocation
32
+ ```
33
+
34
+ For development:
35
+
36
+ ```bash
37
+ git clone https://github.com/engineerinvestor/lifecycle-allocation.git
38
+ cd lifecycle-allocation
39
+ pip install -e ".[dev]"
40
+ ```
41
+
42
+ Requires Python 3.10+.
43
+
44
+ ## Quick Start (Python)
45
+
46
+ ```python
47
+ from lifecycle_allocation import (
48
+ InvestorProfile,
49
+ MarketAssumptions,
50
+ recommended_stock_share,
51
+ compare_strategies,
52
+ )
53
+
54
+ profile = InvestorProfile(
55
+ age=30,
56
+ retirement_age=67,
57
+ investable_wealth=100_000,
58
+ after_tax_income=70_000,
59
+ risk_tolerance=5,
60
+ )
61
+ market = MarketAssumptions(mu=0.05, r=0.02, sigma=0.18)
62
+
63
+ result = recommended_stock_share(profile, market)
64
+ print(f"Recommended stock allocation: {result.alpha_recommended:.1%}")
65
+ print(f"Human capital: ${result.human_capital:,.0f}")
66
+ print(result.explain)
67
+
68
+ # Compare against heuristic strategies
69
+ df = compare_strategies(profile, market)
70
+ print(df.to_string(index=False))
71
+ ```
72
+
73
+ ## Quick Start (CLI)
74
+
75
+ ```bash
76
+ lifecycle-allocation alloc \
77
+ --profile examples/profiles/young_saver.yaml \
78
+ --out ./output \
79
+ --report
80
+ ```
81
+
82
+ This produces `allocation.json`, `summary.md`, and charts in `output/charts/`.
83
+
84
+ ## How It Works
85
+
86
+ 1. Compute a **baseline risky share** (Merton-style): `alpha* = (mu - r) / (gamma * sigma^2)`
87
+ 2. Estimate **human capital** H as the present value of future earnings + retirement benefits, discounted by survival probability and a term structure
88
+ 3. Adjust: `alpha = alpha* x (1 + H/W)`, clamped to [0, 1] (or [0, L_max] with leverage)
89
+
90
+ Young workers with high H/W ratios get higher equity allocations. As you age and accumulate financial wealth, H shrinks relative to W and the allocation naturally declines -- producing a lifecycle glide path from first principles rather than arbitrary rules.
91
+
92
+ ## Example Output
93
+
94
+ | Archetype | Age | Income | Wealth | H/W Ratio | Recommended Equity |
95
+ |---|---|---|---|---|---|
96
+ | Young saver | 30 | $70k | $100k | ~15x | ~90%+ |
97
+ | Mid-career | 45 | $120k | $500k | ~4x | ~65% |
98
+ | Near-retirement | 60 | $90k | $1.2M | ~0.5x | ~40% |
99
+
100
+ *Values depend on market assumptions and risk tolerance. These are illustrative.*
101
+
102
+ ## Tutorial
103
+
104
+ Explore the interactive tutorial notebook for a guided walkthrough:
105
+
106
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/engineerinvestor/lifecycle-allocation/blob/main/examples/notebooks/tutorial.ipynb)
107
+
108
+ Or run locally:
109
+
110
+ ```bash
111
+ jupyter notebook examples/notebooks/tutorial.ipynb
112
+ ```
113
+
114
+ ## Documentation
115
+
116
+ Full documentation is available at [engineerinvestor.github.io/lifecycle-allocation](https://engineerinvestor.github.io/lifecycle-allocation).
117
+
118
+ ## Roadmap
119
+
120
+ | Version | Milestone |
121
+ |---|---|
122
+ | **v0.1** | Core allocation engine, CLI, YAML profiles, strategy comparison, charts |
123
+ | **v0.5** | Monte Carlo simulation, CRRA utility evaluation, Social Security modeling |
124
+ | **v1.0** | Full documentation, tax-aware optimization, couples modeling |
125
+
126
+ ## Contributing
127
+
128
+ Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, code style, and PR guidelines.
129
+
130
+ ## Citation
131
+
132
+ If you use this library in academic work, please cite both the underlying research and the software:
133
+
134
+ ```bibtex
135
+ @techreport{choi2025practical,
136
+ title={Practical Finance: An Approximate Solution to Lifecycle Portfolio Choice},
137
+ author={Choi, James J. and Liu, Canyao and Liu, Pengcheng},
138
+ year={2025},
139
+ institution={National Bureau of Economic Research},
140
+ type={Working Paper},
141
+ number={34166},
142
+ doi={10.3386/w34166},
143
+ url={https://www.nber.org/papers/w34166}
144
+ }
145
+
146
+ @software{engineerinvestor2025lifecycle,
147
+ title={lifecycle-allocation: A Lifecycle Portfolio Choice Framework},
148
+ author={{Engineer Investor}},
149
+ year={2025},
150
+ url={https://github.com/engineerinvestor/lifecycle-allocation},
151
+ version={0.1.0},
152
+ license={MIT}
153
+ }
154
+ ```
155
+
156
+ ## Disclaimer
157
+
158
+ **This library is for education and research purposes only. It is not investment advice.** The authors are not financial advisors. Consult a qualified professional before making investment decisions. Past performance and model outputs do not guarantee future results.
159
+
160
+ ## License
161
+
162
+ [MIT](LICENSE)
@@ -0,0 +1,34 @@
1
+ """Lifecycle portfolio allocation framework inspired by Choi et al."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from lifecycle_allocation.core.allocation import alpha_star, recommended_stock_share
6
+ from lifecycle_allocation.core.human_capital import human_capital_pv
7
+ from lifecycle_allocation.core.models import (
8
+ AllocationResult,
9
+ BenefitModelSpec,
10
+ ConstraintsSpec,
11
+ DiscountCurveSpec,
12
+ IncomeModelSpec,
13
+ InvestorProfile,
14
+ MarketAssumptions,
15
+ MortalitySpec,
16
+ risk_tolerance_to_gamma,
17
+ )
18
+ from lifecycle_allocation.core.strategies import compare_strategies
19
+
20
+ __all__ = [
21
+ "AllocationResult",
22
+ "BenefitModelSpec",
23
+ "ConstraintsSpec",
24
+ "DiscountCurveSpec",
25
+ "IncomeModelSpec",
26
+ "InvestorProfile",
27
+ "MarketAssumptions",
28
+ "MortalitySpec",
29
+ "alpha_star",
30
+ "compare_strategies",
31
+ "human_capital_pv",
32
+ "recommended_stock_share",
33
+ "risk_tolerance_to_gamma",
34
+ ]
@@ -0,0 +1,141 @@
1
+ """CLI entry point for lifecycle-allocation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import click
9
+
10
+ from lifecycle_allocation.core.allocation import recommended_stock_share
11
+ from lifecycle_allocation.core.models import ConstraintsSpec, MarketAssumptions
12
+ from lifecycle_allocation.core.strategies import compare_strategies
13
+ from lifecycle_allocation.io.loaders import load_profile
14
+ from lifecycle_allocation.viz.charts import plot_balance_sheet, plot_strategy_bars
15
+
16
+
17
+ @click.group()
18
+ def cli() -> None:
19
+ """lifecycle-allocation: Lifecycle portfolio allocation framework."""
20
+
21
+
22
+ @cli.command()
23
+ @click.option("--profile", "profile_path", required=True, type=click.Path(exists=True))
24
+ @click.option("--out", "out_dir", required=True, type=click.Path())
25
+ @click.option("--report", is_flag=True, default=False, help="Generate charts")
26
+ @click.option("--mu", type=float, default=None, help="Expected stock return")
27
+ @click.option("--r", "risk_free", type=float, default=None, help="Risk-free rate")
28
+ @click.option("--sigma", type=float, default=None, help="Stock volatility")
29
+ @click.option("--tmax", type=int, default=100, help="Maximum age for computation")
30
+ @click.option("--allow-leverage", is_flag=True, default=False)
31
+ @click.option("--max-leverage", type=float, default=1.0)
32
+ @click.option("--borrowing-spread", type=float, default=None)
33
+ @click.option("--format", "img_format", type=click.Choice(["png", "svg"]), default="png")
34
+ @click.option("--real/--nominal", default=True)
35
+ def alloc(
36
+ profile_path: str,
37
+ out_dir: str,
38
+ report: bool,
39
+ mu: float | None,
40
+ risk_free: float | None,
41
+ sigma: float | None,
42
+ tmax: int,
43
+ allow_leverage: bool,
44
+ max_leverage: float,
45
+ borrowing_spread: float | None,
46
+ img_format: str,
47
+ real: bool,
48
+ ) -> None:
49
+ """Compute lifecycle allocation from a profile."""
50
+ profile, market, curve, constraints = load_profile(profile_path)
51
+
52
+ # CLI overrides
53
+ if mu is not None:
54
+ market = MarketAssumptions(
55
+ mu=mu,
56
+ r=market.r,
57
+ sigma=market.sigma,
58
+ real=market.real,
59
+ borrowing_spread=market.borrowing_spread,
60
+ )
61
+ if risk_free is not None:
62
+ market = MarketAssumptions(
63
+ mu=market.mu,
64
+ r=risk_free,
65
+ sigma=market.sigma,
66
+ real=market.real,
67
+ borrowing_spread=market.borrowing_spread,
68
+ )
69
+ if sigma is not None:
70
+ market = MarketAssumptions(
71
+ mu=market.mu,
72
+ r=market.r,
73
+ sigma=sigma,
74
+ real=market.real,
75
+ borrowing_spread=market.borrowing_spread,
76
+ )
77
+ if borrowing_spread is not None:
78
+ market = MarketAssumptions(
79
+ mu=market.mu,
80
+ r=market.r,
81
+ sigma=market.sigma,
82
+ real=market.real,
83
+ borrowing_spread=borrowing_spread,
84
+ )
85
+ market = MarketAssumptions(
86
+ mu=market.mu,
87
+ r=market.r,
88
+ sigma=market.sigma,
89
+ real=real,
90
+ borrowing_spread=market.borrowing_spread,
91
+ )
92
+
93
+ if allow_leverage or constraints.allow_leverage:
94
+ constraints = ConstraintsSpec(
95
+ allow_leverage=True,
96
+ max_leverage=max_leverage if max_leverage > 1.0 else constraints.max_leverage,
97
+ allow_short=constraints.allow_short,
98
+ min_allocation=constraints.min_allocation,
99
+ )
100
+
101
+ # Compute
102
+ result = recommended_stock_share(profile, market, curve, constraints, t_max=tmax)
103
+ comparison_df = compare_strategies(profile, market, curve, constraints)
104
+
105
+ # Create output directory
106
+ out = Path(out_dir)
107
+ out.mkdir(parents=True, exist_ok=True)
108
+
109
+ # Write allocation.json
110
+ alloc_data = {
111
+ "alpha_star": result.alpha_star,
112
+ "alpha_unconstrained": result.alpha_unconstrained,
113
+ "alpha_recommended": result.alpha_recommended,
114
+ "human_capital": result.human_capital,
115
+ "leverage_applied": result.leverage_applied,
116
+ "borrowing_cost_drag": result.borrowing_cost_drag,
117
+ "components": {
118
+ k: v for k, v in result.components.items() if isinstance(v, (int, float, bool, str))
119
+ },
120
+ }
121
+ with open(out / "allocation.json", "w") as f:
122
+ json.dump(alloc_data, f, indent=2)
123
+
124
+ # Write summary.md
125
+ with open(out / "summary.md", "w") as f:
126
+ f.write("# Lifecycle Allocation Summary\n\n")
127
+ f.write(result.explain)
128
+ f.write("\n\n## Strategy Comparison\n\n")
129
+ f.write("| Strategy | Allocation |\n|---|---|\n")
130
+ for _, row in comparison_df.iterrows():
131
+ f.write(f"| {row['strategy']} | {row['allocation']:.1%} |\n")
132
+
133
+ click.echo(f"Recommended stock allocation: {result.alpha_recommended:.1%}")
134
+ click.echo(f"Results written to {out}")
135
+
136
+ if report:
137
+ charts_dir = out / "charts"
138
+ charts_dir.mkdir(exist_ok=True)
139
+ plot_balance_sheet(result, profile, save_path=charts_dir / f"balance_sheet.{img_format}")
140
+ plot_strategy_bars(comparison_df, save_path=charts_dir / f"strategy_bars.{img_format}")
141
+ click.echo(f"Charts written to {charts_dir}")