Ghid · Python 3.9+
Raport lunar: costul vieții
Pe 1 ale lunii, un raport gata de publicat: cât costă coșul de bază azi și în cel mai ieftin magazin, ce s-a scumpit și ce s-a ieftinit în 30 de zile, pe grupe, și tarifele ANRE în vigoare.
- Rulează pe
- Python 3.9+
- O rulare
- 5 credite
- Pe lună
- 5 credite
- Pornit în
- 5 min
$ MONTHS=12 DAYS=30 python3 basket_report.pyreports/report-2026-11.md: basket 723.35 lei, 12 groups, 9 tariffs, 5 creditsCum funcționează
- Ia coșul pe ultimele
MONTHSluni din/v1/indexes/basket: totalul, totalul cel mai ieftin, schimbarea lunară și anuală. - Ia scumpirile și ieftinirile pe
DAYSzile din/v1/indexes/moves, pe grupe de produse. - Ia tarifele casei din
/v1/tariffs, cu decizia ANRE a fiecăruia. - Scrie
report-YYYY-MM.mdpentru articol șibasket-YYYY-MM.csvpentru grafic.
Cât costă: 2 credite pentru coș, 2 pentru scumpiri, 1 pentru tarife: 5 credite pe lună. Încape în planul Start.
Cum îl rulezi
export SATELIT_KEY=sat_live_...
MONTHS=12 DAYS=30 python3 basket_report.pyCe scoate
reports/report-2026-11.md: basket 723.35 lei, 12 groups, 9 tariffs, 5 creditsScriptul complet
#!/usr/bin/env python3
"""Cost of living report: the food basket, what got dearer or cheaper, and household tariffs, once a month.
SATELIT_KEY=sat_live_... python3 basket_report.py
Optional: MONTHS (12, the basket's span), DAYS (30, the moves' window), OUT_DIR (reports).
Writes report-YYYY-MM.md and basket-YYYY-MM.csv. Standard library only.
Put it in cron: 0 9 1 * * python3 /path/basket_report.py
"""
import csv
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import date
from pathlib import Path
sys.stdout.reconfigure(encoding="utf-8") # names hold ă, ș, ț whatever the console's code page
BASE = os.environ.get("SATELIT_BASE", "https://api.satelit.md/v1")
KEY = os.environ["SATELIT_KEY"]
MONTHS = int(os.environ.get("MONTHS", "12"))
DAYS = int(os.environ.get("DAYS", "30"))
OUT = Path(os.environ.get("OUT_DIR", "reports"))
credits_used = 0
attribution = ""
def api(path, **params):
global credits_used, attribution
query = urllib.parse.urlencode({"lang": "ro", **params})
req = urllib.request.Request(f"{BASE}{path}?{query}", headers={"Authorization": f"Bearer {KEY}"})
for attempt in range(3):
try:
with urllib.request.urlopen(req, timeout=20) as res:
body = json.load(res)
credits_used += body["meta"].get("credits", 0)
attribution = attribution or body["meta"].get("attribution", "")
return body["data"]
except urllib.error.HTTPError as err:
retry = err.headers.get("Retry-After")
if err.code in (429, 503) and retry and attempt < 2:
time.sleep(int(retry))
continue
raise SystemExit(f"{path}: {err.code} {err.read().decode()}")
def pct(n):
return "n/a" if n is None else f"{n:+.2f}%"
def main():
basket = api("/indexes/basket", months=MONTHS)
moves = api("/indexes/moves", days=DAYS)
tariffs = api("/tariffs")
month = date.today().strftime("%Y-%m")
OUT.mkdir(parents=True, exist_ok=True)
points = basket["points"]
first, last = points[0], points[-1]
span = (last["total"] / first["total"] - 1) * 100 if first["total"] else 0
with open(OUT / f"basket-{month}.csv", "w", newline="", encoding="utf-8") as f:
out = csv.writer(f)
out.writerow(["date", "total_lei", "cheapest_total_lei"])
out.writerows([p["date"], p["total"], p["cheapest_total"]] for p in points)
groups = sorted(moves["groups"], key=lambda g: g["change_pct"])
lines = [
f"# Cost of living in Moldova, {month}",
"",
"## Food basket",
f"- {len(basket['items'])} products, {last['date']}: **{last['total']:.2f} lei** "
f"(the cheapest shop for each: {last['cheapest_total']:.2f} lei)",
f"- Since {first['date']}: {span:+.2f}%; month on month {pct(basket['change_mom'])}, year on year {pct(basket['change_yoy'])}",
"",
f"## Prices in shops, {moves['from']} to {moves['to']}",
f"- {moves['compared']} products compared: {moves['up']} dearer, {moves['down']} cheaper, {moves['same']} unchanged, "
f"on average {moves['change_pct']:+.2f}%",
*[f"- {g['label']}: {g['change_pct']:+.2f}% ({g['up']} up, {g['down']} down)" for g in groups],
"",
"## Household tariffs",
*[f"- {t['label']} ({t['provider']}): {t['value']} {t['unit']}, since {t['valid_from']}, {t['decision']}" for t in tariffs],
"",
f"_{attribution}_",
]
report = OUT / f"report-{month}.md"
report.write_text("\n".join(lines) + "\n", "utf-8")
print(f"{report}: basket {last['total']:.2f} lei, {len(groups)} groups, {len(tariffs)} tariffs, {credits_used} credits")
if __name__ == "__main__":
main()
Rutele folosite
Întrebări despre acest ghid
Ce produse sunt în coș?
Lista e în data.items: produsul, cantitatea și unitatea. total e prețul coșului în magazine; cheapest_total e același coș luat din cel mai ieftin magazin pentru fiecare produs.
De când există istoricul?
Prețurile din magazine au istoric din 28 octombrie 2026. Pentru o lună sau un an fără date, change_mom și change_yoy sunt null, iar raportul scrie n/a.
Pot publica raportul?
Da, cu rândul din meta.attribution, pe care scriptul îl pune la final. Tarifele vin din deciziile publice ANRE, numite în raport.