1
2
3
4import { Actor } from 'apify';
5await Actor.init();
6const input = (await Actor.getInput()) ?? {};
7const { mode = 'company_financials', companies = ['Apple', 'MSFT', 'nvidia.com'], include_filings = true, include_peers = true, new_only = false, since_cursor = '', forms = [], max_items = 200 } = input;
8const UPDATE = 'Company cards refreshed from SEC EDGAR hourly on weekdays (13:15 to 23:45 UTC) and daily otherwise; figures are as filed in the newest annual and quarterly reports';
9const state = await Actor.openKeyValueStore('pops4-company-financials-state');
10const prevSeen = (await state.getValue('LAST_FILING_BY_TICKER')) ?? {}; const nextSeen = { ...prevSeen };
11const BASE = 'https://www.pops4.com';
12const UA = 'apify-sec-filings-company-financials/0.2 (data source: SEC EDGAR; served by POPS4 Filing Boards)';
13const log = Actor.log ?? console;
14async function getJson(url) {
15 const r = await fetch(url, { headers: { 'user-agent': UA, accept: 'application/json' } });
16 if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`);
17 return r.json();
18}
19const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
20const pct = (v) => (typeof v === 'number' && Number.isFinite(v) ? Math.round(v * 10000) / 100 : null);
21let pushed = 0;
22async function push(row, eventName) {
23 if (pushed >= max_items) return false;
24 await Actor.pushData(row); pushed += 1;
25 await Actor.charge({ eventName }).catch(() => {});
26 return true;
27}
28
29let secList = null;
30async function loadSecList() {
31 if (secList) return secList;
32 const d = await getJson('https://www.sec.gov/files/company_tickers.json');
33 secList = Object.values(d).map((e) => ({ cik: String(e.cik_str), ticker: String(e.ticker).toUpperCase(), title: String(e.title) }));
34 return secList;
35}
36const norm = (s) => String(s).toLowerCase().replace(/\b(inc|corp|corporation|co|company|ltd|plc|holdings|group|the)\b\.?/g, ' ').replace(/[^a-z0-9]+/g, ' ').trim();
37async function resolve(q) {
38 const raw = String(q).trim(); if (!raw) return null;
39 const list = await loadSecList();
40 const upper = raw.toUpperCase();
41 if (/^[A-Z.\-]{1,6}$/.test(upper)) { const hit = list.find((e) => e.ticker === upper); if (hit) return { ...hit, matched_by: 'ticker' }; }
42 let key = raw.toLowerCase();
43 if (/\./.test(key) && !/\s/.test(key)) key = key.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0].split('.')[0];
44 const nk = norm(key);
45 if (!nk) return null;
46 const exact = list.find((e) => norm(e.title) === nk); if (exact) return { ...exact, matched_by: 'name' };
47 const starts = list.filter((e) => norm(e.title).startsWith(nk)); if (starts.length) return { ...starts[0], matched_by: 'name_prefix' };
48 const word = list.filter((e) => norm(e.title).split(' ').includes(nk)); if (word.length) return { ...word[0], matched_by: 'name_word' };
49 return null;
50}
51function flatten(card, hit, q) {
52 const m = card.metrics ?? {}, cf = card.cashFlow ?? {}, inv = card.investments ?? {}, hw = card.healthWatch ?? {}, h = card.harbor ?? {}, p = card.peers ?? {}, sc = card.speedCash ?? {}, au = card.auditor ?? {}, w = card.where ?? {};
53 const last = (card.filings ?? [])[0] ?? {};
54 const officerChanges = (hw.signals ?? []).find((s) => s.code === '5.02')?.count ?? 0;
55 const row = {
56 query: q, matched_by: hit.matched_by, ticker: card.ticker ?? hit.ticker, cik: card.cik ?? hit.cik, company: card.name ?? hit.title,
57 fiscal_year_end: m.fiscalYearEnd ?? null, years_of_data: num(m.yearsOfData),
58 revenue_usd: num(m.revenue), revenue_growth_1y_pct: pct(m.revenueGrowth1y), revenue_growth_per_year_pct: pct(m.revenueGrowthPerYear),
59 operating_margin_pct: pct(m.operatingMargin), operating_margin_prior_pct: pct(m.operatingMarginPrior), net_margin_pct: pct(m.netMargin),
60 operating_cash_flow_usd: num(cf.operating ?? m.operatingCashFlow), free_cash_flow_usd: num(cf.free), capital_spending_usd: num(cf.capitalSpending), investing_cash_flow_usd: num(cf.investing), financing_cash_flow_usd: num(cf.financing),
61 cash_usd: num(inv.cash), short_term_investments_usd: num(inv.shortTerm), long_term_investments_usd: num(inv.longTerm), total_assets_usd: num(inv.totalAssets), current_ratio: num(inv.currentRatio),
62 equity_ratio_pct: pct(m.equityRatio ?? sc.equityRatio), return_on_equity_pct: pct(m.returnOnEquity), payout_ratio_pct: pct(m.payoutRatio), dividend_raised_years: num(m.dividendYears ?? m.dividendRaisedYears),
63 research_share_of_revenue_pct: pct(m.researchShareOfRevenue), total_debt_usd: num(m.totalDebt),
64 health_warning_signs: num(h.level), health_signs: (h.signs ?? []).map((s) => (typeof s === 'string' ? s : s.label ?? JSON.stringify(s))).join('; '),
65 growth_profile: sc.quadrant?.label ?? null, growth_profile_plain: sc.quadrant?.plain ?? null,
66 auditor_changes_count: (au.changes ?? []).length, non_reliance_filings_count: (au.nonReliance ?? []).length, restated_since: au.restatedSince ?? null,
67 events_8k_12m: num(card.events12m), officer_or_director_changes_12m: officerChanges,
68 sic_code: p.sic ?? null, industry: p.sicDescription ?? null, peer_group_size: Array.isArray(p.growth) ? p.growth[1] : null,
69 peer_median_growth_pct: Array.isArray(p.growth) ? pct(p.growth[0]) : null, peer_median_operating_margin_pct: Array.isArray(p.opMargin) ? pct(p.opMargin[0]) : null, peer_median_equity_ratio_pct: Array.isArray(p.equityRatio) ? pct(p.equityRatio[0]) : null,
70 headquarters: w.headquarters ?? null, incorporated: w.incorporated ?? null, foreign_private_issuer: !!w.crosses_border,
71 last_filing_form: last.form ?? null, last_filing_date: last.filed ?? null, last_filing_items: (last.items ?? []).join('; '), last_filing_url: last.url ?? null,
72 summary: card.summary ?? null,
73 source_facts_url: card.sources?.facts ?? `https://data.sec.gov/api/xbrl/companyfacts/CIK${String(hit.cik).padStart(10, '0')}.json`, source_filings_url: card.sources?.filings ?? null,
74 data_source: 'The company\'s own filings with the U.S. SEC (EDGAR, XBRL company facts)', served_by: 'POPS4 Filing Boards, CC BY 4.0', citation: card.cite ?? null, not_advice: 'Reporting, not investment advice.',
75 };
76 if (include_filings) row.recent_filings = (card.filings ?? []).slice(0, 10).map((f) => ({ form: f.form, filed: f.filed, items: f.items ?? [], url: f.url }));
77 if (include_peers) row.peers = (card.peerList?.rows ?? []).slice(0, 10).map((r) => ({ ticker: r[0], company: r[1], operating_margin_pct: pct(r[4]), growth_pct: pct(r[5]), revenue_usd: num(r[6]) }));
78 return row;
79}
80if (mode === 'company_financials') {
81 for (const q of companies) {
82 if (pushed >= max_items) break;
83 let hit = null;
84 try { hit = await resolve(q); } catch (e) { log.warning(`resolve failed for ${q}: ${e.message}`); }
85 if (!hit) { await push({ query: q, matched_by: null, error: 'No US-listed company matched this name, ticker or website in the SEC company list.' }, 'company'); continue; }
86 let card;
87 try { card = await getJson(`${BASE}/boards/company/${encodeURIComponent(hit.ticker)}.json`); } catch (e) { await push({ query: q, matched_by: hit.matched_by, ticker: hit.ticker, cik: hit.cik, company: hit.title, error: `No company card yet for ${hit.ticker} (${e.message}).` }, 'company'); continue; }
88 if (!card.ok) { await push({ query: q, ticker: hit.ticker, cik: hit.cik, company: hit.title, error: 'Card not available.' }, 'company'); continue; }
89 const lastFiled = (card.filings ?? [])[0]?.filed ?? card.metrics?.fiscalYearEnd ?? '';
90 if (new_only && prevSeen[hit.ticker] && prevSeen[hit.ticker] === lastFiled) { log.info(`${hit.ticker}: no new filing since last run, skipped`); continue; }
91 nextSeen[hit.ticker] = lastFiled;
92 await push({ ...flatten(card, hit, q), new_since_last_run: prevSeen[hit.ticker] ? `filing ${lastFiled} is newer than ${prevSeen[hit.ticker]}` : 'first time seen' }, 'company');
93 }
94} else if (mode === 'live_filings') {
95 const now = await getJson(`${BASE}/boards/now.json`);
96 let events = now.events ?? [];
97 if (since_cursor) events = events.filter((e) => (e.posted ?? '') > since_cursor);
98 if (forms.length) events = events.filter((e) => forms.map((f) => String(f).toUpperCase()).includes(String(e.form).toUpperCase()));
99 for (const e of events) { if (!(await push({ ...e, as_of: now.as_of, data_source: 'SEC EDGAR', served_by: 'POPS4 Filing Boards, CC BY 4.0' }, 'filing_event'))) break; }
100 await Actor.setValue('LAST_CURSOR', { cursor: now.as_of ?? '', hint: 'Pass as since_cursor on the next run to receive only newer events.' });
101}
102if (mode === 'company_financials') await state.setValue('LAST_FILING_BY_TICKER', nextSeen);
103log.info(`Done: ${pushed} rows; new_only=${new_only}.`);
104await Actor.exit();