Download qt3/ranking.py from s-ttp/updraft: direct link, hf CLI and curl.
- Browser
- Download file 7.23 kB
-
https://huggingface.co/spaces/s-ttp/updraft/resolve/main/qt3/ranking.py
- Command line
-
hf download hf://spaces/s-ttp/updraft/qt3/ranking.py
-
curl -L -o ranking.py https://huggingface.co/spaces/s-ttp/updraft/resolve/main/qt3/ranking.py
7.23 kB
| """Today's Quality-Trend ranking, built from the Sharadar API (no local data needed). | |
| Same steps as the live RS-VCP snapshot (Quant Model scripts/build_screens_snapshot.py) and the backtest: | |
| 1. universe top 1,000 US-listed companies by market cap (Sharadar DAILY, latest date) | |
| 2. trend ~300 trading days of SEP prices → MA50/MA200 − 1 and the 6-1-month return; 20-day $ volume | |
| 3. quality SF1 quarterly statements (as filed) → basic-diluted gap, quality score (ROE, ROA, gross | |
| margin, FCF conversion), −equity financing, FCF yield, ROE, buyback yield, net share reduction | |
| 4. slice price ≥ $5, ≥ $5M/day, US-dollar reporters; quality pool = top 30% of the composite | |
| 5. rank pool ranked by 0.5·pct(MA50/MA200) + 0.5·pct(6-1-month return) | |
| About 40 API requests; cached for the day. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import threading | |
| import time | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Callable, Optional | |
| import numpy as np | |
| import pandas as pd | |
| from . import config | |
| from .fundamental import SF1_COLS, latest_inputs | |
| from .sharadar import query, query_tickers | |
| _lock = threading.Lock() | |
| _state = {"building": False, "error": None, "started": None} | |
| def trend(p: pd.DataFrame) -> pd.DataFrame: | |
| out = [] | |
| for t, g in p.sort_values(["ticker", "date"]).groupby("ticker", sort=False): | |
| c = g["closeadj"].to_numpy(float) | |
| if len(c) < 200 or not np.isfinite(c[-1]): | |
| continue | |
| dv = (g["close"].astype(float) * g["volume"].astype(float)).tail(20).mean() | |
| out.append({"ticker": t, "last_bar": str(pd.Timestamp(g["date"].iloc[-1]).date()), | |
| "price": float(g["close"].iloc[-1]), "dv20": float(dv), | |
| "ma50_200": c[-50:].mean() / c[-200:].mean() - 1, | |
| "mom_6_1": c[-21] / c[-126] - 1 if len(c) >= 126 else np.nan, | |
| "ret_1m": c[-1] / c[-22] - 1, "ret_6m": c[-1] / c[-127] - 1 if len(c) >= 127 else np.nan}) | |
| return pd.DataFrame(out) | |
| def rank_table(u: pd.DataFrame) -> pd.DataFrame: | |
| """Steps 4-5 on a merged universe table (pure; unit-tested).""" | |
| pct = lambda d, c: d[c].rank(pct=True) | |
| u = u.copy() | |
| for c in ("roe", "roa", "gross_margin", "fcf_conversion", "fcf_yield", "buyback_yield", "net_share_reduction_yoy", | |
| "basic_diluted_gap", "equity_financing", "currency"): | |
| if c not in u: | |
| u[c] = np.nan # missing statements → the name simply can't enter the pool | |
| u["equity_financing_neg"] = -u["equity_financing"] | |
| liq = (u["price"] >= config.MIN_PRICE) & (u["dv20"] >= config.MIN_DV) | |
| q = u[liq & (u["currency"].fillna("USD") == "USD")].copy() | |
| q["quality_score"] = pd.concat([pct(q, c) for c in ("roe", "roa", "gross_margin", "fcf_conversion")], | |
| axis=1).mean(axis=1) | |
| P = pd.concat([pct(q, c) for c in config.QCD], axis=1) | |
| q["qcd"] = P.mean(axis=1).where(P.notna().mean(axis=1) >= 0.5) | |
| q["qcd_pct"] = q["qcd"].rank(pct=True) | |
| q["trend"] = 0.5 * pct(q, "ma50_200") + 0.5 * pct(q, "mom_6_1") | |
| pool = q[(q["qcd_pct"] >= config.POOL) & q["trend"].notna()] | |
| pool = pool.sort_values("trend", ascending=False, kind="stable").reset_index(drop=True) | |
| pool["rank"] = np.arange(1, len(pool) + 1) | |
| pool.attrs.update(universe=int(len(u)), liquid_usd=int(len(q))) | |
| return pool | |
| def build(key: str, today: Optional[datetime] = None, fetch: Callable = query, | |
| fetch_tickers: Callable = query_tickers) -> dict: | |
| day = (today or datetime.now(timezone.utc)).date() | |
| d = fetch("DAILY", key, date__gte=str(day - timedelta(days=14)), columns=["ticker", "date", "marketcap"]) | |
| d["date"] = pd.to_datetime(d["date"]) | |
| d = d[d["date"] == d["date"].max()].dropna(subset=["marketcap"]) | |
| uni = d.assign(market_cap=pd.to_numeric(d["marketcap"]) * 1e6).nlargest(config.TOPN, "market_cap") | |
| tickers = uni["ticker"].tolist() | |
| tk = fetch_tickers("TICKERS", key, tickers, columns=["table", "ticker", "name", "sector", "industry", "currency"]) | |
| meta = tk[tk["table"] == "SEP"].drop_duplicates("ticker").set_index("ticker")[["name", "sector", "industry"]] | |
| cur = tk[tk["table"] == "SF1"].drop_duplicates("ticker").set_index("ticker")["currency"] | |
| px = fetch_tickers("SEP", key, tickers, date__gte=str(day - timedelta(days=430)), | |
| columns=["ticker", "date", "close", "volume", "closeadj"]) | |
| px["date"] = pd.to_datetime(px["date"]) | |
| for c in ("close", "volume", "closeadj"): | |
| px[c] = pd.to_numeric(px[c], errors="coerce") | |
| tr = trend(px) | |
| sf1 = fetch_tickers("SF1", key, tickers, dimension="ARQ", datekey__gte=str(day - timedelta(days=4 * 365)), | |
| columns=SF1_COLS) | |
| f = latest_inputs(sf1) | |
| u = uni[["ticker", "market_cap"]].merge(tr, on="ticker", how="inner").merge(f, on="ticker", how="left") | |
| u = u.join(meta, on="ticker").assign(currency=u["ticker"].map(cur)) | |
| pool = rank_table(u) | |
| keep = ["rank", "ticker", "name", "sector", "industry", "price", "market_cap", "trend", "qcd_pct", "ma50_200", | |
| "mom_6_1", "ret_1m", "ret_6m", "roe", "fcf_yield", "buyback_yield", "filed"] | |
| rows = pool[[c for c in keep if c in pool]].head(40) | |
| return {"built": datetime.now(timezone.utc).isoformat(timespec="seconds"), | |
| "prices_as_of": str(tr["last_bar"].max()) if not tr.empty else None, | |
| "universe": pool.attrs["universe"], "liquid_usd": pool.attrs["liquid_usd"], "pool": int(len(pool)), | |
| "ranked": json.loads(rows.to_json(orient="records"))} | |
| # ------------------------------------------------------------------ daily cache | |
| def _path() -> str: | |
| os.makedirs(config.CACHE_DIR, exist_ok=True) | |
| return os.path.join(config.CACHE_DIR, "ranking.json") | |
| def cached() -> Optional[dict]: | |
| try: | |
| with open(_path()) as fh: | |
| return json.load(fh) | |
| except (OSError, ValueError): | |
| return None | |
| def age_hours(r: Optional[dict]) -> float: | |
| if not r or not r.get("built"): | |
| return float("inf") | |
| return (datetime.now(timezone.utc) - datetime.fromisoformat(r["built"])).total_seconds() / 3600 | |
| def refresh(force: bool = False) -> Optional[dict]: | |
| """Rebuild if older than RANKING_MAX_AGE_H (blocking; one build at a time).""" | |
| r = cached() | |
| if not force and age_hours(r) < config.RANKING_MAX_AGE_H: | |
| return r | |
| if not _lock.acquire(blocking=False): | |
| return r | |
| try: | |
| _state.update(building=True, error=None, started=time.time()) | |
| r = build(config.NDL_KEY) | |
| tmp = _path() + ".part" | |
| with open(tmp, "w") as fh: | |
| json.dump(r, fh) | |
| os.replace(tmp, _path()) | |
| return r | |
| except Exception as e: # noqa: BLE001 — keep serving the last good ranking | |
| _state["error"] = f"{type(e).__name__}: {e}"[:300] | |
| return cached() | |
| finally: | |
| _state["building"] = False | |
| _lock.release() | |
| def refresh_async() -> None: | |
| if age_hours(cached()) >= config.RANKING_MAX_AGE_H and not _state["building"]: | |
| threading.Thread(target=refresh, daemon=True).start() | |
| def state() -> dict: | |
| return dict(_state) | |