|
| 1 | +"""EDGAR scan 직원수 빌더. 10-K 본문(edgar/panel contentRaw) regex 로 edgar/scan/report/employee.parquet 생성. |
| 2 | +
|
| 3 | +직원수(workforce)는 SEC XBRL 집계(companyfacts·companyconcept)에 ``EntityNumberOfEmployees`` 가 없어서 |
| 4 | +(실측 404) 10-K 본문에서만 얻는다. edgar/panel 의 ``contentRaw``(10-K 텍스트 SSOT. 7,300+ 종목 발행)에 |
| 5 | +직원수 정규식을 적용해 연도별 직원수를 추출한다. companyfacts 직독인 다른 report 관점(buildEdgarReport)과 |
| 6 | +달리 panel 텍스트가 소스라 별 빌더로 분리한다. |
| 7 | +
|
| 8 | +파싱 단일 SSOT. ``parseEmployeeCount`` 는 providers(L1) ``edgar/report/employee`` 가 보유하고 본 scan(L1.5)이 |
| 9 | +downward import 로 공유한다(중복 0). KR 정기보고서 직원현황(성별·정규/계약 분해)과 달리 US 10-K 는 총원 |
| 10 | +단일값이라 employeeCount 단일 컬럼이다(정직한 충실도 차이). |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +import polars as pl |
| 18 | + |
| 19 | +from dartlab.core.logger import getLogger |
| 20 | + |
| 21 | +_log = getLogger(__name__) |
| 22 | + |
| 23 | +EMPLOYEE_COLS = { |
| 24 | + "stockCode": pl.Utf8, |
| 25 | + "year": pl.Utf8, |
| 26 | + "employeeCount": pl.Int64, |
| 27 | + "source": pl.Utf8, |
| 28 | +} |
| 29 | + |
| 30 | +# buildEdgarEmployee 가 panel 에서 읽는 최소 컬럼(메모리. contentRaw 가 전 10-K 텍스트라 무겁다). |
| 31 | +_READ_COLS = ["chapter", "period", "contentRaw"] |
| 32 | + |
| 33 | + |
| 34 | +def employeeRowsFromPanel(panel: pl.DataFrame, ticker: str) -> list[dict]: |
| 35 | + """단일 회사 panel(10-K contentRaw) 에서 연도별 직원수 행 추출. 연도당 첫 유효 매칭. |
| 36 | +
|
| 37 | + ``period`` 앞 4자리를 회계연도로 보고, 연도마다 첫 직원수 매칭을 채택한다(10-K 본문 한정 입력 가정. |
| 38 | + 빌더가 chapter='10-K' 푸시다운). 무매칭 연도는 제외. |
| 39 | +
|
| 40 | + Args: |
| 41 | + panel: ``period``·``contentRaw`` 컬럼(10-K 필터 후) DataFrame. |
| 42 | + ticker: stockCode. |
| 43 | +
|
| 44 | + Returns: |
| 45 | + list[dict]. 연도별 직원수 행(stockCode·year·employeeCount·source). |
| 46 | + """ |
| 47 | + # 파싱 SSOT 는 providers(L1) employee.parseEmployeeCount. scan(L1.5)이 downward lazy import 로 공유. |
| 48 | + from dartlab.providers.edgar.report.employee import parseEmployeeCount |
| 49 | + |
| 50 | + byYear: dict[str, int] = {} |
| 51 | + for period, text in zip(panel["period"].to_list(), panel["contentRaw"].to_list()): |
| 52 | + year = str(period or "")[:4] |
| 53 | + if not year.isdigit() or year in byYear: |
| 54 | + continue |
| 55 | + count = parseEmployeeCount(str(text or "")) |
| 56 | + if count is not None: |
| 57 | + byYear[year] = count |
| 58 | + return [{"stockCode": ticker, "year": y, "employeeCount": c, "source": "10-K"} for y, c in sorted(byYear.items())] |
| 59 | + |
| 60 | + |
| 61 | +def buildEdgarEmployee(*, verbose: bool = False) -> Path: |
| 62 | + """전종목 edgar/panel 에서 edgar/scan/report/employee.parquet 생성. 10-K 직원수 순수 텍스트 추출. |
| 63 | +
|
| 64 | + edgar/panel/{ticker}.parquet 만 순회하며 10-K 본문에서 직원수를 regex 추출한다. 별도 수집 0. lazy |
| 65 | + pushdown(chapter='10-K' + 'employ' 포함)으로 직원 무관 텍스트는 안 읽어 메모리를 절약한다. edgarSync 의 |
| 66 | + edgarPanel 갱신 직후 호출(로컬 panel 재사용). |
| 67 | +
|
| 68 | + Parameters |
| 69 | + ---------- |
| 70 | + verbose : bool |
| 71 | + 진행 로그. |
| 72 | +
|
| 73 | + Returns |
| 74 | + ------- |
| 75 | + Path |
| 76 | + edgar/scan/report/employee.parquet 경로. |
| 77 | +
|
| 78 | + Raises |
| 79 | + ------ |
| 80 | + 없음. panel 부재/공백이면 빈 parquet 을 쓴다(보조 소스, scan 빌드 무중단). |
| 81 | +
|
| 82 | + Examples |
| 83 | + -------- |
| 84 | + >>> from dartlab.scan.builders.edgar.report.employeeBuild import buildEdgarEmployee |
| 85 | + >>> p = buildEdgarEmployee(verbose=True) # doctest: +SKIP |
| 86 | + >>> p.name |
| 87 | + 'employee.parquet' |
| 88 | +
|
| 89 | + Capabilities: |
| 90 | + - 7,300+ 종목 panel 텍스트에서 연도별 직원수 추출. XBRL 부재라 10-K 본문이 유일 소스. 무매칭 |
| 91 | + 기업/연도는 빈 행(패널 자연 미표시). |
| 92 | +
|
| 93 | + AIContext: |
| 94 | + ``scan`` US workforce 의 source. companyfacts 직독 report 관점과 별개로 panel 텍스트가 소스다. |
| 95 | + 런타임 reportSource 가 market 분기로 KR(dart/scan/report/employee)과 분리 소비할 예정. |
| 96 | +
|
| 97 | + Guide: |
| 98 | + - edgarSync edgarPanel 갱신 직후 호출. 발행은 deployEdgarToHF(['scan']) 가 자동. |
| 99 | + - panel 로컬 커버리지에 비례(panel SSOT 가 채워질수록 직원수도 증가). |
| 100 | +
|
| 101 | + When: |
| 102 | + edgarSync scan 프리빌드 단계(buildEdgarReport 직후). 직접 호출은 드물다. |
| 103 | +
|
| 104 | + How: |
| 105 | + panel 마다 lazy scan + chapter='10-K' & contentRaw~'employ' 푸시다운 후 employeeRowsFromPanel |
| 106 | + (연도별 첫 유효 regex 매칭)로 누적해 단일 parquet 으로 쓴다. |
| 107 | +
|
| 108 | + Requires: |
| 109 | + - edgar/panel/{ticker}.parquet (edgarPanel stage 산출) |
| 110 | +
|
| 111 | + SeeAlso: |
| 112 | + - :func:`parseEmployeeCount` (파싱 SSOT. L4 employee 공유) |
| 113 | + - :func:`dartlab.scan.builders.edgar.report.build.buildEdgarReport` (companyfacts 직독 3관점) |
| 114 | + """ |
| 115 | + from dartlab import config as _cfg |
| 116 | + |
| 117 | + panelDir = Path(_cfg.dataDir) / "edgar" / "panel" |
| 118 | + outDir = Path(_cfg.dataDir) / "edgar" / "scan" / "report" |
| 119 | + outDir.mkdir(parents=True, exist_ok=True) |
| 120 | + # panel 은 보조 소스(커버리지 가변). 부재/공백이어도 빈 parquet 으로 graceful 처리(scan 빌드 무중단). |
| 121 | + parquets = sorted(panelDir.glob("*.parquet")) if panelDir.exists() else [] |
| 122 | + if not parquets and verbose: |
| 123 | + _log.info("[edgarReport] employee: edgar/panel 부재. 빈 parquet 생성") |
| 124 | + |
| 125 | + rows: list[dict] = [] |
| 126 | + for fp in parquets: |
| 127 | + ticker = fp.stem.upper() |
| 128 | + try: |
| 129 | + sub = ( |
| 130 | + pl.scan_parquet(fp) |
| 131 | + .filter((pl.col("chapter") == "10-K") & pl.col("contentRaw").str.contains("(?i)employ")) |
| 132 | + .select(["period", "contentRaw"]) |
| 133 | + .collect() |
| 134 | + ) |
| 135 | + except (OSError, pl.exceptions.PolarsError): |
| 136 | + continue |
| 137 | + if sub.is_empty(): |
| 138 | + continue |
| 139 | + rows.extend(employeeRowsFromPanel(sub, ticker)) |
| 140 | + |
| 141 | + out = pl.DataFrame(rows, schema=EMPLOYEE_COLS) if rows else pl.DataFrame(schema=EMPLOYEE_COLS) |
| 142 | + out = out.sort(["stockCode", "year"]) |
| 143 | + outPath = outDir / "employee.parquet" |
| 144 | + out.write_parquet(str(outPath), compression="zstd") |
| 145 | + if verbose: |
| 146 | + _log.info(f"[edgarReport] employee: {out.height}행 ({out['stockCode'].n_unique()}종목) 생성 {outPath}") |
| 147 | + return outPath |
0 commit comments