portal: daily EUR/USD spot check against the pricing FX, alert only (no reprice)
ci/woodpecker/push/woodpecker Pipeline was canceled
ci/woodpecker/push/woodpecker Pipeline was canceled
Reads the ECB reference rate in the sweep, compares to FX_POLICY_EUR_USD (1.16), and emails info@ only when the drift first crosses FX_ALERT_PCT (2%). Marker in portal_state keeps a steady breach from mailing daily and resets when inside the band.
This commit is contained in:
1 parent
6b46dfee90
commit
4af22ca4c4
2 files changed
+83
No files matched your search
+75
@@ -9453,6 +9453,74 @@ async def derive_member_sources() -> dict:
|
|||||||
return {"checked": len(stale), "flipped": flipped}
|
return {"checked": len(stale), "flipped": flipped}
|
||||||
|
|
||||||
|
|
||||||
|
FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.16") or 1.16)
|
||||||
|
FX_ALERT_PCT = float(os.environ.get("FX_ALERT_PCT", "2.0") or 2.0)
|
||||||
|
|
||||||
|
|
||||||
|
def _fx_verdict(rate: float, policy: float = FX_POLICY_EUR_USD,
|
||||||
|
threshold: float = FX_ALERT_PCT) -> dict:
|
||||||
|
"""Compare a live EUR/USD rate to the pricing policy. Pure, so it is testable."""
|
||||||
|
drift = ((rate - policy) / policy * 100.0) if policy else 0.0
|
||||||
|
return {"rate": round(float(rate), 4), "policy": policy,
|
||||||
|
"drift_pct": round(drift, 2), "alert": abs(drift) >= threshold}
|
||||||
|
|
||||||
|
|
||||||
|
async def fx_spot_check(send: bool = True) -> dict:
|
||||||
|
"""Daily spot check of EUR/USD against the pricing FX (1.16). Alerts, never reprices.
|
||||||
|
|
||||||
|
Source: ECB daily reference rate. An alert is sent to info@ only when the drift
|
||||||
|
first crosses FX_ALERT_PCT; staying over the line does not mail every day. When
|
||||||
|
the rate returns inside the band the marker resets, so a later breach is news.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=20.0) as client:
|
||||||
|
r = await client.get("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
|
||||||
|
r.raise_for_status()
|
||||||
|
m = re.search(r'currency=["\']USD["\']\s+rate=["\']([0-9.]+)["\']', r.text)
|
||||||
|
if not m:
|
||||||
|
return {"error": "USD rate not found in ECB feed"}
|
||||||
|
rate = float(m.group(1))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {"error": f"ECB fetch failed: {str(exc)[:120]}"}
|
||||||
|
|
||||||
|
verdict = _fx_verdict(rate)
|
||||||
|
verdict["checked_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
|
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
prev_row = conn.execute("SELECT value FROM portal_state WHERE key = 'fx_alert'").fetchone()
|
||||||
|
prev = json.loads(prev_row[0]) if prev_row and prev_row[0] else {}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
newly_alerting = verdict["alert"] and not prev.get("alerted")
|
||||||
|
verdict["alerted_before"] = bool(prev.get("alerted"))
|
||||||
|
verdict["notified"] = False
|
||||||
|
if newly_alerting and send:
|
||||||
|
direction = "above" if verdict["drift_pct"] > 0 else "below"
|
||||||
|
verdict["notified"] = bool(send_email(
|
||||||
|
ADMIN_INVITER_EMAIL,
|
||||||
|
f"EUR/USD {verdict['drift_pct']:+.1f}% {direction} the pricing FX",
|
||||||
|
f"The ECB rate is {verdict['rate']} USD per EUR; our pricing policy is "
|
||||||
|
f"{verdict['policy']}. Drift: {verdict['drift_pct']:+.1f}%.\n\n"
|
||||||
|
"No prices were changed automatically. Decide whether to re-convert "
|
||||||
|
"GreenPT/Regolo EUR list prices at the new rate (scripts/check_eur_fx.py "
|
||||||
|
"in code/litellm guards the conversion).\n"))
|
||||||
|
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO portal_state (key, value) VALUES ('fx_alert', ?) "
|
||||||
|
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||||
|
(json.dumps({"alerted": bool(verdict["alert"]), "rate": verdict["rate"],
|
||||||
|
"drift_pct": verdict["drift_pct"],
|
||||||
|
"at": verdict["checked_at"]}),))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return verdict
|
||||||
|
|
||||||
|
|
||||||
@app.post("/admin/sweep")
|
@app.post("/admin/sweep")
|
||||||
@limiter.limit("20/minute")
|
@limiter.limit("20/minute")
|
||||||
async def admin_sweep(request: Request):
|
async def admin_sweep(request: Request):
|
||||||
@@ -9511,6 +9579,13 @@ async def admin_sweep(request: Request):
|
|||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
result["member_sources"] = {"error": str(exc)[:200]}
|
result["member_sources"] = {"error": str(exc)[:200]}
|
||||||
|
|
||||||
|
# FX spot check: compare the ECB EUR/USD rate to the pricing policy. Alerts
|
||||||
|
# info@ on a new breach; never reprices anything by itself.
|
||||||
|
try:
|
||||||
|
result["fx_spot_check"] = await fx_spot_check(send=True)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
result["fx_spot_check"] = {"error": str(exc)[:200]}
|
||||||
|
|
||||||
# Paid Open Collective contributors with no portal row — the net for members
|
# Paid Open Collective contributors with no portal row — the net for members
|
||||||
# the sweep cannot see (hidden email, org account). Emails info@ only when it
|
# the sweep cannot see (hidden email, org account). Emails info@ only when it
|
||||||
# finds something, and only when the set changes. Was a daily script on the
|
# finds something, and only when the set changes. Was a daily script on the
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import os, sys
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m
|
||||||
|
v=m._fx_verdict(1.16); assert v["alert"] is False, v
|
||||||
|
v=m._fx_verdict(1.20); assert v["alert"] is True and v["drift_pct"] > 0, v
|
||||||
|
v=m._fx_verdict(1.10); assert v["alert"] is True and v["drift_pct"] < 0, v
|
||||||
|
v=m._fx_verdict(1.157); assert v["alert"] is False, v # 0.26% drift
|
||||||
|
print("FX VERDICT OK: thresholds and signs behave")
|
||||||
Reference in new issue
Block a user