ml4t-models 0.1.0a0__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 (68) hide show
  1. ml4t_models-0.1.0a0/.gitignore +21 -0
  2. ml4t_models-0.1.0a0/CHANGELOG.md +17 -0
  3. ml4t_models-0.1.0a0/LICENSE +21 -0
  4. ml4t_models-0.1.0a0/PKG-INFO +265 -0
  5. ml4t_models-0.1.0a0/README.md +206 -0
  6. ml4t_models-0.1.0a0/pyproject.toml +165 -0
  7. ml4t_models-0.1.0a0/src/ml4t/models/__init__.py +198 -0
  8. ml4t_models-0.1.0a0/src/ml4t/models/_internal/cae_nn.py +75 -0
  9. ml4t_models-0.1.0a0/src/ml4t/models/_internal/latent_factor_utils.py +197 -0
  10. ml4t_models-0.1.0a0/src/ml4t/models/_internal/sae_nn.py +122 -0
  11. ml4t_models-0.1.0a0/src/ml4t/models/_internal/stochastic_discount_factor_nn.py +272 -0
  12. ml4t_models-0.1.0a0/src/ml4t/models/_internal/torch_runtime.py +27 -0
  13. ml4t_models-0.1.0a0/src/ml4t/models/api.py +120 -0
  14. ml4t_models-0.1.0a0/src/ml4t/models/asset_prediction/__init__.py +9 -0
  15. ml4t_models-0.1.0a0/src/ml4t/models/asset_prediction/base.py +45 -0
  16. ml4t_models-0.1.0a0/src/ml4t/models/asset_prediction/sae.py +325 -0
  17. ml4t_models-0.1.0a0/src/ml4t/models/configs/__init__.py +45 -0
  18. ml4t_models-0.1.0a0/src/ml4t/models/configs/asset_prediction.py +35 -0
  19. ml4t_models-0.1.0a0/src/ml4t/models/configs/base.py +14 -0
  20. ml4t_models-0.1.0a0/src/ml4t/models/configs/forecast.py +29 -0
  21. ml4t_models-0.1.0a0/src/ml4t/models/configs/latent_factor.py +94 -0
  22. ml4t_models-0.1.0a0/src/ml4t/models/configs/pipeline.py +21 -0
  23. ml4t_models-0.1.0a0/src/ml4t/models/configs/portfolio.py +81 -0
  24. ml4t_models-0.1.0a0/src/ml4t/models/forecasters/__init__.py +13 -0
  25. ml4t_models-0.1.0a0/src/ml4t/models/forecasters/ar.py +83 -0
  26. ml4t_models-0.1.0a0/src/ml4t/models/forecasters/base.py +31 -0
  27. ml4t_models-0.1.0a0/src/ml4t/models/forecasters/ewma.py +52 -0
  28. ml4t_models-0.1.0a0/src/ml4t/models/forecasters/mean.py +46 -0
  29. ml4t_models-0.1.0a0/src/ml4t/models/integration/__init__.py +57 -0
  30. ml4t_models-0.1.0a0/src/ml4t/models/integration/backtest.py +544 -0
  31. ml4t_models-0.1.0a0/src/ml4t/models/integration/data.py +328 -0
  32. ml4t_models-0.1.0a0/src/ml4t/models/integration/surfaces.py +407 -0
  33. ml4t_models-0.1.0a0/src/ml4t/models/latent_factors/__init__.py +15 -0
  34. ml4t_models-0.1.0a0/src/ml4t/models/latent_factors/base.py +41 -0
  35. ml4t_models-0.1.0a0/src/ml4t/models/latent_factors/cae.py +361 -0
  36. ml4t_models-0.1.0a0/src/ml4t/models/latent_factors/ipca.py +315 -0
  37. ml4t_models-0.1.0a0/src/ml4t/models/latent_factors/pca.py +93 -0
  38. ml4t_models-0.1.0a0/src/ml4t/models/latent_factors/rp_pca.py +224 -0
  39. ml4t_models-0.1.0a0/src/ml4t/models/mappers/__init__.py +9 -0
  40. ml4t_models-0.1.0a0/src/ml4t/models/mappers/base.py +23 -0
  41. ml4t_models-0.1.0a0/src/ml4t/models/mappers/beta_lambda.py +35 -0
  42. ml4t_models-0.1.0a0/src/ml4t/models/pipelines.py +110 -0
  43. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/__init__.py +41 -0
  44. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/base.py +45 -0
  45. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/components.py +254 -0
  46. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/deep_portfolio.py +285 -0
  47. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/linear.py +128 -0
  48. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/losses.py +130 -0
  49. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/lstm.py +241 -0
  50. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/postprocessors.py +123 -0
  51. ml4t_models-0.1.0a0/src/ml4t/models/portfolio/runtime.py +266 -0
  52. ml4t_models-0.1.0a0/src/ml4t/models/stochastic_discount_factor/__init__.py +15 -0
  53. ml4t_models-0.1.0a0/src/ml4t/models/stochastic_discount_factor/base.py +40 -0
  54. ml4t_models-0.1.0a0/src/ml4t/models/stochastic_discount_factor/mapper.py +361 -0
  55. ml4t_models-0.1.0a0/src/ml4t/models/stochastic_discount_factor/model.py +365 -0
  56. ml4t_models-0.1.0a0/src/ml4t/models/types.py +422 -0
  57. ml4t_models-0.1.0a0/tests/test_cae.py +66 -0
  58. ml4t_models-0.1.0a0/tests/test_forecasters.py +55 -0
  59. ml4t_models-0.1.0a0/tests/test_integration_backtest.py +204 -0
  60. ml4t_models-0.1.0a0/tests/test_integration_data.py +82 -0
  61. ml4t_models-0.1.0a0/tests/test_integration_surfaces.py +173 -0
  62. ml4t_models-0.1.0a0/tests/test_ipca.py +81 -0
  63. ml4t_models-0.1.0a0/tests/test_pca_pipeline.py +66 -0
  64. ml4t_models-0.1.0a0/tests/test_portfolio.py +234 -0
  65. ml4t_models-0.1.0a0/tests/test_rp_pca.py +63 -0
  66. ml4t_models-0.1.0a0/tests/test_sae.py +94 -0
  67. ml4t_models-0.1.0a0/tests/test_stochastic_discount_factor.py +143 -0
  68. ml4t_models-0.1.0a0/tests/test_types.py +50 -0
@@ -0,0 +1,21 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .coverage
7
+ htmlcov/
8
+ dist/
9
+ build/
10
+ site/
11
+ .venv/
12
+ .venv-*/
13
+ venv/
14
+ ENV/
15
+ .idea/
16
+ .vscode/
17
+ .hypothesis/
18
+ src/ml4t/models/_version.py
19
+
20
+ CLAUDE.md
21
+ .claude/
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ All notable changes to `ml4t-models` will be documented in this file.
4
+
5
+ ## 0.1.0a0
6
+
7
+ - Added finance-native data contracts for persistent panels, ragged cross-sections, and
8
+ portfolio sequences.
9
+ - Added latent-factor model families: `PCA`, `RP-PCA`, `IPCA`, and `CAE`.
10
+ - Added direct asset prediction with `SAEModel`.
11
+ - Added weight-native stochastic discount factor modeling with
12
+ `StochasticDiscountFactorModel`.
13
+ - Added portfolio learning baselines and deep models.
14
+ - Added factor forecasters, asset mappers, and composable modeling pipelines.
15
+ - Added integration adapters for ML4T data schemas, backtest handoff, and prediction or weight
16
+ surfaces.
17
+ - Added user guide, architecture documentation, and API reference with MkDocs.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stefan Jansen
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,265 @@
1
+ Metadata-Version: 2.4
2
+ Name: ml4t-models
3
+ Version: 0.1.0a0
4
+ Summary: Finance-specific latent-factor and portfolio-learning models for ML4T
5
+ Project-URL: Homepage, https://ml4trading.io/docs/models/
6
+ Project-URL: Documentation, https://ml4trading.io/docs/models/
7
+ Project-URL: Repository, https://github.com/ml4t/models
8
+ Project-URL: Issues, https://github.com/ml4t/models/issues
9
+ Project-URL: Changelog, https://github.com/ml4t/models/blob/main/CHANGELOG.md
10
+ Author-email: Stefan Jansen <stefan@ml4trading.io>
11
+ Maintainer-email: Stefan Jansen <stefan@ml4trading.io>
12
+ License: MIT
13
+ License-File: LICENSE
14
+ Keywords: algorithmic-trading,deep-learning,finance,latent-factors,machine-learning,portfolio-learning,quantitative-finance
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Financial and Insurance Industry
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: License :: OSI Approved :: MIT License
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Office/Business :: Financial :: Investment
25
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
26
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: <3.14,>=3.12
29
+ Requires-Dist: numpy<2.3,>=1.26
30
+ Provides-Extra: all
31
+ Requires-Dist: mkdocs-material>=9.5.0; extra == 'all'
32
+ Requires-Dist: mkdocs<2,>=1.6; extra == 'all'
33
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'all'
34
+ Requires-Dist: ml4t-specs>=0.1.0b0; extra == 'all'
35
+ Requires-Dist: polars>=1.0.0; extra == 'all'
36
+ Requires-Dist: pre-commit>=3.3.0; extra == 'all'
37
+ Requires-Dist: pytest-cov>=5.0.0; extra == 'all'
38
+ Requires-Dist: pytest>=8.0.0; extra == 'all'
39
+ Requires-Dist: ruff>=0.8.0; extra == 'all'
40
+ Requires-Dist: torch>=2.4; extra == 'all'
41
+ Requires-Dist: ty; extra == 'all'
42
+ Provides-Extra: deep
43
+ Requires-Dist: torch>=2.4; extra == 'deep'
44
+ Provides-Extra: dev
45
+ Requires-Dist: pre-commit>=3.3.0; extra == 'dev'
46
+ Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
47
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
48
+ Requires-Dist: ruff>=0.8.0; extra == 'dev'
49
+ Requires-Dist: torch>=2.4; extra == 'dev'
50
+ Requires-Dist: ty; extra == 'dev'
51
+ Provides-Extra: docs
52
+ Requires-Dist: mkdocs-material>=9.5.0; extra == 'docs'
53
+ Requires-Dist: mkdocs<2,>=1.6; extra == 'docs'
54
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'docs'
55
+ Provides-Extra: integration
56
+ Requires-Dist: ml4t-specs>=0.1.0b0; extra == 'integration'
57
+ Requires-Dist: polars>=1.0.0; extra == 'integration'
58
+ Description-Content-Type: text/markdown
59
+
60
+ # ml4t-models
61
+
62
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
63
+ [![PyPI](https://img.shields.io/pypi/v/ml4t-models)](https://pypi.org/project/ml4t-models/)
64
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
65
+
66
+ Finance-native model implementations for latent-factor estimation, stochastic discount factor learning, direct asset prediction, and end-to-end portfolio learning.
67
+
68
+ Documentation: https://ml4trading.io/docs/models/
69
+
70
+ ## Part of the ML4T Library Ecosystem
71
+
72
+ This library is one of six interconnected ML4T libraries supporting the research and production workflow described in [Machine Learning for Trading](https://ml4trading.io).
73
+
74
+ ![ML4T Library Ecosystem](docs/images/ml4t_ecosystem_workflow_color.png)
75
+
76
+ ## What This Library Does
77
+
78
+ `ml4t-models` packages paper-faithful model families that are common in modern empirical asset pricing and portfolio learning:
79
+
80
+ - Latent-factor estimators with explicit structural outputs:
81
+ - `PCAModel`
82
+ - `RPPCAModel`
83
+ - `IPCAModel`
84
+ - `CAEModel`
85
+ - Weight-native stochastic discount factor modeling:
86
+ - `StochasticDiscountFactorModel`
87
+ - Direct asset prediction:
88
+ - `SAEModel` (`SAE` = supervised autoencoder)
89
+ - End-to-end portfolio learning:
90
+ - `LinearFeaturePortfolioModel`
91
+ - `LSTMPortfolioModel`
92
+ - `DeepPortfolioModel`
93
+
94
+ The library is built around finance-native contracts rather than generic tensor trainers:
95
+
96
+ - `PersistentPanelBatch` for stable-ID panels
97
+ - `CrossSectionBatch` for ragged dated cross-sections
98
+ - `PortfolioSequenceBatch` for sequence-to-allocation models
99
+
100
+ It also keeps the predictive steps explicit:
101
+
102
+ - structural extraction
103
+ - factor-premium forecasting
104
+ - asset mapping
105
+ - downstream prediction and weight frames for `ml4t-backtest` and `ml4t-diagnostic`
106
+
107
+ ![ml4t-models Architecture](docs/images/ml4t_models_architecture.svg)
108
+
109
+ ## Installation
110
+
111
+ ```bash
112
+ pip install ml4t-models
113
+ ```
114
+
115
+ Optional extras:
116
+
117
+ ```bash
118
+ pip install ml4t-models[deep] # torch-backed neural models
119
+ pip install ml4t-models[integration] # polars + ml4t-specs bridges
120
+ pip install ml4t-models[docs] # mkdocs site build
121
+ pip install ml4t-models[all]
122
+ ```
123
+
124
+ ## Quick Start
125
+
126
+ ### 1. Latent-Factor Forecast Pipeline
127
+
128
+ ```python
129
+ import numpy as np
130
+
131
+ from ml4t.models import (
132
+ BetaLambdaMapper,
133
+ CrossSectionBatch,
134
+ ExpandingMeanFactorForecaster,
135
+ IPCAConfig,
136
+ IPCAModel,
137
+ LatentFactorForecastPipeline,
138
+ )
139
+
140
+ batch = CrossSectionBatch(
141
+ characteristics=np.random.randn(24, 200, 12),
142
+ returns=np.random.randn(24, 200),
143
+ timestamps=tuple(range(24)),
144
+ )
145
+
146
+ pipeline = LatentFactorForecastPipeline(
147
+ model=IPCAModel(IPCAConfig(n_factors=3)),
148
+ forecaster=ExpandingMeanFactorForecaster(),
149
+ mapper=BetaLambdaMapper(),
150
+ )
151
+ pipeline.fit(batch)
152
+ prediction = pipeline.predict(batch)
153
+
154
+ print(prediction.asset_forecast.expected_returns.shape)
155
+ # (24, 200)
156
+ ```
157
+
158
+ ### 2. Weight-Native Stochastic Discount Factor
159
+
160
+ ```python
161
+ import numpy as np
162
+
163
+ from ml4t.models import CrossSectionBatch, StochasticDiscountFactorConfig, StochasticDiscountFactorModel
164
+
165
+ batch = CrossSectionBatch(
166
+ characteristics=np.random.randn(36, 300, 16),
167
+ returns=np.random.randn(36, 300),
168
+ context_features=np.random.randn(36, 8),
169
+ timestamps=tuple(range(36)),
170
+ )
171
+
172
+ model = StochasticDiscountFactorModel(
173
+ StochasticDiscountFactorConfig(checkpoint_epochs=(256, 512, 768, 1024, 1280))
174
+ )
175
+ model.fit(batch)
176
+ state = model.extract(batch, checkpoint=1280)
177
+
178
+ print(state.asset_weights.shape)
179
+ # (36, 300)
180
+ ```
181
+
182
+ ### 3. End-to-End Portfolio Learning
183
+
184
+ ```python
185
+ import numpy as np
186
+
187
+ from ml4t.models import LSTMPortfolioConfig, LSTMPortfolioModel, PortfolioSequenceBatch
188
+
189
+ batch = PortfolioSequenceBatch(
190
+ features=np.random.randn(8, 63, 20, 10),
191
+ returns=np.random.randn(8, 63, 20),
192
+ timestamps=tuple(range(63)),
193
+ asset_ids=tuple(f"asset_{i}" for i in range(20)),
194
+ )
195
+
196
+ model = LSTMPortfolioModel(LSTMPortfolioConfig(max_iters=20, checkpoint_every=5))
197
+ model.fit(batch)
198
+ weights = model.predict(batch, checkpoint=20)
199
+
200
+ print(weights.weights.shape)
201
+ # (8, 63, 20)
202
+ ```
203
+
204
+ ### 4. Hand Off Predictions To The Rest Of ML4T
205
+
206
+ ```python
207
+ from ml4t.models import predictions_frame_from_asset_forecast, write_backtest_frames
208
+
209
+ frame = predictions_frame_from_asset_forecast(prediction.asset_forecast)
210
+ write_backtest_frames("artifacts/run_001", predictions=frame)
211
+ ```
212
+
213
+ ## Model Families
214
+
215
+ ### Latent Factors
216
+
217
+ These models estimate a structural representation first, then let a separate forecaster produce ex ante factor premia.
218
+
219
+ | Model | Contract | Native output | Predictive step |
220
+ |---|---|---|---|
221
+ | `PCAModel` | `PersistentPanelBatch` | static loadings, factor returns | factor-premium forecaster + mapper |
222
+ | `RPPCAModel` | `PersistentPanelBatch` | risk-premium-aware latent factors | factor-premium forecaster + mapper |
223
+ | `IPCAModel` | `CrossSectionBatch` | characteristic-implied betas, factor history | factor-premium forecaster + mapper |
224
+ | `CAEModel` | `CrossSectionBatch` | nonlinear characteristic betas, factor history | factor-premium forecaster + mapper |
225
+
226
+ ### Stochastic Discount Factor
227
+
228
+ `StochasticDiscountFactorModel` is not a `beta × lambda` latent-factor model. It learns a weight-native no-arbitrage object and exposes:
229
+
230
+ - asset weights
231
+ - SDF series
232
+ - checkpointed phase-aware training state
233
+
234
+ Optional return projections are handled by separate mappers.
235
+
236
+ ### Direct Asset Prediction
237
+
238
+ `SAEModel` is a supervised autoencoder signal model. In this library it is treated as a direct predictor, not a latent-factor model.
239
+
240
+ ### Portfolio Learning
241
+
242
+ Portfolio models learn allocations directly:
243
+
244
+ - `LinearFeaturePortfolioModel` as a deterministic baseline
245
+ - `LSTMPortfolioModel` as a sequence baseline
246
+ - `DeepPortfolioModel` as a structured DeePM-style allocator
247
+
248
+ ## Design Principles
249
+
250
+ - Finance-native data contracts rather than generic dataloaders
251
+ - Explicit structural and predictive stages
252
+ - Checkpoint-aware neural training
253
+ - Clear separation between:
254
+ - model estimation
255
+ - forecasting
256
+ - backtest and diagnostic integration
257
+ - Integration boundaries with sibling libraries instead of duplicated evaluation logic
258
+
259
+ ## Documentation
260
+
261
+ - [Getting Started](docs/getting-started/quickstart.md)
262
+ - [User Guide](docs/user-guide/index.md)
263
+ - [Architecture](docs/reference/architecture.md)
264
+ - [API Reference](docs/api/index.md)
265
+ - [Book Guide](docs/book-guide/index.md)
@@ -0,0 +1,206 @@
1
+ # ml4t-models
2
+
3
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
4
+ [![PyPI](https://img.shields.io/pypi/v/ml4t-models)](https://pypi.org/project/ml4t-models/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ Finance-native model implementations for latent-factor estimation, stochastic discount factor learning, direct asset prediction, and end-to-end portfolio learning.
8
+
9
+ Documentation: https://ml4trading.io/docs/models/
10
+
11
+ ## Part of the ML4T Library Ecosystem
12
+
13
+ This library is one of six interconnected ML4T libraries supporting the research and production workflow described in [Machine Learning for Trading](https://ml4trading.io).
14
+
15
+ ![ML4T Library Ecosystem](docs/images/ml4t_ecosystem_workflow_color.png)
16
+
17
+ ## What This Library Does
18
+
19
+ `ml4t-models` packages paper-faithful model families that are common in modern empirical asset pricing and portfolio learning:
20
+
21
+ - Latent-factor estimators with explicit structural outputs:
22
+ - `PCAModel`
23
+ - `RPPCAModel`
24
+ - `IPCAModel`
25
+ - `CAEModel`
26
+ - Weight-native stochastic discount factor modeling:
27
+ - `StochasticDiscountFactorModel`
28
+ - Direct asset prediction:
29
+ - `SAEModel` (`SAE` = supervised autoencoder)
30
+ - End-to-end portfolio learning:
31
+ - `LinearFeaturePortfolioModel`
32
+ - `LSTMPortfolioModel`
33
+ - `DeepPortfolioModel`
34
+
35
+ The library is built around finance-native contracts rather than generic tensor trainers:
36
+
37
+ - `PersistentPanelBatch` for stable-ID panels
38
+ - `CrossSectionBatch` for ragged dated cross-sections
39
+ - `PortfolioSequenceBatch` for sequence-to-allocation models
40
+
41
+ It also keeps the predictive steps explicit:
42
+
43
+ - structural extraction
44
+ - factor-premium forecasting
45
+ - asset mapping
46
+ - downstream prediction and weight frames for `ml4t-backtest` and `ml4t-diagnostic`
47
+
48
+ ![ml4t-models Architecture](docs/images/ml4t_models_architecture.svg)
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ pip install ml4t-models
54
+ ```
55
+
56
+ Optional extras:
57
+
58
+ ```bash
59
+ pip install ml4t-models[deep] # torch-backed neural models
60
+ pip install ml4t-models[integration] # polars + ml4t-specs bridges
61
+ pip install ml4t-models[docs] # mkdocs site build
62
+ pip install ml4t-models[all]
63
+ ```
64
+
65
+ ## Quick Start
66
+
67
+ ### 1. Latent-Factor Forecast Pipeline
68
+
69
+ ```python
70
+ import numpy as np
71
+
72
+ from ml4t.models import (
73
+ BetaLambdaMapper,
74
+ CrossSectionBatch,
75
+ ExpandingMeanFactorForecaster,
76
+ IPCAConfig,
77
+ IPCAModel,
78
+ LatentFactorForecastPipeline,
79
+ )
80
+
81
+ batch = CrossSectionBatch(
82
+ characteristics=np.random.randn(24, 200, 12),
83
+ returns=np.random.randn(24, 200),
84
+ timestamps=tuple(range(24)),
85
+ )
86
+
87
+ pipeline = LatentFactorForecastPipeline(
88
+ model=IPCAModel(IPCAConfig(n_factors=3)),
89
+ forecaster=ExpandingMeanFactorForecaster(),
90
+ mapper=BetaLambdaMapper(),
91
+ )
92
+ pipeline.fit(batch)
93
+ prediction = pipeline.predict(batch)
94
+
95
+ print(prediction.asset_forecast.expected_returns.shape)
96
+ # (24, 200)
97
+ ```
98
+
99
+ ### 2. Weight-Native Stochastic Discount Factor
100
+
101
+ ```python
102
+ import numpy as np
103
+
104
+ from ml4t.models import CrossSectionBatch, StochasticDiscountFactorConfig, StochasticDiscountFactorModel
105
+
106
+ batch = CrossSectionBatch(
107
+ characteristics=np.random.randn(36, 300, 16),
108
+ returns=np.random.randn(36, 300),
109
+ context_features=np.random.randn(36, 8),
110
+ timestamps=tuple(range(36)),
111
+ )
112
+
113
+ model = StochasticDiscountFactorModel(
114
+ StochasticDiscountFactorConfig(checkpoint_epochs=(256, 512, 768, 1024, 1280))
115
+ )
116
+ model.fit(batch)
117
+ state = model.extract(batch, checkpoint=1280)
118
+
119
+ print(state.asset_weights.shape)
120
+ # (36, 300)
121
+ ```
122
+
123
+ ### 3. End-to-End Portfolio Learning
124
+
125
+ ```python
126
+ import numpy as np
127
+
128
+ from ml4t.models import LSTMPortfolioConfig, LSTMPortfolioModel, PortfolioSequenceBatch
129
+
130
+ batch = PortfolioSequenceBatch(
131
+ features=np.random.randn(8, 63, 20, 10),
132
+ returns=np.random.randn(8, 63, 20),
133
+ timestamps=tuple(range(63)),
134
+ asset_ids=tuple(f"asset_{i}" for i in range(20)),
135
+ )
136
+
137
+ model = LSTMPortfolioModel(LSTMPortfolioConfig(max_iters=20, checkpoint_every=5))
138
+ model.fit(batch)
139
+ weights = model.predict(batch, checkpoint=20)
140
+
141
+ print(weights.weights.shape)
142
+ # (8, 63, 20)
143
+ ```
144
+
145
+ ### 4. Hand Off Predictions To The Rest Of ML4T
146
+
147
+ ```python
148
+ from ml4t.models import predictions_frame_from_asset_forecast, write_backtest_frames
149
+
150
+ frame = predictions_frame_from_asset_forecast(prediction.asset_forecast)
151
+ write_backtest_frames("artifacts/run_001", predictions=frame)
152
+ ```
153
+
154
+ ## Model Families
155
+
156
+ ### Latent Factors
157
+
158
+ These models estimate a structural representation first, then let a separate forecaster produce ex ante factor premia.
159
+
160
+ | Model | Contract | Native output | Predictive step |
161
+ |---|---|---|---|
162
+ | `PCAModel` | `PersistentPanelBatch` | static loadings, factor returns | factor-premium forecaster + mapper |
163
+ | `RPPCAModel` | `PersistentPanelBatch` | risk-premium-aware latent factors | factor-premium forecaster + mapper |
164
+ | `IPCAModel` | `CrossSectionBatch` | characteristic-implied betas, factor history | factor-premium forecaster + mapper |
165
+ | `CAEModel` | `CrossSectionBatch` | nonlinear characteristic betas, factor history | factor-premium forecaster + mapper |
166
+
167
+ ### Stochastic Discount Factor
168
+
169
+ `StochasticDiscountFactorModel` is not a `beta × lambda` latent-factor model. It learns a weight-native no-arbitrage object and exposes:
170
+
171
+ - asset weights
172
+ - SDF series
173
+ - checkpointed phase-aware training state
174
+
175
+ Optional return projections are handled by separate mappers.
176
+
177
+ ### Direct Asset Prediction
178
+
179
+ `SAEModel` is a supervised autoencoder signal model. In this library it is treated as a direct predictor, not a latent-factor model.
180
+
181
+ ### Portfolio Learning
182
+
183
+ Portfolio models learn allocations directly:
184
+
185
+ - `LinearFeaturePortfolioModel` as a deterministic baseline
186
+ - `LSTMPortfolioModel` as a sequence baseline
187
+ - `DeepPortfolioModel` as a structured DeePM-style allocator
188
+
189
+ ## Design Principles
190
+
191
+ - Finance-native data contracts rather than generic dataloaders
192
+ - Explicit structural and predictive stages
193
+ - Checkpoint-aware neural training
194
+ - Clear separation between:
195
+ - model estimation
196
+ - forecasting
197
+ - backtest and diagnostic integration
198
+ - Integration boundaries with sibling libraries instead of duplicated evaluation logic
199
+
200
+ ## Documentation
201
+
202
+ - [Getting Started](docs/getting-started/quickstart.md)
203
+ - [User Guide](docs/user-guide/index.md)
204
+ - [Architecture](docs/reference/architecture.md)
205
+ - [API Reference](docs/api/index.md)
206
+ - [Book Guide](docs/book-guide/index.md)
@@ -0,0 +1,165 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [tool.hatch.version]
6
+ path = "src/ml4t/models/__init__.py"
7
+
8
+ [tool.hatch.build.targets.wheel]
9
+ packages = ["src/ml4t"]
10
+ namespaces = true
11
+
12
+ [tool.hatch.build.targets.sdist]
13
+ include = [
14
+ "/src",
15
+ "/tests",
16
+ "/README.md",
17
+ "/LICENSE",
18
+ "/CHANGELOG.md",
19
+ "/pyproject.toml",
20
+ ]
21
+
22
+ [project]
23
+ name = "ml4t-models"
24
+ dynamic = ["version"]
25
+ description = "Finance-specific latent-factor and portfolio-learning models for ML4T"
26
+ readme = "README.md"
27
+ license = { text = "MIT" }
28
+ authors = [
29
+ { name = "Stefan Jansen", email = "stefan@ml4trading.io" },
30
+ ]
31
+ maintainers = [
32
+ { name = "Stefan Jansen", email = "stefan@ml4trading.io" },
33
+ ]
34
+ keywords = [
35
+ "finance",
36
+ "machine-learning",
37
+ "deep-learning",
38
+ "latent-factors",
39
+ "portfolio-learning",
40
+ "algorithmic-trading",
41
+ "quantitative-finance",
42
+ ]
43
+ classifiers = [
44
+ "Development Status :: 3 - Alpha",
45
+ "Intended Audience :: Financial and Insurance Industry",
46
+ "Intended Audience :: Developers",
47
+ "Intended Audience :: Science/Research",
48
+ "License :: OSI Approved :: MIT License",
49
+ "Operating System :: OS Independent",
50
+ "Programming Language :: Python :: 3",
51
+ "Programming Language :: Python :: 3.12",
52
+ "Programming Language :: Python :: 3.13",
53
+ "Topic :: Office/Business :: Financial :: Investment",
54
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
55
+ "Topic :: Scientific/Engineering :: Information Analysis",
56
+ "Typing :: Typed",
57
+ ]
58
+ requires-python = ">=3.12,<3.14"
59
+ dependencies = [
60
+ "numpy>=1.26,<2.3",
61
+ ]
62
+
63
+ [project.optional-dependencies]
64
+ deep = [
65
+ "torch>=2.4",
66
+ ]
67
+ integration = [
68
+ "polars>=1.0.0",
69
+ "ml4t-specs>=0.1.0b0",
70
+ ]
71
+ dev = [
72
+ "pytest>=8.0.0",
73
+ "pytest-cov>=5.0.0",
74
+ "ruff>=0.8.0",
75
+ "ty",
76
+ "pre-commit>=3.3.0",
77
+ "torch>=2.4",
78
+ ]
79
+ docs = [
80
+ "mkdocs>=1.6,<2",
81
+ "mkdocs-material>=9.5.0",
82
+ "mkdocstrings[python]>=0.24.0",
83
+ ]
84
+ all = [
85
+ "ml4t-models[deep,dev,docs,integration]",
86
+ ]
87
+
88
+ [project.urls]
89
+ Homepage = "https://ml4trading.io/docs/models/"
90
+ Documentation = "https://ml4trading.io/docs/models/"
91
+ Repository = "https://github.com/ml4t/models"
92
+ Issues = "https://github.com/ml4t/models/issues"
93
+ Changelog = "https://github.com/ml4t/models/blob/main/CHANGELOG.md"
94
+
95
+ [dependency-groups]
96
+ dev = [
97
+ "pytest>=8.0.0",
98
+ "pytest-cov>=5.0.0",
99
+ "ruff>=0.8.0",
100
+ "ty",
101
+ "pre-commit>=3.3.0",
102
+ "torch>=2.4",
103
+ "twine>=6.0.0",
104
+ ]
105
+
106
+ [tool.pytest.ini_options]
107
+ pythonpath = ["src"]
108
+ testpaths = ["tests"]
109
+ python_files = ["test_*.py"]
110
+ python_classes = ["Test*"]
111
+ python_functions = ["test_*"]
112
+ addopts = [
113
+ "-ra",
114
+ "--strict-markers",
115
+ "--cov=ml4t.models",
116
+ "--cov-report=term-missing",
117
+ ]
118
+ markers = [
119
+ "slow: marks tests as slow",
120
+ "optional_dependency: marks tests requiring optional heavy dependencies",
121
+ ]
122
+
123
+ [tool.ruff]
124
+ line-length = 100
125
+ target-version = "py312"
126
+ fix = true
127
+
128
+ [tool.ruff.lint]
129
+ select = [
130
+ "E",
131
+ "W",
132
+ "F",
133
+ "I",
134
+ "B",
135
+ "C4",
136
+ "UP",
137
+ "ARG",
138
+ "SIM",
139
+ ]
140
+ ignore = [
141
+ "E501",
142
+ "B008",
143
+ ]
144
+
145
+ [tool.ruff.lint.per-file-ignores]
146
+ "tests/*" = ["ARG001", "ARG002", "B017", "SIM108"]
147
+
148
+ [tool.ty.environment]
149
+ python-version = "3.12"
150
+ root = ["src"]
151
+
152
+ [tool.ty.src]
153
+ include = ["src"]
154
+ exclude = ["tests"]
155
+
156
+ [tool.coverage.run]
157
+ source = ["src/ml4t/models"]
158
+ omit = ["*/__init__.py"]
159
+
160
+ [tool.coverage.report]
161
+ exclude_lines = [
162
+ "pragma: no cover",
163
+ "raise NotImplementedError",
164
+ "@abstractmethod",
165
+ ]