pypricing 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.
Files changed (31) hide show
  1. pypricing-0.0.1/LICENSE +202 -0
  2. pypricing-0.0.1/PKG-INFO +371 -0
  3. pypricing-0.0.1/README.md +324 -0
  4. pypricing-0.0.1/pyproject.toml +102 -0
  5. pypricing-0.0.1/setup.cfg +4 -0
  6. pypricing-0.0.1/src/pypricing/__init__.py +39 -0
  7. pypricing-0.0.1/src/pypricing/data/__init__.py +16 -0
  8. pypricing-0.0.1/src/pypricing/data/index.py +35 -0
  9. pypricing-0.0.1/src/pypricing/data/price_panel.py +414 -0
  10. pypricing-0.0.1/src/pypricing/model_components/__init__.py +1 -0
  11. pypricing-0.0.1/src/pypricing/model_components/cross_elasticity.py +196 -0
  12. pypricing-0.0.1/src/pypricing/model_components/global_terms.py +30 -0
  13. pypricing-0.0.1/src/pypricing/model_components/hierarchical_effects.py +76 -0
  14. pypricing-0.0.1/src/pypricing/model_components/posterior_mu.py +17 -0
  15. pypricing-0.0.1/src/pypricing/model_components/priors.py +46 -0
  16. pypricing-0.0.1/src/pypricing/model_components/sku_effects.py +52 -0
  17. pypricing-0.0.1/src/pypricing/models/__init__.py +11 -0
  18. pypricing-0.0.1/src/pypricing/models/basic.py +738 -0
  19. pypricing-0.0.1/src/pypricing/models/log_log.py +86 -0
  20. pypricing-0.0.1/src/pypricing/models/quadratic_log.py +115 -0
  21. pypricing-0.0.1/src/pypricing/models/sigmoid_saturation.py +126 -0
  22. pypricing-0.0.1/src/pypricing/optimizer.py +258 -0
  23. pypricing-0.0.1/src/pypricing/plotting.py +837 -0
  24. pypricing-0.0.1/src/pypricing/posterior.py +98 -0
  25. pypricing-0.0.1/src/pypricing/py.typed +0 -0
  26. pypricing-0.0.1/src/pypricing/synthetic_data.py +734 -0
  27. pypricing-0.0.1/src/pypricing.egg-info/PKG-INFO +371 -0
  28. pypricing-0.0.1/src/pypricing.egg-info/SOURCES.txt +29 -0
  29. pypricing-0.0.1/src/pypricing.egg-info/dependency_links.txt +1 -0
  30. pypricing-0.0.1/src/pypricing.egg-info/requires.txt +20 -0
  31. pypricing-0.0.1/src/pypricing.egg-info/top_level.txt +1 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,371 @@
1
+ Metadata-Version: 2.4
2
+ Name: pypricing
3
+ Version: 0.0.1
4
+ Summary: Bayesian price analytics with PyMC
5
+ Author-email: Arthur Mello <arthur.bmello@gmail.com>
6
+ Maintainer-email: Arthur Mello <arthur.bmello@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/arthurmello/pypricing
9
+ Project-URL: Documentation, https://pypricing.readthedocs.io
10
+ Project-URL: Repository, https://github.com/arthurmello/pypricing
11
+ Project-URL: Issues, https://github.com/arthurmello/pypricing/issues
12
+ Keywords: bayesian,demand,elasticity,pricing,pymc
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering
24
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: arviz>=0.17
30
+ Requires-Dist: matplotlib>=3.7
31
+ Requires-Dist: numpy>=1.24
32
+ Requires-Dist: pandas>=2.0
33
+ Requires-Dist: pymc>=5.0
34
+ Requires-Dist: pymc-marketing>=0.19.0
35
+ Requires-Dist: scipy>=1.10
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=7.0; extra == "dev"
38
+ Requires-Dist: ruff>=0.15.7; extra == "dev"
39
+ Provides-Extra: docs
40
+ Requires-Dist: sphinx>=7.0; extra == "docs"
41
+ Requires-Dist: myst-nb>=1.0; extra == "docs"
42
+ Requires-Dist: furo>=2024.1.29; extra == "docs"
43
+ Requires-Dist: sphinx-copybutton>=0.5; extra == "docs"
44
+ Provides-Extra: graphviz
45
+ Requires-Dist: graphviz>=0.21; extra == "graphviz"
46
+ Dynamic: license-file
47
+
48
+ # pypricing
49
+
50
+ Bayesian own-price elasticity estimation with PyMC for long-format panels (one row per SKU–time observation).
51
+
52
+ This is currently an MVP for log-demand panels (per-SKU intercept + per-SKU elasticity) with:
53
+
54
+ - optional **shared control** regressors (`control_`* columns)
55
+ - optional **hierarchical / partial pooling** across group columns
56
+ - optional **cross-price elasticities** (`CrossElasticitySpec`)
57
+ - simple diagnostics + plotting helpers
58
+ - posterior predictive simulation for counterfactual price scenarios
59
+ - per-SKU **revenue price optimization** (`optimize_prices`)
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pip install pypricing
65
+ ```
66
+
67
+ Optional model-graph rendering (also needs the [system Graphviz](https://graphviz.org/download/) binaries):
68
+
69
+ ```bash
70
+ pip install 'pypricing[graphviz]'
71
+ ```
72
+
73
+ Docs: [pypricing.readthedocs.io](https://pypricing.readthedocs.io)
74
+
75
+ ### Development
76
+
77
+ From a clone of this repository:
78
+
79
+ ```bash
80
+ uv sync --extra dev
81
+ uv run pytest
82
+ ```
83
+
84
+ For local docs builds: `uv sync --extra docs`.
85
+
86
+ ## Quickstart
87
+
88
+ ```python
89
+ import numpy as np
90
+
91
+ from pypricing import LogLogDemandModel, generate_mock_data
92
+
93
+ # 1) Example data (replace with your own panel)
94
+ df = generate_mock_data(
95
+ n_periods=20,
96
+ n_skus=5,
97
+ n_controls=2, # creates control_1, control_2
98
+ random_state=0,
99
+ )
100
+
101
+ # 2) Fit
102
+ model = LogLogDemandModel()
103
+ idata = model.fit(
104
+ df,
105
+ draws=1000,
106
+ tune=1000,
107
+ chains=4,
108
+ random_seed=42,
109
+ )
110
+
111
+ print(model.run_diagnostics())
112
+ print(model.fit_summary().head())
113
+
114
+ # 3) Counterfactual prediction (quantity column not required)
115
+ df_scenario = df.drop(columns=["quantity"]).copy()
116
+ df_scenario["price"] = df_scenario["price"] * 1.05 # +5% price scenario
117
+
118
+ pred = model.predict(df_scenario, hdi_prob=0.9, random_seed=123)
119
+ print(pred[["sku", "period", "price", "quantity_mean", "quantity_hdi_lower", "quantity_hdi_upper"]].head())
120
+
121
+ # 4) Plots
122
+ _ = model.plot_elasticity_posterior(hdi_prob=0.9)
123
+
124
+ sku0 = model.sku_levels_[0]
125
+ price_grid = np.linspace(df["price"].min(), df["price"].max(), 25)
126
+ controls = {c: float(df.loc[df["sku"] == sku0, c].iloc[0]) for c in model.control_names_}
127
+ _ = model.plot_response_curve(sku=sku0, price_grid=price_grid, controls=controls, hdi_prob=0.9)
128
+ ```
129
+
130
+ ## Data format
131
+
132
+ `LogLogDemandModel.fit(df)` expects a pandas DataFrame with **level-scale** columns:
133
+
134
+ - **Required**
135
+ - `sku` (configurable via `sku_col`)
136
+ - `price` (configurable via `price_col`) — must be **strictly positive**
137
+ - `quantity` (configurable via `quantity_col`) — must be **non-negative**
138
+ - **Optional**
139
+ - `control_`* columns (or pass an explicit `control_columns=(...)` via `PanelColumns`) — must be numeric, no NaNs
140
+ - hierarchy columns (e.g. `category_1`, `category_2`) via `PanelColumns(group_columns=...)`
141
+ - `period` (and often `region`) for `fit_train_test()` / cross-elasticity market cells
142
+
143
+ Internally the model works on logs:
144
+
145
+ - `log_price = log(price)`
146
+ - `log_quantity = log(max(quantity, quantity_floor))`
147
+
148
+ The default `quantity_floor=1.0` allows zero quantities without \log(0).
149
+
150
+ ## What model is being fit?
151
+
152
+ At a high level this package fits **log-demand** with Gaussian noise:
153
+
154
+
155
+ \log Q \sim \mathcal{N}(\mu, \sigma)
156
+
157
+
158
+ Where \mu is a per-SKU demand curve plus optional global control effects.
159
+
160
+ ### Demand curve model classes
161
+
162
+ Pick the model class directly:
163
+
164
+ - `LogLogDemandModel` (default/simple)
165
+ - `QuadraticLogDemandModel`
166
+ - `SigmoidSaturationDemandModel`
167
+
168
+ #### `log_log` (default)
169
+
170
+ Constant elasticity log-log:
171
+
172
+
173
+ $\mu = \alpha_{\text{sku}} + \epsilon_{\text{sku}} \log P + X\beta$
174
+
175
+
176
+ - **Interpretation**: \epsilon_{\text{sku}} is own-price elasticity.
177
+ - Example: \epsilon=-1.5 implies a 1% price increase → ~1.5% quantity decrease (locally / in expectation).
178
+ - **Best when**: you want a simple constant-elasticity approximation.
179
+
180
+ #### `quadratic`
181
+
182
+ Allows elasticity to vary with price (curvature in log-price):
183
+
184
+
185
+ $\mu = \alpha_{\text{sku}} + \beta_{1,\text{sku}}\log P + c_{\text{sku}} (\log P)^2 + X\beta$
186
+
187
+
188
+ This parameterization enforces that the elasticity at a **per-SKU midpoint price** equals `elasticity_sku`.
189
+ The midpoint is computed from the training data as the **median** log-price per SKU.
190
+
191
+ - **Best when**: elasticity changes with price level (e.g., premium vs discount regimes).
192
+
193
+ #### `sigmoid`
194
+
195
+ Saturating response curve in **level price** (softplus / log-sigmoid form):
196
+
197
+
198
+ \mu = \alpha_{\text{sku}} - \mathrm{softplus}(b_{\text{sku}}(P - P_{\text{center,sku}})) + X\beta
199
+
200
+
201
+ The per-SKU **center** `P_{\text{center,sku}} = \exp(\texttt{log\_price\_center\_sku})` is a **learned** parameter.
202
+ Its prior is centered at the empirical per-SKU median log-price from training data (`log_price_midpoint_sku_`), with default `sigma=0.5`.
203
+ The curve is parameterized so the elasticity at `P_{\text{center,sku}}` equals `elasticity_sku` (via `b_sku = -2 * elasticity_sku / price_center_sku`).
204
+
205
+ - **Best when**: response “flattens out” at extreme prices (a simple saturation behavior).
206
+
207
+ ### Controls (`control_`*)
208
+
209
+ If your frame contains `control_*` columns (or you pass `control_columns=(...)`), the model includes a **shared** linear term X\beta:
210
+
211
+ - one global coefficient vector `beta_control` shared across all SKUs
212
+ - controls must also be provided at prediction time
213
+
214
+ ### Priors and customization (`model_config`)
215
+
216
+ You can override priors by passing `model_config` to each model class constructor.
217
+ Each entry uses:
218
+
219
+ ```python
220
+ {
221
+ "dist": <PyMC distribution constructor>,
222
+ "kwargs": { ... },
223
+ }
224
+ ```
225
+
226
+ Example:
227
+
228
+ ```python
229
+ import pymc as pm
230
+ from pypricing import QuadraticLogDemandModel
231
+
232
+ model = QuadraticLogDemandModel(
233
+ model_config={
234
+ "alpha_sku": {"dist": pm.Normal, "kwargs": {"mu": 0.0, "sigma": 1.0}},
235
+ "elasticity_sku": {"dist": pm.Normal, "kwargs": {"mu": -1.0, "sigma": 0.7}},
236
+ "sigma": {"dist": pm.HalfNormal, "kwargs": {"sigma": 0.3}},
237
+ # "curvature_sku": ... (only used by QuadraticLogDemandModel)
238
+ # "beta_control": ... (only used when you have controls)
239
+ }
240
+ )
241
+ ```
242
+
243
+ Defaults today:
244
+
245
+ - `alpha_sku ~ Normal(mu=6, sigma=2)`
246
+ - `elasticity_sku ~ Normal(mu=-1, sigma=2)`
247
+ - `sigma ~ HalfNormal(sigma=0.5)`
248
+ - `beta_control ~ Normal(mu=0, sigma=0.5)` (if controls exist)
249
+ - `curvature_sku ~ Normal(mu=0, sigma=0.2)` (only for `quadratic`)
250
+ - `log_price_center_sku ~ Normal(mu=log_price_midpoint_sku_, sigma=0.5)` (only for `sigmoid`)
251
+
252
+ ## Prediction
253
+
254
+ - `sample_posterior_predictive(df)` returns an `xarray.Dataset` with posterior draws for `log_quantity` and `quantity`.
255
+ - `predict(df)` returns a DataFrame with:
256
+ - `quantity_mean`
257
+ - `quantity_hdi_lower`
258
+ - `quantity_hdi_upper`
259
+
260
+ Prediction requires:
261
+
262
+ - `sku` and `price`
263
+ - all control columns used during fit (if any)
264
+ - `quantity` is **not** required
265
+
266
+ Unknown SKUs at prediction time raise an error (no cold-start handling yet).
267
+
268
+ ## Train/test evaluation (time-aware)
269
+
270
+ `fit_train_test(df, period_col="period", test_size=0.2, ...)`:
271
+
272
+ - holds out the **last** fraction of unique periods (to avoid time leakage)
273
+ - fits on train, predicts on test
274
+ - returns:
275
+ - `rmse` on `quantity_mean`
276
+ - `hdi_coverage`: fraction of true quantities inside the predicted HDI
277
+ - `test_predictions`: the prediction frame
278
+
279
+ ## Save / load
280
+
281
+ `<ModelClass>.save(path)` saves the model `InferenceData` to NetCDF (`.nc`) with model attrs.
282
+
283
+ `<ModelClass>.load(path)` restores the model from that NetCDF artifact and rebuilds the PyMC model.
284
+
285
+ ## Interpretation helper
286
+
287
+ `pypricing.posterior.summarize_quantity_multiplier_one_sku(...)` converts posterior elasticity draws into a posterior over relative quantity change for a price multiplier m via m^{\epsilon}.
288
+
289
+ For all SKUs at once, use the model method:
290
+
291
+ - `model.quantity_multiplier_summary(price_multiplier=..., hdi_prob=...)`
292
+ - returns one row per SKU with mean and HDI bounds of the quantity multiplier
293
+ - optionally, `model.quantity_multiplier_summary(..., return_draws=True)` returns
294
+ `(summary_df, draws_da)` where `draws_da` has dims `("chain", "draw", "sku")`
295
+
296
+ This is only valid for `LogLogDemandModel` (constant elasticity).
297
+
298
+ ## Price optimization
299
+
300
+ `optimize_prices` (also available as `model.optimize_prices(...)`) chooses one price per SKU that maximizes the posterior **mean** of revenue `price * exp(μ)`, where `μ` is the demand-curve mean log-quantity (same convention as prediction; residual `σ` is not folded into `exp(μ)`).
301
+
302
+ ```python
303
+ from pypricing import LogLogDemandModel, generate_mock_data
304
+
305
+ df = generate_mock_data(n_periods=20, n_skus=5, n_controls=1, random_state=0)
306
+ model = LogLogDemandModel()
307
+ model.fit(df, draws=500, tune=500, chains=2, random_seed=0)
308
+
309
+ price_bounds = {
310
+ sku: (float(g["price"].min() * 0.8), float(g["price"].max() * 1.3))
311
+ for sku, g in df.groupby("sku")
312
+ }
313
+ controls_df = (
314
+ df.groupby("sku", as_index=False)[model.control_names_].median()
315
+ )
316
+ opt = model.optimize_prices(price_bounds=price_bounds, controls_df=controls_df)
317
+ print(opt.head())
318
+ ```
319
+
320
+ Caveats:
321
+
322
+ - Optimization is **per-SKU and independent** (1D SciPy search on log-price within bounds).
323
+ - **Not supported** when `cross_elasticity` is enabled (revenue then depends on the full market cell).
324
+ - For `LogLogDemandModel`, expected revenue is proportional to `p^(1+ε)` draw-wise; if elasticity is roughly constant and `|ε| ≠ 1`, the optimum often sits on a **bound**.
325
+ - If the model was fit with controls, pass `controls_df` with one row per SKU.
326
+
327
+ See `docs/source/notebooks/quickstart.ipynb` for plots (`plot_revenue_vs_price`, `plot_optimization_summary`).
328
+
329
+ ## Hierarchy and cross-elasticity
330
+
331
+ Pass column mapping via `PanelColumns`:
332
+
333
+ ```python
334
+ from pypricing import CrossElasticitySpec, LogLogDemandModel, PanelColumns
335
+
336
+ model = LogLogDemandModel(
337
+ panel_columns=PanelColumns(group_columns=("category_1", "category_2")),
338
+ cross_elasticity=CrossElasticitySpec(mode="within_group", group_level=0),
339
+ )
340
+ ```
341
+
342
+ Omit `cross_elasticity` for own-price only. Use `mode="all"` for every directed SKU pair (no `group_level`).
343
+
344
+ ## What is NOT implemented (yet)
345
+
346
+ - Cold-start prediction for unseen SKUs
347
+ - Joint / cross-aware price optimization (use counterfactual prediction on a full market cell instead)
348
+
349
+ ## Documentation
350
+
351
+ Hosted docs (API + notebooks): [https://pypricing.readthedocs.io](https://pypricing.readthedocs.io)
352
+
353
+ To build HTML locally (Sphinx + notebooks, no notebook re-execution):
354
+
355
+ ```bash
356
+ uv sync --extra docs
357
+ cd docs && uv run make html
358
+ # open docs/build/html/index.html
359
+ ```
360
+
361
+ ## Development
362
+
363
+ ```bash
364
+ uv sync --extra dev
365
+ uv run pytest # unit + integration (default)
366
+ uv run pytest -m unit # fast only
367
+ uv run pytest -m integration # short MCMC smoke
368
+ uv run pytest -m recovery # parameter recovery (slower)
369
+ uv run ruff check src tests
370
+ ```
371
+