"""DuckDB warehouse for DAM market history + scikit-learn trend forecast. Both are optional: any failure returns empty results so the price API keeps working from the JSON cache / shipped dataset. """ from __future__ import annotations from datetime import date, timedelta from pathlib import Path ROOT = Path(__file__).resolve().parent.parent DB_PATH = ROOT / "data" / "market.duckdb" _conn = None def _c(): global _conn if _conn is None: import duckdb DB_PATH.parent.mkdir(parents=True, exist_ok=True) _conn = duckdb.connect(str(DB_PATH)) _conn.execute( "CREATE TABLE IF NOT EXISTS market_history(" "crop VARCHAR, day DATE, price DOUBLE, source VARCHAR, " "PRIMARY KEY(crop, day))" ) return _conn def append_rows(rows) -> int: """Upsert live rows (crop/date/price/source) into the warehouse.""" clean = [] for r in rows or []: try: clean.append( ( str(r.get("crop") or "").strip(), str(r.get("date") or date.today().isoformat()), float(r.get("price")), str(r.get("source") or "dam"), ) ) except (TypeError, ValueError): continue clean = [c for c in clean if c[0]] if not clean: return 0 try: conn = _c() conn.executemany( "INSERT OR REPLACE INTO market_history(crop, day, price, source) " "VALUES (?, ?, ?, ?)", clean, ) return len(clean) except Exception: return 0 def history(crop: str, days: int = 30): try: rows = _c().execute( "SELECT day, price FROM market_history WHERE crop = ? " "ORDER BY day DESC LIMIT ?", [crop, int(days)], ).fetchall() return [{"date": str(d), "price": float(p)} for d, p in reversed(rows)] except Exception: return [] def forecast(crop: str, days: int = 7): """Linear-regression trend on stored history (scikit-learn).""" try: rows = _c().execute( "SELECT day, price FROM market_history WHERE crop = ? ORDER BY day", [crop], ).fetchall() if len(rows) < 3: return {"crop": crop, "model": "linear_regression", "points": [], "slope": None} from sklearn.linear_model import LinearRegression base = rows[0][0] x = [[(d - base).days] for d, _ in rows] y = [float(p) for _, p in rows] model = LinearRegression().fit(x, y) last = (rows[-1][0] - base).days points = [] for i in range(1, int(days) + 1): future = base + timedelta(days=last + i) points.append( {"date": future.isoformat(), "price": round(float(model.predict([[last + i]])[0]), 2)} ) return { "crop": crop, "model": "linear_regression", "slope": round(float(model.coef_[0]), 4), "points": points, } except Exception: return {"crop": crop, "model": "linear_regression", "points": [], "slope": None}