Skip to content

Commit f8ca0d8

Browse files
Docs: runnable model tasks and verified book links (#53)
* docs: make model workflows runnable and link verified book examples * docs: clarify stable Python 3.15 core-only qualification * docs: remove workstation path from public bibliography guidance * docs: keep model diagrams and tables readable across screen widths
1 parent 370b046 commit f8ca0d8

30 files changed

Lines changed: 569 additions & 438 deletions

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ __pycache__/
44
.pytest_cache/
55
.ruff_cache/
66
.coverage
7+
coverage.json
78
htmlcov/
89
dist/
910
build/

‎README.md‎

Lines changed: 27 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
[![PyPI](https://img.shields.io/pypi/v/ml4t-models)](https://pypi.org/project/ml4t-models/)
55
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
66

7-
Finance-native model implementations for latent-factor estimation, stochastic discount factor learning, direct asset prediction, and end-to-end portfolio learning.
7+
Finance-specific models for asset pricing, prediction, and portfolio learning.
88

99
Documentation: [ml4trading.io/docs/models](https://www.ml4trading.io/docs/models/)
1010

@@ -45,7 +45,8 @@ It also keeps the predictive steps explicit:
4545
- asset mapping
4646
- downstream prediction and weight frames for `ml4t-backtest` and `ml4t-diagnostic`
4747

48-
![ml4t-models Architecture](docs/images/ml4t_models_architecture.svg)
48+
The [architecture guide](https://www.ml4trading.io/docs/models/reference/architecture/)
49+
connects these data contracts, model outputs, and downstream handoffs.
4950

5051
## Installation
5152

@@ -61,104 +62,52 @@ pip install ml4t-models[integration] # polars + ml4t-specs bridges
6162
pip install ml4t-models[all] # all runtime capabilities
6263
```
6364

64-
Supported stable interpreters are Python 3.12, 3.13, and 3.14. Python 3.15 prereleases run a
65-
separate compatibility gate and are not yet part of the stable support range.
65+
Supported interpreters for all model families are Python 3.12, 3.13, and 3.14.
66+
Python 3.15 is stable, but this package currently qualifies only its NumPy-based core
67+
workflows. The `deep` extra enables Torch only below Python 3.15; use Python 3.12-3.14
68+
for neural models.
6669

6770
Documentation tools are contributor dependencies. From a source checkout, run
6871
`uv sync --extra docs` before building the site.
6972

7073
## Quick Start
7174

72-
### 1. Latent-Factor Forecast Pipeline
75+
The base package can produce a first forecast on a small synthetic panel without credentials or
76+
an accelerator. Run this complete example with `pip install ml4t-models`:
7377

7478
```python
7579
import numpy as np
76-
7780
from ml4t.models import (
7881
BetaLambdaMapper,
79-
CrossSectionBatch,
8082
ExpandingMeanFactorForecaster,
81-
IPCAConfig,
82-
IPCAModel,
8383
LatentFactorForecastPipeline,
84+
PCAConfig,
85+
PCAModel,
86+
PersistentPanelBatch,
8487
)
8588

86-
batch = CrossSectionBatch(
87-
characteristics=np.random.randn(24, 200, 12),
88-
returns=np.random.randn(24, 200),
89-
timestamps=tuple(range(24)),
89+
asset_ids = tuple(f"asset_{i}" for i in range(6))
90+
train = PersistentPanelBatch(
91+
returns=np.random.default_rng(1).normal(scale=0.02, size=(12, 6)),
92+
timestamps=tuple(f"2024-{month:02d}" for month in range(1, 13)),
93+
asset_ids=asset_ids,
9094
)
91-
95+
future = PersistentPanelBatch(timestamps=("2025-01", "2025-02"), asset_ids=asset_ids)
9296
pipeline = LatentFactorForecastPipeline(
93-
model=IPCAModel(IPCAConfig(n_factors=3)),
97+
model=PCAModel(PCAConfig(n_factors=2)),
9498
forecaster=ExpandingMeanFactorForecaster(),
9599
mapper=BetaLambdaMapper(),
96100
)
97-
pipeline.fit(batch)
98-
prediction = pipeline.predict(batch)
99-
100-
print(prediction.asset_forecast.expected_returns.shape)
101-
# (24, 200)
102-
```
103-
104-
### 2. Weight-Native Stochastic Discount Factor
105-
106-
```python
107-
import numpy as np
108-
109-
from ml4t.models import (
110-
CrossSectionBatch,
111-
StochasticDiscountFactorConfig,
112-
StochasticDiscountFactorModel,
113-
)
114-
115-
batch = CrossSectionBatch(
116-
characteristics=np.random.randn(36, 300, 16),
117-
returns=np.random.randn(36, 300),
118-
context_features=np.random.randn(36, 8),
119-
timestamps=tuple(range(36)),
120-
)
121-
122-
model = StochasticDiscountFactorModel(
123-
StochasticDiscountFactorConfig(checkpoint_epochs=(256, 512, 768, 1024))
124-
)
125-
model.fit(batch)
126-
state = model.extract(batch, checkpoint=1280)
127-
128-
print(state.asset_weights.shape)
129-
# (36, 300)
101+
pipeline.fit(train)
102+
forecast = pipeline.predict(future).asset_forecast.expected_returns
103+
assert forecast.shape == (2, 6) and np.isfinite(forecast).all()
104+
print(forecast.shape) # (2, 6)
130105
```
131106

132-
### 3. End-to-End Portfolio Learning
133-
134-
```python
135-
import numpy as np
136-
137-
from ml4t.models import LSTMPortfolioConfig, LSTMPortfolioModel, PortfolioSequenceBatch
138-
139-
batch = PortfolioSequenceBatch(
140-
features=np.random.randn(8, 63, 20, 10),
141-
returns=np.random.randn(8, 63, 20),
142-
timestamps=tuple(range(63)),
143-
asset_ids=tuple(f"asset_{i}" for i in range(20)),
144-
)
145-
146-
model = LSTMPortfolioModel(LSTMPortfolioConfig(max_iters=20, checkpoint_every=5))
147-
model.fit(batch)
148-
weights = model.predict(batch, checkpoint=20)
149-
150-
print(weights.weights.shape)
151-
# (8, 63, 20)
152-
```
153-
154-
### 4. Hand Off Predictions To The Rest Of ML4T
155-
156-
```python
157-
from ml4t.models import predictions_frame_from_asset_forecast, write_backtest_frames
158-
159-
frame = predictions_frame_from_asset_forecast(prediction.asset_forecast)
160-
write_backtest_frames("artifacts/run_001", predictions=frame)
161-
```
107+
The forecast uses the training factor history and preserves the future dates and asset order.
108+
It does not imply trading performance. The [Quickstart](docs/getting-started/quickstart.md)
109+
explains the result, and the [Book Guide](docs/book-guide/index.md) links to pinned teaching files.
110+
The `deep` extra is needed for neural models; the `integration` extra adds Polars and Specs support.
162111

163112
## Model Families
164113

‎docs/_includes/model-families.html‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<figure class="ml4t-flow-map">
2+
<figcaption>Model families and native outputs</figcaption>
3+
<div class="ml4t-flow-map__grid">
4+
<div class="ml4t-flow-map__item">
5+
<strong>Latent factors</strong>
6+
<p><code>PCAModel</code>, <code>RPPCAModel</code>, <code>IPCAModel</code>, <code>CAEModel</code></p>
7+
<p>PCA and RP-PCA use <code>PersistentPanelBatch</code>. IPCA and CAE use <code>CrossSectionBatch</code>.</p>
8+
<p>Native outputs are loadings or conditional betas, factor history, and structural state.</p>
9+
</div>
10+
<div class="ml4t-flow-map__item">
11+
<strong>Stochastic discount factor</strong>
12+
<p><code>StochasticDiscountFactorModel</code></p>
13+
<p>Input: <code>CrossSectionBatch</code>.</p>
14+
<p>Outputs: <code>asset_weights</code>, <code>sdf_values</code>, and phase-aware checkpoints.</p>
15+
</div>
16+
<div class="ml4t-flow-map__item">
17+
<strong>Direct asset prediction</strong>
18+
<p><code>SAEModel</code></p>
19+
<p>Input: <code>CrossSectionBatch</code>.</p>
20+
<p>Output: cross-sectional signals in <code>AssetSignalResult</code>.</p>
21+
</div>
22+
<div class="ml4t-flow-map__item">
23+
<strong>Portfolio learning</strong>
24+
<p><code>LinearFeaturePortfolioModel</code>, <code>LSTMPortfolioModel</code>, <code>DeepPortfolioModel</code></p>
25+
<p>Input: <code>PortfolioSequenceBatch</code>.</p>
26+
<p>Output: target weights in <code>PortfolioWeightsResult</code>.</p>
27+
<p>Neural learners can include trading costs in their training objective.</p>
28+
</div>
29+
<div class="ml4t-flow-map__item ml4t-flow-map__wide">
30+
<strong>Latent-factor return forecasts require three stages</strong>
31+
<ol>
32+
<li>Structural estimation produces <code>LatentFactorState</code>.</li>
33+
<li>A separate factor-premium forecaster produces <code>FactorForecastResult</code>.</li>
34+
<li>An asset mapper combines state and forecast into <code>AssetForecastResult</code>.</li>
35+
</ol>
36+
</div>
37+
<div class="ml4t-flow-map__item ml4t-flow-map__wide">
38+
<strong>Downstream handoff</strong>
39+
<p><code>PredictionsFrame</code> carries forecasts or direct signals. <code>WeightsFrame</code> and <code>ContextFrame</code> support backtests and portfolio diagnostics.</p>
40+
</div>
41+
</div>
42+
</figure>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<figure class="ml4t-flow-map">
2+
<figcaption>Training and checkpoint protocols</figcaption>
3+
<div class="ml4t-flow-map__grid">
4+
<div class="ml4t-flow-map__item">
5+
<strong>Closed-form and alternating models</strong>
6+
<p>PCA and RP-PCA use eigendecomposition. IPCA uses alternating least squares.</p>
7+
<p>These models expose no neural epoch grid; structural output is reported at <code>epoch = 0</code>.</p>
8+
</div>
9+
<div class="ml4t-flow-map__item">
10+
<strong>Neural checkpoints</strong>
11+
<p>CAE, SAE, and neural portfolio learners train for configured epochs or optimization steps.</p>
12+
<p>Emit interval checkpoints or explicit checkpoint lists. Set <code>default_checkpoint</code> for prediction.</p>
13+
</div>
14+
<div class="ml4t-flow-map__item">
15+
<strong>Phased SDF training</strong>
16+
<ol>
17+
<li>Unconditional SDF warm-up</li>
18+
<li>Moment-network fitting</li>
19+
<li>Conditional SDF refinement</li>
20+
</ol>
21+
<p>For long SDF runs, use 4-8 explicit structural checkpoints. Beta-head checkpoints have a separate, usually smaller grid.</p>
22+
</div>
23+
<div class="ml4t-flow-map__item">
24+
<strong>Reporting and evaluation</strong>
25+
<p>Models emit configured checkpoints and metadata. Diagnostics and case studies select, score, and compare them.</p>
26+
<p>Use interval checkpoints for short neural runs and explicit checkpoints for long phased runs. Keep prediction-time defaults explicit.</p>
27+
</div>
28+
</div>
29+
</figure>

‎docs/api/index.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ The package root re-exports the main model classes, configs, batches, results, a
7474
## Stability
7575

7676
The [API Stability](../reference/api-stability.md) page defines the public
77-
surface intended to remain stable through the `0.1` beta series.
77+
surface for the `0.1` stable line.
7878

7979
## Integration
8080

@@ -92,3 +92,14 @@ surface intended to remain stable through the `0.1` beta series.
9292
| `ml4t.models.stochastic_discount_factor` | weight-native SDF estimation and return projections |
9393
| `ml4t.models.asset_prediction` | direct asset-level predictors |
9494
| `ml4t.models.portfolio` | end-to-end portfolio learners |
95+
96+
## Portfolio model signatures
97+
98+
The portfolio models are imported lazily from `ml4t.models`. Their class signatures are rendered
99+
here explicitly so all three supported allocators are covered by the generated reference.
100+
101+
::: ml4t.models.portfolio.linear.LinearFeaturePortfolioModel
102+
103+
::: ml4t.models.portfolio.lstm.LSTMPortfolioModel
104+
105+
::: ml4t.models.portfolio.deep_portfolio.DeepPortfolioModel

0 commit comments

Comments
 (0)