elastica 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- elastica-1.0.0/.gitignore +231 -0
- elastica-1.0.0/CHANGELOG.md +19 -0
- elastica-1.0.0/LICENSE +21 -0
- elastica-1.0.0/PKG-INFO +187 -0
- elastica-1.0.0/README.es.md +146 -0
- elastica-1.0.0/README.md +157 -0
- elastica-1.0.0/pyproject.toml +84 -0
- elastica-1.0.0/src/elastica/__init__.py +44 -0
- elastica-1.0.0/src/elastica/cli.py +211 -0
- elastica-1.0.0/src/elastica/data.py +189 -0
- elastica-1.0.0/src/elastica/dml.py +206 -0
- elastica-1.0.0/src/elastica/estimate.py +113 -0
- elastica-1.0.0/src/elastica/pricing.py +183 -0
- elastica-1.0.0/src/elastica/py.typed +0 -0
- elastica-1.0.0/src/elastica/simulate.py +98 -0
- elastica-1.0.0/tests/__init__.py +0 -0
- elastica-1.0.0/tests/test_cli.py +86 -0
- elastica-1.0.0/tests/test_data.py +135 -0
- elastica-1.0.0/tests/test_dml.py +90 -0
- elastica-1.0.0/tests/test_estimate.py +55 -0
- elastica-1.0.0/tests/test_package.py +5 -0
- elastica-1.0.0/tests/test_pricing.py +140 -0
- elastica-1.0.0/tests/test_simulate.py +60 -0
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
*.lcov
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
cover/
|
|
54
|
+
|
|
55
|
+
# Translations
|
|
56
|
+
*.mo
|
|
57
|
+
*.pot
|
|
58
|
+
|
|
59
|
+
# Django stuff:
|
|
60
|
+
*.log
|
|
61
|
+
local_settings.py
|
|
62
|
+
db.sqlite3
|
|
63
|
+
db.sqlite3-journal
|
|
64
|
+
|
|
65
|
+
# Flask stuff:
|
|
66
|
+
instance/
|
|
67
|
+
.webassets-cache
|
|
68
|
+
|
|
69
|
+
# Scrapy stuff:
|
|
70
|
+
.scrapy
|
|
71
|
+
|
|
72
|
+
# Sphinx documentation
|
|
73
|
+
docs/_build/
|
|
74
|
+
|
|
75
|
+
# PyBuilder
|
|
76
|
+
.pybuilder/
|
|
77
|
+
target/
|
|
78
|
+
|
|
79
|
+
# Jupyter Notebook
|
|
80
|
+
.ipynb_checkpoints
|
|
81
|
+
|
|
82
|
+
# IPython
|
|
83
|
+
profile_default/
|
|
84
|
+
ipython_config.py
|
|
85
|
+
|
|
86
|
+
# pyenv
|
|
87
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
88
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
89
|
+
# .python-version
|
|
90
|
+
|
|
91
|
+
# pipenv
|
|
92
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
93
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
94
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
95
|
+
# install all needed dependencies.
|
|
96
|
+
# Pipfile.lock
|
|
97
|
+
|
|
98
|
+
# uv
|
|
99
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
100
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
101
|
+
# commonly ignored for libraries.
|
|
102
|
+
# uv.lock
|
|
103
|
+
|
|
104
|
+
# poetry
|
|
105
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
106
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
107
|
+
# commonly ignored for libraries.
|
|
108
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
109
|
+
# poetry.lock
|
|
110
|
+
# poetry.toml
|
|
111
|
+
|
|
112
|
+
# pdm
|
|
113
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
114
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
115
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
116
|
+
# pdm.lock
|
|
117
|
+
# pdm.toml
|
|
118
|
+
.pdm-python
|
|
119
|
+
.pdm-build/
|
|
120
|
+
|
|
121
|
+
# pixi
|
|
122
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
123
|
+
# pixi.lock
|
|
124
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
125
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
126
|
+
.pixi/*
|
|
127
|
+
!.pixi/config.toml
|
|
128
|
+
|
|
129
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
130
|
+
__pypackages__/
|
|
131
|
+
|
|
132
|
+
# Celery stuff
|
|
133
|
+
celerybeat-schedule*
|
|
134
|
+
celerybeat.pid
|
|
135
|
+
|
|
136
|
+
# Redis
|
|
137
|
+
*.rdb
|
|
138
|
+
*.aof
|
|
139
|
+
*.pid
|
|
140
|
+
|
|
141
|
+
# RabbitMQ
|
|
142
|
+
mnesia/
|
|
143
|
+
rabbitmq/
|
|
144
|
+
rabbitmq-data/
|
|
145
|
+
|
|
146
|
+
# ActiveMQ
|
|
147
|
+
activemq-data/
|
|
148
|
+
|
|
149
|
+
# SageMath parsed files
|
|
150
|
+
*.sage.py
|
|
151
|
+
|
|
152
|
+
# Environments
|
|
153
|
+
.env
|
|
154
|
+
.envrc
|
|
155
|
+
.venv
|
|
156
|
+
env/
|
|
157
|
+
venv/
|
|
158
|
+
ENV/
|
|
159
|
+
env.bak/
|
|
160
|
+
venv.bak/
|
|
161
|
+
|
|
162
|
+
# Spyder project settings
|
|
163
|
+
.spyderproject
|
|
164
|
+
.spyproject
|
|
165
|
+
|
|
166
|
+
# Rope project settings
|
|
167
|
+
.ropeproject
|
|
168
|
+
|
|
169
|
+
# mkdocs documentation
|
|
170
|
+
/site
|
|
171
|
+
|
|
172
|
+
# mypy
|
|
173
|
+
.mypy_cache/
|
|
174
|
+
.dmypy.json
|
|
175
|
+
dmypy.json
|
|
176
|
+
|
|
177
|
+
# Pyre type checker
|
|
178
|
+
.pyre/
|
|
179
|
+
|
|
180
|
+
# pytype static type analyzer
|
|
181
|
+
.pytype/
|
|
182
|
+
|
|
183
|
+
# Cython debug symbols
|
|
184
|
+
cython_debug/
|
|
185
|
+
|
|
186
|
+
# PyCharm
|
|
187
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
188
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
189
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
190
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
191
|
+
# .idea/
|
|
192
|
+
|
|
193
|
+
# Abstra
|
|
194
|
+
# Abstra is an AI-powered process automation framework.
|
|
195
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
196
|
+
# Learn more at https://abstra.io/docs
|
|
197
|
+
.abstra/
|
|
198
|
+
|
|
199
|
+
# Visual Studio Code
|
|
200
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
|
|
201
|
+
# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
202
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer, you
|
|
203
|
+
# could uncomment the following to ignore the entire vscode folder
|
|
204
|
+
# .vscode/
|
|
205
|
+
# Temporary file for partial code execution
|
|
206
|
+
tempCodeRunnerFile.py
|
|
207
|
+
|
|
208
|
+
# Ruff stuff:
|
|
209
|
+
.ruff_cache/
|
|
210
|
+
|
|
211
|
+
# PyPI configuration file
|
|
212
|
+
.pypirc
|
|
213
|
+
|
|
214
|
+
# Marimo
|
|
215
|
+
marimo/_static/
|
|
216
|
+
marimo/_lsp/
|
|
217
|
+
__marimo__/
|
|
218
|
+
|
|
219
|
+
# Streamlit
|
|
220
|
+
.streamlit/secrets.toml
|
|
221
|
+
|
|
222
|
+
# --- Workspace additions ---
|
|
223
|
+
# macOS
|
|
224
|
+
.DS_Store
|
|
225
|
+
# Editors
|
|
226
|
+
.vscode/
|
|
227
|
+
.idea/
|
|
228
|
+
# Secrets (commit .env.example only)
|
|
229
|
+
.env
|
|
230
|
+
.env.*
|
|
231
|
+
!.env.example
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## [1.0.0] - 2026-10-26
|
|
6
|
+
|
|
7
|
+
First public release.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Double machine learning estimator for the partially linear model with cross-fitting (random or time-blocked folds), repeated splits, orthogonal-score standard errors, naive and linear-OLS benchmarks and identification diagnostics.
|
|
12
|
+
- Transaction loading with column mapping, validation, aggregation to day / week / month and calendar features.
|
|
13
|
+
- Per-product and pooled (fixed effects) estimation.
|
|
14
|
+
- Price recommendations: Lerner rule, guard band around the current price, price range from the confidence interval, expected quantity / revenue / profit change, plain-language warnings.
|
|
15
|
+
- Synthetic data generator with known elasticities and non-linear confounding.
|
|
16
|
+
- `elastica` CLI with `simulate`, `estimate` and `price`.
|
|
17
|
+
- Reproducible benchmark (`examples/benchmark.py`).
|
|
18
|
+
|
|
19
|
+
[1.0.0]: https://github.com/DiegoTepichin/elastica/releases/tag/v1.0.0
|
elastica-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Diego Tepichin
|
|
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.
|
elastica-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: elastica
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Causal price elasticity from transaction data with double machine learning, and the profit-maximizing price that follows.
|
|
5
|
+
Project-URL: Homepage, https://github.com/DiegoTepichin/elastica
|
|
6
|
+
Project-URL: Repository, https://github.com/DiegoTepichin/elastica
|
|
7
|
+
Project-URL: Issues, https://github.com/DiegoTepichin/elastica/issues
|
|
8
|
+
Author: Diego Tepichin
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: causal inference,demand,dml,double machine learning,econometrics,price elasticity,pricing,scikit-learn
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Office/Business
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Requires-Dist: numpy>=1.26
|
|
26
|
+
Requires-Dist: pandas>=2.2
|
|
27
|
+
Requires-Dist: scikit-learn>=1.5
|
|
28
|
+
Requires-Dist: threadpoolctl>=3.1
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# elastica
|
|
32
|
+
|
|
33
|
+
Estimate how price-sensitive your customers really are from plain sales data, with double machine learning, and turn that into a price recommendation you can defend.
|
|
34
|
+
|
|
35
|
+
[](https://github.com/DiegoTepichin/elastica/actions/workflows/ci.yml)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
|
|
38
|
+
[Leer en español](README.es.md)
|
|
39
|
+
|
|
40
|
+

|
|
41
|
+
|
|
42
|
+
## Why
|
|
43
|
+
|
|
44
|
+
The usual way to measure price elasticity, regressing log quantity on log price, is wrong whenever something moves price and demand together. Retailers raise prices in high season, when demand is high anyway, so the naive slope says customers barely react to price. In the benchmark above it is not just off: for many products it comes out **positive**.
|
|
45
|
+
|
|
46
|
+
`elastica` removes that confounding with double machine learning (Chernozhukov et al., 2018): it predicts both price and demand from the calendar and your controls with gradient boosting, then estimates the elasticity from what is left. You get a confidence interval, diagnostics that tell you when not to trust the number, and a price recommendation that stays close to the prices you have actually tried.
|
|
47
|
+
|
|
48
|
+
## Benchmark
|
|
49
|
+
|
|
50
|
+
`examples/benchmark.py` simulates 50 products with a known elasticity, seasonality and two week-long sales peaks that raise both price and demand, then compares three estimators on the same data:
|
|
51
|
+
|
|
52
|
+
| Method | Mean absolute error | Mean bias |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| Naive OLS (log q on log p) | 1.59 | +1.59 |
|
|
55
|
+
| OLS + the same controls, linear | 0.55 | +0.55 |
|
|
56
|
+
| **elastica (DML)** | **0.12** | **+0.09** |
|
|
57
|
+
|
|
58
|
+
elastica's 95 % confidence interval contains the true value in 80 % of runs. The shortfall from 95 % comes from the sharp sales peaks: with two years of daily data the nuisance models cannot fully learn them, which leaves a small bias toward zero. Without the peaks, coverage is 19 of 20 runs. Reproduce it with `uv run --group docs python examples/benchmark.py`.
|
|
59
|
+
|
|
60
|
+
## Install
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install elastica
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Requires Python 3.11+. Dependencies: numpy, pandas, scikit-learn.
|
|
67
|
+
|
|
68
|
+
## Quickstart
|
|
69
|
+
|
|
70
|
+
Generate a demo dataset with known answers, then estimate and price (from a clone of this repository, prefix each command with `uv run`):
|
|
71
|
+
|
|
72
|
+
```text
|
|
73
|
+
$ elastica simulate -o sales.csv
|
|
74
|
+
true elasticities: SKU-001 -2.2, SKU-002 -1.87, SKU-003 -1.53, SKU-004 -1.2
|
|
75
|
+
|
|
76
|
+
$ elastica estimate sales.csv --controls promo
|
|
77
|
+
Product Elasticity 95% CI low 95% CI high Naive Periods
|
|
78
|
+
------- ---------- ---------- ----------- ----- -------
|
|
79
|
+
SKU-001 -2.02 -2.23 -1.81 -0.55 730
|
|
80
|
+
SKU-002 -1.77 -1.97 -1.58 -0.32 730
|
|
81
|
+
SKU-003 -1.47 -1.66 -1.27 -0.05 730
|
|
82
|
+
SKU-004 -1.07 -1.26 -0.89 0.35 730
|
|
83
|
+
|
|
84
|
+
$ elastica price sales.csv --controls promo --cost unit_cost
|
|
85
|
+
Product Elasticity Current Recommended Range low Range high Profit Revenue
|
|
86
|
+
------- ---------- ------- ----------- --------- ---------- ------ -------
|
|
87
|
+
SKU-001 -2.02 105.34 109.15 99.95 123.10 +0.1% -3.6%
|
|
88
|
+
SKU-002 -1.77 67.42 72.35 64.06 80.91 +0.4% -5.3%
|
|
89
|
+
SKU-003 -1.47 128.62 154.35 146.68 154.35 +4.6% -8.1%
|
|
90
|
+
SKU-004 -1.07 96.10 115.33 115.33 115.33 +13.1% -1.3%
|
|
91
|
+
|
|
92
|
+
SKU-003: price capped at the top of the band; consider testing a wider band in small steps
|
|
93
|
+
|
|
94
|
+
SKU-004: the confidence interval includes -1; elastic vs inelastic is uncertain; price capped at the top of the band; consider testing a wider band in small steps
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
*Range* is the recommended price at each end of the elasticity's confidence interval. *Profit* and *Revenue* are the expected changes per period if the model's assumptions hold.
|
|
98
|
+
|
|
99
|
+
## Your data
|
|
100
|
+
|
|
101
|
+
One row per sale or per product and day, in CSV or Parquet. Only three columns are required; name them however you like:
|
|
102
|
+
|
|
103
|
+
| Field | Flag | Required | Notes |
|
|
104
|
+
|---|---|---|---|
|
|
105
|
+
| Date | `--date` | yes | Any format pandas can parse. |
|
|
106
|
+
| Price | `--price` | yes | Unit price actually paid. |
|
|
107
|
+
| Quantity | `--quantity` | yes | Units sold. |
|
|
108
|
+
| Product | `--product` | no | Pass `--product ''` if the file has a single product. |
|
|
109
|
+
| Unit cost | `--cost` | no | Needed for profit-maximizing prices; or pass `--unit-cost 42` for all products. |
|
|
110
|
+
| Controls | `--controls a,b` | no | Anything else that moves price or demand: promotions, store, channel, stock-outs. Text columns are one-hot encoded. |
|
|
111
|
+
|
|
112
|
+
Rows are aggregated to product × day (`--frequency W` or `M` for weekly or monthly) with a quantity-weighted price. Calendar features (trend, month, day of year, week of year, day of week) are added automatically. Periods with zero sales are dropped and counted.
|
|
113
|
+
|
|
114
|
+
## How it works
|
|
115
|
+
|
|
116
|
+
For each product, on log-log data:
|
|
117
|
+
|
|
118
|
+
```
|
|
119
|
+
log q = θ · log p + g(X) + ε θ is the elasticity
|
|
120
|
+
log p = m(X) + v
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
1. **Cross-fitting.** `g` and `m` are learned with gradient boosting on K−1 folds and predicted on the held-out fold, so no observation is predicted by a model that saw it.
|
|
124
|
+
2. **Partialling out.** `θ` is the slope of the outcome residuals on the price residuals: the part of price variation the calendar and controls cannot explain.
|
|
125
|
+
3. **Inference.** Standard errors come from the Neyman-orthogonal score; the whole procedure is repeated with new splits (3 by default) and aggregated by the median.
|
|
126
|
+
4. **Pricing.** Demand is treated as constant-elasticity around the current price, so the profit-maximizing price is `cost · θ / (1 + θ)` when `θ < −1`. The result is clamped to a band around the current price (default 80 %–120 %), because the approximation is only reliable near prices you have observed.
|
|
127
|
+
|
|
128
|
+
Every estimate reports the naive slope and an OLS with linear controls next to the DML estimate, plus the cross-fitted R² of both nuisance models.
|
|
129
|
+
|
|
130
|
+
### Warnings you may see
|
|
131
|
+
|
|
132
|
+
| Warning | Meaning |
|
|
133
|
+
|---|---|
|
|
134
|
+
| weakly identified | The controls explain almost all price changes. There is too little independent price variation to learn from; run a price test. |
|
|
135
|
+
| positive elasticity | Demand rises with price. A confounder is probably missing from `--controls`. |
|
|
136
|
+
| confidence interval includes −1 | The data cannot tell elastic from inelastic demand, so the direction of the optimal price change is uncertain. |
|
|
137
|
+
| capped at the band | The optimum is outside the prices you have tried. Move toward it in small, measured steps. |
|
|
138
|
+
|
|
139
|
+
## Python API
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
import elastica
|
|
143
|
+
|
|
144
|
+
sim = elastica.simulate()
|
|
145
|
+
panel = elastica.prepare(sim.transactions, elastica.Schema(cost="unit_cost", controls=("promo",)))
|
|
146
|
+
|
|
147
|
+
for item in elastica.estimate(panel):
|
|
148
|
+
r = item.result
|
|
149
|
+
rec = elastica.recommend(item)
|
|
150
|
+
print(
|
|
151
|
+
f"{item.product}: {r.elasticity:.2f} [{r.ci_low:.2f}, {r.ci_high:.2f}] naive {r.naive_elasticity:+.2f} -> {rec.current_price:.2f} to {rec.recommended_price:.2f} ({rec.reason})"
|
|
152
|
+
)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
```text
|
|
156
|
+
SKU-001: -2.02 [-2.23, -1.81] naive -0.55 -> 105.34 to 109.15 (optimum inside the band)
|
|
157
|
+
SKU-002: -1.77 [-1.97, -1.58] naive -0.32 -> 67.42 to 72.35 (optimum inside the band)
|
|
158
|
+
SKU-003: -1.47 [-1.66, -1.27] naive -0.05 -> 128.62 to 154.35 (capped at the top of the band)
|
|
159
|
+
SKU-004: -1.07 [-1.26, -0.89] naive +0.35 -> 96.10 to 115.33 (capped at the top of the band)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
More:
|
|
163
|
+
|
|
164
|
+
- `elastica.estimate(panel, pooled=True)`: one estimate across products with product fixed effects, for SKUs with little history.
|
|
165
|
+
- `elastica.EstimateOptions(learner=..., folds=Folds.TIME, n_folds=5, n_repeats=3, confidence=0.9)`: any scikit-learn regressor works as `learner`. Time-blocked folds are more conservative and need about three seasons of history.
|
|
166
|
+
- `elastica.estimate_elasticity(y, d, x)`: the estimator on raw arrays.
|
|
167
|
+
- `elastica.demand_curve(...)`, `estimates_frame`, `recommendations_frame`: tables for plotting and reporting.
|
|
168
|
+
|
|
169
|
+
## Limits
|
|
170
|
+
|
|
171
|
+
- Causal only under the usual assumption: everything that moves both price and demand is in the date or in `--controls`. If a competitor's price drives yours and is not in the data, the estimate is biased.
|
|
172
|
+
- Own-price elasticity only; cross-price effects and substitution between products are not modelled.
|
|
173
|
+
- The price recommendation is a starting point for a test, not an order.
|
|
174
|
+
|
|
175
|
+
## Development
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
uv sync
|
|
179
|
+
uv run pytest
|
|
180
|
+
uv run ruff check . && uv run ruff format --check . && uv run mypy .
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
184
|
+
|
|
185
|
+
## License
|
|
186
|
+
|
|
187
|
+
[MIT](LICENSE) © Diego Tepichin
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# elastica
|
|
2
|
+
|
|
3
|
+
Estima qué tan sensibles al precio son realmente tus clientes a partir de datos de ventas comunes, con double machine learning, y conviértelo en una recomendación de precio que puedas defender.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/DiegoTepichin/elastica/actions/workflows/ci.yml)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
[Read in English](README.md)
|
|
9
|
+
|
|
10
|
+

|
|
11
|
+
|
|
12
|
+
## Por qué
|
|
13
|
+
|
|
14
|
+
La forma habitual de medir la elasticidad precio, una regresión de log cantidad contra log precio, falla siempre que algo mueve precio y demanda al mismo tiempo. Los comercios suben precios en temporada alta, cuando la demanda ya es alta, así que la pendiente ingenua dice que los clientes casi no reaccionan al precio. En el benchmark de arriba no solo se equivoca: para muchos productos sale **positiva**.
|
|
15
|
+
|
|
16
|
+
`elastica` elimina esa confusión con double machine learning (Chernozhukov et al., 2018): predice precio y demanda a partir del calendario y de tus controles con gradient boosting, y estima la elasticidad con lo que queda. Obtienes un intervalo de confianza, diagnósticos que te dicen cuándo no confiar en el número y una recomendación de precio que no se aleja de los precios que de verdad has probado.
|
|
17
|
+
|
|
18
|
+
## Benchmark
|
|
19
|
+
|
|
20
|
+
`examples/benchmark.py` simula 50 productos con elasticidad conocida, estacionalidad y dos picos de ventas de una semana que suben precio y demanda, y compara tres estimadores sobre los mismos datos:
|
|
21
|
+
|
|
22
|
+
| Método | Error absoluto medio | Sesgo medio |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| OLS ingenuo (log q contra log p) | 1.59 | +1.59 |
|
|
25
|
+
| OLS + los mismos controles, lineales | 0.55 | +0.55 |
|
|
26
|
+
| **elastica (DML)** | **0.12** | **+0.09** |
|
|
27
|
+
|
|
28
|
+
El intervalo de confianza al 95 % de elastica contiene el valor real en el 80 % de las corridas. La diferencia contra 95 % viene de los picos de ventas: con dos años de datos diarios los modelos auxiliares no los aprenden del todo, lo que deja un sesgo pequeño hacia cero. Sin los picos, la cobertura es de 19 de 20 corridas. Reprodúcelo con `uv run --group docs python examples/benchmark.py`.
|
|
29
|
+
|
|
30
|
+
## Instalación
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install elastica
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Requiere Python 3.11 o superior. Dependencias: numpy, pandas, scikit-learn.
|
|
37
|
+
|
|
38
|
+
## Inicio rápido
|
|
39
|
+
|
|
40
|
+
Genera datos de ejemplo con respuestas conocidas y después estima y calcula precios (desde un clon de este repositorio, antepón `uv run` a cada comando):
|
|
41
|
+
|
|
42
|
+
```text
|
|
43
|
+
$ elastica simulate -o sales.csv
|
|
44
|
+
true elasticities: SKU-001 -2.2, SKU-002 -1.87, SKU-003 -1.53, SKU-004 -1.2
|
|
45
|
+
|
|
46
|
+
$ elastica estimate sales.csv --controls promo
|
|
47
|
+
Product Elasticity 95% CI low 95% CI high Naive Periods
|
|
48
|
+
------- ---------- ---------- ----------- ----- -------
|
|
49
|
+
SKU-001 -2.02 -2.23 -1.81 -0.55 730
|
|
50
|
+
SKU-002 -1.77 -1.97 -1.58 -0.32 730
|
|
51
|
+
SKU-003 -1.47 -1.66 -1.27 -0.05 730
|
|
52
|
+
SKU-004 -1.07 -1.26 -0.89 0.35 730
|
|
53
|
+
|
|
54
|
+
$ elastica price sales.csv --controls promo --cost unit_cost
|
|
55
|
+
Product Elasticity Current Recommended Range low Range high Profit Revenue
|
|
56
|
+
------- ---------- ------- ----------- --------- ---------- ------ -------
|
|
57
|
+
SKU-001 -2.02 105.34 109.15 99.95 123.10 +0.1% -3.6%
|
|
58
|
+
SKU-002 -1.77 67.42 72.35 64.06 80.91 +0.4% -5.3%
|
|
59
|
+
SKU-003 -1.47 128.62 154.35 146.68 154.35 +4.6% -8.1%
|
|
60
|
+
SKU-004 -1.07 96.10 115.33 115.33 115.33 +13.1% -1.3%
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
*Range* es el precio recomendado en cada extremo del intervalo de confianza de la elasticidad. *Profit* y *Revenue* son los cambios esperados por periodo en utilidad e ingreso si se cumplen los supuestos del modelo.
|
|
64
|
+
|
|
65
|
+
## Tus datos
|
|
66
|
+
|
|
67
|
+
Una fila por venta o por producto y día, en CSV o Parquet. Solo tres columnas son obligatorias y pueden llamarse como quieras:
|
|
68
|
+
|
|
69
|
+
| Campo | Opción | Obligatorio | Notas |
|
|
70
|
+
|---|---|---|---|
|
|
71
|
+
| Fecha | `--date` | sí | Cualquier formato que pandas entienda. |
|
|
72
|
+
| Precio | `--price` | sí | Precio unitario pagado. |
|
|
73
|
+
| Cantidad | `--quantity` | sí | Unidades vendidas. |
|
|
74
|
+
| Producto | `--product` | no | Usa `--product ''` si el archivo tiene un solo producto. |
|
|
75
|
+
| Costo unitario | `--cost` | no | Necesario para maximizar utilidad; o `--unit-cost 42` para todos los productos. |
|
|
76
|
+
| Controles | `--controls a,b` | no | Todo lo demás que mueva precio o demanda: promociones, tienda, canal, quiebres de inventario. Las columnas de texto se codifican one-hot. |
|
|
77
|
+
|
|
78
|
+
Las filas se agregan a producto × día (`--frequency W` o `M` para semanal o mensual) con un precio ponderado por cantidad. Las variables de calendario (tendencia, mes, día del año, semana del año, día de la semana) se agregan solas. Los periodos sin ventas se descartan y se cuentan.
|
|
79
|
+
|
|
80
|
+
## Cómo funciona
|
|
81
|
+
|
|
82
|
+
Para cada producto, en logaritmos:
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
log q = θ · log p + g(X) + ε θ es la elasticidad
|
|
86
|
+
log p = m(X) + v
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
1. **Cross-fitting.** `g` y `m` se aprenden con gradient boosting en K−1 particiones y se predicen en la que quedó fuera, así ninguna observación la predice un modelo que la vio.
|
|
90
|
+
2. **Partialling out.** `θ` es la pendiente de los residuos de la demanda contra los residuos del precio: la parte de la variación del precio que el calendario y los controles no explican.
|
|
91
|
+
3. **Inferencia.** Los errores estándar salen del score ortogonal de Neyman; todo el procedimiento se repite con nuevas particiones (3 por defecto) y se agrega con la mediana.
|
|
92
|
+
4. **Precio.** La demanda se aproxima con elasticidad constante alrededor del precio actual, así que el precio que maximiza la utilidad es `costo · θ / (1 + θ)` cuando `θ < −1`. El resultado se limita a una banda alrededor del precio actual (80 %–120 % por defecto), porque la aproximación solo es confiable cerca de los precios observados.
|
|
93
|
+
|
|
94
|
+
Cada estimación reporta junto al DML la pendiente ingenua y un OLS con controles lineales, más el R² con cross-fitting de ambos modelos auxiliares.
|
|
95
|
+
|
|
96
|
+
### Advertencias que puedes ver
|
|
97
|
+
|
|
98
|
+
| Advertencia | Significado |
|
|
99
|
+
|---|---|
|
|
100
|
+
| weakly identified | Los controles explican casi todos los cambios de precio. Queda muy poca variación independiente para aprender; haz una prueba de precios. |
|
|
101
|
+
| positive elasticity | La demanda sube con el precio. Probablemente falta un confusor en `--controls`. |
|
|
102
|
+
| confidence interval includes −1 | Los datos no distinguen entre demanda elástica e inelástica; la dirección del cambio óptimo es incierta. |
|
|
103
|
+
| capped at the band | El óptimo está fuera de los precios que has probado. Acércate a él con pasos pequeños y medidos. |
|
|
104
|
+
|
|
105
|
+
## API de Python
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
import elastica
|
|
109
|
+
|
|
110
|
+
sim = elastica.simulate()
|
|
111
|
+
panel = elastica.prepare(sim.transactions, elastica.Schema(cost="unit_cost", controls=("promo",)))
|
|
112
|
+
|
|
113
|
+
for item in elastica.estimate(panel):
|
|
114
|
+
r = item.result
|
|
115
|
+
rec = elastica.recommend(item)
|
|
116
|
+
print(
|
|
117
|
+
f"{item.product}: {r.elasticity:.2f} [{r.ci_low:.2f}, {r.ci_high:.2f}] naive {r.naive_elasticity:+.2f} -> {rec.current_price:.2f} to {rec.recommended_price:.2f} ({rec.reason})"
|
|
118
|
+
)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Más:
|
|
122
|
+
|
|
123
|
+
- `elastica.estimate(panel, pooled=True)`: una sola estimación para todos los productos con efectos fijos por producto, para SKUs con poca historia.
|
|
124
|
+
- `elastica.EstimateOptions(learner=..., folds=Folds.TIME, n_folds=5, n_repeats=3, confidence=0.9)`: cualquier regresor de scikit-learn sirve como `learner`. Las particiones por bloques de tiempo son más conservadoras y necesitan unas tres temporadas de historia.
|
|
125
|
+
- `elastica.estimate_elasticity(y, d, x)`: el estimador sobre arreglos.
|
|
126
|
+
- `elastica.demand_curve(...)`, `estimates_frame`, `recommendations_frame`: tablas para graficar y reportar.
|
|
127
|
+
|
|
128
|
+
## Límites
|
|
129
|
+
|
|
130
|
+
- Es causal solo bajo el supuesto habitual: todo lo que mueve a la vez precio y demanda está en la fecha o en `--controls`. Si el precio de un competidor mueve el tuyo y no está en los datos, la estimación tiene sesgo.
|
|
131
|
+
- Solo elasticidad propia; no modela efectos cruzados ni sustitución entre productos.
|
|
132
|
+
- La recomendación de precio es el punto de partida de una prueba, no una orden.
|
|
133
|
+
|
|
134
|
+
## Desarrollo
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
uv sync
|
|
138
|
+
uv run pytest
|
|
139
|
+
uv run ruff check . && uv run ruff format --check . && uv run mypy .
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Ver [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
143
|
+
|
|
144
|
+
## Licencia
|
|
145
|
+
|
|
146
|
+
[MIT](LICENSE) © Diego Tepichin
|