pymc-forecast 0.0.1__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.
- pymc_forecast-0.0.1/.gitignore +27 -0
- pymc_forecast-0.0.1/LICENSE +201 -0
- pymc_forecast-0.0.1/PKG-INFO +138 -0
- pymc_forecast-0.0.1/PLAN.md +129 -0
- pymc_forecast-0.0.1/README.md +109 -0
- pymc_forecast-0.0.1/pymc_forecast/__init__.py +108 -0
- pymc_forecast-0.0.1/pymc_forecast/data/victoria_electricity.csv +1345 -0
- pymc_forecast-0.0.1/pymc_forecast/data.py +181 -0
- pymc_forecast-0.0.1/pymc_forecast/datasets.py +181 -0
- pymc_forecast-0.0.1/pymc_forecast/evaluate.py +285 -0
- pymc_forecast-0.0.1/pymc_forecast/exceptions.py +47 -0
- pymc_forecast-0.0.1/pymc_forecast/features.py +82 -0
- pymc_forecast-0.0.1/pymc_forecast/forecaster.py +342 -0
- pymc_forecast-0.0.1/pymc_forecast/gaussian.py +129 -0
- pymc_forecast-0.0.1/pymc_forecast/markov.py +167 -0
- pymc_forecast-0.0.1/pymc_forecast/metrics.py +236 -0
- pymc_forecast-0.0.1/pymc_forecast/model.py +307 -0
- pymc_forecast-0.0.1/pymc_forecast/prediction.py +186 -0
- pymc_forecast-0.0.1/pymc_forecast/statespace.py +436 -0
- pymc_forecast-0.0.1/pyproject.toml +82 -0
- pymc_forecast-0.0.1/tests/conftest.py +0 -0
- pymc_forecast-0.0.1/tests/example_models.py +172 -0
- pymc_forecast-0.0.1/tests/test_data.py +110 -0
- pymc_forecast-0.0.1/tests/test_datasets.py +62 -0
- pymc_forecast-0.0.1/tests/test_evaluate.py +173 -0
- pymc_forecast-0.0.1/tests/test_features.py +52 -0
- pymc_forecast-0.0.1/tests/test_forecaster.py +151 -0
- pymc_forecast-0.0.1/tests/test_markov.py +144 -0
- pymc_forecast-0.0.1/tests/test_metrics.py +149 -0
- pymc_forecast-0.0.1/tests/test_model.py +90 -0
- pymc_forecast-0.0.1/tests/test_mvn.py +97 -0
- pymc_forecast-0.0.1/tests/test_package.py +5 -0
- pymc_forecast-0.0.1/tests/test_prediction.py +90 -0
- pymc_forecast-0.0.1/tests/test_replay_mechanism.py +134 -0
- pymc_forecast-0.0.1/tests/test_statespace.py +261 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Claude Code session data
|
|
2
|
+
.claude/
|
|
3
|
+
|
|
4
|
+
# Python
|
|
5
|
+
__pycache__/
|
|
6
|
+
*.py[cod]
|
|
7
|
+
*.egg-info/
|
|
8
|
+
dist/
|
|
9
|
+
build/
|
|
10
|
+
.venv/
|
|
11
|
+
uv.lock
|
|
12
|
+
|
|
13
|
+
# Tooling caches
|
|
14
|
+
.pytest_cache/
|
|
15
|
+
.ruff_cache/
|
|
16
|
+
.coverage
|
|
17
|
+
htmlcov/
|
|
18
|
+
|
|
19
|
+
# Notebooks / editors
|
|
20
|
+
.ipynb_checkpoints/
|
|
21
|
+
.DS_Store
|
|
22
|
+
.idea/
|
|
23
|
+
.vscode/
|
|
24
|
+
|
|
25
|
+
# Docs
|
|
26
|
+
docs/_build/
|
|
27
|
+
docs/jupyter_execute/
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pymc-forecast
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Bayesian time-series forecasting with PyMC: train/forecast plumbing, backtesting, and metrics.
|
|
5
|
+
Project-URL: Repository, https://github.com/pymc-labs/pymc_forecast
|
|
6
|
+
Project-URL: Issues, https://github.com/pymc-labs/pymc_forecast/issues
|
|
7
|
+
Author: PyMC Labs
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: bayesian,forecasting,pymc,time-series
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Requires-Dist: arviz>=0.20
|
|
20
|
+
Requires-Dist: numpy
|
|
21
|
+
Requires-Dist: pooch
|
|
22
|
+
Requires-Dist: pymc>=5.20
|
|
23
|
+
Requires-Dist: xarray
|
|
24
|
+
Provides-Extra: dataframes
|
|
25
|
+
Requires-Dist: pandas; extra == 'dataframes'
|
|
26
|
+
Provides-Extra: extras
|
|
27
|
+
Requires-Dist: pymc-extras>=0.10; extra == 'extras'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# pymc_forecast
|
|
31
|
+
|
|
32
|
+
[](https://github.com/pymc-labs/pymc_forecast/actions/workflows/ci.yml)
|
|
33
|
+
[](https://pymc-labs.github.io/pymc_forecast/)
|
|
34
|
+
|
|
35
|
+
Bayesian time-series forecasting with [PyMC](https://www.pymc.io): you write the
|
|
36
|
+
generative model; the package handles the train/forecast plumbing, inference,
|
|
37
|
+
backtesting, and evaluation.
|
|
38
|
+
|
|
39
|
+
A PyMC port of [numpyro_forecast](https://github.com/juanitorduz/numpyro_forecast)
|
|
40
|
+
(itself a port of Pyro's `pyro.contrib.forecast`) — redesigned around PyMC idioms
|
|
41
|
+
rather than a 1:1 translation.
|
|
42
|
+
|
|
43
|
+
> **Status: early development.** The design and roadmap live in
|
|
44
|
+
> [PLAN.md](PLAN.md) and the
|
|
45
|
+
> [issue tracker](https://github.com/pymc-labs/pymc_forecast/issues).
|
|
46
|
+
|
|
47
|
+
**Documentation:** <https://pymc-labs.github.io/pymc_forecast/> — API reference and
|
|
48
|
+
executed example notebooks (univariate, hierarchical, covariates, state-space).
|
|
49
|
+
|
|
50
|
+
## Quickstart
|
|
51
|
+
|
|
52
|
+
Write a model with one `predict()` call, fit it, and forecast:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import numpy as np, pandas as pd, pymc as pm, pytensor.tensor as pt
|
|
56
|
+
from pymc_forecast import Forecaster, backtest, evaluate_forecast, predict, time_series
|
|
57
|
+
|
|
58
|
+
# a trending weekly series; hold out the last 8 weeks
|
|
59
|
+
dates = pd.date_range("2024-01-07", periods=60, freq="W")
|
|
60
|
+
y = pd.Series(np.cumsum(np.random.default_rng(0).normal(0.2, 1.0, 60)) + 10, index=dates)
|
|
61
|
+
train, test = y.iloc[:52], y.iloc[52:]
|
|
62
|
+
|
|
63
|
+
def model(h, covariates):
|
|
64
|
+
# a per-step drift latent; time_series adds the matching `_future` latent
|
|
65
|
+
drift = time_series(h, "drift", lambda name, dims: pm.Normal(name, 0.0, 0.5, dims=dims))
|
|
66
|
+
sigma = pm.HalfNormal("sigma", 1.0)
|
|
67
|
+
predict(
|
|
68
|
+
h,
|
|
69
|
+
lambda name, mu, dims, obs: pm.Normal(name, mu, sigma, dims=dims, observed=obs),
|
|
70
|
+
pt.cumsum(drift), # local-linear trend
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
fc = Forecaster(model, train, num_steps=5_000, random_seed=0) # ADVI
|
|
74
|
+
idata = fc.forecast(horizon=8, num_samples=500, random_seed=0)
|
|
75
|
+
forecast = idata["predictions"]["forecast"] # dims: (chain, draw, time_future)
|
|
76
|
+
|
|
77
|
+
# score against the held-out weeks (aligned by dim name, not axis position)
|
|
78
|
+
truth = test.to_xarray().rename({"index": "time_future"})
|
|
79
|
+
print(evaluate_forecast(forecast, truth)) # {'mae': ..., 'rmse': ..., 'crps': ..., 'coverage': ...}
|
|
80
|
+
|
|
81
|
+
# rolling-origin backtest over the whole series
|
|
82
|
+
results = backtest(y, None, model, min_train_window=48, test_window=4, stride=4,
|
|
83
|
+
num_samples=200, forecaster_options={"num_steps": 3_000}, random_seed=0)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Swap `Forecaster` for `HMCForecaster` (NUTS, with `nuts_sampler="nutpie"/"numpyro"/...`)
|
|
87
|
+
or `PathfinderForecaster` (pymc-extras) — the fit/forecast interface is identical.
|
|
88
|
+
For models with real covariates, pass full-horizon `covariates` to `.forecast()`
|
|
89
|
+
instead of `horizon=`. See `markov_time_series` for state-space latents and
|
|
90
|
+
`predict_mvn` for observation noise correlated across time.
|
|
91
|
+
|
|
92
|
+
[pymc-extras statespace](https://github.com/pymc-devs/pymc-extras) structural models
|
|
93
|
+
(level/trend, seasonality, SARIMAX, ...) are first-class citizens too: define one as a
|
|
94
|
+
`StatespaceModel` and fit it with `StatespaceForecaster` — the same `forecast`
|
|
95
|
+
(including exogenous-regression covariates), `predict_in_sample`, `backtest`, and
|
|
96
|
+
metrics calls apply, with the Kalman filter marginalizing the latent states instead
|
|
97
|
+
of sampling them (see `docs/examples/scan_vs_statespace_local_level.ipynb`).
|
|
98
|
+
The pymc-extras integrations (`PathfinderForecaster`, `StatespaceForecaster`) are an
|
|
99
|
+
optional extra: install with `pip install 'pymc-forecast[extras]'`.
|
|
100
|
+
|
|
101
|
+
## Design principles
|
|
102
|
+
|
|
103
|
+
- **One model trains and forecasts.** In-sample time latents are fitted; the
|
|
104
|
+
forecast horizon uses separate `{name}_future` variables that
|
|
105
|
+
`pm.sample_posterior_predictive` draws from the prior while replaying the
|
|
106
|
+
posterior for everything else.
|
|
107
|
+
- **Dims and coords everywhere.** No positional axis conventions: variables carry
|
|
108
|
+
named dims (`"time"`, `"time_future"`, `"obs"`, batch dims), results are
|
|
109
|
+
`arviz.InferenceData` / `xarray` objects with real coordinates, and metrics are
|
|
110
|
+
dim-aware.
|
|
111
|
+
- **Not AutoML.** No model zoo, no automatic feature pipelines — a clean path from
|
|
112
|
+
a hand-written PyMC model to probabilistic forecasts and scores.
|
|
113
|
+
- **Leverage the ecosystem.** ADVI/NUTS from PyMC core, Pathfinder and state-space
|
|
114
|
+
models from [pymc-extras](https://github.com/pymc-devs/pymc-extras), diagnostics
|
|
115
|
+
and storage from [ArviZ](https://python.arviz.org).
|
|
116
|
+
|
|
117
|
+
## Development
|
|
118
|
+
|
|
119
|
+
Requires Python >= 3.11 and [uv](https://docs.astral.sh/uv/):
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
uv sync --all-extras
|
|
123
|
+
uv run pytest
|
|
124
|
+
uv run ruff check .
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
To build the documentation (the example notebooks are committed fully executed;
|
|
128
|
+
CI re-executes them with reduced sampling settings):
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
uv sync --all-extras --group docs
|
|
132
|
+
uv run sphinx-build -b html docs docs/_build/html
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
Apache-2.0. Portions derived from
|
|
138
|
+
[numpyro_forecast](https://github.com/juanitorduz/numpyro_forecast) (Apache-2.0).
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# Porting `numpyro_forecast` to PyMC
|
|
2
|
+
|
|
3
|
+
Design and porting plan for building `pymc_forecast` from
|
|
4
|
+
[juanitorduz/numpyro_forecast](https://github.com/juanitorduz/numpyro_forecast)
|
|
5
|
+
(itself a JAX/NumPyro port of Pyro's `pyro.contrib.forecast`).
|
|
6
|
+
|
|
7
|
+
**This is a redesign, not a translation**: we adopt PyMC idioms throughout —
|
|
8
|
+
named dims/coords instead of positional axis conventions, `InferenceData`/xarray
|
|
9
|
+
results instead of raw arrays, and pymc-extras for Pathfinder and state-space
|
|
10
|
+
models. No API or layout compatibility with the NumPyro version is kept.
|
|
11
|
+
|
|
12
|
+
The actionable roadmap lives in the
|
|
13
|
+
[issue tracker](https://github.com/pymc-labs/pymc_forecast/issues); this document
|
|
14
|
+
records the source-package analysis and the concept mapping behind those issues.
|
|
15
|
+
|
|
16
|
+
## What the source package is
|
|
17
|
+
|
|
18
|
+
A small, focused toolkit for Bayesian time-series forecasting. The user writes the
|
|
19
|
+
generative model; the package handles train/forecast plumbing, inference, and
|
|
20
|
+
evaluation. ~3.3k lines in the main package + ~2k in `functional/` and `contrib/`,
|
|
21
|
+
plus ~40 test modules.
|
|
22
|
+
|
|
23
|
+
Core design invariants of the source:
|
|
24
|
+
|
|
25
|
+
1. **One model both trains and forecasts.** In-sample time latents use a fixed site
|
|
26
|
+
name (e.g. `drift`); the forecast horizon uses a separate `{name}_future` site.
|
|
27
|
+
The guide/posterior never sees the future site, so `Predictive` replays the
|
|
28
|
+
posterior for in-sample latents and draws the forecast suffix from the prior.
|
|
29
|
+
2. **Horizon inferred from shapes**: `future = covariates.shape[-2] - data.shape[-2]`.
|
|
30
|
+
3. **Array layout**: time at axis `-2`, observation dim at `-1`, batch dims left
|
|
31
|
+
(dropped in this port in favor of dims/coords).
|
|
32
|
+
|
|
33
|
+
Module inventory of the source:
|
|
34
|
+
|
|
35
|
+
| Module | Lines | Role |
|
|
36
|
+
|---|---|---|
|
|
37
|
+
| `functional/models.py` | 417 | `Horizon`, `time_series`, `markov_time_series` (scan), `predict`, `predict_glm`, `forecasting_model` |
|
|
38
|
+
| `surgery.py` | 368 | Distribution surgery: `shift_loc`, `slice_time`, `prefix_condition` (singledispatch; elementwise families + MVN Gaussian conditional) |
|
|
39
|
+
| `functional/svi.py` | 278 | Guide/optimizer resolution, `fit_svi` (AutoNormal default) |
|
|
40
|
+
| `functional/mcmc.py` | 249 | Kernel resolution, `fit_mcmc` (NUTS default) |
|
|
41
|
+
| `functional/prediction.py` | 279 | `forecast`, `predict_in_sample` via `Predictive`, chunked/vmapped sampling |
|
|
42
|
+
| `functional/posterior.py` | 135 | `draw_posterior` dispatch over fit types |
|
|
43
|
+
| `forecaster.py` | 556 | OOP shims: `ForecastingModel`, `Forecaster` (SVI), `HMCForecaster`, `PathfinderForecaster` |
|
|
44
|
+
| `contrib/blackjax.py` | 581 | Pathfinder VI via BlackJAX |
|
|
45
|
+
| `evaluate.py` | 1090 | `backtest` (expanding/rolling windows), `backtest_vectorized` (vmapped SVI), `evaluate_forecast`, result dataclasses |
|
|
46
|
+
| `metrics.py` | 220 | CRPS, pinball, interval score, MASE factory |
|
|
47
|
+
| `convert.py` | 380 | Fits → ArviZ-schema `xarray.DataTree`, forecast groups |
|
|
48
|
+
| `features.py` | 80 | Fourier design matrices, periodic tiling |
|
|
49
|
+
| `datasets.py` | 137 | BART ridership, Victoria electricity |
|
|
50
|
+
| `arrays.py`, `typing.py`, `exceptions.py`, `optional.py` | ~390 | Helpers, jaxtyping/beartype runtime typing, error taxonomy |
|
|
51
|
+
|
|
52
|
+
## Concept mapping: NumPyro → PyMC
|
|
53
|
+
|
|
54
|
+
| numpyro_forecast concept | pymc_forecast equivalent |
|
|
55
|
+
|---|---|
|
|
56
|
+
| Model = pure callable `(covariates, data=None)` | Model-builder callable returning a `pm.Model` (built fresh per fit/forecast call with different horizons) |
|
|
57
|
+
| `Horizon` from array shapes, plates `time` / `time_future` | `Horizon` from coords: dims `"time"` / `"time_future"` with real coordinate values (dates, periods) |
|
|
58
|
+
| `time_series`: site + `{name}_future` site, concat on axis -2 | Same trick: an RV with `dims="time"` plus a fresh `{name}_future` RV with `dims="time_future"`, `pt.concatenate` — `sample_posterior_predictive` replays trace vars and **samples vars missing from the trace from the prior**, which is exactly the `_future`-site mechanism |
|
|
59
|
+
| `markov_time_series` (numpyro `scan`) | `pytensor.scan` inside the model (with `collect_default_updates`) or `CustomDist` with a scan-based dist; forecast scan seeded from the final in-sample state. For linear-Gaussian cases: `pymc_extras.statespace` |
|
|
60
|
+
| `predict(noise_dist, prediction)` + `shift_loc` | Unnecessary as surgery — PyMC likelihoods take `mu` directly. `predict()` becomes API sugar registering `obs` (observed, dims `("time", ...)`) + `obs_future` (unobserved, dims `("time_future", ...)`) + a `forecast` deterministic |
|
|
61
|
+
| `slice_time` / `prefix_condition` (elementwise) | Free: index the latent/params on the future coords when building the future likelihood; conditional = marginal for elementwise noise |
|
|
62
|
+
| `prefix_condition` (MultivariateNormal over time) | Must be ported: explicit Gaussian conditional (Cholesky/solve) in PyTensor, mirroring `_mvn_prefix_condition` |
|
|
63
|
+
| `fit_svi` + `AutoNormal` guide | `pm.fit(method="advi")` (mean-field ≙ AutoNormal); `fullrank_advi` ≙ AutoMultivariateNormal; optimizer via `obj_optimizer=pm.adam(...)` |
|
|
64
|
+
| `fit_mcmc` + NUTS, kernel resolution | `pm.sample()`; backend choice via `nuts_sampler=` (`"pymc"`, `"nutpie"`, `"numpyro"`, `"blackjax"`) replaces kernel resolution |
|
|
65
|
+
| Pathfinder via BlackJAX (581 lines) | Collapses to a thin wrapper over `pymc_extras.fit_pathfinder` |
|
|
66
|
+
| `draw_posterior` (fit-type dispatch) | `approx.sample(n)` for VI; thin/subsample `idata.posterior` for MCMC — normalize both to `InferenceData` |
|
|
67
|
+
| `Predictive` → `forecast` site | `pm.sample_posterior_predictive(idata, var_names=[...], predictions=True)` on the extended-horizon model — the predictions group comes labeled with forecast-time coords |
|
|
68
|
+
| `backtest` (per-window refit) | Same structure, framework-agnostic loop; PRNG keys → integer `random_seed` streams |
|
|
69
|
+
| `backtest_vectorized` (vmapped SVI over windows) | **No vmap equivalent.** Mitigation: rolling windows have fixed shapes → build the window model once with `pm.Data`, iterate via `pm.set_data` to avoid recompiles; nutpie compiled-model reuse for MCMC. Statistical parity, not wall-clock parity |
|
|
70
|
+
| `convert.py` → ArviZ DataTree | Mostly free: PyMC returns `InferenceData` natively and `predictions=True` creates the predictions groups. Keep a small helper for forecast-time coord labeling |
|
|
71
|
+
| `metrics.py` / `evaluate_forecast` (jitted JAX, axis conventions) | Dim-aware xarray/NumPy implementations: metrics take forecast draws and truth as labeled arrays, reduce over named dims |
|
|
72
|
+
| `features.py`, `datasets.py` | Near-verbatim port to NumPy; feature builders return labeled outputs (coords for the feature dim) |
|
|
73
|
+
| jaxtyping/beartype runtime typing | Drop; plain annotations + dim/coord validation at API boundaries |
|
|
74
|
+
| Exceptions taxonomy | Port with renames (guide/kernel resolution errors → VI-method/sampler resolution errors) |
|
|
75
|
+
|
|
76
|
+
## Where pymc-extras fits
|
|
77
|
+
|
|
78
|
+
- **`pymc_extras.statespace`**: structural time series (level/trend, seasonality,
|
|
79
|
+
cycles, AR, regression components), SARIMAX, VARMAX — with Kalman filtering and
|
|
80
|
+
built-in `.forecast()`. This covers the linear-Gaussian slice of what
|
|
81
|
+
`markov_time_series` is used for, with exact marginalization instead of sampling
|
|
82
|
+
per-step latents (usually better posteriors and faster). The port should
|
|
83
|
+
interoperate: statespace models as first-class citizens in `backtest`/metrics.
|
|
84
|
+
- **`fit_pathfinder`**: replaces the entire BlackJAX contrib module.
|
|
85
|
+
- Scan-based `markov_time_series` remains valuable for arbitrary nonlinear /
|
|
86
|
+
non-Gaussian transitions that statespace can't express.
|
|
87
|
+
|
|
88
|
+
## Key design decisions
|
|
89
|
+
|
|
90
|
+
1. **Dims/coords everywhere (decided).** No positional axis conventions anywhere in
|
|
91
|
+
the API: model variables carry named dims, forecast outputs are
|
|
92
|
+
`InferenceData`/xarray with real time coordinates, metrics reduce over named
|
|
93
|
+
dims. Coords (e.g. `pandas.DatetimeIndex`) flow from input data through to
|
|
94
|
+
forecast outputs.
|
|
95
|
+
2. **Model API shape.** Keep the two-level design — a functional core where the
|
|
96
|
+
user writes a model body against a `Horizon` (primitives: `time_series`,
|
|
97
|
+
`markov_time_series`, `predict`, `predict_glm`) executed inside a managed
|
|
98
|
+
`pm.Model` context, plus an OOP `ForecastingModel` facade. The builder
|
|
99
|
+
constructs a fresh model per call (train: no future coords; forecast: extended
|
|
100
|
+
coords), which is idiomatic PyMC and keeps the "one model definition" invariant.
|
|
101
|
+
3. **Randomness.** `rng_key` threading → `random_seed` integers / numpy Generators;
|
|
102
|
+
derive per-window seeds deterministically in `backtest`.
|
|
103
|
+
4. **Performance posture.** Accept that per-window refits recompile unless shapes
|
|
104
|
+
are fixed; document `nuts_sampler="nutpie"` / `"numpyro"` for speed; use
|
|
105
|
+
`pm.Data` + `set_data` wherever shapes allow.
|
|
106
|
+
|
|
107
|
+
## What gets dropped or shrinks
|
|
108
|
+
|
|
109
|
+
- `surgery.py` singledispatch machinery — dissolves into direct likelihood
|
|
110
|
+
construction (only the MVN conditional survives).
|
|
111
|
+
- `contrib/blackjax.py` (581 lines) → thin wrapper around pymc-extras.
|
|
112
|
+
- `convert.py` (380 lines) → small coords/labeling helper on native `InferenceData`.
|
|
113
|
+
- `arrays.py` axis-layout helpers → replaced by coord handling.
|
|
114
|
+
- jaxtyping/beartype import hook, JAX-specific vmap invariant tests.
|
|
115
|
+
|
|
116
|
+
## Risks / open questions
|
|
117
|
+
|
|
118
|
+
- **Posterior replay semantics**: upstream relies on "guide never sees `_future`
|
|
119
|
+
sites". PyMC's `sample_posterior_predictive` prior-samples missing vars, but
|
|
120
|
+
deterministic replay vs. resampling of *dependent* vars needs careful
|
|
121
|
+
`var_names` handling — cover with the upstream consistency tests (SVI vs. MCMC
|
|
122
|
+
forecasts agree on conjugate examples). Prototype first.
|
|
123
|
+
- **Scan + posterior replay**: replaying scan-internal latents from a trace while
|
|
124
|
+
continuing the state forward is the trickiest mechanism; prototype early.
|
|
125
|
+
- **Wall-clock**: no vmapped multi-window SVI; decide how much of
|
|
126
|
+
`backtest_vectorized`'s speed promise to keep.
|
|
127
|
+
- **Multivariate/hierarchical batch semantics**: upstream leans on NumPyro plates +
|
|
128
|
+
broadcasting; dims/coords cover it, but the shape-heavy tests should be ported
|
|
129
|
+
wholesale (translated to dims).
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# pymc_forecast
|
|
2
|
+
|
|
3
|
+
[](https://github.com/pymc-labs/pymc_forecast/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pymc-labs.github.io/pymc_forecast/)
|
|
5
|
+
|
|
6
|
+
Bayesian time-series forecasting with [PyMC](https://www.pymc.io): you write the
|
|
7
|
+
generative model; the package handles the train/forecast plumbing, inference,
|
|
8
|
+
backtesting, and evaluation.
|
|
9
|
+
|
|
10
|
+
A PyMC port of [numpyro_forecast](https://github.com/juanitorduz/numpyro_forecast)
|
|
11
|
+
(itself a port of Pyro's `pyro.contrib.forecast`) — redesigned around PyMC idioms
|
|
12
|
+
rather than a 1:1 translation.
|
|
13
|
+
|
|
14
|
+
> **Status: early development.** The design and roadmap live in
|
|
15
|
+
> [PLAN.md](PLAN.md) and the
|
|
16
|
+
> [issue tracker](https://github.com/pymc-labs/pymc_forecast/issues).
|
|
17
|
+
|
|
18
|
+
**Documentation:** <https://pymc-labs.github.io/pymc_forecast/> — API reference and
|
|
19
|
+
executed example notebooks (univariate, hierarchical, covariates, state-space).
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
Write a model with one `predict()` call, fit it, and forecast:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import numpy as np, pandas as pd, pymc as pm, pytensor.tensor as pt
|
|
27
|
+
from pymc_forecast import Forecaster, backtest, evaluate_forecast, predict, time_series
|
|
28
|
+
|
|
29
|
+
# a trending weekly series; hold out the last 8 weeks
|
|
30
|
+
dates = pd.date_range("2024-01-07", periods=60, freq="W")
|
|
31
|
+
y = pd.Series(np.cumsum(np.random.default_rng(0).normal(0.2, 1.0, 60)) + 10, index=dates)
|
|
32
|
+
train, test = y.iloc[:52], y.iloc[52:]
|
|
33
|
+
|
|
34
|
+
def model(h, covariates):
|
|
35
|
+
# a per-step drift latent; time_series adds the matching `_future` latent
|
|
36
|
+
drift = time_series(h, "drift", lambda name, dims: pm.Normal(name, 0.0, 0.5, dims=dims))
|
|
37
|
+
sigma = pm.HalfNormal("sigma", 1.0)
|
|
38
|
+
predict(
|
|
39
|
+
h,
|
|
40
|
+
lambda name, mu, dims, obs: pm.Normal(name, mu, sigma, dims=dims, observed=obs),
|
|
41
|
+
pt.cumsum(drift), # local-linear trend
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
fc = Forecaster(model, train, num_steps=5_000, random_seed=0) # ADVI
|
|
45
|
+
idata = fc.forecast(horizon=8, num_samples=500, random_seed=0)
|
|
46
|
+
forecast = idata["predictions"]["forecast"] # dims: (chain, draw, time_future)
|
|
47
|
+
|
|
48
|
+
# score against the held-out weeks (aligned by dim name, not axis position)
|
|
49
|
+
truth = test.to_xarray().rename({"index": "time_future"})
|
|
50
|
+
print(evaluate_forecast(forecast, truth)) # {'mae': ..., 'rmse': ..., 'crps': ..., 'coverage': ...}
|
|
51
|
+
|
|
52
|
+
# rolling-origin backtest over the whole series
|
|
53
|
+
results = backtest(y, None, model, min_train_window=48, test_window=4, stride=4,
|
|
54
|
+
num_samples=200, forecaster_options={"num_steps": 3_000}, random_seed=0)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Swap `Forecaster` for `HMCForecaster` (NUTS, with `nuts_sampler="nutpie"/"numpyro"/...`)
|
|
58
|
+
or `PathfinderForecaster` (pymc-extras) — the fit/forecast interface is identical.
|
|
59
|
+
For models with real covariates, pass full-horizon `covariates` to `.forecast()`
|
|
60
|
+
instead of `horizon=`. See `markov_time_series` for state-space latents and
|
|
61
|
+
`predict_mvn` for observation noise correlated across time.
|
|
62
|
+
|
|
63
|
+
[pymc-extras statespace](https://github.com/pymc-devs/pymc-extras) structural models
|
|
64
|
+
(level/trend, seasonality, SARIMAX, ...) are first-class citizens too: define one as a
|
|
65
|
+
`StatespaceModel` and fit it with `StatespaceForecaster` — the same `forecast`
|
|
66
|
+
(including exogenous-regression covariates), `predict_in_sample`, `backtest`, and
|
|
67
|
+
metrics calls apply, with the Kalman filter marginalizing the latent states instead
|
|
68
|
+
of sampling them (see `docs/examples/scan_vs_statespace_local_level.ipynb`).
|
|
69
|
+
The pymc-extras integrations (`PathfinderForecaster`, `StatespaceForecaster`) are an
|
|
70
|
+
optional extra: install with `pip install 'pymc-forecast[extras]'`.
|
|
71
|
+
|
|
72
|
+
## Design principles
|
|
73
|
+
|
|
74
|
+
- **One model trains and forecasts.** In-sample time latents are fitted; the
|
|
75
|
+
forecast horizon uses separate `{name}_future` variables that
|
|
76
|
+
`pm.sample_posterior_predictive` draws from the prior while replaying the
|
|
77
|
+
posterior for everything else.
|
|
78
|
+
- **Dims and coords everywhere.** No positional axis conventions: variables carry
|
|
79
|
+
named dims (`"time"`, `"time_future"`, `"obs"`, batch dims), results are
|
|
80
|
+
`arviz.InferenceData` / `xarray` objects with real coordinates, and metrics are
|
|
81
|
+
dim-aware.
|
|
82
|
+
- **Not AutoML.** No model zoo, no automatic feature pipelines — a clean path from
|
|
83
|
+
a hand-written PyMC model to probabilistic forecasts and scores.
|
|
84
|
+
- **Leverage the ecosystem.** ADVI/NUTS from PyMC core, Pathfinder and state-space
|
|
85
|
+
models from [pymc-extras](https://github.com/pymc-devs/pymc-extras), diagnostics
|
|
86
|
+
and storage from [ArviZ](https://python.arviz.org).
|
|
87
|
+
|
|
88
|
+
## Development
|
|
89
|
+
|
|
90
|
+
Requires Python >= 3.11 and [uv](https://docs.astral.sh/uv/):
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
uv sync --all-extras
|
|
94
|
+
uv run pytest
|
|
95
|
+
uv run ruff check .
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
To build the documentation (the example notebooks are committed fully executed;
|
|
99
|
+
CI re-executes them with reduced sampling settings):
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
uv sync --all-extras --group docs
|
|
103
|
+
uv run sphinx-build -b html docs docs/_build/html
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
Apache-2.0. Portions derived from
|
|
109
|
+
[numpyro_forecast](https://github.com/juanitorduz/numpyro_forecast) (Apache-2.0).
|