From 37bc56787a1e53d50f781b36f3496ed8fd9d8417 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Sat, 5 Dec 2026 14:51:13 -0600 Subject: [PATCH] Use exact historical IPEDS completions --- apps/nextpath/data/soc-cip-map.json | 24 ++-- scripts/nextpath-opportunity-refresh.py | 105 ++++++++++-------- .../test_nextpath_opportunity_refresh.py | 50 +++++++-- 3 files changed, 110 insertions(+), 69 deletions(-) diff --git a/apps/nextpath/data/soc-cip-map.json b/apps/nextpath/data/soc-cip-map.json index b2ef414..c94e989 100644 --- a/apps/nextpath/data/soc-cip-map.json +++ b/apps/nextpath/data/soc-cip-map.json @@ -2,17 +2,17 @@ "version": "nextpath-soc-cip-2026-01", "source_url": "https://nces.ed.gov/ipeds/cipcode/resources.aspx?y=56", "mappings": { - "15-1252.00": {"cip4": ["1107"], "coverage": 0.8, "job_query": "software developer"}, - "29-1141.00": {"cip4": ["5138"], "coverage": 0.9, "job_query": "registered nurse"}, - "47-2111.00": {"cip4": ["4603"], "coverage": 0.8, "job_query": "electrician"}, - "49-9021.00": {"cip4": ["4702"], "coverage": 0.8, "job_query": "HVAC technician"}, - "25-2021.00": {"cip4": ["1312"], "coverage": 0.7, "job_query": "elementary teacher"}, - "27-1024.00": {"cip4": ["5004"], "coverage": 0.7, "job_query": "graphic designer"}, - "13-2011.00": {"cip4": ["5203"], "coverage": 0.9, "job_query": "accountant auditor"}, - "17-2051.00": {"cip4": ["1408"], "coverage": 0.9, "job_query": "civil engineer"}, - "35-1011.00": {"cip4": ["1205"], "coverage": 0.7, "job_query": "chef head cook"}, - "21-1012.00": {"cip4": ["1311", "4407"], "coverage": 0.6, "job_query": "career counselor"}, - "13-1081.00": {"cip4": ["5202"], "coverage": 0.7, "job_query": "logistics"}, - "29-1292.00": {"cip4": ["5106"], "coverage": 0.9, "job_query": "dental hygienist"} + "15-1252.00": {"cip6": ["110701"], "coverage": 0.7, "job_query": "software developer"}, + "29-1141.00": {"cip6": ["513801"], "coverage": 0.9, "job_query": "registered nurse"}, + "47-2111.00": {"cip6": ["460302"], "coverage": 0.9, "job_query": "electrician"}, + "49-9021.00": {"cip6": ["470201"], "coverage": 0.9, "job_query": "HVAC technician"}, + "25-2021.00": {"cip6": ["131202"], "coverage": 0.8, "job_query": "elementary teacher"}, + "27-1024.00": {"cip6": ["500409"], "coverage": 0.8, "job_query": "graphic designer"}, + "13-2011.00": {"cip6": ["520301"], "coverage": 0.9, "job_query": "accountant auditor"}, + "17-2051.00": {"cip6": ["140801"], "coverage": 0.9, "job_query": "civil engineer"}, + "35-1011.00": {"cip6": ["120503"], "coverage": 0.8, "job_query": "chef head cook"}, + "21-1012.00": {"cip6": ["131101", "131102"], "coverage": 0.8, "job_query": "career counselor"}, + "13-1081.00": {"cip6": ["520203"], "coverage": 0.9, "job_query": "logistics"}, + "29-1292.00": {"cip6": ["510602"], "coverage": 0.9, "job_query": "dental hygienist"} } } diff --git a/scripts/nextpath-opportunity-refresh.py b/scripts/nextpath-opportunity-refresh.py index 51c9d1d..e229a85 100644 --- a/scripts/nextpath-opportunity-refresh.py +++ b/scripts/nextpath-opportunity-refresh.py @@ -9,17 +9,21 @@ successful snapshot. from __future__ import annotations import argparse +import csv +import io import json import os import tempfile import urllib.parse import urllib.request +import zipfile from collections.abc import Iterable from datetime import datetime, timezone from pathlib import Path from typing import Any -SCORECARD_URL = "https://api.data.gov/ed/collegescorecard/v1/schools.json" +IPEDS_URL = "https://nces.ed.gov/ipeds/datacenter/data" +IPEDS_YEARS = (2022, 2023, 2024) PROJECTIONS_CENTRAL = "https://public.projectionscentral.org/Projections/LongTermRestJson" AYLA_JOBS = "https://aylagov.com/api/jobs/search" @@ -30,86 +34,94 @@ def get_json(url: str, timeout: int = 45) -> dict[str, Any]: return json.load(response) -def scorecard_programs(api_key: str) -> list[dict[str, Any]]: - fields = "id,ope6_id,school.name,latest.programs.cip_4_digit" - programs: list[dict[str, Any]] = [] - page = 0 - while True: - query = urllib.parse.urlencode({ - "api_key": api_key, - "school.state": "AZ", - "per_page": 100, - "page": page, - "fields": fields, - }) - body = get_json(f"{SCORECARD_URL}?{query}") - for school in body.get("results", []): - programs.extend(school.get("latest.programs.cip_4_digit") or []) - metadata = body.get("metadata", {}) - if (page + 1) * int(metadata.get("per_page", 100)) >= int(metadata.get("total", 0)): - return programs - page += 1 +def cached_download(url: str, path: Path) -> Path: + if path.is_file() and path.stat().st_size > 0: + return path + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + request = urllib.request.Request(url, headers={"User-Agent": "NextPath/1.0"}) + with urllib.request.urlopen(request, timeout=120) as response, temporary.open("wb") as stream: + while block := response.read(1024 * 1024): + stream.write(block) + os.replace(temporary, path) + return path -def annual_completions(programs: Iterable[dict[str, Any]], cip4: set[str]) -> int: - # Scorecard calls this IPEDS awards. Deduplicate branch records sharing the - # same OPE6 institution and program, retaining the largest reported value. - deduplicated: dict[tuple[str, str], int] = {} - for program in programs: - code = str(program.get("code", "")).replace(".", "").zfill(4) - if code not in cip4: - continue - awards = program.get("counts", {}).get("ipeds_awards1") - if not isinstance(awards, (int, float)) or awards < 0: - continue - key = (str(program.get("ope6_id") or program.get("unit_id")), code) - deduplicated[key] = max(deduplicated.get(key, 0), int(awards)) - return sum(deduplicated.values()) +def zip_rows(path: Path) -> Iterable[dict[str, str]]: + with zipfile.ZipFile(path) as archive: + name = archive.namelist()[0] + with archive.open(name) as raw: + # IPEDS changed encodings across annual exports: newer headers can + # carry a UTF-8 BOM while older institution names contain legacy + # bytes. Replacement is safe because matching uses ASCII IDs, + # state abbreviations and CIP fields rather than institution text. + yield from csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8-sig", errors="replace")) -def projected_openings(body: dict[str, Any]) -> tuple[int, str]: +def ipeds_completion_history(cip6: set[str], cache_dir: Path) -> dict[str, int]: + history: dict[str, int] = {} + for year in IPEDS_YEARS: + directory = cached_download(f"{IPEDS_URL}/HD{year}.zip", cache_dir / f"HD{year}.zip") + completions = cached_download(f"{IPEDS_URL}/C{year}_A.zip", cache_dir / f"C{year}_A.zip") + arizona = {row["UNITID"] for row in zip_rows(directory) if row.get("STABBR") == "AZ"} + total = 0 + for row in zip_rows(completions): + code = row.get("CIPCODE", "").replace(".", "") + if row.get("UNITID") not in arizona or code not in cip6 or row.get("MAJORNUM") != "1": + continue + awards = int(row.get("CTOTALT") or -1) + if awards >= 0: + total += awards + history[str(year)] = total + return history + + +def projected_openings(body: dict[str, Any]) -> tuple[int, str, float]: rows = body.get("rows") or [] row = next((item for item in rows if item.get("Area") == "Arizona"), rows[0] if rows else None) if not row: raise ValueError("Projections Central returned no Arizona projection") count = int(str(row.get("AvgAnnualOpenings", "0")).replace(",", "")) period = f"{row.get('BaseYear', '')}-{row.get('ProjYear', '')}" - return count, period.strip("-") + return count, period.strip("-"), float(row.get("PercentChange", 0)) -def public_market_evidence(onet: str, job_query: str) -> tuple[int, str, int]: +def public_market_evidence(onet: str, job_query: str) -> tuple[int, str, float, int]: soc = onet.split(".", 1)[0] projections = get_json(f"{PROJECTIONS_CENTRAL}/04/{urllib.parse.quote(soc, safe='-')}") - openings, period = projected_openings(projections) + openings, period, growth = projected_openings(projections) query = urllib.parse.urlencode({ "search": job_query, "limit": 1, "filters": json.dumps({"state": "AZ"}, separators=(",", ":")), }) jobs = get_json(f"{AYLA_JOBS}?{query}") - return openings, period, int(jobs.get("pagination", {}).get("total", 0)) + return openings, period, growth, int(jobs.get("pagination", {}).get("total", 0)) -def refresh(mapping_path: Path, output_path: Path, api_key: str) -> None: +def refresh(mapping_path: Path, output_path: Path) -> None: mapping = json.loads(mapping_path.read_text()) - programs = scorecard_programs(api_key) + source_cache = output_path.parent / "source-cache" / "ipeds" observed = datetime.now(timezone.utc) occupations: dict[str, Any] = {} for onet, spec in mapping["mappings"].items(): - graduates = annual_completions(programs, set(spec["cip4"])) - openings, period, postings = public_market_evidence(onet, spec["job_query"]) + history = ipeds_completion_history(set(spec["cip6"]), source_cache) + graduates = history[str(IPEDS_YEARS[-1])] + openings, period, growth, postings = public_market_evidence(onet, spec["job_query"]) if graduates <= 0: raise ValueError(f"no Arizona completions found for {onet}") occupations[onet] = { "arizona_annual_graduates": graduates, + "arizona_graduate_history": history, "arizona_projected_annual_openings": openings, + "projected_employment_growth_percent": growth, "active_postings": postings, - "graduate_academic_year": "latest College Scorecard IPEDS awards cohort", + "graduate_academic_year": str(IPEDS_YEARS[-1]), "projection_period": period, "postings_observed_at": observed.isoformat().replace("+00:00", "Z"), "geography": "Arizona", "soc_to_cip_mapping_coverage": spec["coverage"], - "graduate_source_url": "https://collegescorecard.ed.gov/data/", + "graduate_source_url": "https://nces.ed.gov/ipeds/use-the-data/download-access-database", "projection_source_url": "https://projectionscentral.org/directdownloads", "posting_source_url": "https://aylagov.com/developers", } @@ -136,9 +148,8 @@ def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--mapping", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--data-gov-key", default=os.environ.get("DATA_GOV_API_KEY", "DEMO_KEY")) args = parser.parse_args() - refresh(args.mapping, args.output, args.data_gov_key) + refresh(args.mapping, args.output) if __name__ == "__main__": diff --git a/tests/jeannie/test_nextpath_opportunity_refresh.py b/tests/jeannie/test_nextpath_opportunity_refresh.py index dc5e344..560c124 100644 --- a/tests/jeannie/test_nextpath_opportunity_refresh.py +++ b/tests/jeannie/test_nextpath_opportunity_refresh.py @@ -1,6 +1,10 @@ import importlib.util +import csv +import io import pathlib +import tempfile import unittest +import zipfile ROOT = pathlib.Path(__file__).resolve().parents[2] @@ -12,20 +16,46 @@ SPEC.loader.exec_module(MODULE) class NextPathOpportunityRefreshTests(unittest.TestCase): - def test_completions_deduplicate_branches(self): - programs = [ - {"code": "11.07", "ope6_id": "one", "counts": {"ipeds_awards1": 10}}, - {"code": "1107", "ope6_id": "one", "counts": {"ipeds_awards1": 8}}, - {"code": "1107", "ope6_id": "two", "counts": {"ipeds_awards1": 5}}, - {"code": "5138", "ope6_id": "three", "counts": {"ipeds_awards1": 99}}, - ] - self.assertEqual(MODULE.annual_completions(programs, {"1107"}), 15) + def write_zip(self, path, member, fieldnames, rows): + output = io.StringIO() + writer = csv.DictWriter(output, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + with zipfile.ZipFile(path, "w") as archive: + archive.writestr(member, output.getvalue()) + + def test_ipeds_history_uses_exact_cip_and_arizona_primary_major(self): + with tempfile.TemporaryDirectory() as temporary: + cache = pathlib.Path(temporary) + for year in MODULE.IPEDS_YEARS: + self.write_zip( + cache / f"HD{year}.zip", + f"HD{year}.csv", + ["UNITID", "STABBR"], + [{"UNITID": "1", "STABBR": "AZ"}, {"UNITID": "2", "STABBR": "CA"}], + ) + self.write_zip( + cache / f"C{year}_A.zip", + f"C{year}_A.csv", + ["UNITID", "CIPCODE", "MAJORNUM", "CTOTALT"], + [ + {"UNITID": "1", "CIPCODE": "52.0203", "MAJORNUM": "1", "CTOTALT": "103"}, + {"UNITID": "1", "CIPCODE": "52.0201", "MAJORNUM": "1", "CTOTALT": "999"}, + {"UNITID": "1", "CIPCODE": "52.0203", "MAJORNUM": "2", "CTOTALT": "40"}, + {"UNITID": "2", "CIPCODE": "52.0203", "MAJORNUM": "1", "CTOTALT": "88"}, + ], + ) + self.assertEqual( + MODULE.ipeds_completion_history({"520203"}, cache), + {str(year): 103 for year in MODULE.IPEDS_YEARS}, + ) def test_extracts_arizona_projection(self): body = {"rows": [{ - "Area": "Arizona", "AvgAnnualOpenings": "1,234", "BaseYear": "2024", "ProjYear": "2034" + "Area": "Arizona", "AvgAnnualOpenings": "1,234", "BaseYear": "2024", "ProjYear": "2034", + "PercentChange": "14.5", }]} - self.assertEqual(MODULE.projected_openings(body), (1234, "2024-2034")) + self.assertEqual(MODULE.projected_openings(body), (1234, "2024-2034", 14.5)) if __name__ == "__main__":