spb/company-atlas
Public
Python 66.3%
TypeScript 22.7%
JavaScript 8.6%
HTML 1.4%
CSS 0.7%
1"""Platform aggregates: `/stats`, `/stats/history`, `/system`, `/pulse`, `/index`, `/methodology`."""2from __future__ import annotations34from typing import Any56from fastapi import APIRouter, Query, Request78from companyatlas.api import aggregates as agg9from companyatlas.api import queries as q10from companyatlas.api.common import cached, cached_response11from companyatlas.config import settings12from companyatlas.db import connection13from companyatlas.taxonomy import CCI_FORMULA_VERSION, CCI_WEIGHTS, EVENT_SUBTYPES, METRICS_FORMULA_VERSION, EventType, Metric1415ORDER = 1016router = APIRouter(prefix="/api/v1", tags=["platform"])1718LAUNCH_SUBTYPES = ["PRODUCT_LAUNCH", "NEW_PRODUCT", "FEATURE_LAUNCH", "AI_LAUNCH", "API_LAUNCH", "SDK_RELEASE"]192021@router.get("/stats", summary="Platform counters (cached 60 s)")22async def stats(request: Request) -> Any:23 return cached_response(request, await agg.cached_global_stats(), 60)242526@router.get("/stats/history", summary="Global daily history")27async def stats_history(request: Request, days: int = Query(90, ge=1, le=730)) -> Any:28 async def produce() -> dict[str, Any]:29 async with connection() as conn:30 return {"items": await agg.global_daily_rows(conn, days)}31 return cached_response(request, await cached(f"stats:history:{days}", 300, produce), 300)323334@router.get("/system", summary="Public aggregate health")35async def system(request: Request) -> Any:36 async def produce() -> dict[str, Any]:37 async with connection() as conn:38 return await agg.system_health(conn)39 return cached_response(request, await cached("system", 30, produce), 30)404142@router.get("/index", summary="Global Corporate Activity Index")43async def index(request: Request, days: int = Query(365, ge=30, le=1095)) -> Any:44 async def produce() -> dict[str, Any]:45 async with connection() as conn:46 return await agg.activity_index(conn, days)47 return cached_response(request, await cached(f"index:{days}", 300, produce), 300)484950@router.get("/pulse", summary="Homepage aggregate (cached 60 s)")51async def pulse(request: Request) -> Any:52 async def produce() -> dict[str, Any]:53 stats_payload = await agg.cached_global_stats()54 async with connection() as conn:55 live = await agg.live_events(conn, 12)56 movers = await agg.ranking_cards(conn, "most_active", "7d", limit=10, sparkline=True)57 hiring = await agg.ranking_cards(conn, "hiring_growth", "30d", limit=8)58 launches = await agg.live_events(conn, 8, event_subtypes=LAUNCH_SUBTYPES)59 pricing = await agg.live_events(conn, 8, event_type="PRICING")60 ai = await agg.ranking_cards(conn, "ai_active", "30d", limit=8)61 trending = await agg.trend_rows(conn, 7, 10)62 idx = await agg.activity_index(conn, 30)63 buckets = await agg.map_buckets(conn, "events_30d")64 industries = (await agg.cached_industry_rows())[:12]65 countries = (await agg.cached_country_rows())[:12]66 return {"stats": stats_payload, "live": live, "movers": movers, "hiring": hiring, "launches": launches, "pricing": pricing, "ai": ai,67 "industries": industries, "countries": countries, "trending": trending,68 "activity_index": {"value": idx["value"], "delta_7d": idx["delta_7d"], "series": idx["series"][-30:]}, "map": buckets[:300]}69 return cached_response(request, await cached("pulse", 60, produce), 60)707172METRIC_DOCS: dict[str, tuple[str, list[str]]] = {73 Metric.ACTIVITY_SCORE: (("Company Activity Score 0–100: weighted volume and significance of detected changes across monitored surfaces (website, products, "74 "news, jobs, leadership, documentation, pricing) over rolling windows, normalised by sensor coverage."),75 ["changes", "meaningful_changes", "events", "surfaces", "sensor_coverage"]),76 Metric.HIRING_MOMENTUM_7D: ("Hiring momentum over 7 days: net change of publicly listed open positions (%); negative when listings disappear.",77 ["jobs_open", "jobs_new", "jobs_removed"]),78 Metric.HIRING_MOMENTUM_30D: ("Hiring momentum over 30 days (%).", ["jobs_open", "jobs_new", "jobs_removed"]),79 Metric.HIRING_MOMENTUM_90D: ("Hiring momentum over 90 days (%).", ["jobs_open", "jobs_new", "jobs_removed"]),80 Metric.OPEN_JOBS: ("Number of publicly listed open positions currently observed on monitored career surfaces.", ["jobs_open"]),81 Metric.AI_ADOPTION: (("AI Adoption Score 0–100 from observable public signals only: AI products, AI job postings, documentation, marketing, "82 "partnerships, research and leadership roles. Never claims internal use without evidence."),83 ["ai_jobs", "ai_products", "ai_docs", "ai_news", "ai_leadership"]),84 Metric.PRODUCT_VELOCITY: ("Product Velocity 0–100: cadence of product launches, updates, renames and removals detected on product surfaces.",85 ["product_events", "changelog_entries", "feature_launches"]),86 Metric.GEO_EXPANSION: ("Geographic Expansion 0–100: new locations, new countries and geographic hiring spread.", ["new_locations", "new_countries", "job_countries"]),87 Metric.DEVELOPER_MOMENTUM: ("Developer Momentum 0–100: API/SDK launches, documentation and changelog activity.", ["developer_events", "doc_changes", "api_changes"]),88 Metric.COMMUNICATION_ACTIVITY: ("Communication Activity 0–100: newsroom, blog and feed publication cadence.", ["news_items", "blog_posts"]),89 Metric.PRICING_ACTIVITY: ("Pricing Activity 0–100: detected plan and price changes.", ["pricing_events"]),90 Metric.LEADERSHIP_ACTIVITY: ("Leadership Activity 0–100: additions, removals and title changes on monitored leadership pages.", ["leadership_events"]),91 Metric.CORPORATE_CHANGE_INDEX: (f"Corporate Change Index: weighted composite — {', '.join(f'{k} {v:.2f}' for k, v in CCI_WEIGHTS.items())}.",92 list(CCI_WEIGHTS)),93 Metric.ANOMALY_SCORE: ("Unusual activity 0–100: z-score of current activity against the company's own baseline (56-day window).",94 ["baseline_mean", "baseline_stddev", "current"]),95 Metric.HISTORICAL_COVERAGE: ("Historical Completeness 0–100: sensor uptime, continuity and surface coverage of the record.",96 ["sensor_uptime", "continuity", "surface_coverage", "failed_periods"]),97}9899100@router.get("/methodology", summary="How metrics, significance and confidence are computed")101async def methodology(request: Request) -> Any:102 payload = {103 "metrics": [{"metric": m.value, "formula_version": CCI_FORMULA_VERSION if m is Metric.CORPORATE_CHANGE_INDEX else METRICS_FORMULA_VERSION,104 "description": METRIC_DOCS[m][0], "inputs": METRIC_DOCS[m][1]} for m in Metric],105 "significance_bands": {"noise": [0.0, settings.noise_threshold], "minor": [settings.noise_threshold, settings.meaningful_threshold],106 "meaningful": [settings.meaningful_threshold, settings.major_threshold],107 "major": [settings.major_threshold, settings.critical_threshold], "critical": [settings.critical_threshold, 1.0]},108 "event_types": [t.value for t in EventType],109 "event_subtypes": [{"event_subtype": k, "event_type": v[0].value, "default_importance": v[1]} for k, v in EVENT_SUBTYPES.items()],110 "confidence_labels": [{"label": "VERIFIED", "min_confidence": 0.95}, {"label": "HIGH_CONFIDENCE", "min_confidence": 0.85},111 {"label": "LIKELY", "min_confidence": 0.7}, {"label": "INFERRED", "min_confidence": 0.5},112 {"label": "LOW_CONFIDENCE", "min_confidence": 0.0}],113 "windows": list(q.WINDOWS), "cci_weights": dict(CCI_WEIGHTS), "baseline_window_days": settings.baseline_window_days, "anomaly_z": settings.anomaly_z,114 "language": "Interpretive language is careful by design: events say 'no longer listed', never 'fired'; inferred facts carry a confidence label.",115 }116 return cached_response(request, payload, 3600)117