Spaces:
Sleeping
Sleeping
Commit ·
1e11bce
1
Parent(s): 45fbe37
Add comprehensive tests for pricing engine and API endpoints
Browse files- Introduced `test_pricing_engine.py` to validate pricing logic and guardrails for synthetic and Kaggle pricing requests.
- Created `test_api.py` to ensure API endpoints function correctly, including health checks and price recommendations.
- Added `smoke_test.py` to verify that the project compiles without errors.
- Implemented dummy settings and tracker classes to facilitate testing.
- Enhanced test coverage for flash sale detection and competitor price adjustments.
- .dockerignore +14 -0
- .env.example +16 -0
- Dockerfile +23 -0
- Dockerfile.streamlit +21 -0
- app/__init__.py +1 -0
- app/__pycache__/__init__.cpython-313.pyc +0 -0
- app/__pycache__/api.cpython-313.pyc +0 -0
- app/__pycache__/cache.cpython-313.pyc +0 -0
- app/__pycache__/config.cpython-313.pyc +0 -0
- app/__pycache__/dashboard.cpython-313.pyc +0 -0
- app/__pycache__/feature_engineering.cpython-313.pyc +0 -0
- app/__pycache__/modeling.cpython-313.pyc +0 -0
- app/__pycache__/pricing_engine.cpython-313.pyc +0 -0
- app/__pycache__/schemas.cpython-313.pyc +0 -0
- app/__pycache__/streaming.cpython-313.pyc +0 -0
- app/api.py +117 -0
- app/cache.py +33 -0
- app/config.py +42 -0
- app/dashboard.py +554 -0
- app/feature_engineering.py +150 -0
- app/modeling.py +194 -0
- app/pricing_engine.py +358 -0
- app/schemas.py +94 -0
- app/streaming.py +42 -0
- data/processed/price_history.csv +70 -0
- data/raw/kaggle/retail_price.csv +0 -0
- data/raw/pricing_events.csv +0 -0
- deploy/ec2/dynamic-pricing-api.service +17 -0
- deploy/ec2/dynamic-pricing-dashboard.service +17 -0
- deploy/ec2/start_api.sh +13 -0
- deploy/ec2/start_dashboard.sh +15 -0
- docker-compose.yml +29 -0
- models/training_metrics.json +22 -0
- requirements.txt +17 -0
- scripts/__pycache__/generate_sample_data.cpython-313.pyc +0 -0
- scripts/__pycache__/train_model.cpython-313.pyc +0 -0
- scripts/generate_sample_data.py +120 -0
- scripts/train_model.py +45 -0
- tests/__pycache__/smoke_test.cpython-313-pytest-8.3.3.pyc +0 -0
- tests/__pycache__/test_api.cpython-313-pytest-8.3.3.pyc +0 -0
- tests/__pycache__/test_pricing_engine.cpython-313-pytest-8.3.3.pyc +0 -0
- tests/smoke_test.py +8 -0
- tests/test_api.py +215 -0
- tests/test_pricing_engine.py +156 -0
.dockerignore
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.gitignore
|
| 3 |
+
.pytest_cache
|
| 4 |
+
.venv
|
| 5 |
+
__pycache__/
|
| 6 |
+
*.py[cod]
|
| 7 |
+
*.pyo
|
| 8 |
+
*.pyd
|
| 9 |
+
*.log
|
| 10 |
+
.env
|
| 11 |
+
.env.*
|
| 12 |
+
!.env.example
|
| 13 |
+
tests/
|
| 14 |
+
deploy/
|
.env.example
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
APP_NAME=dynamic-pricing-engine
|
| 2 |
+
MODEL_PATH=models/best_pricing_model.joblib
|
| 3 |
+
METRICS_PATH=models/training_metrics.json
|
| 4 |
+
RAW_DATA_PATH=data/raw/pricing_events.csv
|
| 5 |
+
PRICE_HISTORY_PATH=data/processed/price_history.csv
|
| 6 |
+
COMPETITOR_API_URL=
|
| 7 |
+
COMPETITOR_WEIGHT=0.30
|
| 8 |
+
MODEL_WEIGHT=0.70
|
| 9 |
+
MIN_MARGIN=0.08
|
| 10 |
+
MAX_PRICE_MULTIPLIER=1.35
|
| 11 |
+
REDIS_URL=
|
| 12 |
+
KAFKA_BOOTSTRAP_SERVERS=localhost:9092
|
| 13 |
+
KAFKA_TOPIC_ORDERS=pricing.orders
|
| 14 |
+
KAFKA_TOPIC_CLICKS=pricing.clicks
|
| 15 |
+
FLASH_SALE_ORDER_THRESHOLD=20
|
| 16 |
+
FLASH_SALE_LOOKBACK_MINUTES=5
|
Dockerfile
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.13-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
+
PYTHONUNBUFFERED=1 \
|
| 5 |
+
PIP_NO_CACHE_DIR=1
|
| 6 |
+
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
COPY requirements.txt .
|
| 10 |
+
RUN pip install --upgrade pip && pip install -r requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY app ./app
|
| 13 |
+
COPY scripts ./scripts
|
| 14 |
+
COPY data ./data
|
| 15 |
+
COPY models ./models
|
| 16 |
+
COPY .env.example ./.env.example
|
| 17 |
+
COPY README.md ./README.md
|
| 18 |
+
|
| 19 |
+
EXPOSE 8000
|
| 20 |
+
|
| 21 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"
|
| 22 |
+
|
| 23 |
+
CMD ["uvicorn", "app.api:app", "--host", "0.0.0.0", "--port", "8000"]
|
Dockerfile.streamlit
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.13-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
+
PYTHONUNBUFFERED=1 \
|
| 5 |
+
PIP_NO_CACHE_DIR=1
|
| 6 |
+
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
COPY requirements.txt .
|
| 10 |
+
RUN pip install --upgrade pip && pip install -r requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY app ./app
|
| 13 |
+
COPY scripts ./scripts
|
| 14 |
+
COPY data ./data
|
| 15 |
+
COPY models ./models
|
| 16 |
+
COPY .env.example ./.env.example
|
| 17 |
+
COPY README.md ./README.md
|
| 18 |
+
|
| 19 |
+
EXPOSE 8501
|
| 20 |
+
|
| 21 |
+
CMD ["streamlit", "run", "app/dashboard.py", "--server.address=0.0.0.0", "--server.port=8501", "--server.headless=true"]
|
app/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Dynamic pricing engine package."""
|
app/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (235 Bytes). View file
|
|
|
app/__pycache__/api.cpython-313.pyc
ADDED
|
Binary file (5.63 kB). View file
|
|
|
app/__pycache__/cache.cpython-313.pyc
ADDED
|
Binary file (2.07 kB). View file
|
|
|
app/__pycache__/config.cpython-313.pyc
ADDED
|
Binary file (2.64 kB). View file
|
|
|
app/__pycache__/dashboard.cpython-313.pyc
ADDED
|
Binary file (24.5 kB). View file
|
|
|
app/__pycache__/feature_engineering.cpython-313.pyc
ADDED
|
Binary file (5.02 kB). View file
|
|
|
app/__pycache__/modeling.cpython-313.pyc
ADDED
|
Binary file (6.31 kB). View file
|
|
|
app/__pycache__/pricing_engine.cpython-313.pyc
ADDED
|
Binary file (19.1 kB). View file
|
|
|
app/__pycache__/schemas.cpython-313.pyc
ADDED
|
Binary file (5.43 kB). View file
|
|
|
app/__pycache__/streaming.cpython-313.pyc
ADDED
|
Binary file (3.12 kB). View file
|
|
|
app/api.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
from datetime import UTC, datetime
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from fastapi import FastAPI, HTTPException
|
| 9 |
+
|
| 10 |
+
from app.config import get_settings
|
| 11 |
+
from app.pricing_engine import PricingEngine
|
| 12 |
+
from app.schemas import (
|
| 13 |
+
KagglePricingRequest,
|
| 14 |
+
KagglePricingResponse,
|
| 15 |
+
MonitoringSummary,
|
| 16 |
+
OrderEvent,
|
| 17 |
+
PricingRequest,
|
| 18 |
+
PricingResponse,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
engine: PricingEngine | None = None
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@asynccontextmanager
|
| 26 |
+
async def lifespan(_: FastAPI):
|
| 27 |
+
global engine
|
| 28 |
+
settings = get_settings()
|
| 29 |
+
if settings.model_path.exists():
|
| 30 |
+
engine = PricingEngine(settings)
|
| 31 |
+
else:
|
| 32 |
+
engine = None
|
| 33 |
+
yield
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
app = FastAPI(title="Dynamic Pricing Engine", version="1.0.0", lifespan=lifespan)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@app.get("/health")
|
| 40 |
+
def health() -> dict[str, object]:
|
| 41 |
+
settings = get_settings()
|
| 42 |
+
return {
|
| 43 |
+
"status": "ok",
|
| 44 |
+
"model_loaded": engine is not None,
|
| 45 |
+
"dataset_profile": getattr(engine, "dataset_profile", None),
|
| 46 |
+
"supported_endpoints": {
|
| 47 |
+
"synthetic": "/price/recommend",
|
| 48 |
+
"kaggle_retail": "/price/recommend/kaggle",
|
| 49 |
+
},
|
| 50 |
+
"model_path": str(settings.model_path),
|
| 51 |
+
"metrics_path": str(settings.metrics_path),
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@app.post("/price/recommend", response_model=PricingResponse)
|
| 56 |
+
def recommend_price(request: PricingRequest) -> PricingResponse:
|
| 57 |
+
if engine is None:
|
| 58 |
+
raise HTTPException(status_code=503, detail="Model is not loaded. Train the model first.")
|
| 59 |
+
try:
|
| 60 |
+
recommendation = engine.recommend_price(request)
|
| 61 |
+
except ValueError as exc:
|
| 62 |
+
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
| 63 |
+
return recommendation.response
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@app.post("/price/recommend/kaggle", response_model=KagglePricingResponse)
|
| 67 |
+
def recommend_kaggle_price(request: KagglePricingRequest) -> KagglePricingResponse:
|
| 68 |
+
if engine is None:
|
| 69 |
+
raise HTTPException(status_code=503, detail="Model is not loaded. Train the model first.")
|
| 70 |
+
try:
|
| 71 |
+
recommendation = engine.recommend_kaggle_price(request)
|
| 72 |
+
except ValueError as exc:
|
| 73 |
+
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
| 74 |
+
return recommendation.response
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@app.post("/events/order")
|
| 78 |
+
def register_order(event: OrderEvent) -> dict[str, object]:
|
| 79 |
+
if engine is None:
|
| 80 |
+
raise HTTPException(status_code=503, detail="Model is not loaded. Train the model first.")
|
| 81 |
+
is_flash_sale = engine.register_order_event(event)
|
| 82 |
+
return {
|
| 83 |
+
"sku_id": event.sku_id,
|
| 84 |
+
"flash_sale_active": is_flash_sale,
|
| 85 |
+
"registered_at": datetime.now(UTC).isoformat(),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@app.get("/monitoring/summary", response_model=MonitoringSummary)
|
| 90 |
+
def monitoring_summary() -> MonitoringSummary:
|
| 91 |
+
if engine is None:
|
| 92 |
+
raise HTTPException(status_code=503, detail="Model is not loaded. Train the model first.")
|
| 93 |
+
settings = get_settings()
|
| 94 |
+
average_recommended_price = None
|
| 95 |
+
last_price_update = None
|
| 96 |
+
|
| 97 |
+
if settings.price_history_path.exists():
|
| 98 |
+
history = pd.read_csv(settings.price_history_path)
|
| 99 |
+
if not history.empty:
|
| 100 |
+
average_recommended_price = float(history["recommended_price"].mean())
|
| 101 |
+
last_price_update = pd.to_datetime(history["generated_at"].iloc[-1]).to_pydatetime()
|
| 102 |
+
|
| 103 |
+
return MonitoringSummary(
|
| 104 |
+
tracked_skus=len(engine.flash_sale_tracker.events),
|
| 105 |
+
recent_order_events=engine.flash_sale_tracker.recent_event_count(),
|
| 106 |
+
flash_sale_skus=engine.flash_sale_tracker.flash_sale_skus(),
|
| 107 |
+
average_recommended_price=average_recommended_price,
|
| 108 |
+
last_price_update=last_price_update,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@app.get("/metrics")
|
| 113 |
+
def metrics() -> dict[str, object]:
|
| 114 |
+
settings = get_settings()
|
| 115 |
+
if not settings.metrics_path.exists():
|
| 116 |
+
raise HTTPException(status_code=404, detail="Metrics file not found.")
|
| 117 |
+
return json.loads(settings.metrics_path.read_text(encoding="utf-8"))
|
app/cache.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from datetime import UTC, datetime
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import redis
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class RedisCache:
|
| 11 |
+
def __init__(self, redis_url: str):
|
| 12 |
+
self.redis_url = redis_url
|
| 13 |
+
self.client = redis.from_url(redis_url, decode_responses=True) if redis_url else None
|
| 14 |
+
|
| 15 |
+
def is_enabled(self) -> bool:
|
| 16 |
+
return self.client is not None
|
| 17 |
+
|
| 18 |
+
def set_json(self, key: str, payload: dict[str, Any], ttl_seconds: int = 300) -> None:
|
| 19 |
+
if self.client is None:
|
| 20 |
+
return
|
| 21 |
+
serialized = json.dumps(
|
| 22 |
+
{
|
| 23 |
+
"payload": payload,
|
| 24 |
+
"cached_at": datetime.now(UTC).isoformat(),
|
| 25 |
+
}
|
| 26 |
+
)
|
| 27 |
+
self.client.setex(key, ttl_seconds, serialized)
|
| 28 |
+
|
| 29 |
+
def get_json(self, key: str) -> dict[str, Any] | None:
|
| 30 |
+
if self.client is None:
|
| 31 |
+
return None
|
| 32 |
+
value = self.client.get(key)
|
| 33 |
+
return json.loads(value) if value else None
|
app/config.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Settings(BaseSettings):
|
| 11 |
+
app_name: str = "dynamic-pricing-engine"
|
| 12 |
+
model_path: Path = BASE_DIR / "models" / "best_pricing_model.joblib"
|
| 13 |
+
metrics_path: Path = BASE_DIR / "models" / "training_metrics.json"
|
| 14 |
+
raw_data_path: Path = BASE_DIR / "data" / "raw" / "pricing_events.csv"
|
| 15 |
+
price_history_path: Path = BASE_DIR / "data" / "processed" / "price_history.csv"
|
| 16 |
+
competitor_api_url: str = ""
|
| 17 |
+
competitor_weight: float = 0.30
|
| 18 |
+
model_weight: float = 0.70
|
| 19 |
+
min_margin: float = 0.08
|
| 20 |
+
max_price_multiplier: float = 1.35
|
| 21 |
+
redis_url: str = ""
|
| 22 |
+
kafka_bootstrap_servers: str = "localhost:9092"
|
| 23 |
+
kafka_topic_orders: str = "pricing.orders"
|
| 24 |
+
kafka_topic_clicks: str = "pricing.clicks"
|
| 25 |
+
flash_sale_order_threshold: int = 20
|
| 26 |
+
flash_sale_lookback_minutes: int = 5
|
| 27 |
+
|
| 28 |
+
model_config = SettingsConfigDict(
|
| 29 |
+
env_file=".env",
|
| 30 |
+
env_file_encoding="utf-8",
|
| 31 |
+
case_sensitive=False,
|
| 32 |
+
protected_namespaces=("settings_",),
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@lru_cache(maxsize=1)
|
| 37 |
+
def get_settings() -> Settings:
|
| 38 |
+
settings = Settings()
|
| 39 |
+
settings.model_path.parent.mkdir(parents=True, exist_ok=True)
|
| 40 |
+
settings.raw_data_path.parent.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
settings.price_history_path.parent.mkdir(parents=True, exist_ok=True)
|
| 42 |
+
return settings
|
app/dashboard.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import plotly.express as px
|
| 9 |
+
import plotly.graph_objects as go
|
| 10 |
+
import streamlit as st
|
| 11 |
+
|
| 12 |
+
ROOT_DIR = Path(__file__).resolve().parents[1]
|
| 13 |
+
if str(ROOT_DIR) not in sys.path:
|
| 14 |
+
sys.path.insert(0, str(ROOT_DIR))
|
| 15 |
+
|
| 16 |
+
from app.feature_engineering import load_kaggle_retail_training_data
|
| 17 |
+
from app.modeling import load_model_bundle
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
st.set_page_config(
|
| 21 |
+
page_title="Retail Pricing Studio",
|
| 22 |
+
layout="wide",
|
| 23 |
+
initial_sidebar_state="expanded",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def inject_styles() -> None:
|
| 28 |
+
st.markdown(
|
| 29 |
+
"""
|
| 30 |
+
<style>
|
| 31 |
+
/* ── Base ─────────────────────────────────────────── */
|
| 32 |
+
.stApp { background: var(--background-color); }
|
| 33 |
+
|
| 34 |
+
/* ── Metric card ──────────────────────────────────── */
|
| 35 |
+
.mcard {
|
| 36 |
+
background: var(--secondary-background-color);
|
| 37 |
+
border: 1px solid rgba(148,163,184,0.15);
|
| 38 |
+
border-radius: 12px;
|
| 39 |
+
padding: 14px 16px;
|
| 40 |
+
}
|
| 41 |
+
.mcard-label {
|
| 42 |
+
font-size: 11px;
|
| 43 |
+
font-weight: 600;
|
| 44 |
+
letter-spacing: 0.07em;
|
| 45 |
+
text-transform: uppercase;
|
| 46 |
+
color: var(--text-color);
|
| 47 |
+
opacity: 0.5;
|
| 48 |
+
margin-bottom: 4px;
|
| 49 |
+
}
|
| 50 |
+
.mcard-value {
|
| 51 |
+
font-size: 22px;
|
| 52 |
+
font-weight: 700;
|
| 53 |
+
color: var(--text-color);
|
| 54 |
+
line-height: 1.2;
|
| 55 |
+
}
|
| 56 |
+
.mcard-sub {
|
| 57 |
+
font-size: 12px;
|
| 58 |
+
color: var(--text-color);
|
| 59 |
+
opacity: 0.45;
|
| 60 |
+
margin-top: 3px;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
/* ── Signal banner ────────────────────────────────── */
|
| 64 |
+
.signal-banner {
|
| 65 |
+
border-radius: 10px;
|
| 66 |
+
padding: 12px 16px;
|
| 67 |
+
display: flex;
|
| 68 |
+
align-items: center;
|
| 69 |
+
justify-content: space-between;
|
| 70 |
+
margin-bottom: 0;
|
| 71 |
+
}
|
| 72 |
+
.signal-banner.green { background: rgba( 16,185,129,0.10); border: 1px solid rgba( 16,185,129,0.25); }
|
| 73 |
+
.signal-banner.orange { background: rgba(234, 88, 12,0.10); border: 1px solid rgba(234, 88, 12,0.25); }
|
| 74 |
+
.signal-banner.gray { background: rgba(100,116,139,0.10); border: 1px solid rgba(100,116,139,0.22); }
|
| 75 |
+
|
| 76 |
+
.signal-title { font-size: 14px; font-weight: 700; }
|
| 77 |
+
.signal-banner.green .signal-title { color: #10b981; }
|
| 78 |
+
.signal-banner.orange .signal-title { color: #ea580c; }
|
| 79 |
+
.signal-banner.gray .signal-title { color: #64748b; }
|
| 80 |
+
|
| 81 |
+
.signal-text { font-size: 13px; color: var(--text-color); opacity: 0.7; margin-top: 2px; }
|
| 82 |
+
|
| 83 |
+
.signal-badge {
|
| 84 |
+
font-size: 11px;
|
| 85 |
+
font-weight: 600;
|
| 86 |
+
letter-spacing: 0.04em;
|
| 87 |
+
padding: 4px 10px;
|
| 88 |
+
border-radius: 999px;
|
| 89 |
+
white-space: nowrap;
|
| 90 |
+
}
|
| 91 |
+
.signal-banner.green .signal-badge { background: rgba(16,185,129,0.18); color:#10b981; }
|
| 92 |
+
.signal-banner.orange .signal-badge { background: rgba(234,88,12,0.18); color:#ea580c; }
|
| 93 |
+
.signal-banner.gray .signal-badge { background: rgba(100,116,139,0.18);color:#64748b; }
|
| 94 |
+
|
| 95 |
+
/* ── Section divider label ────────────────────────── */
|
| 96 |
+
.section-sep {
|
| 97 |
+
font-size: 10px;
|
| 98 |
+
font-weight: 700;
|
| 99 |
+
letter-spacing: 0.1em;
|
| 100 |
+
text-transform: uppercase;
|
| 101 |
+
color: var(--text-color);
|
| 102 |
+
opacity: 0.35;
|
| 103 |
+
margin: 20px 0 6px;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
/* ── KV table in right panel ──────────────────────── */
|
| 107 |
+
.kv-table { width: 100%; border-collapse: collapse; }
|
| 108 |
+
.kv-table td {
|
| 109 |
+
font-size: 13px;
|
| 110 |
+
padding: 7px 0;
|
| 111 |
+
border-bottom: 1px solid rgba(148,163,184,0.12);
|
| 112 |
+
vertical-align: middle;
|
| 113 |
+
}
|
| 114 |
+
.kv-table tr:last-child td { border-bottom: none; }
|
| 115 |
+
.kv-table .kv-key { color: var(--text-color); opacity: 0.55; width: 55%; }
|
| 116 |
+
.kv-table .kv-val { color: var(--text-color); font-weight: 600; text-align: right; }
|
| 117 |
+
|
| 118 |
+
/* ── Page header ──────────────────────────────────── */
|
| 119 |
+
.page-header {
|
| 120 |
+
display: flex;
|
| 121 |
+
align-items: baseline;
|
| 122 |
+
justify-content: space-between;
|
| 123 |
+
margin-bottom: 20px;
|
| 124 |
+
}
|
| 125 |
+
.page-title {
|
| 126 |
+
font-size: 20px;
|
| 127 |
+
font-weight: 700;
|
| 128 |
+
color: var(--text-color);
|
| 129 |
+
}
|
| 130 |
+
.page-context {
|
| 131 |
+
font-size: 12px;
|
| 132 |
+
color: var(--text-color);
|
| 133 |
+
opacity: 0.45;
|
| 134 |
+
}
|
| 135 |
+
</style>
|
| 136 |
+
""",
|
| 137 |
+
unsafe_allow_html=True,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ── Helpers ────────────────────────────────────────────────────────────────────
|
| 142 |
+
|
| 143 |
+
def candidate_kaggle_paths() -> list[Path]:
|
| 144 |
+
return [
|
| 145 |
+
ROOT_DIR / "data" / "raw" / "kaggle" / "retail_price.csv",
|
| 146 |
+
ROOT_DIR / "data" / "raw" / "retail_price.csv",
|
| 147 |
+
]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@st.cache_resource
|
| 151 |
+
def load_bundle() -> dict[str, object] | None:
|
| 152 |
+
model_path = ROOT_DIR / "models" / "best_pricing_model.joblib"
|
| 153 |
+
if not model_path.exists():
|
| 154 |
+
return None
|
| 155 |
+
return load_model_bundle(model_path)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@st.cache_data
|
| 159 |
+
def load_metrics() -> dict[str, object]:
|
| 160 |
+
metrics_path = ROOT_DIR / "models" / "training_metrics.json"
|
| 161 |
+
if not metrics_path.exists():
|
| 162 |
+
return {}
|
| 163 |
+
return json.loads(metrics_path.read_text(encoding="utf-8"))
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@st.cache_data
|
| 167 |
+
def load_kaggle_data() -> tuple[pd.DataFrame, Path | None]:
|
| 168 |
+
for path in candidate_kaggle_paths():
|
| 169 |
+
if path.exists():
|
| 170 |
+
return load_kaggle_retail_training_data(path), path
|
| 171 |
+
return pd.DataFrame(), None
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def fmt_inr(value: float) -> str:
|
| 175 |
+
if pd.isna(value):
|
| 176 |
+
return "—"
|
| 177 |
+
return f"₹ {value:,.2f}"
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def safe_float(value: object, fallback: float = 0.0) -> float:
|
| 181 |
+
return fallback if pd.isna(value) else float(value)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def safe_int(value: object, fallback: int = 0) -> int:
|
| 185 |
+
return fallback if pd.isna(value) else int(value)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def price_signal(predicted: float, actual: float) -> tuple[str, str, str]:
|
| 189 |
+
"""Returns (title, text, color_class) where color_class is green/orange/gray."""
|
| 190 |
+
if actual == 0:
|
| 191 |
+
return "Hold Price", "Insufficient data to compute signal.", "gray"
|
| 192 |
+
delta_pct = ((predicted - actual) / actual) * 100
|
| 193 |
+
if delta_pct >= 5:
|
| 194 |
+
return (
|
| 195 |
+
"Increase Opportunity",
|
| 196 |
+
f"Model suggests a {delta_pct:.1f}% upward repricing opportunity.",
|
| 197 |
+
"green",
|
| 198 |
+
)
|
| 199 |
+
if delta_pct <= -5:
|
| 200 |
+
return (
|
| 201 |
+
"Defensive Discount",
|
| 202 |
+
f"Model suggests a {abs(delta_pct):.1f}% lower price to stay competitive.",
|
| 203 |
+
"orange",
|
| 204 |
+
)
|
| 205 |
+
return "Hold Price", "Current price is already close to the model recommendation.", "gray"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def render_metric(label: str, value: str, sub: str) -> None:
|
| 209 |
+
st.markdown(
|
| 210 |
+
f'<div class="mcard">'
|
| 211 |
+
f' <div class="mcard-label">{label}</div>'
|
| 212 |
+
f' <div class="mcard-value">{value}</div>'
|
| 213 |
+
f' <div class="mcard-sub">{sub}</div>'
|
| 214 |
+
f'</div>',
|
| 215 |
+
unsafe_allow_html=True,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def render_signal(title: str, text: str, color: str) -> None:
|
| 220 |
+
st.markdown(
|
| 221 |
+
f'<div class="signal-banner {color}">'
|
| 222 |
+
f' <div>'
|
| 223 |
+
f' <div class="signal-title">{title}</div>'
|
| 224 |
+
f' <div class="signal-text">{text}</div>'
|
| 225 |
+
f' </div>'
|
| 226 |
+
f' <span class="signal-badge">{title}</span>'
|
| 227 |
+
f'</div>',
|
| 228 |
+
unsafe_allow_html=True,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def section_label(text: str) -> None:
|
| 233 |
+
st.markdown(f'<div class="section-sep">{text}</div>', unsafe_allow_html=True)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# ── Plotly theme helpers ───────────────────────────────────────────────────────
|
| 237 |
+
|
| 238 |
+
CHART_LAYOUT = dict(
|
| 239 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 240 |
+
plot_bgcolor="rgba(0,0,0,0)",
|
| 241 |
+
font_color="#94a3b8",
|
| 242 |
+
margin=dict(l=8, r=8, t=36, b=8),
|
| 243 |
+
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
|
| 244 |
+
xaxis=dict(showgrid=False, linecolor="rgba(148,163,184,0.15)"),
|
| 245 |
+
yaxis=dict(gridcolor="rgba(148,163,184,0.10)", linecolor="rgba(148,163,184,0.15)"),
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# ── Bootstrap ─────────────────────────────────────────────────────────────────
|
| 250 |
+
|
| 251 |
+
inject_styles()
|
| 252 |
+
bundle = load_bundle()
|
| 253 |
+
metrics = load_metrics()
|
| 254 |
+
data, kaggle_path = load_kaggle_data()
|
| 255 |
+
|
| 256 |
+
# ── Guards ─────────────────────────────────────────────────────────────────────
|
| 257 |
+
|
| 258 |
+
if bundle is None:
|
| 259 |
+
st.error("No trained model artifact found. Train the Kaggle model first.")
|
| 260 |
+
st.code(
|
| 261 |
+
"python scripts/train_model.py --profile kaggle_retail "
|
| 262 |
+
"--data-path data/raw/kaggle/retail_price.csv"
|
| 263 |
+
)
|
| 264 |
+
st.stop()
|
| 265 |
+
|
| 266 |
+
if bundle.get("dataset_profile") != "kaggle_retail":
|
| 267 |
+
st.warning(
|
| 268 |
+
"The loaded model is not the Kaggle retail profile. "
|
| 269 |
+
"Retrain with `--profile kaggle_retail` to use this dashboard."
|
| 270 |
+
)
|
| 271 |
+
st.code(
|
| 272 |
+
"python scripts/train_model.py --profile kaggle_retail "
|
| 273 |
+
"--data-path data/raw/kaggle/retail_price.csv"
|
| 274 |
+
)
|
| 275 |
+
st.stop()
|
| 276 |
+
|
| 277 |
+
if data.empty or kaggle_path is None:
|
| 278 |
+
st.error(
|
| 279 |
+
"Kaggle retail dataset not found. "
|
| 280 |
+
"Place `retail_price.csv` in `data/raw/kaggle/` or `data/raw/`."
|
| 281 |
+
)
|
| 282 |
+
st.stop()
|
| 283 |
+
|
| 284 |
+
pipeline = bundle["pipeline"]
|
| 285 |
+
numeric_features = bundle["numeric_features"]
|
| 286 |
+
categorical_features = bundle["categorical_features"]
|
| 287 |
+
target_column = bundle["target_column"]
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# ── Sidebar ────────────────────────────────────────────────────────────────────
|
| 291 |
+
|
| 292 |
+
with st.sidebar:
|
| 293 |
+
st.markdown("### Scenario Builder")
|
| 294 |
+
|
| 295 |
+
category_options = sorted(data["product_category_name"].dropna().unique())
|
| 296 |
+
selected_category = st.selectbox("Category", category_options)
|
| 297 |
+
|
| 298 |
+
category_frame = data[data["product_category_name"] == selected_category].copy()
|
| 299 |
+
product_options = sorted(category_frame["product_id"].dropna().unique())
|
| 300 |
+
selected_product = st.selectbox("Product", product_options)
|
| 301 |
+
|
| 302 |
+
product_frame = category_frame[category_frame["product_id"] == selected_product].copy()
|
| 303 |
+
if "month_year" in product_frame.columns:
|
| 304 |
+
product_frame["_label"] = product_frame["month_year"].astype(str)
|
| 305 |
+
month_options = product_frame["_label"].tolist()
|
| 306 |
+
selected_month_label = st.selectbox("Period", month_options, index=len(month_options) - 1)
|
| 307 |
+
selected_row = product_frame[product_frame["_label"] == selected_month_label].iloc[-1].copy()
|
| 308 |
+
else:
|
| 309 |
+
selected_month_label = ""
|
| 310 |
+
selected_row = product_frame.iloc[-1].copy()
|
| 311 |
+
|
| 312 |
+
st.divider()
|
| 313 |
+
st.caption("COMMERCIAL")
|
| 314 |
+
qty = st.slider(
|
| 315 |
+
"Units sold", 0, int(max(data["qty"].max(), 20)), safe_int(selected_row["qty"], 1)
|
| 316 |
+
)
|
| 317 |
+
customers = st.slider(
|
| 318 |
+
"Customers", 0, int(max(data["customers"].max(), 20)), safe_int(selected_row["customers"], 1)
|
| 319 |
+
)
|
| 320 |
+
freight_price = st.number_input(
|
| 321 |
+
"Freight price", min_value=0.0, value=safe_float(selected_row["freight_price"]), step=0.5
|
| 322 |
+
)
|
| 323 |
+
lag_price = st.number_input(
|
| 324 |
+
"Previous price", min_value=0.0, value=safe_float(selected_row["lag_price"]), step=0.5
|
| 325 |
+
)
|
| 326 |
+
product_score = st.slider(
|
| 327 |
+
"Product rating", 0.0, 5.0, safe_float(selected_row["product_score"]), 0.1
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
st.divider()
|
| 331 |
+
st.caption("COMPETITIVE")
|
| 332 |
+
comp_1 = st.number_input("Competitor 1", min_value=0.0, value=safe_float(selected_row["comp_1"]), step=0.5)
|
| 333 |
+
comp_2 = st.number_input("Competitor 2", min_value=0.0, value=safe_float(selected_row["comp_2"]), step=0.5)
|
| 334 |
+
comp_3 = st.number_input("Competitor 3", min_value=0.0, value=safe_float(selected_row["comp_3"]), step=0.5)
|
| 335 |
+
ps1 = st.slider("Competitor 1 rating", 0.0, 5.0, safe_float(selected_row["ps1"]), 0.1)
|
| 336 |
+
ps2 = st.slider("Competitor 2 rating", 0.0, 5.0, safe_float(selected_row["ps2"]), 0.1)
|
| 337 |
+
ps3 = st.slider("Competitor 3 rating", 0.0, 5.0, safe_float(selected_row["ps3"]), 0.1)
|
| 338 |
+
|
| 339 |
+
st.divider()
|
| 340 |
+
st.caption("PRODUCT")
|
| 341 |
+
product_name_lenght = st.slider(
|
| 342 |
+
"Name length", 0, int(max(data["product_name_lenght"].max(), 50)),
|
| 343 |
+
safe_int(selected_row["product_name_lenght"])
|
| 344 |
+
)
|
| 345 |
+
product_description_lenght = st.slider(
|
| 346 |
+
"Description length", 0, int(max(data["product_description_lenght"].max(), 200)),
|
| 347 |
+
safe_int(selected_row["product_description_lenght"])
|
| 348 |
+
)
|
| 349 |
+
product_photos_qty = st.slider(
|
| 350 |
+
"Photos", 0, int(max(data["product_photos_qty"].max(), 10)),
|
| 351 |
+
safe_int(selected_row["product_photos_qty"])
|
| 352 |
+
)
|
| 353 |
+
product_weight_g = st.slider(
|
| 354 |
+
"Weight (g)", 0, int(max(data["product_weight_g"].max(), 5000)),
|
| 355 |
+
safe_int(selected_row["product_weight_g"])
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# ── Compute scenario ───────────────────────────────────────────────────────────
|
| 360 |
+
|
| 361 |
+
scenario = selected_row.copy()
|
| 362 |
+
scenario.update({
|
| 363 |
+
"qty": qty, "customers": customers, "freight_price": freight_price,
|
| 364 |
+
"lag_price": lag_price, "product_score": product_score,
|
| 365 |
+
"comp_1": comp_1, "comp_2": comp_2, "comp_3": comp_3,
|
| 366 |
+
"ps1": ps1, "ps2": ps2, "ps3": ps3,
|
| 367 |
+
"product_name_lenght": product_name_lenght,
|
| 368 |
+
"product_description_lenght": product_description_lenght,
|
| 369 |
+
"product_photos_qty": product_photos_qty,
|
| 370 |
+
"product_weight_g": product_weight_g,
|
| 371 |
+
})
|
| 372 |
+
|
| 373 |
+
feature_frame = pd.DataFrame([scenario])[numeric_features + categorical_features]
|
| 374 |
+
predicted_price = float(pipeline.predict(feature_frame)[0])
|
| 375 |
+
actual_price = float(selected_row[target_column])
|
| 376 |
+
price_gap = predicted_price - actual_price
|
| 377 |
+
|
| 378 |
+
comp_series = pd.Series([comp_1, comp_2, comp_3]).replace(0, pd.NA).dropna()
|
| 379 |
+
avg_competitor_price = float(comp_series.mean()) if not comp_series.empty else float("nan")
|
| 380 |
+
|
| 381 |
+
sig_title, sig_text, sig_color = price_signal(predicted_price, actual_price)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
# ── Page header ────────────────────────────────────────────────────────────────
|
| 385 |
+
|
| 386 |
+
context_parts = [c for c in [selected_category, selected_product, selected_month_label] if c]
|
| 387 |
+
st.markdown(
|
| 388 |
+
f'<div class="page-header">'
|
| 389 |
+
f' <span class="page-title">Retail Pricing Studio</span>'
|
| 390 |
+
f' <span class="page-context">{" · ".join(context_parts)}</span>'
|
| 391 |
+
f'</div>',
|
| 392 |
+
unsafe_allow_html=True,
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
render_signal(sig_title, sig_text, sig_color)
|
| 396 |
+
st.write("") # spacing
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
# ── KPI row ────────────────────────────────────────────────────────────────────
|
| 400 |
+
|
| 401 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 402 |
+
with c1:
|
| 403 |
+
render_metric("Recommendation", fmt_inr(predicted_price), "Predicted unit price")
|
| 404 |
+
with c2:
|
| 405 |
+
render_metric("Current price", fmt_inr(actual_price), "Reference record")
|
| 406 |
+
with c3:
|
| 407 |
+
delta_sign = "+" if price_gap >= 0 else ""
|
| 408 |
+
render_metric("Delta", f"{delta_sign}{fmt_inr(price_gap)}", "Predicted vs current")
|
| 409 |
+
with c4:
|
| 410 |
+
render_metric("Avg competitor", fmt_inr(avg_competitor_price), "Across 3 references")
|
| 411 |
+
|
| 412 |
+
st.write("")
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
# ── Main content ───────────────────────────────────────────────────────────────
|
| 416 |
+
|
| 417 |
+
left_col, right_col = st.columns([1.5, 1], gap="medium")
|
| 418 |
+
|
| 419 |
+
# ── Left: charts ───────────────────────────────────────────────────────────────
|
| 420 |
+
|
| 421 |
+
with left_col:
|
| 422 |
+
# Price history
|
| 423 |
+
if "month_year" in product_frame.columns:
|
| 424 |
+
hist = product_frame[["month_year", target_column]].copy()
|
| 425 |
+
hist["month_year"] = pd.to_datetime(hist["month_year"], dayfirst=True, errors="coerce")
|
| 426 |
+
hist = hist.sort_values("month_year")
|
| 427 |
+
|
| 428 |
+
if not hist.empty:
|
| 429 |
+
scenario_date = hist["month_year"].max() + pd.offsets.MonthBegin(1)
|
| 430 |
+
combined = pd.concat(
|
| 431 |
+
[
|
| 432 |
+
hist.rename(columns={target_column: "unit_price"}).assign(series="Historical"),
|
| 433 |
+
pd.DataFrame({
|
| 434 |
+
"month_year": [scenario_date],
|
| 435 |
+
"unit_price": [predicted_price],
|
| 436 |
+
"series": ["Scenario"],
|
| 437 |
+
}),
|
| 438 |
+
],
|
| 439 |
+
ignore_index=True,
|
| 440 |
+
)
|
| 441 |
+
fig_line = px.line(
|
| 442 |
+
combined, x="month_year", y="unit_price", color="series", markers=True,
|
| 443 |
+
color_discrete_map={"Historical": "#0ea5e9", "Scenario": "#f97316"},
|
| 444 |
+
title="Price history",
|
| 445 |
+
)
|
| 446 |
+
fig_line.update_layout(height=260, **CHART_LAYOUT)
|
| 447 |
+
fig_line.update_traces(line_width=2)
|
| 448 |
+
st.plotly_chart(fig_line, use_container_width=True)
|
| 449 |
+
|
| 450 |
+
# Competitive comparison
|
| 451 |
+
comp_df = pd.DataFrame({
|
| 452 |
+
"label": ["Current", "Predicted", "Comp 1", "Comp 2", "Comp 3"],
|
| 453 |
+
"price": [actual_price, predicted_price, comp_1, comp_2, comp_3],
|
| 454 |
+
"color": ["#0ea5e9", "#f97316", "#94a3b8", "#94a3b8", "#94a3b8"],
|
| 455 |
+
})
|
| 456 |
+
fig_bar = go.Figure(
|
| 457 |
+
go.Bar(
|
| 458 |
+
x=comp_df["label"],
|
| 459 |
+
y=comp_df["price"],
|
| 460 |
+
marker_color=comp_df["color"],
|
| 461 |
+
text=[fmt_inr(v) for v in comp_df["price"]],
|
| 462 |
+
textposition="outside",
|
| 463 |
+
textfont_size=11,
|
| 464 |
+
)
|
| 465 |
+
)
|
| 466 |
+
fig_bar.update_layout(height=260, title="Market comparison", **CHART_LAYOUT)
|
| 467 |
+
st.plotly_chart(fig_bar, use_container_width=True)
|
| 468 |
+
|
| 469 |
+
# Category distribution
|
| 470 |
+
cat_data = data[data["product_category_name"] == selected_category]
|
| 471 |
+
fig_hist = px.histogram(
|
| 472 |
+
cat_data, x=target_column, nbins=24,
|
| 473 |
+
title=f"{selected_category.replace('_', ' ').title()} — price distribution",
|
| 474 |
+
color_discrete_sequence=["#0ea5e9"],
|
| 475 |
+
)
|
| 476 |
+
fig_hist.add_vline(
|
| 477 |
+
x=predicted_price, line_dash="dash", line_color="#f97316",
|
| 478 |
+
annotation_text="Predicted", annotation_position="top right",
|
| 479 |
+
annotation_font_size=11,
|
| 480 |
+
)
|
| 481 |
+
fig_hist.update_layout(height=240, **CHART_LAYOUT)
|
| 482 |
+
st.plotly_chart(fig_hist, use_container_width=True)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
# ── Right: panels ──────────────────────────────────────────────────────────────
|
| 486 |
+
|
| 487 |
+
with right_col:
|
| 488 |
+
|
| 489 |
+
# Scenario summary
|
| 490 |
+
section_label("Scenario")
|
| 491 |
+
summary_rows = [
|
| 492 |
+
("Units sold", qty),
|
| 493 |
+
("Customers", customers),
|
| 494 |
+
("Freight price", fmt_inr(freight_price)),
|
| 495 |
+
("Previous price", fmt_inr(lag_price)),
|
| 496 |
+
("Product rating", f"{product_score:.1f}"),
|
| 497 |
+
]
|
| 498 |
+
rows_html = "".join(
|
| 499 |
+
f'<tr><td class="kv-key">{k}</td><td class="kv-val">{v}</td></tr>'
|
| 500 |
+
for k, v in summary_rows
|
| 501 |
+
)
|
| 502 |
+
st.markdown(
|
| 503 |
+
f'<table class="kv-table">{rows_html}</table>',
|
| 504 |
+
unsafe_allow_html=True,
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
# Competitive pressure
|
| 508 |
+
section_label("Competitive pressure")
|
| 509 |
+
comp_rows = [
|
| 510 |
+
("Competitor 1", fmt_inr(comp_1), f"{ps1:.1f} ★"),
|
| 511 |
+
("Competitor 2", fmt_inr(comp_2), f"{ps2:.1f} ★"),
|
| 512 |
+
("Competitor 3", fmt_inr(comp_3), f"{ps3:.1f} ★"),
|
| 513 |
+
]
|
| 514 |
+
comp_html = "".join(
|
| 515 |
+
f'<tr>'
|
| 516 |
+
f' <td class="kv-key">{name}</td>'
|
| 517 |
+
f' <td class="kv-val">{price}</td>'
|
| 518 |
+
f' <td class="kv-val" style="opacity:0.5;font-weight:400">{rating}</td>'
|
| 519 |
+
f'</tr>'
|
| 520 |
+
for name, price, rating in comp_rows
|
| 521 |
+
)
|
| 522 |
+
st.markdown(f'<table class="kv-table">{comp_html}</table>', unsafe_allow_html=True)
|
| 523 |
+
|
| 524 |
+
if not pd.isna(avg_competitor_price):
|
| 525 |
+
pressure = "below" if predicted_price < avg_competitor_price else "above"
|
| 526 |
+
gap_abs = abs(predicted_price - avg_competitor_price)
|
| 527 |
+
st.caption(
|
| 528 |
+
f"Predicted price is {fmt_inr(gap_abs)} {pressure} the average competitor price."
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# Repricing opportunities
|
| 532 |
+
section_label("Top repricing opportunities")
|
| 533 |
+
sample_n = min(len(data), 250)
|
| 534 |
+
sample_df = data.sample(sample_n, random_state=42).copy()
|
| 535 |
+
sample_feats = sample_df[numeric_features + categorical_features]
|
| 536 |
+
sample_df["predicted_unit_price"] = pipeline.predict(sample_feats)
|
| 537 |
+
sample_df["opportunity_gap"] = sample_df["predicted_unit_price"] - sample_df[target_column]
|
| 538 |
+
|
| 539 |
+
top_ops = (
|
| 540 |
+
sample_df.sort_values("opportunity_gap", ascending=False)
|
| 541 |
+
.head(8)[["product_id", "product_category_name", target_column, "predicted_unit_price", "opportunity_gap"]]
|
| 542 |
+
.rename(columns={
|
| 543 |
+
"product_id": "Product",
|
| 544 |
+
"product_category_name": "Category",
|
| 545 |
+
target_column: "Current",
|
| 546 |
+
"predicted_unit_price": "Predicted",
|
| 547 |
+
"opportunity_gap": "Upside",
|
| 548 |
+
})
|
| 549 |
+
)
|
| 550 |
+
top_ops["Current"] = top_ops["Current"].map(fmt_inr)
|
| 551 |
+
top_ops["Predicted"] = top_ops["Predicted"].map(fmt_inr)
|
| 552 |
+
top_ops["Upside"] = top_ops["Upside"].map(lambda x: f"+{fmt_inr(x)}" if x >= 0 else fmt_inr(x))
|
| 553 |
+
|
| 554 |
+
st.dataframe(top_ops, use_container_width=True, hide_index=True, height=260)
|
app/feature_engineering.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Iterable
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
NUMERIC_FEATURES = [
|
| 11 |
+
"hour_of_day",
|
| 12 |
+
"day_of_week",
|
| 13 |
+
"is_weekend",
|
| 14 |
+
"is_festival",
|
| 15 |
+
"inventory_level",
|
| 16 |
+
"inventory_days_cover",
|
| 17 |
+
"competitor_price",
|
| 18 |
+
"click_through_rate",
|
| 19 |
+
"conversion_rate",
|
| 20 |
+
"units_sold_last_5m",
|
| 21 |
+
"units_sold_last_1h",
|
| 22 |
+
"base_cost",
|
| 23 |
+
"current_price",
|
| 24 |
+
"demand_index",
|
| 25 |
+
"inventory_pressure",
|
| 26 |
+
"competitor_gap",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
CATEGORICAL_FEATURES = ["category", "brand", "customer_segment"]
|
| 30 |
+
TARGET_COLUMN = "optimal_price"
|
| 31 |
+
|
| 32 |
+
KAGGLE_RETAIL_NUMERIC_FEATURES = [
|
| 33 |
+
"qty",
|
| 34 |
+
"freight_price",
|
| 35 |
+
"product_name_lenght",
|
| 36 |
+
"product_description_lenght",
|
| 37 |
+
"product_photos_qty",
|
| 38 |
+
"product_weight_g",
|
| 39 |
+
"product_score",
|
| 40 |
+
"customers",
|
| 41 |
+
"weekday",
|
| 42 |
+
"weekend",
|
| 43 |
+
"holiday",
|
| 44 |
+
"volume",
|
| 45 |
+
"comp_1",
|
| 46 |
+
"ps1",
|
| 47 |
+
"fp1",
|
| 48 |
+
"comp_2",
|
| 49 |
+
"ps2",
|
| 50 |
+
"fp2",
|
| 51 |
+
"comp_3",
|
| 52 |
+
"ps3",
|
| 53 |
+
"fp3",
|
| 54 |
+
"lag_price",
|
| 55 |
+
"month",
|
| 56 |
+
"year",
|
| 57 |
+
]
|
| 58 |
+
KAGGLE_RETAIL_CATEGORICAL_FEATURES = ["product_id", "product_category_name"]
|
| 59 |
+
KAGGLE_RETAIL_TARGET_COLUMN = "unit_price"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def add_derived_features(frame: pd.DataFrame) -> pd.DataFrame:
|
| 63 |
+
enriched = frame.copy()
|
| 64 |
+
enriched["demand_index"] = (
|
| 65 |
+
enriched["units_sold_last_1h"] * 0.55
|
| 66 |
+
+ enriched["units_sold_last_5m"] * 0.35
|
| 67 |
+
+ enriched["conversion_rate"] * 100 * 0.10
|
| 68 |
+
)
|
| 69 |
+
enriched["inventory_pressure"] = np.where(
|
| 70 |
+
enriched["inventory_level"] <= 20,
|
| 71 |
+
1.25,
|
| 72 |
+
np.where(enriched["inventory_level"] <= 60, 1.05, 0.92),
|
| 73 |
+
)
|
| 74 |
+
enriched["competitor_gap"] = (
|
| 75 |
+
enriched["current_price"] - enriched["competitor_price"]
|
| 76 |
+
) / enriched["competitor_price"].clip(lower=1.0)
|
| 77 |
+
return enriched
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load_training_data(path: Path) -> pd.DataFrame:
|
| 81 |
+
frame = pd.read_csv(path)
|
| 82 |
+
return add_derived_features(frame)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def load_kaggle_retail_training_data(path: Path) -> pd.DataFrame:
|
| 86 |
+
frame = pd.read_csv(path)
|
| 87 |
+
|
| 88 |
+
if "month_year" in frame.columns:
|
| 89 |
+
parsed_month_year = pd.to_datetime(frame["month_year"], dayfirst=True, errors="coerce")
|
| 90 |
+
if "month" not in frame.columns:
|
| 91 |
+
frame["month"] = parsed_month_year.dt.month
|
| 92 |
+
if "year" not in frame.columns:
|
| 93 |
+
frame["year"] = parsed_month_year.dt.year
|
| 94 |
+
|
| 95 |
+
numeric_defaults = [
|
| 96 |
+
"comp_1",
|
| 97 |
+
"ps1",
|
| 98 |
+
"fp1",
|
| 99 |
+
"comp_2",
|
| 100 |
+
"ps2",
|
| 101 |
+
"fp2",
|
| 102 |
+
"comp_3",
|
| 103 |
+
"ps3",
|
| 104 |
+
"fp3",
|
| 105 |
+
"lag_price",
|
| 106 |
+
]
|
| 107 |
+
for column in numeric_defaults:
|
| 108 |
+
if column not in frame.columns:
|
| 109 |
+
frame[column] = np.nan
|
| 110 |
+
|
| 111 |
+
if "volume" not in frame.columns:
|
| 112 |
+
frame["volume"] = (
|
| 113 |
+
frame.get("product_name_lenght", 0).fillna(0)
|
| 114 |
+
* frame.get("product_description_lenght", 0).fillna(0)
|
| 115 |
+
* frame.get("product_photos_qty", 0).fillna(0).clip(lower=1)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if "weekday" not in frame.columns:
|
| 119 |
+
frame["weekday"] = 0
|
| 120 |
+
if "weekend" not in frame.columns:
|
| 121 |
+
frame["weekend"] = 0
|
| 122 |
+
if "holiday" not in frame.columns:
|
| 123 |
+
frame["holiday"] = 0
|
| 124 |
+
|
| 125 |
+
ensure_columns(
|
| 126 |
+
frame,
|
| 127 |
+
KAGGLE_RETAIL_NUMERIC_FEATURES
|
| 128 |
+
+ KAGGLE_RETAIL_CATEGORICAL_FEATURES
|
| 129 |
+
+ [KAGGLE_RETAIL_TARGET_COLUMN],
|
| 130 |
+
)
|
| 131 |
+
return frame
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def split_xy(
|
| 135 |
+
frame: pd.DataFrame,
|
| 136 |
+
numeric_features: list[str] | None = None,
|
| 137 |
+
categorical_features: list[str] | None = None,
|
| 138 |
+
target_column: str = TARGET_COLUMN,
|
| 139 |
+
) -> tuple[pd.DataFrame, pd.Series]:
|
| 140 |
+
selected_numeric = numeric_features or NUMERIC_FEATURES
|
| 141 |
+
selected_categorical = categorical_features or CATEGORICAL_FEATURES
|
| 142 |
+
features = frame[selected_numeric + selected_categorical].copy()
|
| 143 |
+
target = frame[target_column].copy()
|
| 144 |
+
return features, target
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def ensure_columns(frame: pd.DataFrame, required_columns: Iterable[str]) -> None:
|
| 148 |
+
missing = [column for column in required_columns if column not in frame.columns]
|
| 149 |
+
if missing:
|
| 150 |
+
raise ValueError(f"Missing required columns: {missing}")
|
app/modeling.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import joblib
|
| 8 |
+
import numpy as np
|
| 9 |
+
from sklearn.compose import ColumnTransformer
|
| 10 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 11 |
+
from sklearn.impute import SimpleImputer
|
| 12 |
+
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
|
| 13 |
+
from sklearn.model_selection import train_test_split
|
| 14 |
+
from sklearn.pipeline import Pipeline
|
| 15 |
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
| 16 |
+
from xgboost import XGBRegressor
|
| 17 |
+
|
| 18 |
+
from app.feature_engineering import (
|
| 19 |
+
CATEGORICAL_FEATURES,
|
| 20 |
+
KAGGLE_RETAIL_CATEGORICAL_FEATURES,
|
| 21 |
+
KAGGLE_RETAIL_NUMERIC_FEATURES,
|
| 22 |
+
KAGGLE_RETAIL_TARGET_COLUMN,
|
| 23 |
+
NUMERIC_FEATURES,
|
| 24 |
+
TARGET_COLUMN,
|
| 25 |
+
load_kaggle_retail_training_data,
|
| 26 |
+
load_training_data,
|
| 27 |
+
split_xy,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class TrainingResult:
|
| 33 |
+
model_name: str
|
| 34 |
+
mae: float
|
| 35 |
+
rmse: float
|
| 36 |
+
r2: float
|
| 37 |
+
artifact_path: Path
|
| 38 |
+
dataset_profile: str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build_preprocessor(
|
| 42 |
+
numeric_features: list[str], categorical_features: list[str]
|
| 43 |
+
) -> ColumnTransformer:
|
| 44 |
+
numeric_pipeline = Pipeline(
|
| 45 |
+
steps=[
|
| 46 |
+
("imputer", SimpleImputer(strategy="median")),
|
| 47 |
+
("scaler", StandardScaler()),
|
| 48 |
+
]
|
| 49 |
+
)
|
| 50 |
+
categorical_pipeline = Pipeline(
|
| 51 |
+
steps=[
|
| 52 |
+
("imputer", SimpleImputer(strategy="most_frequent")),
|
| 53 |
+
("encoder", OneHotEncoder(handle_unknown="ignore")),
|
| 54 |
+
]
|
| 55 |
+
)
|
| 56 |
+
return ColumnTransformer(
|
| 57 |
+
transformers=[
|
| 58 |
+
("numeric", numeric_pipeline, numeric_features),
|
| 59 |
+
("categorical", categorical_pipeline, categorical_features),
|
| 60 |
+
]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def build_models() -> dict[str, object]:
|
| 65 |
+
return {
|
| 66 |
+
"random_forest": RandomForestRegressor(
|
| 67 |
+
n_estimators=250,
|
| 68 |
+
max_depth=16,
|
| 69 |
+
min_samples_leaf=2,
|
| 70 |
+
random_state=42,
|
| 71 |
+
n_jobs=-1,
|
| 72 |
+
),
|
| 73 |
+
"xgboost": XGBRegressor(
|
| 74 |
+
n_estimators=350,
|
| 75 |
+
max_depth=8,
|
| 76 |
+
learning_rate=0.05,
|
| 77 |
+
subsample=0.9,
|
| 78 |
+
colsample_bytree=0.9,
|
| 79 |
+
objective="reg:squarederror",
|
| 80 |
+
random_state=42,
|
| 81 |
+
),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_dataset_profile(dataset_profile: str) -> dict[str, object]:
|
| 86 |
+
profiles = {
|
| 87 |
+
"synthetic": {
|
| 88 |
+
"loader": load_training_data,
|
| 89 |
+
"numeric_features": NUMERIC_FEATURES,
|
| 90 |
+
"categorical_features": CATEGORICAL_FEATURES,
|
| 91 |
+
"target_column": TARGET_COLUMN,
|
| 92 |
+
},
|
| 93 |
+
"kaggle_retail": {
|
| 94 |
+
"loader": load_kaggle_retail_training_data,
|
| 95 |
+
"numeric_features": KAGGLE_RETAIL_NUMERIC_FEATURES,
|
| 96 |
+
"categorical_features": KAGGLE_RETAIL_CATEGORICAL_FEATURES,
|
| 97 |
+
"target_column": KAGGLE_RETAIL_TARGET_COLUMN,
|
| 98 |
+
},
|
| 99 |
+
}
|
| 100 |
+
if dataset_profile not in profiles:
|
| 101 |
+
raise ValueError(
|
| 102 |
+
f"Unsupported dataset profile '{dataset_profile}'. "
|
| 103 |
+
f"Expected one of: {', '.join(profiles)}"
|
| 104 |
+
)
|
| 105 |
+
return profiles[dataset_profile]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def train_best_model(
|
| 109 |
+
data_path: Path,
|
| 110 |
+
artifact_path: Path,
|
| 111 |
+
metrics_path: Path,
|
| 112 |
+
dataset_profile: str = "synthetic",
|
| 113 |
+
) -> TrainingResult:
|
| 114 |
+
profile = get_dataset_profile(dataset_profile)
|
| 115 |
+
frame = profile["loader"](data_path)
|
| 116 |
+
numeric_features = profile["numeric_features"]
|
| 117 |
+
categorical_features = profile["categorical_features"]
|
| 118 |
+
target_column = profile["target_column"]
|
| 119 |
+
x, y = split_xy(
|
| 120 |
+
frame,
|
| 121 |
+
numeric_features=numeric_features,
|
| 122 |
+
categorical_features=categorical_features,
|
| 123 |
+
target_column=target_column,
|
| 124 |
+
)
|
| 125 |
+
x_train, x_test, y_train, y_test = train_test_split(
|
| 126 |
+
x, y, test_size=0.2, random_state=42
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
preprocessor = build_preprocessor(
|
| 130 |
+
numeric_features=numeric_features,
|
| 131 |
+
categorical_features=categorical_features,
|
| 132 |
+
)
|
| 133 |
+
candidates = build_models()
|
| 134 |
+
best_result: TrainingResult | None = None
|
| 135 |
+
serialized_bundle = None
|
| 136 |
+
metrics_summary: dict[str, dict[str, float]] = {}
|
| 137 |
+
|
| 138 |
+
for model_name, estimator in candidates.items():
|
| 139 |
+
pipeline = Pipeline(
|
| 140 |
+
steps=[
|
| 141 |
+
("preprocessor", preprocessor),
|
| 142 |
+
("model", estimator),
|
| 143 |
+
]
|
| 144 |
+
)
|
| 145 |
+
pipeline.fit(x_train, y_train)
|
| 146 |
+
predictions = pipeline.predict(x_test)
|
| 147 |
+
mae = float(mean_absolute_error(y_test, predictions))
|
| 148 |
+
rmse = float(np.sqrt(mean_squared_error(y_test, predictions)))
|
| 149 |
+
r2 = float(r2_score(y_test, predictions))
|
| 150 |
+
metrics_summary[model_name] = {"mae": mae, "rmse": rmse, "r2": r2}
|
| 151 |
+
|
| 152 |
+
if best_result is None or mae < best_result.mae:
|
| 153 |
+
best_result = TrainingResult(
|
| 154 |
+
model_name=model_name,
|
| 155 |
+
mae=mae,
|
| 156 |
+
rmse=rmse,
|
| 157 |
+
r2=r2,
|
| 158 |
+
artifact_path=artifact_path,
|
| 159 |
+
dataset_profile=dataset_profile,
|
| 160 |
+
)
|
| 161 |
+
serialized_bundle = {
|
| 162 |
+
"pipeline": pipeline,
|
| 163 |
+
"model_name": model_name,
|
| 164 |
+
"dataset_profile": dataset_profile,
|
| 165 |
+
"numeric_features": numeric_features,
|
| 166 |
+
"categorical_features": categorical_features,
|
| 167 |
+
"target_column": target_column,
|
| 168 |
+
"features": numeric_features + categorical_features,
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
if best_result is None or serialized_bundle is None:
|
| 172 |
+
raise RuntimeError("No model was trained.")
|
| 173 |
+
|
| 174 |
+
artifact_path.parent.mkdir(parents=True, exist_ok=True)
|
| 175 |
+
metrics_path.parent.mkdir(parents=True, exist_ok=True)
|
| 176 |
+
joblib.dump(serialized_bundle, artifact_path)
|
| 177 |
+
|
| 178 |
+
metrics_payload = {
|
| 179 |
+
"dataset_profile": dataset_profile,
|
| 180 |
+
"data_path": str(data_path),
|
| 181 |
+
"best_model": best_result.model_name,
|
| 182 |
+
"best_model_metrics": {
|
| 183 |
+
"mae": best_result.mae,
|
| 184 |
+
"rmse": best_result.rmse,
|
| 185 |
+
"r2": best_result.r2,
|
| 186 |
+
},
|
| 187 |
+
"all_models": metrics_summary,
|
| 188 |
+
}
|
| 189 |
+
metrics_path.write_text(json.dumps(metrics_payload, indent=2), encoding="utf-8")
|
| 190 |
+
return best_result
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def load_model_bundle(artifact_path: Path) -> dict[str, object]:
|
| 194 |
+
return joblib.load(artifact_path)
|
app/pricing_engine.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
from collections import defaultdict, deque
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from datetime import UTC, datetime, timedelta
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
from app.cache import RedisCache
|
| 13 |
+
from app.config import Settings
|
| 14 |
+
from app.feature_engineering import KAGGLE_RETAIL_CATEGORICAL_FEATURES, KAGGLE_RETAIL_NUMERIC_FEATURES
|
| 15 |
+
from app.feature_engineering import add_derived_features
|
| 16 |
+
from app.modeling import load_model_bundle
|
| 17 |
+
from app.schemas import (
|
| 18 |
+
KagglePricingRequest,
|
| 19 |
+
KagglePricingResponse,
|
| 20 |
+
OrderEvent,
|
| 21 |
+
PricingRequest,
|
| 22 |
+
PricingResponse,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class PricingRecommendation:
|
| 28 |
+
response: PricingResponse
|
| 29 |
+
ml_price: float
|
| 30 |
+
blended_price: float
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass
|
| 34 |
+
class KagglePricingRecommendation:
|
| 35 |
+
response: KagglePricingResponse
|
| 36 |
+
ml_price: float
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class FlashSaleTracker:
|
| 40 |
+
def __init__(self, threshold: int, lookback_minutes: int):
|
| 41 |
+
self.threshold = threshold
|
| 42 |
+
self.lookback = timedelta(minutes=lookback_minutes)
|
| 43 |
+
self.events: dict[str, deque[datetime]] = defaultdict(deque)
|
| 44 |
+
|
| 45 |
+
def register(self, event: OrderEvent) -> bool:
|
| 46 |
+
queue = self.events[event.sku_id]
|
| 47 |
+
queue.append(event.event_time)
|
| 48 |
+
self._trim(event.sku_id, event.event_time)
|
| 49 |
+
return len(queue) >= self.threshold
|
| 50 |
+
|
| 51 |
+
def is_flash_sale(self, sku_id: str, now: datetime | None = None) -> bool:
|
| 52 |
+
reference_time = now or datetime.now(UTC)
|
| 53 |
+
self._trim(sku_id, reference_time)
|
| 54 |
+
return len(self.events[sku_id]) >= self.threshold
|
| 55 |
+
|
| 56 |
+
def recent_event_count(self) -> int:
|
| 57 |
+
now = datetime.now(UTC)
|
| 58 |
+
total = 0
|
| 59 |
+
for sku_id in list(self.events.keys()):
|
| 60 |
+
self._trim(sku_id, now)
|
| 61 |
+
total += len(self.events[sku_id])
|
| 62 |
+
return total
|
| 63 |
+
|
| 64 |
+
def flash_sale_skus(self) -> list[str]:
|
| 65 |
+
now = datetime.now(UTC)
|
| 66 |
+
active = []
|
| 67 |
+
for sku_id in list(self.events.keys()):
|
| 68 |
+
self._trim(sku_id, now)
|
| 69 |
+
if len(self.events[sku_id]) >= self.threshold:
|
| 70 |
+
active.append(sku_id)
|
| 71 |
+
return active
|
| 72 |
+
|
| 73 |
+
def _trim(self, sku_id: str, reference_time: datetime) -> None:
|
| 74 |
+
queue = self.events[sku_id]
|
| 75 |
+
while queue and reference_time - queue[0] > self.lookback:
|
| 76 |
+
queue.popleft()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class CompetitorPriceClient:
|
| 80 |
+
def __init__(self, settings: Settings):
|
| 81 |
+
self.settings = settings
|
| 82 |
+
|
| 83 |
+
def get_price(self, sku_id: str, fallback_price: float) -> float:
|
| 84 |
+
if not self.settings.competitor_api_url:
|
| 85 |
+
return fallback_price
|
| 86 |
+
try:
|
| 87 |
+
response = requests.get(
|
| 88 |
+
self.settings.competitor_api_url,
|
| 89 |
+
params={"sku_id": sku_id},
|
| 90 |
+
timeout=0.7,
|
| 91 |
+
)
|
| 92 |
+
response.raise_for_status()
|
| 93 |
+
payload = response.json()
|
| 94 |
+
return float(payload.get("competitor_price", fallback_price))
|
| 95 |
+
except Exception:
|
| 96 |
+
return fallback_price
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class PricingEngine:
|
| 100 |
+
def __init__(self, settings: Settings):
|
| 101 |
+
if not settings.model_path.exists():
|
| 102 |
+
raise FileNotFoundError(
|
| 103 |
+
f"Model artifact not found at {settings.model_path}. Train the model first."
|
| 104 |
+
)
|
| 105 |
+
self.settings = settings
|
| 106 |
+
self.bundle = load_model_bundle(settings.model_path)
|
| 107 |
+
self.dataset_profile = str(self.bundle.get("dataset_profile", "synthetic"))
|
| 108 |
+
self.pipeline = self.bundle["pipeline"]
|
| 109 |
+
self.flash_sale_tracker = FlashSaleTracker(
|
| 110 |
+
threshold=settings.flash_sale_order_threshold,
|
| 111 |
+
lookback_minutes=settings.flash_sale_lookback_minutes,
|
| 112 |
+
)
|
| 113 |
+
self.competitor_client = CompetitorPriceClient(settings)
|
| 114 |
+
self.cache = RedisCache(settings.redis_url)
|
| 115 |
+
|
| 116 |
+
def recommend_price(self, request: PricingRequest) -> PricingRecommendation:
|
| 117 |
+
if self.dataset_profile != "synthetic":
|
| 118 |
+
raise ValueError(
|
| 119 |
+
"The loaded model is not compatible with the synthetic pricing request schema."
|
| 120 |
+
)
|
| 121 |
+
frame = pd.DataFrame([request.model_dump()])
|
| 122 |
+
live_competitor_price = self.competitor_client.get_price(
|
| 123 |
+
request.sku_id, request.competitor_price
|
| 124 |
+
)
|
| 125 |
+
frame["competitor_price"] = live_competitor_price
|
| 126 |
+
enriched = add_derived_features(frame)
|
| 127 |
+
ml_price = float(self.pipeline.predict(enriched)[0])
|
| 128 |
+
|
| 129 |
+
blended_price = (
|
| 130 |
+
ml_price * self.settings.model_weight
|
| 131 |
+
+ live_competitor_price * self.settings.competitor_weight
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
inventory_adjustment = self._inventory_adjustment(
|
| 135 |
+
inventory_level=request.inventory_level,
|
| 136 |
+
inventory_days_cover=request.inventory_days_cover,
|
| 137 |
+
)
|
| 138 |
+
demand_adjustment = self._demand_adjustment(
|
| 139 |
+
units_sold_last_5m=request.units_sold_last_5m,
|
| 140 |
+
units_sold_last_1h=request.units_sold_last_1h,
|
| 141 |
+
conversion_rate=request.conversion_rate,
|
| 142 |
+
is_festival=request.is_festival,
|
| 143 |
+
)
|
| 144 |
+
detected_flash_sale = self.flash_sale_tracker.is_flash_sale(request.sku_id)
|
| 145 |
+
flash_sale_multiplier = 1.12 if detected_flash_sale else 1.0
|
| 146 |
+
|
| 147 |
+
candidate_price = blended_price * inventory_adjustment * demand_adjustment
|
| 148 |
+
candidate_price *= flash_sale_multiplier
|
| 149 |
+
guardrailed_price = self._apply_guardrails(
|
| 150 |
+
candidate_price=candidate_price,
|
| 151 |
+
base_cost=request.base_cost,
|
| 152 |
+
current_price=request.current_price,
|
| 153 |
+
)
|
| 154 |
+
confidence = self._confidence_score(request, live_competitor_price)
|
| 155 |
+
reason = self._build_reason(
|
| 156 |
+
inventory_adjustment=inventory_adjustment,
|
| 157 |
+
demand_adjustment=demand_adjustment,
|
| 158 |
+
detected_flash_sale=detected_flash_sale,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
response = PricingResponse(
|
| 162 |
+
sku_id=request.sku_id,
|
| 163 |
+
recommended_price=round(guardrailed_price, 2),
|
| 164 |
+
ml_price=round(ml_price, 2),
|
| 165 |
+
blended_price=round(blended_price, 2),
|
| 166 |
+
inventory_adjustment=round(inventory_adjustment, 3),
|
| 167 |
+
demand_adjustment=round(demand_adjustment, 3),
|
| 168 |
+
flash_sale_multiplier=round(flash_sale_multiplier, 3),
|
| 169 |
+
confidence=round(confidence, 3),
|
| 170 |
+
detected_flash_sale=detected_flash_sale,
|
| 171 |
+
reason=reason,
|
| 172 |
+
generated_at=datetime.now(UTC),
|
| 173 |
+
)
|
| 174 |
+
self._append_price_history(response, request.base_cost)
|
| 175 |
+
return PricingRecommendation(
|
| 176 |
+
response=response,
|
| 177 |
+
ml_price=ml_price,
|
| 178 |
+
blended_price=blended_price,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def recommend_kaggle_price(
|
| 182 |
+
self, request: KagglePricingRequest
|
| 183 |
+
) -> KagglePricingRecommendation:
|
| 184 |
+
if self.dataset_profile != "kaggle_retail":
|
| 185 |
+
raise ValueError(
|
| 186 |
+
"The loaded model is not compatible with the Kaggle retail pricing request schema."
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
payload = request.model_dump()
|
| 190 |
+
current_price = payload.pop("current_price")
|
| 191 |
+
feature_frame = pd.DataFrame([payload])[
|
| 192 |
+
KAGGLE_RETAIL_NUMERIC_FEATURES + KAGGLE_RETAIL_CATEGORICAL_FEATURES
|
| 193 |
+
]
|
| 194 |
+
ml_price = float(self.pipeline.predict(feature_frame)[0])
|
| 195 |
+
|
| 196 |
+
competitor_values = [
|
| 197 |
+
payload["comp_1"] or 0.0,
|
| 198 |
+
payload["comp_2"] or 0.0,
|
| 199 |
+
payload["comp_3"] or 0.0,
|
| 200 |
+
]
|
| 201 |
+
non_zero_competitors = [value for value in competitor_values if value > 0]
|
| 202 |
+
competitor_anchor = (
|
| 203 |
+
sum(non_zero_competitors) / len(non_zero_competitors)
|
| 204 |
+
if non_zero_competitors
|
| 205 |
+
else None
|
| 206 |
+
)
|
| 207 |
+
confidence = self._kaggle_confidence_score(request, competitor_anchor)
|
| 208 |
+
reason = self._build_kaggle_reason(current_price, ml_price, competitor_anchor)
|
| 209 |
+
|
| 210 |
+
response = KagglePricingResponse(
|
| 211 |
+
product_id=request.product_id,
|
| 212 |
+
product_category_name=request.product_category_name,
|
| 213 |
+
recommended_price=round(ml_price, 2),
|
| 214 |
+
current_price=round(current_price, 2),
|
| 215 |
+
gap_to_current_price=round(ml_price - current_price, 2),
|
| 216 |
+
competitor_anchor_price=(
|
| 217 |
+
round(competitor_anchor, 2) if competitor_anchor is not None else None
|
| 218 |
+
),
|
| 219 |
+
confidence=round(confidence, 3),
|
| 220 |
+
reason=reason,
|
| 221 |
+
generated_at=datetime.now(UTC),
|
| 222 |
+
)
|
| 223 |
+
return KagglePricingRecommendation(response=response, ml_price=ml_price)
|
| 224 |
+
|
| 225 |
+
def register_order_event(self, event: OrderEvent) -> bool:
|
| 226 |
+
if event.event_time.tzinfo is None:
|
| 227 |
+
event = OrderEvent(
|
| 228 |
+
sku_id=event.sku_id,
|
| 229 |
+
quantity=event.quantity,
|
| 230 |
+
event_time=event.event_time.replace(tzinfo=UTC),
|
| 231 |
+
)
|
| 232 |
+
return self.flash_sale_tracker.register(event)
|
| 233 |
+
|
| 234 |
+
def get_cached_recommendation(self, sku_id: str) -> dict[str, object] | None:
|
| 235 |
+
return self.cache.get_json(f"price:{sku_id}")
|
| 236 |
+
|
| 237 |
+
def _inventory_adjustment(self, inventory_level: int, inventory_days_cover: float) -> float:
|
| 238 |
+
if inventory_level <= 15 or inventory_days_cover < 3:
|
| 239 |
+
return 1.10
|
| 240 |
+
if inventory_level >= 120 or inventory_days_cover > 21:
|
| 241 |
+
return 0.93
|
| 242 |
+
return 1.0
|
| 243 |
+
|
| 244 |
+
def _demand_adjustment(
|
| 245 |
+
self,
|
| 246 |
+
units_sold_last_5m: int,
|
| 247 |
+
units_sold_last_1h: int,
|
| 248 |
+
conversion_rate: float,
|
| 249 |
+
is_festival: int,
|
| 250 |
+
) -> float:
|
| 251 |
+
rapid_demand = units_sold_last_5m >= 8 or units_sold_last_1h >= 40
|
| 252 |
+
strong_conversion = conversion_rate >= 0.045
|
| 253 |
+
if rapid_demand and strong_conversion:
|
| 254 |
+
return 1.08 + (0.03 if is_festival else 0.0)
|
| 255 |
+
if units_sold_last_1h <= 8 and conversion_rate < 0.02:
|
| 256 |
+
return 0.94
|
| 257 |
+
return 1.0
|
| 258 |
+
|
| 259 |
+
def _apply_guardrails(self, candidate_price: float, base_cost: float, current_price: float) -> float:
|
| 260 |
+
min_price = base_cost * (1.0 + self.settings.min_margin)
|
| 261 |
+
max_price = current_price * self.settings.max_price_multiplier
|
| 262 |
+
return max(min(candidate_price, max_price), min_price)
|
| 263 |
+
|
| 264 |
+
def _confidence_score(self, request: PricingRequest, competitor_price: float) -> float:
|
| 265 |
+
signal_score = min(request.conversion_rate * 12 + request.click_through_rate * 4, 0.45)
|
| 266 |
+
inventory_score = 0.25 if request.inventory_level > 10 else 0.12
|
| 267 |
+
competitor_score = 0.20 if competitor_price > 0 else 0.08
|
| 268 |
+
recency_score = 0.10 if request.units_sold_last_1h > 0 else 0.04
|
| 269 |
+
return min(signal_score + inventory_score + competitor_score + recency_score, 0.98)
|
| 270 |
+
|
| 271 |
+
def _build_reason(
|
| 272 |
+
self,
|
| 273 |
+
inventory_adjustment: float,
|
| 274 |
+
demand_adjustment: float,
|
| 275 |
+
detected_flash_sale: bool,
|
| 276 |
+
) -> str:
|
| 277 |
+
reasons = ["ML baseline with competitor blending"]
|
| 278 |
+
if inventory_adjustment > 1.0:
|
| 279 |
+
reasons.append("low inventory pressure")
|
| 280 |
+
elif inventory_adjustment < 1.0:
|
| 281 |
+
reasons.append("overstock discount")
|
| 282 |
+
if demand_adjustment > 1.0:
|
| 283 |
+
reasons.append("strong short-term demand")
|
| 284 |
+
elif demand_adjustment < 1.0:
|
| 285 |
+
reasons.append("soft demand correction")
|
| 286 |
+
if detected_flash_sale:
|
| 287 |
+
reasons.append("flash sale multiplier active")
|
| 288 |
+
return ", ".join(reasons)
|
| 289 |
+
|
| 290 |
+
def _kaggle_confidence_score(
|
| 291 |
+
self,
|
| 292 |
+
request: KagglePricingRequest,
|
| 293 |
+
competitor_anchor: float | None,
|
| 294 |
+
) -> float:
|
| 295 |
+
demand_score = min((request.qty / 40) + (request.customers / 80), 0.40)
|
| 296 |
+
rating_score = min(request.product_score / 10, 0.20)
|
| 297 |
+
competitor_score = 0.20 if competitor_anchor is not None else 0.08
|
| 298 |
+
recency_score = 0.10 if request.lag_price > 0 else 0.04
|
| 299 |
+
seasonal_score = 0.10 if request.holiday or request.weekend else 0.05
|
| 300 |
+
return min(
|
| 301 |
+
demand_score + rating_score + competitor_score + recency_score + seasonal_score,
|
| 302 |
+
0.97,
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
def _build_kaggle_reason(
|
| 306 |
+
self,
|
| 307 |
+
current_price: float,
|
| 308 |
+
ml_price: float,
|
| 309 |
+
competitor_anchor: float | None,
|
| 310 |
+
) -> str:
|
| 311 |
+
reasons = ["Kaggle retail model baseline"]
|
| 312 |
+
if competitor_anchor is not None:
|
| 313 |
+
if ml_price > competitor_anchor:
|
| 314 |
+
reasons.append("positioned above competitor average")
|
| 315 |
+
elif ml_price < competitor_anchor:
|
| 316 |
+
reasons.append("positioned below competitor average")
|
| 317 |
+
else:
|
| 318 |
+
reasons.append("aligned with competitor average")
|
| 319 |
+
if ml_price > current_price:
|
| 320 |
+
reasons.append("upside versus current price")
|
| 321 |
+
elif ml_price < current_price:
|
| 322 |
+
reasons.append("defensive move versus current price")
|
| 323 |
+
else:
|
| 324 |
+
reasons.append("flat versus current price")
|
| 325 |
+
return ", ".join(reasons)
|
| 326 |
+
|
| 327 |
+
def _append_price_history(self, response: PricingResponse, base_cost: float) -> None:
|
| 328 |
+
path = self.settings.price_history_path
|
| 329 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 330 |
+
file_exists = path.exists()
|
| 331 |
+
with path.open("a", newline="", encoding="utf-8") as handle:
|
| 332 |
+
writer = csv.writer(handle)
|
| 333 |
+
if not file_exists:
|
| 334 |
+
writer.writerow(
|
| 335 |
+
[
|
| 336 |
+
"generated_at",
|
| 337 |
+
"sku_id",
|
| 338 |
+
"recommended_price",
|
| 339 |
+
"ml_price",
|
| 340 |
+
"blended_price",
|
| 341 |
+
"confidence",
|
| 342 |
+
"detected_flash_sale",
|
| 343 |
+
"base_cost",
|
| 344 |
+
]
|
| 345 |
+
)
|
| 346 |
+
writer.writerow(
|
| 347 |
+
[
|
| 348 |
+
response.generated_at.isoformat(),
|
| 349 |
+
response.sku_id,
|
| 350 |
+
response.recommended_price,
|
| 351 |
+
response.ml_price,
|
| 352 |
+
response.blended_price,
|
| 353 |
+
response.confidence,
|
| 354 |
+
int(response.detected_flash_sale),
|
| 355 |
+
round(base_cost, 2),
|
| 356 |
+
]
|
| 357 |
+
)
|
| 358 |
+
self.cache.set_json(f"price:{response.sku_id}", response.model_dump(mode="json"))
|
app/schemas.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import UTC, datetime
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from pydantic import BaseModel, Field
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class PricingRequest(BaseModel):
|
| 8 |
+
sku_id: str = Field(..., examples=["SKU-1001"])
|
| 9 |
+
category: str
|
| 10 |
+
brand: str
|
| 11 |
+
customer_segment: str
|
| 12 |
+
hour_of_day: int = Field(..., ge=0, le=23)
|
| 13 |
+
day_of_week: int = Field(..., ge=0, le=6)
|
| 14 |
+
is_weekend: int = Field(..., ge=0, le=1)
|
| 15 |
+
is_festival: int = Field(..., ge=0, le=1)
|
| 16 |
+
inventory_level: int = Field(..., ge=0)
|
| 17 |
+
inventory_days_cover: float = Field(..., ge=0)
|
| 18 |
+
competitor_price: float = Field(..., gt=0)
|
| 19 |
+
click_through_rate: float = Field(..., ge=0)
|
| 20 |
+
conversion_rate: float = Field(..., ge=0)
|
| 21 |
+
units_sold_last_5m: int = Field(..., ge=0)
|
| 22 |
+
units_sold_last_1h: int = Field(..., ge=0)
|
| 23 |
+
base_cost: float = Field(..., gt=0)
|
| 24 |
+
current_price: float = Field(..., gt=0)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class PricingResponse(BaseModel):
|
| 28 |
+
sku_id: str
|
| 29 |
+
recommended_price: float
|
| 30 |
+
ml_price: float
|
| 31 |
+
blended_price: float
|
| 32 |
+
inventory_adjustment: float
|
| 33 |
+
demand_adjustment: float
|
| 34 |
+
flash_sale_multiplier: float
|
| 35 |
+
confidence: float
|
| 36 |
+
detected_flash_sale: bool
|
| 37 |
+
reason: str
|
| 38 |
+
generated_at: datetime
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class KagglePricingRequest(BaseModel):
|
| 42 |
+
product_id: str
|
| 43 |
+
product_category_name: str
|
| 44 |
+
qty: int = Field(..., ge=0)
|
| 45 |
+
freight_price: float = Field(..., ge=0)
|
| 46 |
+
product_name_lenght: int = Field(..., ge=0)
|
| 47 |
+
product_description_lenght: int = Field(..., ge=0)
|
| 48 |
+
product_photos_qty: int = Field(..., ge=0)
|
| 49 |
+
product_weight_g: int = Field(..., ge=0)
|
| 50 |
+
product_score: float = Field(..., ge=0)
|
| 51 |
+
customers: int = Field(..., ge=0)
|
| 52 |
+
weekday: int = Field(..., ge=0)
|
| 53 |
+
weekend: int = Field(..., ge=0, le=1)
|
| 54 |
+
holiday: int = Field(..., ge=0, le=1)
|
| 55 |
+
volume: float = Field(..., ge=0)
|
| 56 |
+
comp_1: float = Field(..., ge=0)
|
| 57 |
+
ps1: float = Field(..., ge=0)
|
| 58 |
+
fp1: float = Field(..., ge=0)
|
| 59 |
+
comp_2: float = Field(..., ge=0)
|
| 60 |
+
ps2: float = Field(..., ge=0)
|
| 61 |
+
fp2: float = Field(..., ge=0)
|
| 62 |
+
comp_3: float = Field(..., ge=0)
|
| 63 |
+
ps3: float = Field(..., ge=0)
|
| 64 |
+
fp3: float = Field(..., ge=0)
|
| 65 |
+
lag_price: float = Field(..., ge=0)
|
| 66 |
+
month: int = Field(..., ge=1, le=12)
|
| 67 |
+
year: int = Field(..., ge=2000)
|
| 68 |
+
current_price: float = Field(..., gt=0)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class KagglePricingResponse(BaseModel):
|
| 72 |
+
product_id: str
|
| 73 |
+
product_category_name: str
|
| 74 |
+
recommended_price: float
|
| 75 |
+
current_price: float
|
| 76 |
+
gap_to_current_price: float
|
| 77 |
+
competitor_anchor_price: Optional[float] = None
|
| 78 |
+
confidence: float
|
| 79 |
+
reason: str
|
| 80 |
+
generated_at: datetime
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class OrderEvent(BaseModel):
|
| 84 |
+
sku_id: str
|
| 85 |
+
quantity: int = Field(..., ge=1)
|
| 86 |
+
event_time: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class MonitoringSummary(BaseModel):
|
| 90 |
+
tracked_skus: int
|
| 91 |
+
recent_order_events: int
|
| 92 |
+
flash_sale_skus: list[str]
|
| 93 |
+
average_recommended_price: Optional[float] = None
|
| 94 |
+
last_price_update: Optional[datetime] = None
|
app/streaming.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from kafka import KafkaConsumer, KafkaProducer
|
| 7 |
+
|
| 8 |
+
from app.config import Settings
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PricingEventProducer:
|
| 12 |
+
def __init__(self, settings: Settings):
|
| 13 |
+
self.producer = KafkaProducer(
|
| 14 |
+
bootstrap_servers=settings.kafka_bootstrap_servers,
|
| 15 |
+
value_serializer=lambda value: json.dumps(value).encode("utf-8"),
|
| 16 |
+
)
|
| 17 |
+
self.order_topic = settings.kafka_topic_orders
|
| 18 |
+
self.click_topic = settings.kafka_topic_clicks
|
| 19 |
+
|
| 20 |
+
def publish_order(self, payload: dict[str, Any]) -> None:
|
| 21 |
+
self.producer.send(self.order_topic, payload)
|
| 22 |
+
self.producer.flush()
|
| 23 |
+
|
| 24 |
+
def publish_click(self, payload: dict[str, Any]) -> None:
|
| 25 |
+
self.producer.send(self.click_topic, payload)
|
| 26 |
+
self.producer.flush()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class PricingEventConsumer:
|
| 30 |
+
def __init__(self, settings: Settings, topic: str):
|
| 31 |
+
self.consumer = KafkaConsumer(
|
| 32 |
+
topic,
|
| 33 |
+
bootstrap_servers=settings.kafka_bootstrap_servers,
|
| 34 |
+
value_deserializer=lambda value: json.loads(value.decode("utf-8")),
|
| 35 |
+
auto_offset_reset="latest",
|
| 36 |
+
enable_auto_commit=True,
|
| 37 |
+
group_id="dynamic-pricing-engine",
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
def poll_forever(self):
|
| 41 |
+
for message in self.consumer:
|
| 42 |
+
yield message.value
|
data/processed/price_history.csv
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
generated_at,sku_id,recommended_price,ml_price,blended_price,confidence,detected_flash_sale,base_cost
|
| 2 |
+
2026-04-21T16:35:56.869147+00:00,SKU-1001,1846.47,1952.53,1846.47,0.98,0,1099.0
|
| 3 |
+
2026-04-21T16:36:06.169412+00:00,SKU-1001,1824.11,1920.58,1824.11,0.98,0,1099.0
|
| 4 |
+
2026-04-21T16:36:09.061906+00:00,SKU-1001,1830.16,1929.23,1830.16,0.98,0,1099.0
|
| 5 |
+
2026-04-21T16:36:12.102664+00:00,SKU-1001,1726.65,1781.35,1726.65,0.98,0,1099.0
|
| 6 |
+
2026-04-21T16:36:16.456700+00:00,SKU-1001,1809.18,1899.25,1809.18,0.98,0,1099.0
|
| 7 |
+
2026-04-21T16:36:19.487604+00:00,SKU-1001,1683.61,1900.91,1810.33,0.98,0,1099.0
|
| 8 |
+
2026-04-21T16:36:21.447530+00:00,SKU-1001,1683.22,1900.31,1809.91,0.98,0,1099.0
|
| 9 |
+
2026-04-21T16:36:21.965440+00:00,SKU-1001,1617.1,1798.74,1738.82,0.98,0,1099.0
|
| 10 |
+
2026-04-21T16:36:22.727797+00:00,SKU-1001,1617.1,1798.74,1738.82,0.98,0,1099.0
|
| 11 |
+
2026-04-21T16:36:25.535797+00:00,SKU-1001,1688.4,1908.26,1815.48,0.98,0,1099.0
|
| 12 |
+
2026-04-21T16:36:27.590880+00:00,SKU-1001,1688.87,1908.98,1815.99,0.98,0,1099.0
|
| 13 |
+
2026-04-21T16:36:28.254023+00:00,SKU-1001,1830.86,1918.78,1822.84,0.98,0,1099.0
|
| 14 |
+
2026-04-21T16:36:34.377046+00:00,SKU-1001,118692.0,2235.42,2044.5,0.98,0,109900.0
|
| 15 |
+
2026-04-21T16:36:46.348417+00:00,SKU-1001,118702.8,2235.42,2044.5,0.98,0,109910.0
|
| 16 |
+
2026-04-21T16:44:11.552598+00:00,SKU-1001,1846.47,1952.53,1846.47,0.98,0,1099.0
|
| 17 |
+
2026-04-21T16:44:21.857252+00:00,SKU-1001,1720.19,1772.13,1720.19,0.98,0,1099.0
|
| 18 |
+
2026-04-21T16:44:24.992938+00:00,SKU-1001,1721.57,1774.09,1721.57,0.98,0,1099.0
|
| 19 |
+
2026-04-21T16:44:28.848864+00:00,SKU-1001,1773.28,1847.97,1773.28,0.98,0,1099.0
|
| 20 |
+
2026-04-21T16:44:32.162255+00:00,SKU-1001,1796.95,1881.79,1796.95,0.98,0,1099.0
|
| 21 |
+
2026-04-21T16:44:34.207941+00:00,SKU-1001,1798.55,1884.07,1798.55,0.98,0,1109.0
|
| 22 |
+
2026-04-21T16:44:34.739059+00:00,SKU-1001,1804.9,1893.15,1804.9,0.98,0,1129.0
|
| 23 |
+
2026-04-21T16:44:35.259757+00:00,SKU-1001,1813.52,1905.46,1813.52,0.98,0,1149.0
|
| 24 |
+
2026-04-21T16:44:35.850007+00:00,SKU-1001,1811.27,1902.24,1811.27,0.98,0,1169.0
|
| 25 |
+
2026-04-21T16:44:53.610970+00:00,SKU-1001,1806.22,1895.02,1806.22,0.98,0,1169.0
|
| 26 |
+
2026-04-21T16:48:43.383478+00:00,SKU-1001,1846.47,1952.53,1846.47,0.98,0,1099.0
|
| 27 |
+
2026-04-21T16:48:45.430289+00:00,SKU-1001,1846.47,1952.53,1846.47,0.98,0,1099.0
|
| 28 |
+
2026-04-21T16:48:50.348704+00:00,SKU-1001,1843.94,1948.91,1843.94,0.98,0,1099.0
|
| 29 |
+
2026-04-21T16:48:55.262242+00:00,SKU-1001,1936.2,2080.72,1936.2,0.98,0,1099.0
|
| 30 |
+
2026-04-21T16:49:01.321018+00:00,SKU-1001,1940.43,2086.75,1940.43,0.98,0,1099.0
|
| 31 |
+
2026-04-21T16:49:02.387350+00:00,SKU-1001,1964.07,2120.52,1964.07,0.98,0,1099.0
|
| 32 |
+
2026-04-21T16:49:09.054868+00:00,SKU-1005,1964.07,2120.52,1964.07,0.98,0,1099.0
|
| 33 |
+
2026-04-21T16:49:12.592472+00:00,SKU-1005,1962.94,2118.91,1962.94,0.98,0,1099.0
|
| 34 |
+
2026-04-21T16:49:13.194465+00:00,SKU-1005,1981.43,2145.32,1981.43,0.98,0,1099.0
|
| 35 |
+
2026-04-21T16:49:17.226819+00:00,SKU-1005,1974.93,2136.04,1974.93,0.98,0,1099.0
|
| 36 |
+
2026-04-21T16:49:20.262071+00:00,SKU-1005,2023.65,2163.3,1994.01,0.98,0,1099.0
|
| 37 |
+
2026-04-21T16:49:20.651755+00:00,SKU-1005,2023.65,2163.3,1994.01,0.98,0,1099.0
|
| 38 |
+
2026-04-21T16:49:23.217861+00:00,SKU-1005,2023.65,2163.3,1994.01,0.98,0,1109.0
|
| 39 |
+
2026-04-21T16:49:23.517370+00:00,SKU-1005,2023.65,2173.31,2001.01,0.98,0,1119.0
|
| 40 |
+
2026-04-21T16:49:23.690003+00:00,SKU-1005,2023.65,2173.31,2001.01,0.98,0,1129.0
|
| 41 |
+
2026-04-21T16:49:24.026589+00:00,SKU-1005,2023.65,2194.31,2015.72,0.98,0,1149.0
|
| 42 |
+
2026-04-21T16:49:24.508323+00:00,SKU-1005,2023.65,2205.4,2023.48,0.98,0,1179.0
|
| 43 |
+
2026-04-21T16:49:24.699328+00:00,SKU-1005,2023.65,2209.74,2026.52,0.98,0,1189.0
|
| 44 |
+
2026-04-21T16:49:24.944724+00:00,SKU-1005,2023.65,2214.01,2029.5,0.98,0,1199.0
|
| 45 |
+
2026-04-21T16:49:25.126635+00:00,SKU-1005,2023.65,2225.49,2037.54,0.98,0,1209.0
|
| 46 |
+
2026-04-21T16:49:25.301081+00:00,SKU-1005,2023.65,2228.17,2039.42,0.98,0,1219.0
|
| 47 |
+
2026-04-21T16:49:27.441434+00:00,SKU-1005,2037.15,2228.17,2039.42,0.98,0,1219.0
|
| 48 |
+
2026-04-21T16:49:27.887462+00:00,SKU-1005,2064.15,2234.03,2043.52,0.98,0,1219.0
|
| 49 |
+
2026-04-21T16:49:28.140492+00:00,SKU-1005,2077.65,2239.74,2047.52,0.98,0,1219.0
|
| 50 |
+
2026-04-21T16:49:28.616463+00:00,SKU-1005,2118.15,2274.12,2071.58,0.98,0,1219.0
|
| 51 |
+
2026-04-21T16:49:29.118558+00:00,SKU-1005,2158.65,2301.54,2090.78,0.98,0,1219.0
|
| 52 |
+
2026-04-21T16:49:29.550719+00:00,SKU-1005,2185.65,2319.45,2103.31,0.98,0,1219.0
|
| 53 |
+
2026-04-21T16:49:57.818086+00:00,SKU-1005,2019.39,2199.55,2019.39,0.98,0,1219.0
|
| 54 |
+
2026-04-21T16:50:01.947178+00:00,SKU-1005,2035.79,2222.99,2035.79,0.98,0,1219.0
|
| 55 |
+
2026-04-21T16:50:02.383211+00:00,SKU-1005,2033.13,2219.19,2033.13,0.98,0,1219.0
|
| 56 |
+
2026-04-21T16:50:04.637259+00:00,SKU-1005,1930.52,2072.6,1930.52,0.98,0,1219.0
|
| 57 |
+
2026-04-21T16:50:08.002970+00:00,SKU-1005,1611.32,1616.6,1611.32,0.98,0,100.0
|
| 58 |
+
2026-04-21T16:50:13.499079+00:00,SKU-1005,202.5,1352.2,1426.24,0.98,0,100.0
|
| 59 |
+
2026-04-21T16:50:16.797317+00:00,SKU-1005,229.5,1352.2,1426.24,0.98,0,100.0
|
| 60 |
+
2026-04-21T16:50:17.456294+00:00,SKU-1005,229.5,1362.9,1433.73,0.83,0,100.0
|
| 61 |
+
2026-04-21T16:50:24.212795+00:00,SKU-1005,229.5,271.31,249.92,0.83,0,100.0
|
| 62 |
+
2026-04-21T16:50:27.827508+00:00,SKU-1005,229.5,272.15,250.5,0.83,0,100.0
|
| 63 |
+
2026-04-21T16:50:29.384452+00:00,SKU-1005,229.5,272.75,250.93,0.83,0,100.0
|
| 64 |
+
2026-04-21T16:50:30.105410+00:00,SKU-1005,229.5,268.04,247.63,0.83,0,100.0
|
| 65 |
+
2026-04-21T16:50:32.755645+00:00,SKU-1005,229.5,269.37,248.56,0.83,0,100.0
|
| 66 |
+
2026-04-21T16:50:34.454427+00:00,SKU-1005,229.5,269.05,248.33,0.83,0,100.0
|
| 67 |
+
2026-04-21T16:50:37.080575+00:00,SKU-1005,229.5,258.19,240.73,0.83,0,100.0
|
| 68 |
+
2026-04-21T16:50:41.376678+00:00,SKU-1005,229.5,255.08,238.56,0.83,0,100.0
|
| 69 |
+
2026-04-21T16:50:44.174612+00:00,SKU-1005,229.5,250.01,235.01,0.83,0,100.0
|
| 70 |
+
2026-04-21T16:50:46.691114+00:00,SKU-1005,229.5,238.24,226.77,0.83,0,100.0
|
data/raw/kaggle/retail_price.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/raw/pricing_events.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
deploy/ec2/dynamic-pricing-api.service
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[Unit]
|
| 2 |
+
Description=Dynamic Pricing Engine FastAPI Service
|
| 3 |
+
After=network.target
|
| 4 |
+
|
| 5 |
+
[Service]
|
| 6 |
+
Type=simple
|
| 7 |
+
User=ubuntu
|
| 8 |
+
WorkingDirectory=/opt/dynamic-pricing-engine
|
| 9 |
+
EnvironmentFile=/opt/dynamic-pricing-engine/.env
|
| 10 |
+
Environment=PROJECT_DIR=/opt/dynamic-pricing-engine
|
| 11 |
+
Environment=VENV_DIR=/opt/dynamic-pricing-engine/.venv
|
| 12 |
+
ExecStart=/opt/dynamic-pricing-engine/deploy/ec2/start_api.sh
|
| 13 |
+
Restart=always
|
| 14 |
+
RestartSec=5
|
| 15 |
+
|
| 16 |
+
[Install]
|
| 17 |
+
WantedBy=multi-user.target
|
deploy/ec2/dynamic-pricing-dashboard.service
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[Unit]
|
| 2 |
+
Description=Dynamic Pricing Engine Streamlit Dashboard
|
| 3 |
+
After=network.target
|
| 4 |
+
|
| 5 |
+
[Service]
|
| 6 |
+
Type=simple
|
| 7 |
+
User=ubuntu
|
| 8 |
+
WorkingDirectory=/opt/dynamic-pricing-engine
|
| 9 |
+
EnvironmentFile=/opt/dynamic-pricing-engine/.env
|
| 10 |
+
Environment=PROJECT_DIR=/opt/dynamic-pricing-engine
|
| 11 |
+
Environment=VENV_DIR=/opt/dynamic-pricing-engine/.venv
|
| 12 |
+
ExecStart=/opt/dynamic-pricing-engine/deploy/ec2/start_dashboard.sh
|
| 13 |
+
Restart=always
|
| 14 |
+
RestartSec=5
|
| 15 |
+
|
| 16 |
+
[Install]
|
| 17 |
+
WantedBy=multi-user.target
|
deploy/ec2/start_api.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
PROJECT_DIR="${PROJECT_DIR:-/opt/dynamic-pricing-engine}"
|
| 5 |
+
VENV_DIR="${VENV_DIR:-$PROJECT_DIR/.venv}"
|
| 6 |
+
HOST="${HOST:-0.0.0.0}"
|
| 7 |
+
PORT="${PORT:-8000}"
|
| 8 |
+
WORKERS="${WORKERS:-1}"
|
| 9 |
+
|
| 10 |
+
cd "$PROJECT_DIR"
|
| 11 |
+
source "$VENV_DIR/bin/activate"
|
| 12 |
+
|
| 13 |
+
exec uvicorn app.api:app --host "$HOST" --port "$PORT" --workers "$WORKERS"
|
deploy/ec2/start_dashboard.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
PROJECT_DIR="${PROJECT_DIR:-/opt/dynamic-pricing-engine}"
|
| 5 |
+
VENV_DIR="${VENV_DIR:-$PROJECT_DIR/.venv}"
|
| 6 |
+
HOST="${HOST:-0.0.0.0}"
|
| 7 |
+
PORT="${PORT:-8501}"
|
| 8 |
+
|
| 9 |
+
cd "$PROJECT_DIR"
|
| 10 |
+
source "$VENV_DIR/bin/activate"
|
| 11 |
+
|
| 12 |
+
exec streamlit run app/dashboard.py \
|
| 13 |
+
--server.address "$HOST" \
|
| 14 |
+
--server.port "$PORT" \
|
| 15 |
+
--server.headless true
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
api:
|
| 3 |
+
build:
|
| 4 |
+
context: .
|
| 5 |
+
dockerfile: Dockerfile
|
| 6 |
+
container_name: dynamic-pricing-api
|
| 7 |
+
env_file:
|
| 8 |
+
- .env.example
|
| 9 |
+
ports:
|
| 10 |
+
- "8000:8000"
|
| 11 |
+
volumes:
|
| 12 |
+
- ./data:/app/data
|
| 13 |
+
- ./models:/app/models
|
| 14 |
+
restart: unless-stopped
|
| 15 |
+
dashboard:
|
| 16 |
+
build:
|
| 17 |
+
context: .
|
| 18 |
+
dockerfile: Dockerfile.streamlit
|
| 19 |
+
container_name: dynamic-pricing-dashboard
|
| 20 |
+
env_file:
|
| 21 |
+
- .env.example
|
| 22 |
+
ports:
|
| 23 |
+
- "8501:8501"
|
| 24 |
+
volumes:
|
| 25 |
+
- ./data:/app/data
|
| 26 |
+
- ./models:/app/models
|
| 27 |
+
depends_on:
|
| 28 |
+
- api
|
| 29 |
+
restart: unless-stopped
|
models/training_metrics.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dataset_profile": "kaggle_retail",
|
| 3 |
+
"data_path": "data\\raw\\kaggle\\retail_price.csv",
|
| 4 |
+
"best_model": "random_forest",
|
| 5 |
+
"best_model_metrics": {
|
| 6 |
+
"mae": 3.105130602318404,
|
| 7 |
+
"rmse": 6.731112904256394,
|
| 8 |
+
"r2": 0.9916132145995052
|
| 9 |
+
},
|
| 10 |
+
"all_models": {
|
| 11 |
+
"random_forest": {
|
| 12 |
+
"mae": 3.105130602318404,
|
| 13 |
+
"rmse": 6.731112904256394,
|
| 14 |
+
"r2": 0.9916132145995052
|
| 15 |
+
},
|
| 16 |
+
"xgboost": {
|
| 17 |
+
"mae": 3.311133864318597,
|
| 18 |
+
"rmse": 6.585257755436754,
|
| 19 |
+
"r2": 0.9919727398685239
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.115.0
|
| 2 |
+
uvicorn==0.30.6
|
| 3 |
+
streamlit==1.39.0
|
| 4 |
+
pandas==2.2.3
|
| 5 |
+
numpy==2.1.1
|
| 6 |
+
scikit-learn==1.5.2
|
| 7 |
+
xgboost==2.1.1
|
| 8 |
+
joblib==1.4.2
|
| 9 |
+
pydantic==2.9.2
|
| 10 |
+
pydantic-settings==2.5.2
|
| 11 |
+
requests==2.32.3
|
| 12 |
+
redis==5.1.1
|
| 13 |
+
kafka-python==2.0.2
|
| 14 |
+
python-dotenv==1.0.1
|
| 15 |
+
plotly==5.24.1
|
| 16 |
+
pytest==8.3.3
|
| 17 |
+
httpx==0.27.2
|
scripts/__pycache__/generate_sample_data.cpython-313.pyc
ADDED
|
Binary file (6.42 kB). View file
|
|
|
scripts/__pycache__/train_model.cpython-313.pyc
ADDED
|
Binary file (2.21 kB). View file
|
|
|
scripts/generate_sample_data.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
ROOT_DIR = Path(__file__).resolve().parents[1]
|
| 11 |
+
if str(ROOT_DIR) not in sys.path:
|
| 12 |
+
sys.path.insert(0, str(ROOT_DIR))
|
| 13 |
+
|
| 14 |
+
from app.config import get_settings
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_dataset(rows: int, seed: int = 42) -> pd.DataFrame:
|
| 18 |
+
rng = np.random.default_rng(seed)
|
| 19 |
+
categories = np.array(["electronics", "fashion", "home", "beauty", "grocery"])
|
| 20 |
+
brands = np.array(["brand_a", "brand_b", "brand_c", "brand_d"])
|
| 21 |
+
segments = np.array(["budget", "standard", "premium", "loyal"])
|
| 22 |
+
|
| 23 |
+
category = rng.choice(categories, size=rows, p=[0.24, 0.22, 0.18, 0.16, 0.20])
|
| 24 |
+
brand = rng.choice(brands, size=rows)
|
| 25 |
+
customer_segment = rng.choice(segments, size=rows, p=[0.25, 0.40, 0.20, 0.15])
|
| 26 |
+
hour_of_day = rng.integers(0, 24, size=rows)
|
| 27 |
+
day_of_week = rng.integers(0, 7, size=rows)
|
| 28 |
+
is_weekend = (day_of_week >= 5).astype(int)
|
| 29 |
+
is_festival = rng.binomial(1, 0.12, size=rows)
|
| 30 |
+
inventory_level = rng.integers(5, 180, size=rows)
|
| 31 |
+
inventory_days_cover = np.round(rng.uniform(1.0, 28.0, size=rows), 2)
|
| 32 |
+
base_cost = np.round(rng.uniform(150.0, 2200.0, size=rows), 2)
|
| 33 |
+
|
| 34 |
+
category_factor = {
|
| 35 |
+
"electronics": 1.55,
|
| 36 |
+
"fashion": 1.35,
|
| 37 |
+
"home": 1.25,
|
| 38 |
+
"beauty": 1.48,
|
| 39 |
+
"grocery": 1.18,
|
| 40 |
+
}
|
| 41 |
+
segment_factor = {
|
| 42 |
+
"budget": 0.95,
|
| 43 |
+
"standard": 1.0,
|
| 44 |
+
"premium": 1.16,
|
| 45 |
+
"loyal": 1.08,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
base_markup = np.array([category_factor[item] for item in category]) * np.array(
|
| 49 |
+
[segment_factor[item] for item in customer_segment]
|
| 50 |
+
)
|
| 51 |
+
competitor_price = np.round(base_cost * base_markup * rng.uniform(0.92, 1.08, size=rows), 2)
|
| 52 |
+
current_price = np.round(competitor_price * rng.uniform(0.96, 1.08, size=rows), 2)
|
| 53 |
+
click_through_rate = np.round(rng.uniform(0.01, 0.15, size=rows), 4)
|
| 54 |
+
conversion_rate = np.round(rng.uniform(0.008, 0.08, size=rows), 4)
|
| 55 |
+
units_sold_last_5m = rng.poisson(4 + is_festival * 2 + is_weekend, size=rows)
|
| 56 |
+
units_sold_last_1h = rng.poisson(18 + is_festival * 10 + is_weekend * 4, size=rows)
|
| 57 |
+
|
| 58 |
+
demand_multiplier = (
|
| 59 |
+
1
|
| 60 |
+
+ is_festival * 0.10
|
| 61 |
+
+ is_weekend * 0.04
|
| 62 |
+
+ (hour_of_day >= 18).astype(int) * 0.05
|
| 63 |
+
+ (conversion_rate * 2.5)
|
| 64 |
+
+ (units_sold_last_1h / 300)
|
| 65 |
+
)
|
| 66 |
+
inventory_multiplier = np.where(
|
| 67 |
+
inventory_level < 20,
|
| 68 |
+
1.11,
|
| 69 |
+
np.where(inventory_level > 120, 0.93, 1.0),
|
| 70 |
+
)
|
| 71 |
+
optimal_price = (
|
| 72 |
+
base_cost
|
| 73 |
+
* base_markup
|
| 74 |
+
* demand_multiplier
|
| 75 |
+
* inventory_multiplier
|
| 76 |
+
* rng.uniform(0.97, 1.03, size=rows)
|
| 77 |
+
)
|
| 78 |
+
optimal_price = np.minimum(optimal_price, current_price * 1.30)
|
| 79 |
+
optimal_price = np.maximum(optimal_price, base_cost * 1.08)
|
| 80 |
+
|
| 81 |
+
frame = pd.DataFrame(
|
| 82 |
+
{
|
| 83 |
+
"sku_id": [f"SKU-{1000 + idx}" for idx in range(rows)],
|
| 84 |
+
"category": category,
|
| 85 |
+
"brand": brand,
|
| 86 |
+
"customer_segment": customer_segment,
|
| 87 |
+
"hour_of_day": hour_of_day,
|
| 88 |
+
"day_of_week": day_of_week,
|
| 89 |
+
"is_weekend": is_weekend,
|
| 90 |
+
"is_festival": is_festival,
|
| 91 |
+
"inventory_level": inventory_level,
|
| 92 |
+
"inventory_days_cover": inventory_days_cover,
|
| 93 |
+
"competitor_price": competitor_price,
|
| 94 |
+
"click_through_rate": click_through_rate,
|
| 95 |
+
"conversion_rate": conversion_rate,
|
| 96 |
+
"units_sold_last_5m": units_sold_last_5m,
|
| 97 |
+
"units_sold_last_1h": units_sold_last_1h,
|
| 98 |
+
"base_cost": base_cost,
|
| 99 |
+
"current_price": current_price,
|
| 100 |
+
"optimal_price": np.round(optimal_price, 2),
|
| 101 |
+
}
|
| 102 |
+
)
|
| 103 |
+
return frame
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def main() -> None:
|
| 107 |
+
parser = argparse.ArgumentParser(description="Generate synthetic pricing events data.")
|
| 108 |
+
parser.add_argument("--rows", type=int, default=25000, help="Number of rows to generate")
|
| 109 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
| 110 |
+
args = parser.parse_args()
|
| 111 |
+
|
| 112 |
+
settings = get_settings()
|
| 113 |
+
frame = generate_dataset(rows=args.rows, seed=args.seed)
|
| 114 |
+
settings.raw_data_path.parent.mkdir(parents=True, exist_ok=True)
|
| 115 |
+
frame.to_csv(settings.raw_data_path, index=False)
|
| 116 |
+
print(f"Saved {len(frame)} rows to {settings.raw_data_path}")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
main()
|
scripts/train_model.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
ROOT_DIR = Path(__file__).resolve().parents[1]
|
| 8 |
+
if str(ROOT_DIR) not in sys.path:
|
| 9 |
+
sys.path.insert(0, str(ROOT_DIR))
|
| 10 |
+
|
| 11 |
+
from app.config import get_settings
|
| 12 |
+
from app.modeling import train_best_model
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def main() -> None:
|
| 16 |
+
parser = argparse.ArgumentParser(description="Train pricing model on synthetic or Kaggle data.")
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
"--profile",
|
| 19 |
+
default="synthetic",
|
| 20 |
+
choices=["synthetic", "kaggle_retail"],
|
| 21 |
+
help="Dataset profile to train on.",
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"--data-path",
|
| 25 |
+
default=None,
|
| 26 |
+
help="Optional override for the CSV file path.",
|
| 27 |
+
)
|
| 28 |
+
args = parser.parse_args()
|
| 29 |
+
|
| 30 |
+
settings = get_settings()
|
| 31 |
+
data_path = Path(args.data_path) if args.data_path else settings.raw_data_path
|
| 32 |
+
result = train_best_model(
|
| 33 |
+
data_path=data_path,
|
| 34 |
+
artifact_path=settings.model_path,
|
| 35 |
+
metrics_path=settings.metrics_path,
|
| 36 |
+
dataset_profile=args.profile,
|
| 37 |
+
)
|
| 38 |
+
print(
|
| 39 |
+
f"Profile: {result.dataset_profile} | Best model: {result.model_name} | "
|
| 40 |
+
f"MAE={result.mae:.2f} | RMSE={result.rmse:.2f} | R2={result.r2:.3f}"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
main()
|
tests/__pycache__/smoke_test.cpython-313-pytest-8.3.3.pyc
ADDED
|
Binary file (2.57 kB). View file
|
|
|
tests/__pycache__/test_api.cpython-313-pytest-8.3.3.pyc
ADDED
|
Binary file (15.9 kB). View file
|
|
|
tests/__pycache__/test_pricing_engine.cpython-313-pytest-8.3.3.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
tests/smoke_test.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import compileall
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_project_compiles() -> None:
|
| 6 |
+
root = Path(__file__).resolve().parent.parent
|
| 7 |
+
assert compileall.compile_dir(root / "app", quiet=1)
|
| 8 |
+
assert compileall.compile_dir(root / "scripts", quiet=1)
|
tests/test_api.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from datetime import UTC, datetime
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from fastapi.testclient import TestClient
|
| 8 |
+
|
| 9 |
+
from app import api
|
| 10 |
+
from app.schemas import KagglePricingResponse, MonitoringSummary, PricingResponse
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class _DummySettings:
|
| 15 |
+
model_path: Path
|
| 16 |
+
metrics_path: Path
|
| 17 |
+
price_history_path: Path
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class _DummyTracker:
|
| 21 |
+
def __init__(self) -> None:
|
| 22 |
+
self.events = {"SKU-1": []}
|
| 23 |
+
|
| 24 |
+
def recent_event_count(self) -> int:
|
| 25 |
+
return 3
|
| 26 |
+
|
| 27 |
+
def flash_sale_skus(self) -> list[str]:
|
| 28 |
+
return ["SKU-1"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class _SyntheticEngine:
|
| 32 |
+
dataset_profile = "synthetic"
|
| 33 |
+
|
| 34 |
+
def __init__(self) -> None:
|
| 35 |
+
self.flash_sale_tracker = _DummyTracker()
|
| 36 |
+
|
| 37 |
+
def recommend_price(self, _request):
|
| 38 |
+
response = PricingResponse(
|
| 39 |
+
sku_id="SKU-1",
|
| 40 |
+
recommended_price=125.0,
|
| 41 |
+
ml_price=120.0,
|
| 42 |
+
blended_price=123.0,
|
| 43 |
+
inventory_adjustment=1.0,
|
| 44 |
+
demand_adjustment=1.0,
|
| 45 |
+
flash_sale_multiplier=1.0,
|
| 46 |
+
confidence=0.81,
|
| 47 |
+
detected_flash_sale=False,
|
| 48 |
+
reason="test synthetic response",
|
| 49 |
+
generated_at=datetime.now(UTC),
|
| 50 |
+
)
|
| 51 |
+
return type("SyntheticResult", (), {"response": response})()
|
| 52 |
+
|
| 53 |
+
def register_order_event(self, _event) -> bool:
|
| 54 |
+
return False
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class _KaggleEngine:
|
| 58 |
+
dataset_profile = "kaggle_retail"
|
| 59 |
+
|
| 60 |
+
def __init__(self) -> None:
|
| 61 |
+
self.flash_sale_tracker = _DummyTracker()
|
| 62 |
+
|
| 63 |
+
def recommend_price(self, _request):
|
| 64 |
+
raise ValueError("The loaded model is not compatible with the synthetic pricing request schema.")
|
| 65 |
+
|
| 66 |
+
def recommend_kaggle_price(self, _request):
|
| 67 |
+
response = KagglePricingResponse(
|
| 68 |
+
product_id="P-1",
|
| 69 |
+
product_category_name="electronics",
|
| 70 |
+
recommended_price=199.0,
|
| 71 |
+
current_price=189.0,
|
| 72 |
+
gap_to_current_price=10.0,
|
| 73 |
+
competitor_anchor_price=193.0,
|
| 74 |
+
confidence=0.76,
|
| 75 |
+
reason="test kaggle response",
|
| 76 |
+
generated_at=datetime.now(UTC),
|
| 77 |
+
)
|
| 78 |
+
return type("KaggleResult", (), {"response": response})()
|
| 79 |
+
|
| 80 |
+
def register_order_event(self, _event) -> bool:
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _build_client(monkeypatch, tmp_path: Path, engine_instance):
|
| 85 |
+
model_path = tmp_path / "model.joblib"
|
| 86 |
+
metrics_path = tmp_path / "metrics.json"
|
| 87 |
+
history_path = tmp_path / "history.csv"
|
| 88 |
+
model_path.write_text("stub", encoding="utf-8")
|
| 89 |
+
metrics_path.write_text('{"ok": true}', encoding="utf-8")
|
| 90 |
+
history_path.write_text(
|
| 91 |
+
"generated_at,recommended_price\n2026-04-22T10:00:00+00:00,150.0\n",
|
| 92 |
+
encoding="utf-8",
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
settings = _DummySettings(
|
| 96 |
+
model_path=model_path,
|
| 97 |
+
metrics_path=metrics_path,
|
| 98 |
+
price_history_path=history_path,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
monkeypatch.setattr(api, "get_settings", lambda: settings)
|
| 102 |
+
monkeypatch.setattr(api, "PricingEngine", lambda _settings: engine_instance)
|
| 103 |
+
return TestClient(api.app)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_health_reports_active_profile(monkeypatch, tmp_path: Path) -> None:
|
| 107 |
+
with _build_client(monkeypatch, tmp_path, _SyntheticEngine()) as client:
|
| 108 |
+
response = client.get("/health")
|
| 109 |
+
assert response.status_code == 200
|
| 110 |
+
payload = response.json()
|
| 111 |
+
assert payload["model_loaded"] is True
|
| 112 |
+
assert payload["dataset_profile"] == "synthetic"
|
| 113 |
+
assert payload["supported_endpoints"]["kaggle_retail"] == "/price/recommend/kaggle"
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def test_synthetic_recommendation_endpoint(monkeypatch, tmp_path: Path) -> None:
|
| 117 |
+
with _build_client(monkeypatch, tmp_path, _SyntheticEngine()) as client:
|
| 118 |
+
response = client.post(
|
| 119 |
+
"/price/recommend",
|
| 120 |
+
json={
|
| 121 |
+
"sku_id": "SKU-1",
|
| 122 |
+
"category": "electronics",
|
| 123 |
+
"brand": "brand_a",
|
| 124 |
+
"customer_segment": "premium",
|
| 125 |
+
"hour_of_day": 12,
|
| 126 |
+
"day_of_week": 2,
|
| 127 |
+
"is_weekend": 0,
|
| 128 |
+
"is_festival": 0,
|
| 129 |
+
"inventory_level": 30,
|
| 130 |
+
"inventory_days_cover": 10,
|
| 131 |
+
"competitor_price": 100,
|
| 132 |
+
"click_through_rate": 0.05,
|
| 133 |
+
"conversion_rate": 0.03,
|
| 134 |
+
"units_sold_last_5m": 4,
|
| 135 |
+
"units_sold_last_1h": 18,
|
| 136 |
+
"base_cost": 70,
|
| 137 |
+
"current_price": 115,
|
| 138 |
+
},
|
| 139 |
+
)
|
| 140 |
+
assert response.status_code == 200
|
| 141 |
+
assert response.json()["recommended_price"] == 125.0
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_kaggle_recommendation_endpoint(monkeypatch, tmp_path: Path) -> None:
|
| 145 |
+
with _build_client(monkeypatch, tmp_path, _KaggleEngine()) as client:
|
| 146 |
+
response = client.post(
|
| 147 |
+
"/price/recommend/kaggle",
|
| 148 |
+
json={
|
| 149 |
+
"product_id": "P-1",
|
| 150 |
+
"product_category_name": "electronics",
|
| 151 |
+
"qty": 10,
|
| 152 |
+
"freight_price": 5,
|
| 153 |
+
"product_name_lenght": 20,
|
| 154 |
+
"product_description_lenght": 80,
|
| 155 |
+
"product_photos_qty": 2,
|
| 156 |
+
"product_weight_g": 800,
|
| 157 |
+
"product_score": 4.2,
|
| 158 |
+
"customers": 7,
|
| 159 |
+
"weekday": 3,
|
| 160 |
+
"weekend": 0,
|
| 161 |
+
"holiday": 0,
|
| 162 |
+
"volume": 3200,
|
| 163 |
+
"comp_1": 195,
|
| 164 |
+
"ps1": 4.0,
|
| 165 |
+
"fp1": 5,
|
| 166 |
+
"comp_2": 193,
|
| 167 |
+
"ps2": 4.1,
|
| 168 |
+
"fp2": 4,
|
| 169 |
+
"comp_3": 191,
|
| 170 |
+
"ps3": 4.3,
|
| 171 |
+
"fp3": 6,
|
| 172 |
+
"lag_price": 188,
|
| 173 |
+
"month": 4,
|
| 174 |
+
"year": 2026,
|
| 175 |
+
"current_price": 189,
|
| 176 |
+
},
|
| 177 |
+
)
|
| 178 |
+
assert response.status_code == 200
|
| 179 |
+
assert response.json()["gap_to_current_price"] == 10.0
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_profile_mismatch_returns_conflict(monkeypatch, tmp_path: Path) -> None:
|
| 183 |
+
with _build_client(monkeypatch, tmp_path, _KaggleEngine()) as client:
|
| 184 |
+
response = client.post(
|
| 185 |
+
"/price/recommend",
|
| 186 |
+
json={
|
| 187 |
+
"sku_id": "SKU-1",
|
| 188 |
+
"category": "electronics",
|
| 189 |
+
"brand": "brand_a",
|
| 190 |
+
"customer_segment": "premium",
|
| 191 |
+
"hour_of_day": 12,
|
| 192 |
+
"day_of_week": 2,
|
| 193 |
+
"is_weekend": 0,
|
| 194 |
+
"is_festival": 0,
|
| 195 |
+
"inventory_level": 30,
|
| 196 |
+
"inventory_days_cover": 10,
|
| 197 |
+
"competitor_price": 100,
|
| 198 |
+
"click_through_rate": 0.05,
|
| 199 |
+
"conversion_rate": 0.03,
|
| 200 |
+
"units_sold_last_5m": 4,
|
| 201 |
+
"units_sold_last_1h": 18,
|
| 202 |
+
"base_cost": 70,
|
| 203 |
+
"current_price": 115,
|
| 204 |
+
},
|
| 205 |
+
)
|
| 206 |
+
assert response.status_code == 409
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_monitoring_summary_uses_history_file(monkeypatch, tmp_path: Path) -> None:
|
| 210 |
+
with _build_client(monkeypatch, tmp_path, _SyntheticEngine()) as client:
|
| 211 |
+
response = client.get("/monitoring/summary")
|
| 212 |
+
assert response.status_code == 200
|
| 213 |
+
payload = MonitoringSummary.model_validate(response.json())
|
| 214 |
+
assert payload.average_recommended_price == 150.0
|
| 215 |
+
assert payload.flash_sale_skus == ["SKU-1"]
|
tests/test_pricing_engine.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from datetime import UTC, datetime
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from app.config import Settings
|
| 7 |
+
from app.pricing_engine import PricingEngine
|
| 8 |
+
from app.schemas import KagglePricingRequest, OrderEvent, PricingRequest
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class _StaticSyntheticPipeline:
|
| 12 |
+
def predict(self, _frame):
|
| 13 |
+
return [200.0]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class _StaticKagglePipeline:
|
| 17 |
+
def predict(self, _frame):
|
| 18 |
+
return [212.5]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _build_settings(tmp_path: Path) -> Settings:
|
| 22 |
+
model_path = tmp_path / "model.joblib"
|
| 23 |
+
metrics_path = tmp_path / "metrics.json"
|
| 24 |
+
raw_data_path = tmp_path / "raw.csv"
|
| 25 |
+
price_history_path = tmp_path / "history.csv"
|
| 26 |
+
model_path.write_text("stub", encoding="utf-8")
|
| 27 |
+
metrics_path.write_text("{}", encoding="utf-8")
|
| 28 |
+
raw_data_path.write_text("", encoding="utf-8")
|
| 29 |
+
return Settings(
|
| 30 |
+
model_path=model_path,
|
| 31 |
+
metrics_path=metrics_path,
|
| 32 |
+
raw_data_path=raw_data_path,
|
| 33 |
+
price_history_path=price_history_path,
|
| 34 |
+
redis_url="",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_synthetic_recommendation_applies_guardrails(monkeypatch, tmp_path: Path) -> None:
|
| 39 |
+
monkeypatch.setattr(
|
| 40 |
+
"app.pricing_engine.load_model_bundle",
|
| 41 |
+
lambda _path: {"dataset_profile": "synthetic", "pipeline": _StaticSyntheticPipeline()},
|
| 42 |
+
)
|
| 43 |
+
engine = PricingEngine(_build_settings(tmp_path))
|
| 44 |
+
engine.competitor_client.get_price = lambda _sku_id, fallback_price: fallback_price
|
| 45 |
+
|
| 46 |
+
result = engine.recommend_price(
|
| 47 |
+
PricingRequest(
|
| 48 |
+
sku_id="SKU-9",
|
| 49 |
+
category="electronics",
|
| 50 |
+
brand="brand_a",
|
| 51 |
+
customer_segment="premium",
|
| 52 |
+
hour_of_day=20,
|
| 53 |
+
day_of_week=5,
|
| 54 |
+
is_weekend=1,
|
| 55 |
+
is_festival=1,
|
| 56 |
+
inventory_level=10,
|
| 57 |
+
inventory_days_cover=2.0,
|
| 58 |
+
competitor_price=195.0,
|
| 59 |
+
click_through_rate=0.08,
|
| 60 |
+
conversion_rate=0.05,
|
| 61 |
+
units_sold_last_5m=10,
|
| 62 |
+
units_sold_last_1h=60,
|
| 63 |
+
base_cost=100.0,
|
| 64 |
+
current_price=130.0,
|
| 65 |
+
)
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
assert result.response.recommended_price == 175.5
|
| 69 |
+
assert result.response.flash_sale_multiplier == 1.0
|
| 70 |
+
assert result.response.inventory_adjustment == 1.1
|
| 71 |
+
assert result.response.demand_adjustment == 1.11
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_flash_sale_detection_activates_multiplier(monkeypatch, tmp_path: Path) -> None:
|
| 75 |
+
monkeypatch.setattr(
|
| 76 |
+
"app.pricing_engine.load_model_bundle",
|
| 77 |
+
lambda _path: {"dataset_profile": "synthetic", "pipeline": _StaticSyntheticPipeline()},
|
| 78 |
+
)
|
| 79 |
+
engine = PricingEngine(_build_settings(tmp_path))
|
| 80 |
+
engine.competitor_client.get_price = lambda _sku_id, fallback_price: fallback_price
|
| 81 |
+
|
| 82 |
+
now = datetime.now(UTC)
|
| 83 |
+
for _ in range(engine.settings.flash_sale_order_threshold):
|
| 84 |
+
engine.register_order_event(OrderEvent(sku_id="SKU-1", quantity=1, event_time=now))
|
| 85 |
+
|
| 86 |
+
result = engine.recommend_price(
|
| 87 |
+
PricingRequest(
|
| 88 |
+
sku_id="SKU-1",
|
| 89 |
+
category="electronics",
|
| 90 |
+
brand="brand_a",
|
| 91 |
+
customer_segment="premium",
|
| 92 |
+
hour_of_day=20,
|
| 93 |
+
day_of_week=5,
|
| 94 |
+
is_weekend=1,
|
| 95 |
+
is_festival=0,
|
| 96 |
+
inventory_level=50,
|
| 97 |
+
inventory_days_cover=8.0,
|
| 98 |
+
competitor_price=200.0,
|
| 99 |
+
click_through_rate=0.06,
|
| 100 |
+
conversion_rate=0.05,
|
| 101 |
+
units_sold_last_5m=8,
|
| 102 |
+
units_sold_last_1h=50,
|
| 103 |
+
base_cost=100.0,
|
| 104 |
+
current_price=150.0,
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
assert result.response.detected_flash_sale is True
|
| 109 |
+
assert result.response.flash_sale_multiplier == 1.12
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_kaggle_recommendation_uses_current_and_competitor_context(
|
| 113 |
+
monkeypatch, tmp_path: Path
|
| 114 |
+
) -> None:
|
| 115 |
+
monkeypatch.setattr(
|
| 116 |
+
"app.pricing_engine.load_model_bundle",
|
| 117 |
+
lambda _path: {"dataset_profile": "kaggle_retail", "pipeline": _StaticKagglePipeline()},
|
| 118 |
+
)
|
| 119 |
+
engine = PricingEngine(_build_settings(tmp_path))
|
| 120 |
+
|
| 121 |
+
result = engine.recommend_kaggle_price(
|
| 122 |
+
KagglePricingRequest(
|
| 123 |
+
product_id="P-55",
|
| 124 |
+
product_category_name="home",
|
| 125 |
+
qty=12,
|
| 126 |
+
freight_price=4.5,
|
| 127 |
+
product_name_lenght=24,
|
| 128 |
+
product_description_lenght=90,
|
| 129 |
+
product_photos_qty=3,
|
| 130 |
+
product_weight_g=700,
|
| 131 |
+
product_score=4.4,
|
| 132 |
+
customers=8,
|
| 133 |
+
weekday=2,
|
| 134 |
+
weekend=0,
|
| 135 |
+
holiday=0,
|
| 136 |
+
volume=6480,
|
| 137 |
+
comp_1=208.0,
|
| 138 |
+
ps1=4.0,
|
| 139 |
+
fp1=5.0,
|
| 140 |
+
comp_2=210.0,
|
| 141 |
+
ps2=4.1,
|
| 142 |
+
fp2=5.0,
|
| 143 |
+
comp_3=206.0,
|
| 144 |
+
ps3=4.2,
|
| 145 |
+
fp3=6.0,
|
| 146 |
+
lag_price=198.0,
|
| 147 |
+
month=4,
|
| 148 |
+
year=2026,
|
| 149 |
+
current_price=199.0,
|
| 150 |
+
)
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
assert result.response.recommended_price == 212.5
|
| 154 |
+
assert result.response.gap_to_current_price == 13.5
|
| 155 |
+
assert result.response.competitor_anchor_price == 208.0
|
| 156 |
+
assert "current price" in result.response.reason
|