elastica 1.0.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """Causal price elasticity with double machine learning."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from elastica.data import DataError, Frequency, Panel, Schema, prepare, read_transactions
6
+ from elastica.dml import DMLResult, Folds, estimate_elasticity
7
+ from elastica.estimate import EstimateOptions, ProductEstimate, estimate, estimates_frame
8
+ from elastica.pricing import (
9
+ PriceBand,
10
+ Recommendation,
11
+ demand_curve,
12
+ optimal_price,
13
+ recommend,
14
+ recommendations_frame,
15
+ )
16
+ from elastica.simulate import Simulation, SimulationConfig, simulate
17
+
18
+ __version__ = version("elastica")
19
+
20
+ __all__ = [
21
+ "DMLResult",
22
+ "DataError",
23
+ "EstimateOptions",
24
+ "Folds",
25
+ "Frequency",
26
+ "Panel",
27
+ "PriceBand",
28
+ "ProductEstimate",
29
+ "Recommendation",
30
+ "Schema",
31
+ "Simulation",
32
+ "SimulationConfig",
33
+ "__version__",
34
+ "demand_curve",
35
+ "estimate",
36
+ "estimate_elasticity",
37
+ "estimates_frame",
38
+ "optimal_price",
39
+ "prepare",
40
+ "read_transactions",
41
+ "recommend",
42
+ "recommendations_frame",
43
+ "simulate",
44
+ ]
elastica/cli.py ADDED
@@ -0,0 +1,211 @@
1
+ """`elastica` command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING
9
+
10
+ from elastica import __version__
11
+ from elastica.data import DataError, Frequency, Schema, prepare, read_transactions
12
+ from elastica.dml import Folds
13
+ from elastica.estimate import EstimateOptions, ProductEstimate, estimate, estimates_frame
14
+ from elastica.pricing import PriceBand, recommend, recommendations_frame
15
+ from elastica.simulate import SimulationConfig, simulate
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Callable, Sequence
19
+
20
+ import pandas as pd
21
+
22
+ EXIT_OK = 0
23
+ EXIT_FAILURE = 1
24
+
25
+
26
+ def main(argv: Sequence[str] | None = None) -> int:
27
+ args = _parser().parse_args(argv)
28
+ handler: Callable[[argparse.Namespace], int] = args.handler
29
+ try:
30
+ return handler(args)
31
+ except (DataError, ValueError) as exc:
32
+ print(f"error: {exc}", file=sys.stderr)
33
+ return EXIT_FAILURE
34
+
35
+
36
+ def _parser() -> argparse.ArgumentParser:
37
+ parser = argparse.ArgumentParser(
38
+ prog="elastica",
39
+ description="Estimate causal price elasticity with double ML and recommend prices.",
40
+ )
41
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
42
+ commands = parser.add_subparsers(required=True, metavar="COMMAND")
43
+
44
+ sim = commands.add_parser("simulate", help="write synthetic sales with known elasticities")
45
+ sim.add_argument("-o", "--output", type=Path, required=True, help="output .csv")
46
+ sim.add_argument("--products", type=int, default=4)
47
+ sim.add_argument("--days", type=int, default=730)
48
+ sim.add_argument("--seed", type=int, default=7)
49
+ sim.set_defaults(handler=_simulate)
50
+
51
+ est = commands.add_parser("estimate", help="estimate the price elasticity of each product")
52
+ _add_data_arguments(est)
53
+ est.add_argument("-o", "--output", type=Path, help="also write results to .csv")
54
+ est.set_defaults(handler=_estimate)
55
+
56
+ price = commands.add_parser("price", help="recommend a price for each product")
57
+ _add_data_arguments(price)
58
+ price.add_argument("--unit-cost", type=float, help="unit cost for every product")
59
+ price.add_argument(
60
+ "--band",
61
+ default="0.8,1.2",
62
+ help="lowest and highest price as multiples of the current one (default 0.8,1.2)",
63
+ )
64
+ price.add_argument("-o", "--output", type=Path, help="also write results to .csv")
65
+ price.set_defaults(handler=_price)
66
+ return parser
67
+
68
+
69
+ def _add_data_arguments(parser: argparse.ArgumentParser) -> None:
70
+ parser.add_argument("data", type=Path, help="transactions .csv or .parquet")
71
+ columns = parser.add_argument_group("columns")
72
+ columns.add_argument("--date", default="date")
73
+ columns.add_argument("--price", default="price")
74
+ columns.add_argument("--quantity", default="quantity")
75
+ columns.add_argument("--product", default="product", help="use '' for a single product")
76
+ columns.add_argument("--cost", help="column with the unit cost")
77
+ columns.add_argument("--controls", default="", help="comma-separated control columns")
78
+ model = parser.add_argument_group("model")
79
+ model.add_argument(
80
+ "--frequency", choices=[f.value for f in Frequency], default=Frequency.DAY.value
81
+ )
82
+ model.add_argument("--pooled", action="store_true", help="one estimate across products")
83
+ model.add_argument("--folds", choices=[f.value for f in Folds], default=Folds.RANDOM.value)
84
+ model.add_argument("--n-folds", type=int, default=5)
85
+ model.add_argument("--repeats", type=int, default=3)
86
+ model.add_argument("--confidence", type=float, default=0.95)
87
+ model.add_argument("--seed", type=int, default=0)
88
+
89
+
90
+ def _simulate(args: argparse.Namespace) -> int:
91
+ config = SimulationConfig(n_products=args.products, n_days=args.days, seed=args.seed)
92
+ sim = simulate(config)
93
+ sim.transactions.to_csv(args.output, index=False)
94
+ print(f"wrote {len(sim.transactions)} rows to {args.output}", file=sys.stderr)
95
+ print("true elasticities: " + ", ".join(f"{k} {v}" for k, v in sim.true_elasticity.items()))
96
+ return EXIT_OK
97
+
98
+
99
+ def _run_estimates(args: argparse.Namespace) -> list[ProductEstimate]:
100
+ schema = Schema(
101
+ date=args.date,
102
+ price=args.price,
103
+ quantity=args.quantity,
104
+ product=args.product or None,
105
+ cost=args.cost,
106
+ controls=tuple(c.strip() for c in args.controls.split(",") if c.strip()),
107
+ )
108
+ panel = prepare(read_transactions(args.data), schema, Frequency(args.frequency))
109
+ if panel.dropped:
110
+ print(f"dropped {panel.dropped} period(s) with zero sales or price", file=sys.stderr)
111
+ options = EstimateOptions(
112
+ folds=Folds(args.folds),
113
+ n_folds=args.n_folds,
114
+ n_repeats=args.repeats,
115
+ confidence=args.confidence,
116
+ seed=args.seed,
117
+ )
118
+ return estimate(panel, options, pooled=args.pooled)
119
+
120
+
121
+ def _estimate(args: argparse.Namespace) -> int:
122
+ estimates = _run_estimates(args)
123
+ frame = estimates_frame(estimates)
124
+ level = round(args.confidence * 100)
125
+ print(
126
+ render(
127
+ frame,
128
+ {
129
+ "product": "Product",
130
+ "elasticity": "Elasticity",
131
+ "ci_low": f"{level}% CI low",
132
+ "ci_high": f"{level}% CI high",
133
+ "naive_elasticity": "Naive",
134
+ "n_obs": "Periods",
135
+ },
136
+ )
137
+ )
138
+ _print_warnings(frame)
139
+ _write(frame, args.output)
140
+ return EXIT_OK if any(e.result for e in estimates) else EXIT_FAILURE
141
+
142
+
143
+ def _price(args: argparse.Namespace) -> int:
144
+ lower, upper = (float(v) for v in args.band.split(","))
145
+ band = PriceBand(lower, upper)
146
+ recommendations = [
147
+ recommend(e, unit_cost=args.unit_cost, band=band) for e in _run_estimates(args)
148
+ ]
149
+ frame = recommendations_frame(recommendations)
150
+ print(
151
+ render(
152
+ frame,
153
+ {
154
+ "product": "Product",
155
+ "elasticity": "Elasticity",
156
+ "current_price": "Current",
157
+ "recommended_price": "Recommended",
158
+ "price_low": "Range low",
159
+ "price_high": "Range high",
160
+ "profit_change": "Profit",
161
+ "revenue_change": "Revenue",
162
+ },
163
+ )
164
+ )
165
+ _print_warnings(frame)
166
+ _write(frame, args.output)
167
+ return EXIT_OK
168
+
169
+
170
+ PERCENT_COLUMNS = {"profit_change", "revenue_change", "quantity_change"}
171
+
172
+
173
+ def render(frame: pd.DataFrame, columns: dict[str, str]) -> str:
174
+ rows = [list(columns.values())]
175
+ for record in frame.to_dict("records"):
176
+ rows.append([_cell(name, record[name]) for name in columns])
177
+ widths = [max(len(row[i]) for row in rows) for i in range(len(columns))]
178
+ lines = []
179
+ for index, row in enumerate(rows):
180
+ cells = [row[0].ljust(widths[0])] + [
181
+ cell.rjust(width) for cell, width in zip(row[1:], widths[1:], strict=True)
182
+ ]
183
+ lines.append(" ".join(cells))
184
+ if index == 0:
185
+ lines.append(" ".join("-" * width for width in widths))
186
+ return "\n".join(lines)
187
+
188
+
189
+ def _cell(name: str, value: object) -> str:
190
+ if value is None or (isinstance(value, float) and value != value):
191
+ return "—"
192
+ if isinstance(value, float):
193
+ return f"{value:+.1%}" if name in PERCENT_COLUMNS else f"{value:,.2f}"
194
+ return str(value)
195
+
196
+
197
+ def _print_warnings(frame: pd.DataFrame) -> None:
198
+ sys.stdout.flush()
199
+ for record in frame.to_dict("records"):
200
+ if record["warnings"]:
201
+ print(f"\n{record['product']}: {record['warnings']}", file=sys.stderr)
202
+
203
+
204
+ def _write(frame: pd.DataFrame, output: Path | None) -> None:
205
+ if output is not None:
206
+ frame.to_csv(output, index=False)
207
+ print(f"wrote {output}", file=sys.stderr)
208
+
209
+
210
+ if __name__ == "__main__":
211
+ raise SystemExit(main())
elastica/data.py ADDED
@@ -0,0 +1,189 @@
1
+ """Turn raw transactions into a product x period panel ready for estimation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from enum import StrEnum
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ LOG_PRICE = "log_price"
13
+ LOG_QUANTITY = "log_quantity"
14
+ CALENDAR_FEATURES = ("trend", "month", "day_of_year", "week_sin", "week_cos")
15
+ DAILY_FEATURES = ("day_of_week",)
16
+ ALL_PRODUCTS = "all"
17
+
18
+
19
+ class DataError(ValueError):
20
+ """The input cannot be used for estimation; the message says why."""
21
+
22
+
23
+ class Frequency(StrEnum):
24
+ DAY = "D"
25
+ WEEK = "W"
26
+ MONTH = "M"
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Schema:
31
+ """Which input columns hold each field. Only date, price and quantity are required."""
32
+
33
+ date: str = "date"
34
+ price: str = "price"
35
+ quantity: str = "quantity"
36
+ product: str | None = "product"
37
+ cost: str | None = None
38
+ controls: tuple[str, ...] = ()
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class Panel:
43
+ frame: pd.DataFrame
44
+ """One row per product and period: product, period, price, quantity, log columns, features."""
45
+ features: tuple[str, ...]
46
+ frequency: Frequency
47
+ costs: dict[str, float] = field(default_factory=dict)
48
+ dropped: int = 0
49
+ """Periods dropped because their quantity or price was zero."""
50
+
51
+ @property
52
+ def products(self) -> list[str]:
53
+ return sorted(self.frame["product"].unique())
54
+
55
+ def for_product(self, product: str) -> pd.DataFrame:
56
+ return self.frame[self.frame["product"] == product]
57
+
58
+
59
+ def read_transactions(path: str | Path) -> pd.DataFrame:
60
+ file = Path(path)
61
+ if not file.exists():
62
+ raise DataError(f"{file} does not exist")
63
+ if file.suffix.lower() == ".parquet":
64
+ try:
65
+ return pd.read_parquet(file)
66
+ except ImportError as exc:
67
+ raise DataError("reading Parquet needs pyarrow: pip install pyarrow") from exc
68
+ return pd.read_csv(file)
69
+
70
+
71
+ def prepare(
72
+ transactions: pd.DataFrame, schema: Schema | None = None, frequency: Frequency = Frequency.DAY
73
+ ) -> Panel:
74
+ """Validate, aggregate to product x period and add calendar features."""
75
+ schema = schema or Schema()
76
+ frame, controls = _encode_controls(_normalize(transactions, schema), schema.controls)
77
+ costs = _costs(frame)
78
+ aggregated = _aggregate(frame, controls, frequency)
79
+ positive = (aggregated["quantity"] > 0) & (aggregated["price"] > 0)
80
+ panel = aggregated[positive].copy()
81
+ if panel.empty:
82
+ raise DataError("no period has both a positive price and a positive quantity")
83
+ calendar = _add_calendar(panel, frequency)
84
+ panel[LOG_PRICE] = np.log(panel["price"])
85
+ panel[LOG_QUANTITY] = np.log(panel["quantity"])
86
+ return Panel(
87
+ frame=panel.reset_index(drop=True),
88
+ features=(*calendar, *controls),
89
+ frequency=frequency,
90
+ costs=costs,
91
+ dropped=int((~positive).sum()),
92
+ )
93
+
94
+
95
+ def _normalize(transactions: pd.DataFrame, schema: Schema) -> pd.DataFrame:
96
+ required = [schema.date, schema.price, schema.quantity, *schema.controls]
97
+ optional = [c for c in (schema.product, schema.cost) if c is not None]
98
+ missing = [c for c in [*required, *optional] if c not in transactions.columns]
99
+ if missing:
100
+ available = ", ".join(map(str, transactions.columns))
101
+ raise DataError(f"missing column(s) {', '.join(missing)}; available: {available}")
102
+ frame = pd.DataFrame(
103
+ {
104
+ "date": _dates(transactions[schema.date]),
105
+ "price": _numbers(transactions[schema.price], schema.price),
106
+ "quantity": _numbers(transactions[schema.quantity], schema.quantity),
107
+ "product": transactions[schema.product].astype(str) if schema.product else ALL_PRODUCTS,
108
+ }
109
+ )
110
+ if schema.cost:
111
+ frame["cost"] = _numbers(transactions[schema.cost], schema.cost)
112
+ for control in schema.controls:
113
+ frame[control] = transactions[control].to_numpy()
114
+ if (frame["price"] < 0).any() or (frame["quantity"] < 0).any():
115
+ raise DataError("price and quantity must not be negative")
116
+ return frame
117
+
118
+
119
+ def _dates(column: pd.Series) -> pd.Series:
120
+ try:
121
+ return pd.to_datetime(column, format="mixed")
122
+ except (ValueError, TypeError) as exc:
123
+ raise DataError(f"column {column.name!r} has values that are not dates") from exc
124
+
125
+
126
+ def _numbers(column: pd.Series, name: str) -> pd.Series:
127
+ numbers = pd.to_numeric(column, errors="coerce")
128
+ bad = numbers.isna() & column.notna()
129
+ if bad.any():
130
+ example = column[bad].iloc[0]
131
+ raise DataError(f"column {name!r} has non-numeric values, e.g. {example!r}")
132
+ if numbers.isna().any():
133
+ raise DataError(f"column {name!r} has missing values")
134
+ return numbers.astype(float)
135
+
136
+
137
+ def _encode_controls(
138
+ frame: pd.DataFrame, controls: tuple[str, ...]
139
+ ) -> tuple[pd.DataFrame, list[str]]:
140
+ """One-hot encode non-numeric controls; return the frame and the final control columns."""
141
+ names: list[str] = []
142
+ for control in controls:
143
+ if pd.api.types.is_numeric_dtype(frame[control]):
144
+ names.append(control)
145
+ continue
146
+ dummies = pd.get_dummies(frame[control].astype(str), prefix=control, dtype=float)
147
+ frame = pd.concat([frame.drop(columns=control), dummies], axis=1)
148
+ names.extend(dummies.columns)
149
+ return frame, names
150
+
151
+
152
+ def _costs(frame: pd.DataFrame) -> dict[str, float]:
153
+ if "cost" not in frame.columns:
154
+ return {}
155
+ return {str(k): float(v) for k, v in frame.groupby("product")["cost"].median().items()}
156
+
157
+
158
+ def _aggregate(frame: pd.DataFrame, controls: list[str], frequency: Frequency) -> pd.DataFrame:
159
+ frame = frame.assign(
160
+ period=frame["date"].dt.to_period(frequency.value).dt.start_time,
161
+ revenue=frame["price"] * frame["quantity"],
162
+ )
163
+ grouped = frame.groupby(["product", "period"], sort=True)
164
+ result = grouped.agg(
165
+ quantity=("quantity", "sum"),
166
+ revenue=("revenue", "sum"),
167
+ list_price=("price", "mean"),
168
+ **{c: (c, "mean") for c in controls},
169
+ ).reset_index()
170
+ with np.errstate(divide="ignore", invalid="ignore"):
171
+ weighted = result["revenue"] / result["quantity"]
172
+ result["price"] = weighted.where(result["quantity"] > 0, result["list_price"])
173
+ return result.drop(columns=["revenue", "list_price"])
174
+
175
+
176
+ def _add_calendar(panel: pd.DataFrame, frequency: Frequency) -> list[str]:
177
+ period = panel["period"]
178
+ start = period.min()
179
+ panel["trend"] = (period - start).dt.days / 365.25
180
+ panel["month"] = period.dt.month.astype(float)
181
+ panel["day_of_year"] = period.dt.day_of_year.astype(float)
182
+ week = period.dt.isocalendar().week.astype(float)
183
+ panel["week_sin"] = np.sin(2 * np.pi * week / 52.18)
184
+ panel["week_cos"] = np.cos(2 * np.pi * week / 52.18)
185
+ features = list(CALENDAR_FEATURES)
186
+ if frequency is Frequency.DAY:
187
+ panel["day_of_week"] = period.dt.day_of_week.astype(float)
188
+ features.extend(DAILY_FEATURES)
189
+ return features
elastica/dml.py ADDED
@@ -0,0 +1,206 @@
1
+ """Double machine learning for the partially linear model ``y = θ·d + g(X) + ε``.
2
+
3
+ With ``y = log quantity`` and ``d = log price``, ``θ`` is the price elasticity of demand.
4
+ Reference: Chernozhukov et al. (2018), "Double/debiased machine learning for treatment and
5
+ structural parameters", The Econometrics Journal 21(1).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+ from statistics import NormalDist
13
+ from typing import Protocol, Self
14
+
15
+ import numpy as np
16
+ from numpy.typing import NDArray
17
+ from sklearn.base import clone
18
+ from sklearn.ensemble import HistGradientBoostingRegressor
19
+ from sklearn.model_selection import KFold
20
+ from threadpoolctl import threadpool_limits
21
+
22
+ Array = NDArray[np.float64]
23
+
24
+ MIN_OBSERVATIONS = 60
25
+ WEAK_PRICE_SHARE = 0.05
26
+
27
+
28
+ class Regressor(Protocol):
29
+ """Any scikit-learn style regressor."""
30
+
31
+ def fit(self, x: Array, y: Array) -> Self: ...
32
+ def predict(self, x: Array) -> Array: ...
33
+
34
+
35
+ class Folds(StrEnum):
36
+ RANDOM = "random"
37
+ """Shuffled folds, re-drawn on every repetition."""
38
+ TIME = "time"
39
+ """Contiguous blocks in time order, which limits leakage between neighbouring periods."""
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class DMLResult:
44
+ elasticity: float
45
+ std_error: float
46
+ ci_low: float
47
+ ci_high: float
48
+ confidence: float
49
+ naive_elasticity: float
50
+ """Slope of log quantity on log price with no controls."""
51
+ linear_elasticity: float
52
+ """Price coefficient of an OLS that adds the controls linearly."""
53
+ n_obs: int
54
+ outcome_r2: float
55
+ """Cross-fitted R² of the model predicting log quantity from the controls."""
56
+ price_r2: float
57
+ """Cross-fitted R² of the model predicting log price from the controls."""
58
+ warnings: tuple[str, ...]
59
+
60
+ @property
61
+ def residual_price_share(self) -> float:
62
+ """Share of price variation left after removing what the controls explain."""
63
+ return max(0.0, 1.0 - self.price_r2)
64
+
65
+ @property
66
+ def p_value(self) -> float:
67
+ """Two-sided p-value for ``elasticity == 0``."""
68
+ if self.std_error == 0:
69
+ return 0.0
70
+ return 2 * (1 - NormalDist().cdf(abs(self.elasticity / self.std_error)))
71
+
72
+
73
+ def default_learner(seed: int = 0) -> Regressor:
74
+ model: Regressor = HistGradientBoostingRegressor(
75
+ max_iter=100,
76
+ learning_rate=0.1,
77
+ max_leaf_nodes=15,
78
+ min_samples_leaf=10,
79
+ random_state=seed,
80
+ )
81
+ return model
82
+
83
+
84
+ def estimate_elasticity(
85
+ y: Array,
86
+ d: Array,
87
+ x: Array,
88
+ *,
89
+ learner: Regressor | None = None,
90
+ folds: Folds = Folds.RANDOM,
91
+ n_folds: int = 5,
92
+ n_repeats: int = 3,
93
+ confidence: float = 0.95,
94
+ seed: int = 0,
95
+ ) -> DMLResult:
96
+ """Estimate θ with cross-fitting. Rows must be in time order when ``folds`` is ``TIME``."""
97
+ y, d, x = _check_inputs(y, d, x, n_folds)
98
+ estimates: list[tuple[float, float]] = []
99
+ r2_y: list[float] = []
100
+ r2_d: list[float] = []
101
+ for repeat in range(n_repeats):
102
+ model = learner if learner is not None else default_learner(seed + repeat)
103
+ splitter = _splitter(folds, n_folds, seed + repeat)
104
+ y_hat = _cross_fit(model, x, y, splitter)
105
+ d_hat = _cross_fit(model, x, d, splitter)
106
+ estimates.append(_orthogonal_estimate(y - y_hat, d - d_hat))
107
+ r2_y.append(_r2(y, y_hat))
108
+ r2_d.append(_r2(d, d_hat))
109
+ theta, std_error = _aggregate(estimates)
110
+ z = NormalDist().inv_cdf(0.5 + confidence / 2)
111
+ price_r2 = float(np.median(r2_d))
112
+ return DMLResult(
113
+ elasticity=theta,
114
+ std_error=std_error,
115
+ ci_low=theta - z * std_error,
116
+ ci_high=theta + z * std_error,
117
+ confidence=confidence,
118
+ naive_elasticity=_ols_slope(y, d, None),
119
+ linear_elasticity=_ols_slope(y, d, x),
120
+ n_obs=len(y),
121
+ outcome_r2=float(np.median(r2_y)),
122
+ price_r2=price_r2,
123
+ warnings=_warnings(theta, len(y), price_r2),
124
+ )
125
+
126
+
127
+ def _check_inputs(y: Array, d: Array, x: Array, n_folds: int) -> tuple[Array, Array, Array]:
128
+ y = np.asarray(y, dtype=float)
129
+ d = np.asarray(d, dtype=float)
130
+ x = np.asarray(x, dtype=float)
131
+ if x.ndim == 1:
132
+ x = x.reshape(-1, 1)
133
+ if not (len(y) == len(d) == len(x)):
134
+ raise ValueError("y, d and x must have the same number of rows")
135
+ if len(y) < 2 * n_folds:
136
+ raise ValueError(f"need at least {2 * n_folds} observations for {n_folds} folds")
137
+ if not (np.isfinite(y).all() and np.isfinite(d).all() and np.isfinite(x).all()):
138
+ raise ValueError("inputs contain NaN or infinite values")
139
+ if np.ptp(d) == 0:
140
+ raise ValueError("price never changes, so its effect cannot be estimated")
141
+ return y, d, x
142
+
143
+
144
+ def _splitter(folds: Folds, n_folds: int, seed: int) -> KFold:
145
+ if folds is Folds.TIME:
146
+ return KFold(n_splits=n_folds, shuffle=False)
147
+ return KFold(n_splits=n_folds, shuffle=True, random_state=seed)
148
+
149
+
150
+ def _cross_fit(model: Regressor, x: Array, target: Array, splitter: KFold) -> Array:
151
+ predictions = np.empty_like(target)
152
+ with threadpool_limits(limits=1, user_api="openmp"):
153
+ for train, test in splitter.split(x):
154
+ fitted: Regressor = clone(model).fit(x[train], target[train])
155
+ predictions[test] = fitted.predict(x[test])
156
+ return predictions
157
+
158
+
159
+ def _orthogonal_estimate(y_res: Array, d_res: Array) -> tuple[float, float]:
160
+ """θ and its variance from the Neyman-orthogonal partialling-out score."""
161
+ jacobian = float(np.mean(d_res**2))
162
+ if jacobian == 0:
163
+ raise ValueError("the controls explain price perfectly; no variation is left")
164
+ theta = float(np.mean(d_res * y_res)) / jacobian
165
+ score = (y_res - theta * d_res) * d_res
166
+ variance = float(np.mean(score**2)) / jacobian**2 / len(y_res)
167
+ return theta, variance
168
+
169
+
170
+ def _aggregate(estimates: list[tuple[float, float]]) -> tuple[float, float]:
171
+ """Median over repetitions, with the spread between repetitions added to the variance."""
172
+ thetas = np.array([t for t, _ in estimates])
173
+ theta = float(np.median(thetas))
174
+ variances = np.array([v for _, v in estimates]) + (thetas - theta) ** 2
175
+ return theta, float(np.sqrt(np.median(variances)))
176
+
177
+
178
+ def _r2(target: Array, predicted: Array) -> float:
179
+ total = float(np.sum((target - target.mean()) ** 2))
180
+ if total == 0:
181
+ return 0.0
182
+ return 1 - float(np.sum((target - predicted) ** 2)) / total
183
+
184
+
185
+ def _ols_slope(y: Array, d: Array, x: Array | None) -> float:
186
+ columns = [np.ones_like(d), d] if x is None else [np.ones_like(d), d, *x.T]
187
+ design = np.column_stack(columns)
188
+ coefficients, *_ = np.linalg.lstsq(design, y, rcond=None)
189
+ return float(coefficients[1])
190
+
191
+
192
+ def _warnings(theta: float, n_obs: int, price_r2: float) -> tuple[str, ...]:
193
+ messages = []
194
+ if n_obs < MIN_OBSERVATIONS:
195
+ messages.append(f"only {n_obs} observations; the estimate is imprecise")
196
+ if 1 - price_r2 < WEAK_PRICE_SHARE:
197
+ messages.append(
198
+ "the controls explain almost all price changes, so little independent price "
199
+ "variation is left; the estimate is weakly identified"
200
+ )
201
+ if theta > 0:
202
+ messages.append(
203
+ "positive elasticity: demand rises with price, which usually means a confounder "
204
+ "is missing from the controls"
205
+ )
206
+ return tuple(messages)
elastica/estimate.py ADDED
@@ -0,0 +1,113 @@
1
+ """Elasticity per product (or pooled across products) over a prepared panel."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from elastica.data import LOG_PRICE, LOG_QUANTITY, Panel
11
+ from elastica.dml import DMLResult, Folds, Regressor, estimate_elasticity
12
+
13
+ POOLED = "(pooled)"
14
+ RECENT_PERIODS = 4
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class EstimateOptions:
19
+ learner: Regressor | None = None
20
+ folds: Folds = Folds.RANDOM
21
+ n_folds: int = 5
22
+ n_repeats: int = 3
23
+ confidence: float = 0.95
24
+ seed: int = 0
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class ProductEstimate:
29
+ product: str
30
+ result: DMLResult | None
31
+ current_price: float
32
+ """Median price over the most recent periods, the anchor for price recommendations."""
33
+ current_quantity: float
34
+ """Mean quantity per period over the same recent periods."""
35
+ unit_cost: float | None
36
+ error: str | None = None
37
+
38
+
39
+ def estimate(
40
+ panel: Panel, options: EstimateOptions | None = None, *, pooled: bool = False
41
+ ) -> list[ProductEstimate]:
42
+ """One estimate per product, or a single fixed-effects estimate when ``pooled``."""
43
+ options = options or EstimateOptions()
44
+ if pooled:
45
+ return [_pooled(panel, options)]
46
+ return [_one(panel, product, options) for product in panel.products]
47
+
48
+
49
+ def estimates_frame(estimates: list[ProductEstimate]) -> pd.DataFrame:
50
+ rows = []
51
+ for item in estimates:
52
+ result = item.result
53
+ rows.append(
54
+ {
55
+ "product": item.product,
56
+ "elasticity": result.elasticity if result else np.nan,
57
+ "ci_low": result.ci_low if result else np.nan,
58
+ "ci_high": result.ci_high if result else np.nan,
59
+ "std_error": result.std_error if result else np.nan,
60
+ "naive_elasticity": result.naive_elasticity if result else np.nan,
61
+ "linear_elasticity": result.linear_elasticity if result else np.nan,
62
+ "n_obs": result.n_obs if result else 0,
63
+ "price_r2": result.price_r2 if result else np.nan,
64
+ "current_price": item.current_price,
65
+ "unit_cost": item.unit_cost,
66
+ "warnings": "; ".join(result.warnings) if result else item.error,
67
+ }
68
+ )
69
+ return pd.DataFrame(rows)
70
+
71
+
72
+ def _one(panel: Panel, product: str, options: EstimateOptions) -> ProductEstimate:
73
+ frame = panel.for_product(product).sort_values("period")
74
+ return _fit(frame, list(panel.features), product, panel.costs.get(product), options)
75
+
76
+
77
+ def _pooled(panel: Panel, options: EstimateOptions) -> ProductEstimate:
78
+ frame = panel.frame.sort_values("period")
79
+ dummies = pd.get_dummies(frame["product"], prefix="product", dtype=float, drop_first=True)
80
+ frame = pd.concat([frame, dummies], axis=1)
81
+ features = [*panel.features, *dummies.columns]
82
+ costs = list(panel.costs.values())
83
+ cost = float(np.median(costs)) if costs else None
84
+ return _fit(frame, features, POOLED, cost, options)
85
+
86
+
87
+ def _fit(
88
+ frame: pd.DataFrame,
89
+ features: list[str],
90
+ product: str,
91
+ cost: float | None,
92
+ options: EstimateOptions,
93
+ ) -> ProductEstimate:
94
+ recent = frame[
95
+ frame["period"] >= frame["period"].drop_duplicates().nlargest(RECENT_PERIODS).min()
96
+ ]
97
+ current_price = float(recent["price"].median())
98
+ current_quantity = float(recent.groupby("product")["quantity"].mean().sum())
99
+ try:
100
+ result = estimate_elasticity(
101
+ frame[LOG_QUANTITY].to_numpy(),
102
+ frame[LOG_PRICE].to_numpy(),
103
+ frame[features].to_numpy(dtype=float),
104
+ learner=options.learner,
105
+ folds=options.folds,
106
+ n_folds=options.n_folds,
107
+ n_repeats=options.n_repeats,
108
+ confidence=options.confidence,
109
+ seed=options.seed,
110
+ )
111
+ except ValueError as exc:
112
+ return ProductEstimate(product, None, current_price, current_quantity, cost, str(exc))
113
+ return ProductEstimate(product, result, current_price, current_quantity, cost)
elastica/pricing.py ADDED
@@ -0,0 +1,183 @@
1
+ """Turn an elasticity into a price, under explicit and conservative assumptions.
2
+
3
+ Demand is modelled as constant-elasticity around the current price, ``q = q0 · (p / p0)^θ``.
4
+ That approximation is only trustworthy near prices that were actually observed, so every
5
+ recommendation is kept inside a band around the current price.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+ from typing import TYPE_CHECKING
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+
17
+ if TYPE_CHECKING:
18
+ from elastica.estimate import ProductEstimate
19
+
20
+
21
+ class Objective(StrEnum):
22
+ PROFIT = "profit"
23
+ REVENUE = "revenue"
24
+
25
+
26
+ class Reason(StrEnum):
27
+ OPTIMUM = "optimum inside the band"
28
+ UPPER = "capped at the top of the band"
29
+ LOWER = "capped at the bottom of the band"
30
+ NO_ESTIMATE = "no elasticity estimate"
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class PriceBand:
35
+ """Multipliers of the current price that bound any recommendation."""
36
+
37
+ lower: float = 0.8
38
+ upper: float = 1.2
39
+
40
+ def __post_init__(self) -> None:
41
+ if not 0 < self.lower <= 1 <= self.upper:
42
+ raise ValueError("the band must satisfy 0 < lower <= 1 <= upper")
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class Recommendation:
47
+ product: str
48
+ objective: Objective
49
+ current_price: float
50
+ recommended_price: float
51
+ price_range: tuple[float, float]
52
+ """Recommended price at each end of the elasticity's confidence interval."""
53
+ elasticity: float | None
54
+ unit_cost: float | None
55
+ quantity_change: float
56
+ revenue_change: float
57
+ profit_change: float | None
58
+ reason: Reason
59
+ warnings: tuple[str, ...]
60
+
61
+
62
+ def optimal_price(elasticity: float, unit_cost: float) -> float | None:
63
+ """Profit-maximizing price ``c · θ / (1 + θ)``; None when demand is inelastic (θ ≥ -1)."""
64
+ if elasticity >= -1:
65
+ return None
66
+ return unit_cost * elasticity / (1 + elasticity)
67
+
68
+
69
+ def recommend(
70
+ item: ProductEstimate, *, unit_cost: float | None = None, band: PriceBand | None = None
71
+ ) -> Recommendation:
72
+ band = band or PriceBand()
73
+ cost = unit_cost if unit_cost is not None else item.unit_cost
74
+ objective = Objective.PROFIT if cost is not None else Objective.REVENUE
75
+ current = item.current_price
76
+ if item.result is None:
77
+ return Recommendation(
78
+ item.product, objective, current, current, (current, current), None, cost,
79
+ 0.0, 0.0, 0.0 if cost is not None else None, Reason.NO_ESTIMATE,
80
+ (item.error or "no estimate",),
81
+ ) # fmt: skip
82
+ theta = item.result.elasticity
83
+ price, reason = _best_price(theta, cost, current, band)
84
+ ends = sorted(
85
+ _best_price(bound, cost, current, band)[0]
86
+ for bound in (item.result.ci_low, item.result.ci_high)
87
+ )
88
+ ratio = price / current
89
+ quantity_ratio = ratio**theta
90
+ profit_change = None
91
+ if cost is not None and current != cost:
92
+ profit_change = (price - cost) * quantity_ratio / (current - cost) - 1
93
+ return Recommendation(
94
+ product=item.product,
95
+ objective=objective,
96
+ current_price=current,
97
+ recommended_price=round(price, 2),
98
+ price_range=(round(ends[0], 2), round(ends[1], 2)),
99
+ elasticity=theta,
100
+ unit_cost=cost,
101
+ quantity_change=quantity_ratio - 1,
102
+ revenue_change=ratio * quantity_ratio - 1,
103
+ profit_change=profit_change,
104
+ reason=reason,
105
+ warnings=_warnings(item, cost, reason),
106
+ )
107
+
108
+
109
+ def demand_curve(
110
+ current_price: float,
111
+ current_quantity: float,
112
+ elasticity: float,
113
+ *,
114
+ unit_cost: float | None = None,
115
+ band: PriceBand | None = None,
116
+ points: int = 41,
117
+ ) -> pd.DataFrame:
118
+ """Price, quantity, revenue and (with a cost) profit across the band."""
119
+ band = band or PriceBand()
120
+ prices = np.linspace(band.lower * current_price, band.upper * current_price, points)
121
+ quantity = current_quantity * (prices / current_price) ** elasticity
122
+ frame = pd.DataFrame({"price": prices, "quantity": quantity, "revenue": prices * quantity})
123
+ if unit_cost is not None:
124
+ frame["profit"] = (prices - unit_cost) * quantity
125
+ return frame
126
+
127
+
128
+ def recommendations_frame(recommendations: list[Recommendation]) -> pd.DataFrame:
129
+ return pd.DataFrame(
130
+ [
131
+ {
132
+ "product": r.product,
133
+ "objective": r.objective.value,
134
+ "elasticity": r.elasticity,
135
+ "unit_cost": r.unit_cost,
136
+ "current_price": r.current_price,
137
+ "recommended_price": r.recommended_price,
138
+ "price_low": r.price_range[0],
139
+ "price_high": r.price_range[1],
140
+ "quantity_change": r.quantity_change,
141
+ "revenue_change": r.revenue_change,
142
+ "profit_change": r.profit_change,
143
+ "reason": r.reason.value,
144
+ "warnings": "; ".join(r.warnings),
145
+ }
146
+ for r in recommendations
147
+ ]
148
+ )
149
+
150
+
151
+ def _best_price(
152
+ elasticity: float, cost: float | None, current: float, band: PriceBand
153
+ ) -> tuple[float, Reason]:
154
+ low, high = band.lower * current, band.upper * current
155
+ if cost is None:
156
+ # Revenue p·q grows with price when θ > -1 and falls when θ < -1.
157
+ return (high, Reason.UPPER) if elasticity > -1 else (low, Reason.LOWER)
158
+ target = optimal_price(elasticity, cost)
159
+ if target is None or target > high:
160
+ return high, Reason.UPPER
161
+ if target < low:
162
+ return low, Reason.LOWER
163
+ return target, Reason.OPTIMUM
164
+
165
+
166
+ def _warnings(item: ProductEstimate, cost: float | None, reason: Reason) -> tuple[str, ...]:
167
+ assert item.result is not None
168
+ messages = list(item.result.warnings)
169
+ if item.result.elasticity >= -1:
170
+ messages.append(
171
+ "demand looks inelastic, so the model keeps pushing the price up; it is capped at "
172
+ "the band because the constant-elasticity assumption breaks down far from observed "
173
+ "prices"
174
+ )
175
+ if cost is not None and item.current_price <= cost:
176
+ messages.append("the current price does not cover the unit cost")
177
+ if cost is None:
178
+ messages.append("no unit cost given: maximizing revenue, not profit")
179
+ if item.result.ci_low < -1 < item.result.ci_high:
180
+ messages.append("the confidence interval includes -1; elastic vs inelastic is uncertain")
181
+ if reason is not Reason.OPTIMUM and cost is not None:
182
+ messages.append(f"price {reason.value}; consider testing a wider band in small steps")
183
+ return tuple(messages)
elastica/py.typed ADDED
File without changes
elastica/simulate.py ADDED
@@ -0,0 +1,98 @@
1
+ """Synthetic daily sales with a known price elasticity and realistic confounding.
2
+
3
+ Demand and price both rise in high season and around two sharp sales peaks (mid-November and
4
+ Christmas), so a naive regression of quantity on price underestimates how price-sensitive
5
+ customers are. Season and peaks are observable from the date, which is what lets double machine
6
+ learning recover the true elasticity; the peaks are non-linear in the calendar, which is what
7
+ defeats a linear regression with the same controls.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class Simulation:
20
+ transactions: pd.DataFrame
21
+ """Columns: date, product, price, quantity, promo, unit_cost."""
22
+ true_elasticity: dict[str, float]
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class SimulationConfig:
27
+ n_products: int = 4
28
+ n_days: int = 730
29
+ start: str = "2024-01-01"
30
+ elasticity_range: tuple[float, float] = (-2.2, -1.2)
31
+ base_price: float = 100.0
32
+ base_quantity: float = 60.0
33
+ season_on_price: float = 0.15
34
+ season_on_demand: float = 0.6
35
+ peak_on_price: float = 0.2
36
+ peak_on_demand: float = 0.8
37
+ promo_rate: float = 0.12
38
+ promo_discount: float = 0.2
39
+ promo_lift: float = 0.3
40
+ price_noise: float = 0.08
41
+ demand_noise: float = 0.15
42
+ margin: float = 0.55
43
+ seed: int = 7
44
+
45
+
46
+ def simulate(config: SimulationConfig | None = None) -> Simulation:
47
+ cfg = config or SimulationConfig()
48
+ rng = np.random.default_rng(cfg.seed)
49
+ dates = pd.date_range(cfg.start, periods=cfg.n_days, freq="D")
50
+ day_of_year = dates.day_of_year.to_numpy()
51
+ season = np.sin(2 * np.pi * (day_of_year - 80) / 365.25)
52
+ weekend = (dates.day_of_week.to_numpy() >= 5).astype(float)
53
+ peak = _peaks(day_of_year)
54
+
55
+ low, high = cfg.elasticity_range
56
+ elasticities = np.round(np.linspace(low, high, cfg.n_products), 2)
57
+ frames = []
58
+ truth: dict[str, float] = {}
59
+ for index, elasticity in enumerate(elasticities):
60
+ product = f"SKU-{index + 1:03d}"
61
+ truth[product] = float(elasticity)
62
+ base_price = cfg.base_price * rng.uniform(0.6, 1.6)
63
+ promo = rng.random(cfg.n_days) < cfg.promo_rate
64
+ log_price = (
65
+ np.log(base_price)
66
+ + cfg.season_on_price * season
67
+ + cfg.peak_on_price * peak
68
+ - cfg.promo_discount * promo
69
+ + rng.normal(0, cfg.price_noise, cfg.n_days)
70
+ )
71
+ log_demand = (
72
+ np.log(cfg.base_quantity)
73
+ + elasticity * (log_price - np.log(base_price))
74
+ + cfg.season_on_demand * season
75
+ + cfg.peak_on_demand * peak
76
+ + cfg.promo_lift * promo
77
+ + 0.25 * weekend
78
+ + rng.normal(0, cfg.demand_noise, cfg.n_days)
79
+ )
80
+ frames.append(
81
+ pd.DataFrame(
82
+ {
83
+ "date": dates,
84
+ "product": product,
85
+ "price": np.round(np.exp(log_price), 2),
86
+ "quantity": rng.poisson(np.exp(log_demand)),
87
+ "promo": promo.astype(int),
88
+ "unit_cost": round(base_price * (1 - cfg.margin), 2),
89
+ }
90
+ )
91
+ )
92
+ return Simulation(pd.concat(frames, ignore_index=True), truth)
93
+
94
+
95
+ def _peaks(day_of_year: np.ndarray) -> np.ndarray:
96
+ """Narrow bumps (about a week wide) centred on mid-November and Christmas."""
97
+ centres = (320, 357)
98
+ return np.sum([np.exp(-0.5 * ((day_of_year - c) / 5.0) ** 2) for c in centres], axis=0)
@@ -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
+ [![CI](https://github.com/DiegoTepichin/elastica/actions/workflows/ci.yml/badge.svg)](https://github.com/DiegoTepichin/elastica/actions/workflows/ci.yml)
36
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
37
+
38
+ [Leer en español](README.es.md)
39
+
40
+ ![Estimated vs true elasticity on 50 simulated products: naive OLS and OLS with linear controls are biased toward zero, elastica lands on the diagonal](https://raw.githubusercontent.com/DiegoTepichin/elastica/main/docs/benchmark.svg)
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,13 @@
1
+ elastica/__init__.py,sha256=YNmqJvcKJ1RbivtK0P-hes5ajVx62Q6BCYyJqnu3uhY,1056
2
+ elastica/cli.py,sha256=tY2ahXtJBSfsO57kO1cLhyUC32-Iwg_b4EZGQO14LKc,7819
3
+ elastica/data.py,sha256=D0r7A6BrCkUE2vvpUvojv1Uohb-4B4nZkNC7dewRX6c,7009
4
+ elastica/dml.py,sha256=xrEcCmreB4-8YoEYZu5eEFQ_RGLzPZQR6_802wAiH9U,7351
5
+ elastica/estimate.py,sha256=LmRvHAWboib6ANGugDwe1TxAm884L9ypADnmVe_t98g,4083
6
+ elastica/pricing.py,sha256=An7j8gkqED32_vaP-AvVjGbnbsyPCQXsfYLwYILhPOo,6570
7
+ elastica/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ elastica/simulate.py,sha256=ugf81n0L4lYCZYDLhmVsHycJAqQX4xCB7t6TD6_F72k,3564
9
+ elastica-1.0.0.dist-info/METADATA,sha256=6tpx0vyvnGQ8YJsEZOpz4ez05mUnAcgjHThfXTpc1zU,10015
10
+ elastica-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ elastica-1.0.0.dist-info/entry_points.txt,sha256=OiN4xAEjJgxtn3L-5pWnnEBDH-M3XDhWZDAWqQXDzGc,47
12
+ elastica-1.0.0.dist-info/licenses/LICENSE,sha256=KqUp30oQmCvUSAgdjZN7rp5cgwS06fkPzdyjEQjeTfU,1071
13
+ elastica-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ elastica = elastica.cli:main
@@ -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.