@v587d/capital-generation 2.31.3 → 2.31.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +46 -8
  3. package/automation/package.json +1 -1
  4. package/chart-ui/package.json +1 -1
  5. package/config/package.json +1 -1
  6. package/lib/analysis/registry.js +6 -1
  7. package/lib/collector-runtime.js +8 -0
  8. package/lib/data-collector/catalog-taxonomy.js +11 -0
  9. package/lib/sources/eastmoney-http.js +274 -0
  10. package/lib/sources/sec-http.d.ts +9 -0
  11. package/lib/sources/sec-http.js +643 -0
  12. package/lib/sources/us-official-http.d.ts +4 -0
  13. package/lib/sources/us-official-http.js +654 -0
  14. package/lib/time/tools.js +6 -0
  15. package/lib/web-retriever/local-fetch.d.ts +1 -1
  16. package/lib/web-retriever/local-fetch.js +1 -1
  17. package/lib/web-retriever/wind-client.d.ts +1 -1
  18. package/lib/web-retriever/wind-client.js +1 -1
  19. package/package.json +1 -1
  20. package/plugin-page/README.en.md +7 -0
  21. package/plugin-page/README.zh.md +7 -0
  22. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +47 -37
  23. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +4 -2
  24. package/python/analysis/modules/comps_valuation/LICENSE +21 -0
  25. package/python/analysis/modules/comps_valuation/module.json +61 -0
  26. package/python/analysis/modules/comps_valuation/module.py +360 -0
  27. package/python/analysis/modules/earnings_bridge/LICENSE +21 -0
  28. package/python/analysis/modules/earnings_bridge/module.json +58 -0
  29. package/python/analysis/modules/earnings_bridge/module.py +452 -0
  30. package/python/analysis/modules/kline_quality/LICENSE +21 -0
  31. package/python/analysis/modules/kline_quality/module.json +61 -0
  32. package/python/analysis/modules/kline_quality/module.py +538 -0
  33. package/python/analysis/modules/portfolio_stress/LICENSE +21 -0
  34. package/python/analysis/modules/portfolio_stress/module.json +89 -0
  35. package/python/analysis/modules/portfolio_stress/module.py +537 -0
  36. package/python/analysis/modules/simple_backtest/LICENSE +21 -0
  37. package/python/analysis/modules/simple_backtest/module.json +66 -0
  38. package/python/analysis/modules/simple_backtest/module.py +648 -0
  39. package/python/analysis/modules/statement_integrity/LICENSE +21 -0
  40. package/python/analysis/modules/statement_integrity/module.json +62 -0
  41. package/python/analysis/modules/statement_integrity/module.py +621 -0
  42. package/python/analysis/modules/technical_indicators/LICENSE +21 -0
  43. package/python/analysis/modules/technical_indicators/module.json +170 -0
  44. package/python/analysis/modules/technical_indicators/module.py +854 -0
  45. package/python/analysis/modules/valuation_sensitivity/LICENSE +21 -0
  46. package/python/analysis/modules/valuation_sensitivity/module.json +73 -0
  47. package/python/analysis/modules/valuation_sensitivity/module.py +589 -0
  48. package/watchlist/package.json +1 -1
@@ -0,0 +1,654 @@
1
+ /** US official data sources (Treasury, NY Fed): zero-key public endpoints, one throttle per host,
2
+ * rows are plain arrays (no upstream pagination). SEC (same file family) is added separately. */
3
+ import { buildDataKey } from '../data-collector/hub.js';
4
+ import { getDataTimeContract } from '../time/tools.js';
5
+ import { createRequestThrottle } from '../net/throttle.js';
6
+ import { createSecSources } from './sec-http.js';
7
+ const TREASURY_CSV_URL = 'https://home.treasury.gov/resource-center/data-chart-center/interest-rates/daily-treasury-rates.csv';
8
+ const NYFED_RATES_URL = 'https://markets.newyorkfed.org/api/rates';
9
+ /** SEC's fair-access policy asks for a declarative UA with contact; env override lets the user supply their own. */
10
+ const DEFAULT_USER_AGENT = 'capital-generation (+https://github.com/v587d/capital-generation)';
11
+ function userAgent() {
12
+ const env = globalThis.process?.env;
13
+ const override = env?.SEC_USER_AGENT?.trim();
14
+ return override !== undefined && override.length > 0 ? override : DEFAULT_USER_AGENT;
15
+ }
16
+ const nyfedThrottle = createRequestThrottle(1000);
17
+ /** Treasury year files are serial-slow (~19s TTFB from this egress), so years are fetched with
18
+ * staggered starts instead of a serial throttle; five files finish in ~22s, one file in ~19s. */
19
+ const TREASURY_STAGGER_MS = 800;
20
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
+ const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
22
+ function isRecord(value) {
23
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
24
+ }
25
+ function sourceError(message, code = 'us_official_invalid_response') {
26
+ const error = new Error(message);
27
+ error.code = code;
28
+ return error;
29
+ }
30
+ function assertKnown(params, allowed) {
31
+ for (const key of Object.keys(params)) {
32
+ if (!allowed.includes(key))
33
+ throw new Error(`unsupported parameter: ${key} (allowed: ${allowed.join(', ')})`);
34
+ }
35
+ }
36
+ function calendarDate(value, name) {
37
+ if (typeof value !== 'string' || !DATE_PATTERN.test(value.trim()))
38
+ throw new Error(`parameter ${name} must be a valid YYYY-MM-DD date`);
39
+ const text = value.trim();
40
+ const parsed = new Date(`${text}T00:00:00Z`);
41
+ if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text)
42
+ throw new Error(`parameter ${name} must be a valid YYYY-MM-DD date`);
43
+ return text;
44
+ }
45
+ function numberOrNull(value) {
46
+ if (value === undefined || value === null || value === '')
47
+ return null;
48
+ const parsed = typeof value === 'number' ? value : Number(String(value).replaceAll(',', '').trim());
49
+ return Number.isFinite(parsed) ? parsed : null;
50
+ }
51
+ function textOrNull(value) {
52
+ const text = typeof value === 'string' ? value.trim() : '';
53
+ return text.length === 0 ? null : text;
54
+ }
55
+ async function fetchText(url, signal, label) {
56
+ signal.throwIfAborted();
57
+ let response;
58
+ try {
59
+ response = await fetch(url, { headers: { 'User-Agent': userAgent(), Accept: '*/*', 'Accept-Encoding': 'gzip, deflate' }, signal });
60
+ }
61
+ catch (error) {
62
+ if (error instanceof Error && error.name === 'AbortError')
63
+ throw error;
64
+ throw sourceError(`${label} request failed: ${error instanceof Error ? error.message : String(error)}`, 'us_official_http_error');
65
+ }
66
+ if (!response.ok)
67
+ throw sourceError(`${label} returned HTTP ${response.status}`, response.status === 403 ? 'us_official_forbidden' : 'us_official_http_error');
68
+ return response.text();
69
+ }
70
+ async function requestText(throttle, url, signal, label) {
71
+ signal.throwIfAborted();
72
+ return throttle(() => fetchText(url, signal, label));
73
+ }
74
+ function normalizeDateRange(params) {
75
+ assertKnown(params, ['start_date', 'end_date']);
76
+ const start_date = calendarDate(params.start_date, 'start_date');
77
+ const end_date = calendarDate(params.end_date, 'end_date');
78
+ if (start_date > end_date)
79
+ throw new Error('start_date must not be later than end_date');
80
+ return { start_date, end_date };
81
+ }
82
+ function createSource(options) {
83
+ const schema = {
84
+ capability: options.capability,
85
+ time_contract: getDataTimeContract(options.capability),
86
+ name: options.name,
87
+ source: `http:us-official.${options.capability}`,
88
+ data_key: buildDataKey('us_official', 'http', options.capability),
89
+ source_label: 'us_official',
90
+ paginated: false,
91
+ cacheMaxAgeMs: options.cacheMaxAgeMs,
92
+ rowShape: { rootArray: true },
93
+ summary: options.summary,
94
+ description: options.description,
95
+ input_schema: options.inputSchema,
96
+ output_schema: options.outputSchema,
97
+ };
98
+ return {
99
+ schema,
100
+ normalizeParams: (params) => options.normalize(params),
101
+ validateOutput: options.validateOutput,
102
+ execute: async (request, signal) => options.execute(options.normalize(request.params), signal),
103
+ };
104
+ }
105
+ const dateRangeInput = {
106
+ type: 'object',
107
+ properties: {
108
+ start_date: { type: 'string', description: '起始日 YYYY-MM-DD(含端点)' },
109
+ end_date: { type: 'string', description: '截止日 YYYY-MM-DD(含端点)' },
110
+ },
111
+ required: ['start_date', 'end_date'],
112
+ additionalProperties: false,
113
+ };
114
+ // ── US Treasury yield curve ──────────────────────────────────────────────────
115
+ /** Header names as published; older year files lack `1.5 Month` / `4 Mo`, so missing columns are null. */
116
+ const TREASURY_TENORS = {
117
+ '1 Mo': 'd1m',
118
+ '1.5 Month': 'd1_5m',
119
+ '2 Mo': 'd2m',
120
+ '3 Mo': 'd3m',
121
+ '4 Mo': 'd4m',
122
+ '6 Mo': 'd6m',
123
+ '1 Yr': 'd1y',
124
+ '2 Yr': 'd2y',
125
+ '3 Yr': 'd3y',
126
+ '5 Yr': 'd5y',
127
+ '7 Yr': 'd7y',
128
+ '10 Yr': 'd10y',
129
+ '20 Yr': 'd20y',
130
+ '30 Yr': 'd30y',
131
+ };
132
+ const TREASURY_ROW_FIELDS = Object.values(TREASURY_TENORS);
133
+ /** 5 year files = 5 requests; a 10-year window would double the serial latency for little gain. */
134
+ const TREASURY_MAX_DAYS = 1830;
135
+ const nullableNumber = { oneOf: [{ type: 'number' }, { type: 'null' }] };
136
+ const nullableString = { oneOf: [{ type: 'string' }, { type: 'null' }] };
137
+ const treasuryRow = {
138
+ type: 'object',
139
+ properties: {
140
+ date: { type: 'string' },
141
+ ...Object.fromEntries(TREASURY_ROW_FIELDS.map((field) => [field, nullableNumber])),
142
+ },
143
+ required: ['date'],
144
+ additionalProperties: false,
145
+ };
146
+ function parseTreasuryCsv(csv, label) {
147
+ const lines = csv.split(/\r?\n/).filter((line) => line.trim().length > 0);
148
+ if (lines.length === 0)
149
+ return [];
150
+ const header = lines[0].split(',').map((cell) => cell.replace(/^"|"$/g, '').trim());
151
+ if (header[0] !== 'Date')
152
+ throw sourceError(`${label} header changed: first column is ${JSON.stringify(header[0])}`);
153
+ const columns = header.map((name) => TREASURY_TENORS[name] ?? null);
154
+ if (columns.every((column) => column === null))
155
+ throw sourceError(`${label} header has no known tenor column`);
156
+ const rows = [];
157
+ for (const line of lines.slice(1)) {
158
+ const cells = line.split(',').map((cell) => cell.replace(/^"|"$/g, '').trim());
159
+ if (cells.length !== header.length)
160
+ throw sourceError(`${label} row has ${cells.length} cells for ${header.length} columns`);
161
+ const match = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(cells[0]);
162
+ if (match === null)
163
+ throw sourceError(`${label} date is not M/D/YYYY: ${JSON.stringify(cells[0])}`);
164
+ const date = `${match[3]}-${match[1].padStart(2, '0')}-${match[2].padStart(2, '0')}`;
165
+ const row = { date };
166
+ for (const field of TREASURY_ROW_FIELDS)
167
+ row[field] = null;
168
+ columns.forEach((field, index) => {
169
+ if (field !== null)
170
+ row[field] = numberOrNull(cells[index]);
171
+ });
172
+ rows.push(row);
173
+ }
174
+ return rows;
175
+ }
176
+ async function executeTreasury(params, signal) {
177
+ const startDate = String(params.start_date);
178
+ const endDate = String(params.end_date);
179
+ const startYear = Number(startDate.slice(0, 4));
180
+ const endYear = Number(endDate.slice(0, 4));
181
+ const years = [];
182
+ for (let year = startYear; year <= endYear; year += 1)
183
+ years.push(year);
184
+ const csvs = await Promise.all(years.map(async (year, index) => {
185
+ if (index > 0)
186
+ await sleep(index * TREASURY_STAGGER_MS);
187
+ const url = `${TREASURY_CSV_URL}/${year}/all?type=daily_treasury_yield_curve&field_tdr_date_value=${year}&page&_format=csv`;
188
+ return fetchText(url, signal, `Treasury ${year} yield curve`);
189
+ }));
190
+ const rows = [];
191
+ csvs.forEach((csv, index) => {
192
+ const year = years[index];
193
+ for (const row of parseTreasuryCsv(csv, `Treasury ${year} yield curve`)) {
194
+ if (String(row.date) < startDate || String(row.date) > endDate)
195
+ continue;
196
+ rows.push(row);
197
+ }
198
+ });
199
+ rows.sort((a, b) => String(a.date).localeCompare(String(b.date)));
200
+ for (let index = 1; index < rows.length; index += 1) {
201
+ if (rows[index - 1].date === rows[index].date)
202
+ throw sourceError(`Treasury yield curve returned duplicate date ${String(rows[index].date)}`);
203
+ }
204
+ return { data: rows, schema: treasuryRow };
205
+ }
206
+ // ── NY Fed reference rates ───────────────────────────────────────────────────
207
+ const NYFED_RATE_TYPES = {
208
+ sofr: 'secured',
209
+ tgcr: 'secured',
210
+ bgcr: 'secured',
211
+ effr: 'unsecured',
212
+ obfr: 'unsecured',
213
+ };
214
+ const NYFED_RATES = Object.keys(NYFED_RATE_TYPES);
215
+ const nyfedRow = {
216
+ type: 'object',
217
+ properties: {
218
+ effective_date: { type: 'string' },
219
+ rate_type: { type: 'string' },
220
+ percent_rate: nullableNumber,
221
+ percentile_1: nullableNumber,
222
+ percentile_25: nullableNumber,
223
+ percentile_75: nullableNumber,
224
+ percentile_99: nullableNumber,
225
+ target_rate_from: nullableNumber,
226
+ target_rate_to: nullableNumber,
227
+ volume_billions: nullableNumber,
228
+ revision_indicator: { oneOf: [{ type: 'string' }, { type: 'null' }] },
229
+ },
230
+ required: ['effective_date', 'rate_type'],
231
+ additionalProperties: false,
232
+ };
233
+ function normalizeNyfed(params) {
234
+ assertKnown(params, ['rate', 'start_date', 'end_date']);
235
+ const rate = String(params.rate ?? '').trim().toLowerCase();
236
+ if (!(rate in NYFED_RATE_TYPES))
237
+ throw new Error(`rate must be one of ${NYFED_RATES.join(', ')}`);
238
+ const range = normalizeDateRange({ start_date: params.start_date, end_date: params.end_date });
239
+ return { rate, ...range };
240
+ }
241
+ function parseNyfedRow(raw) {
242
+ const date = typeof raw.effectiveDate === 'string' ? raw.effectiveDate.trim() : '';
243
+ if (!DATE_PATTERN.test(date))
244
+ throw sourceError(`NY Fed effectiveDate is not YYYY-MM-DD: ${JSON.stringify(String(raw.effectiveDate ?? ''))}`);
245
+ const rateType = textOrNull(raw.type);
246
+ if (rateType === null)
247
+ throw sourceError('NY Fed row has no type');
248
+ return {
249
+ effective_date: date,
250
+ rate_type: rateType,
251
+ percent_rate: numberOrNull(raw.percentRate),
252
+ percentile_1: numberOrNull(raw.percentPercentile1),
253
+ percentile_25: numberOrNull(raw.percentPercentile25),
254
+ percentile_75: numberOrNull(raw.percentPercentile75),
255
+ percentile_99: numberOrNull(raw.percentPercentile99),
256
+ target_rate_from: numberOrNull(raw.targetRateFrom),
257
+ target_rate_to: numberOrNull(raw.targetRateTo),
258
+ volume_billions: numberOrNull(raw.volumeInBillions),
259
+ revision_indicator: textOrNull(raw.revisionIndicator),
260
+ };
261
+ }
262
+ async function executeNyfed(params, signal) {
263
+ const rate = String(params.rate);
264
+ const url = `${NYFED_RATES_URL}/${NYFED_RATE_TYPES[rate]}/${rate}/search.json?startDate=${String(params.start_date)}&endDate=${String(params.end_date)}`;
265
+ const text = await requestText(nyfedThrottle, url, signal, `NY Fed ${rate.toUpperCase()}`);
266
+ let payload;
267
+ try {
268
+ payload = JSON.parse(text);
269
+ }
270
+ catch {
271
+ throw sourceError(`NY Fed ${rate.toUpperCase()} returned non-JSON: ${JSON.stringify(text.slice(0, 120))}`);
272
+ }
273
+ if (!isRecord(payload) || !Array.isArray(payload.refRates))
274
+ throw sourceError(`NY Fed ${rate.toUpperCase()} response shape changed (refRates missing)`);
275
+ const rows = payload.refRates.map((raw) => {
276
+ if (!isRecord(raw))
277
+ throw sourceError(`NY Fed ${rate.toUpperCase()} returned a non-object row`);
278
+ return parseNyfedRow(raw);
279
+ });
280
+ rows.sort((a, b) => String(a.effective_date).localeCompare(String(b.effective_date)));
281
+ for (let index = 1; index < rows.length; index += 1) {
282
+ if (rows[index - 1].effective_date === rows[index].effective_date)
283
+ throw sourceError(`NY Fed ${rate.toUpperCase()} returned duplicate effectiveDate ${String(rows[index].effective_date)}`);
284
+ }
285
+ return { data: rows, schema: nyfedRow };
286
+ }
287
+ // ── FINRA short volume / short interest ──────────────────────────────────────
288
+ // FINRA is a self-regulatory organization, not a government agency: its terms carry a
289
+ // non-commercial caveat, so both capabilities are documented as research-grade sources.
290
+ const FINRA_SHORT_VOLUME_URL = 'https://cdn.finra.org/equity/regsho/daily/CNMSshvol';
291
+ const FINRA_SHORT_INTEREST_URL = 'https://api.finra.org/data/group/otcMarket/name/consolidatedShortInterest';
292
+ const finraThrottle = createRequestThrottle(500);
293
+ const FINRA_SHORT_VOLUME_HEADER = ['Date', 'Symbol', 'ShortVolume', 'ShortExemptVolume', 'TotalVolume', 'Market'];
294
+ function shiftDate(date, days) {
295
+ const parsed = new Date(`${date}T00:00:00Z`);
296
+ parsed.setUTCDate(parsed.getUTCDate() + days);
297
+ return parsed.toISOString().slice(0, 10);
298
+ }
299
+ function isWeekend(date) {
300
+ const day = new Date(`${date}T00:00:00Z`).getUTCDay();
301
+ return day === 0 || day === 6;
302
+ }
303
+ function previousWeekday(date) {
304
+ let cursor = date;
305
+ for (let index = 0; index < 7; index += 1) {
306
+ cursor = shiftDate(cursor, -1);
307
+ if (!isWeekend(cursor))
308
+ return cursor;
309
+ }
310
+ return cursor;
311
+ }
312
+ function lastBusinessDayOfMonth(year, month) {
313
+ const cursor = new Date(Date.UTC(year, month, 0));
314
+ while (cursor.getUTCDay() === 0 || cursor.getUTCDay() === 6)
315
+ cursor.setUTCDate(cursor.getUTCDate() - 1);
316
+ return cursor.toISOString().slice(0, 10);
317
+ }
318
+ /** Current calendar date in US/Eastern: FINRA files are keyed by the ET business day. */
319
+ function etToday() {
320
+ const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date());
321
+ const pick = (type) => parts.find((part) => part.type === type)?.value ?? '';
322
+ return `${pick('year')}-${pick('month')}-${pick('day')}`;
323
+ }
324
+ async function finraText(url, signal, label, allowMissing) {
325
+ signal.throwIfAborted();
326
+ return finraThrottle(async () => {
327
+ let response;
328
+ try {
329
+ response = await fetch(url, { headers: { 'User-Agent': userAgent(), Accept: '*/*' }, signal });
330
+ }
331
+ catch (error) {
332
+ if (error instanceof Error && error.name === 'AbortError')
333
+ throw error;
334
+ throw sourceError(`${label} request failed: ${error instanceof Error ? error.message : String(error)}`, 'finra_http_error');
335
+ }
336
+ if (allowMissing && (response.status === 403 || response.status === 404))
337
+ return null;
338
+ if (!response.ok)
339
+ throw sourceError(`${label} returned HTTP ${response.status}`, 'finra_http_error');
340
+ return response.text();
341
+ });
342
+ }
343
+ async function finraPost(body, signal, label) {
344
+ signal.throwIfAborted();
345
+ return finraThrottle(async () => {
346
+ let response;
347
+ try {
348
+ response = await fetch(FINRA_SHORT_INTEREST_URL, {
349
+ method: 'POST',
350
+ headers: { 'User-Agent': userAgent(), 'Content-Type': 'application/json', Accept: 'application/json' },
351
+ body: JSON.stringify(body),
352
+ signal,
353
+ });
354
+ }
355
+ catch (error) {
356
+ if (error instanceof Error && error.name === 'AbortError')
357
+ throw error;
358
+ throw sourceError(`${label} request failed: ${error instanceof Error ? error.message : String(error)}`, 'finra_http_error');
359
+ }
360
+ // 204 = this settlement date has no rows for the filter; a legitimate empty, not a failure.
361
+ if (response.status === 204)
362
+ return [];
363
+ if (!response.ok)
364
+ throw sourceError(`${label} returned HTTP ${response.status}`, 'finra_http_error');
365
+ const text = await response.text();
366
+ let payload;
367
+ try {
368
+ payload = JSON.parse(text);
369
+ }
370
+ catch {
371
+ throw sourceError(`${label} returned non-JSON: ${JSON.stringify(text.slice(0, 120))}`);
372
+ }
373
+ if (!Array.isArray(payload))
374
+ throw sourceError(`${label} response is not an array`);
375
+ return payload;
376
+ });
377
+ }
378
+ const finraShortVolumeRow = {
379
+ type: 'object',
380
+ properties: {
381
+ trade_date: { type: 'string' },
382
+ symbol: { type: 'string' },
383
+ short_volume: { type: 'number' },
384
+ short_exempt_volume: { type: 'number' },
385
+ total_volume: { type: 'number' },
386
+ market: { type: 'string' },
387
+ },
388
+ required: ['trade_date', 'symbol', 'short_volume', 'short_exempt_volume', 'total_volume', 'market'],
389
+ additionalProperties: false,
390
+ };
391
+ function normalizeFinraSymbols(value, max) {
392
+ if (!Array.isArray(value) || value.length === 0)
393
+ throw new Error('symbols must be a non-empty array');
394
+ if (value.length > max)
395
+ throw new Error(`symbols exceeds maximum ${max}`);
396
+ return [...new Set(value.map((item) => {
397
+ if (typeof item !== 'string')
398
+ throw new Error('symbols[] must be a string');
399
+ const symbol = item.trim().toUpperCase();
400
+ if (!/^[A-Z][A-Z0-9.\-]{0,9}$/.test(symbol))
401
+ throw new Error(`symbols[] must be a US ticker, got ${JSON.stringify(item)}`);
402
+ return symbol;
403
+ }))];
404
+ }
405
+ function normalizeShortVolume(params) {
406
+ assertKnown(params, ['trade_date', 'symbols']);
407
+ const trade_date = params.trade_date === undefined ? undefined : calendarDate(params.trade_date, 'trade_date');
408
+ const symbols = params.symbols === undefined ? undefined : normalizeFinraSymbols(params.symbols, 50);
409
+ return { ...(trade_date === undefined ? {} : { trade_date }), ...(symbols === undefined ? {} : { symbols }) };
410
+ }
411
+ function parseShortVolume(text, label) {
412
+ const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
413
+ if (lines.length === 0)
414
+ return [];
415
+ const header = lines[0].split('|').map((cell) => cell.trim());
416
+ if (header.join('|') !== FINRA_SHORT_VOLUME_HEADER.join('|'))
417
+ throw sourceError(`${label} header changed: ${lines[0]}`);
418
+ // The file ends with a bare row count (measured 2026-11-25: trailer "12376" for 12,376 data rows).
419
+ let body = lines.slice(1);
420
+ let declaredRows = null;
421
+ const trailer = body.at(-1)?.trim();
422
+ if (trailer !== undefined && /^\d+$/.test(trailer)) {
423
+ declaredRows = Number(trailer);
424
+ body = body.slice(0, -1);
425
+ }
426
+ const rows = [];
427
+ for (const line of body) {
428
+ const cells = line.split('|').map((cell) => cell.trim());
429
+ if (cells.length !== 6)
430
+ throw sourceError(`${label} row has ${cells.length} cells: ${line.slice(0, 120)}`);
431
+ if (!/^\d{8}$/.test(cells[0]))
432
+ throw sourceError(`${label} date is not YYYYMMDD: ${JSON.stringify(cells[0])}`);
433
+ const tradeDate = `${cells[0].slice(0, 4)}-${cells[0].slice(4, 6)}-${cells[0].slice(6, 8)}`;
434
+ const numbers = cells.slice(2, 5).map((cell) => Number(cell));
435
+ if (numbers.some((value) => !Number.isFinite(value) || value < 0))
436
+ throw sourceError(`${label} has a non-numeric volume: ${line.slice(0, 120)}`);
437
+ rows.push({ trade_date: tradeDate, symbol: cells[1], short_volume: numbers[0], short_exempt_volume: numbers[1], total_volume: numbers[2], market: cells[5] });
438
+ }
439
+ if (declaredRows !== null && declaredRows !== rows.length)
440
+ throw sourceError(`${label} trailer declares ${declaredRows} rows but ${rows.length} parsed`);
441
+ return rows;
442
+ }
443
+ async function executeShortVolume(params, signal) {
444
+ const explicit = params.trade_date === undefined ? undefined : String(params.trade_date);
445
+ const wanted = params.symbols === undefined ? undefined : new Set(params.symbols);
446
+ let tradeDate = explicit;
447
+ let text = null;
448
+ if (tradeDate !== undefined) {
449
+ text = await finraText(`${FINRA_SHORT_VOLUME_URL}${tradeDate.replaceAll('-', '')}.txt`, signal, `FINRA short volume ${tradeDate}`, true);
450
+ if (text === null)
451
+ throw sourceError(`FINRA short volume has no file for ${tradeDate}: not a business day or not published yet`, 'finra_not_published');
452
+ }
453
+ else {
454
+ // Walk back from the current ET date; the file appears after the close, so "today" may 403.
455
+ let cursor = etToday();
456
+ for (let index = 0; index < 10 && text === null; index += 1) {
457
+ cursor = shiftDate(cursor, index === 0 ? 0 : -1);
458
+ if (isWeekend(cursor))
459
+ continue;
460
+ const candidate = await finraText(`${FINRA_SHORT_VOLUME_URL}${cursor.replaceAll('-', '')}.txt`, signal, `FINRA short volume ${cursor}`, true);
461
+ if (candidate !== null) {
462
+ tradeDate = cursor;
463
+ text = candidate;
464
+ }
465
+ }
466
+ if (text === null || tradeDate === undefined)
467
+ throw sourceError('FINRA short volume has no published file in the last 10 calendar days', 'finra_not_published');
468
+ }
469
+ const rows = parseShortVolume(text, `FINRA short volume ${tradeDate}`)
470
+ .filter((row) => wanted === undefined || wanted.has(String(row.symbol)));
471
+ return { data: rows, schema: finraShortVolumeRow };
472
+ }
473
+ const finraShortInterestRow = {
474
+ type: 'object',
475
+ properties: {
476
+ symbol: { type: 'string' },
477
+ issue_name: nullableString,
478
+ settlement_date: { type: 'string' },
479
+ current_short_position: nullableNumber,
480
+ previous_short_position: nullableNumber,
481
+ change_previous: nullableNumber,
482
+ change_percent: nullableNumber,
483
+ average_daily_volume: nullableNumber,
484
+ days_to_cover: nullableNumber,
485
+ market_class_code: nullableString,
486
+ exchange_code: nullableString,
487
+ stock_split_flag: nullableString,
488
+ revision_flag: nullableString,
489
+ accounting_year_month: nullableNumber,
490
+ },
491
+ required: ['symbol', 'settlement_date'],
492
+ additionalProperties: false,
493
+ };
494
+ function normalizeShortInterest(params) {
495
+ assertKnown(params, ['symbols', 'settlement_date']);
496
+ const symbols = normalizeFinraSymbols(params.symbols, 10);
497
+ const settlement_date = params.settlement_date === undefined ? undefined : calendarDate(params.settlement_date, 'settlement_date');
498
+ return { symbols, ...(settlement_date === undefined ? {} : { settlement_date }) };
499
+ }
500
+ /** FINRA settles on the 15th and the last business day of each month; probe newest first. */
501
+ function settlementCandidates() {
502
+ const today = etToday();
503
+ const [year, month] = today.split('-').map(Number);
504
+ const candidates = [];
505
+ for (let back = 0; back < 3; back += 1) {
506
+ const cursor = new Date(Date.UTC(year, month - 1 - back, 1));
507
+ const candidateYear = cursor.getUTCFullYear();
508
+ const candidateMonth = cursor.getUTCMonth() + 1;
509
+ const fifteenth = `${candidateYear}-${String(candidateMonth).padStart(2, '0')}-15`;
510
+ candidates.push(isWeekend(fifteenth) ? previousWeekday(fifteenth) : fifteenth);
511
+ candidates.push(lastBusinessDayOfMonth(candidateYear, candidateMonth));
512
+ }
513
+ return [...new Set(candidates)].filter((date) => date <= today).sort().reverse();
514
+ }
515
+ function parseShortInterestRow(raw, expectedDate, label) {
516
+ const settlement = textOrNull(raw.settlementDate);
517
+ if (settlement !== expectedDate)
518
+ throw sourceError(`${label} returned settlementDate ${String(settlement)} for ${expectedDate}`);
519
+ const symbol = textOrNull(raw.symbolCode);
520
+ if (symbol === null)
521
+ throw sourceError(`${label} row has no symbolCode`);
522
+ return {
523
+ symbol,
524
+ issue_name: textOrNull(raw.issueName),
525
+ settlement_date: settlement,
526
+ current_short_position: numberOrNull(raw.currentShortPositionQuantity),
527
+ previous_short_position: numberOrNull(raw.previousShortPositionQuantity),
528
+ change_previous: numberOrNull(raw.changePreviousNumber),
529
+ change_percent: numberOrNull(raw.changePercent),
530
+ average_daily_volume: numberOrNull(raw.averageDailyVolumeQuantity),
531
+ days_to_cover: numberOrNull(raw.daysToCoverQuantity),
532
+ market_class_code: textOrNull(raw.marketClassCode),
533
+ exchange_code: textOrNull(raw.issuerServicesGroupExchangeCode),
534
+ stock_split_flag: textOrNull(raw.stockSplitFlag),
535
+ revision_flag: textOrNull(raw.revisionFlag),
536
+ accounting_year_month: numberOrNull(raw.accountingYearMonthNumber),
537
+ };
538
+ }
539
+ async function fetchShortInterest(symbol, settlementDate, signal) {
540
+ const rows = await finraPost({
541
+ limit: 1,
542
+ compareFilters: [
543
+ { compareType: 'EQUAL', fieldName: 'settlementDate', fieldValue: settlementDate },
544
+ { compareType: 'EQUAL', fieldName: 'symbolCode', fieldValue: symbol },
545
+ ],
546
+ }, signal, `FINRA short interest ${symbol} ${settlementDate}`);
547
+ return rows.map((raw) => {
548
+ if (!isRecord(raw))
549
+ throw sourceError('FINRA short interest row is not an object');
550
+ return parseShortInterestRow(raw, settlementDate, `FINRA short interest ${symbol}`);
551
+ });
552
+ }
553
+ async function executeShortInterest(params, signal) {
554
+ const symbols = params.symbols;
555
+ let settlementDate = params.settlement_date === undefined ? undefined : String(params.settlement_date);
556
+ if (settlementDate === undefined) {
557
+ for (const candidate of settlementCandidates()) {
558
+ const probe = await fetchShortInterest(symbols[0], candidate, signal);
559
+ if (probe.length > 0) {
560
+ settlementDate = candidate;
561
+ break;
562
+ }
563
+ }
564
+ if (settlementDate === undefined)
565
+ throw sourceError('FINRA short interest has no published settlement date in the last 3 months', 'finra_not_published');
566
+ }
567
+ const rows = [];
568
+ for (const symbol of symbols) {
569
+ rows.push(...await fetchShortInterest(symbol, settlementDate, signal));
570
+ }
571
+ return { data: rows, schema: finraShortInterestRow };
572
+ }
573
+ export function createUsOfficialSources() {
574
+ return [
575
+ createSource({
576
+ capability: 'us_treasury_yield_curve',
577
+ cacheMaxAgeMs: 3_600_000,
578
+ name: 'get_us_treasury_yield_curve',
579
+ summary: '美债收益率曲线(按年文件拼接,日频)',
580
+ description: '获取美国财政部每日国债收益率曲线(home.treasury.gov daily_treasury_yield_curve,零 key、官方 CSV)。⛔ **按年文件拼接**:URL 的年份段与 `field_tdr_date_value` 都是年份,本层按区间跨年逐文件下载后本地裁剪,不是只取当前年(实测 2019 年文件没有 `1.5 Month` / `4 Mo` 两列,列集随年份变化,缺列的行该字段为 null——⛔ 不要按固定列数解析)。区间上限 1830 天(5 个年文件;本机实测单文件 TTFB 约 19s,所以跨年按 800ms 错开并发拉取,5 个文件约 22s 完成——⛔ 不要改回串行,会撞 30s Hub 超时)。未来年份的文件实测是 HTTP 200 + 空 body(不是 404),该年按空处理。一行一个业务日,`date` 是**美东业务日**(不是北京时间;节假日没有行),收益率单位是**百分数原值**(4.27 读作 4.27%),不是比例。列映射按表头显式转成 ASCII:`1 Mo→d1m`、`1.5 Month→d1_5m`、`2 Mo→d2m`、`3 Mo→d3m`、`4 Mo→d4m`、`6 Mo→d6m`、`1 Yr→d1y`、`2 Yr→d2y`、`3 Yr→d3y`、`5 Yr→d5y`、`7 Yr→d7y`、`10 Yr→d10y`、`20 Yr→d20y`、`30 Yr→d30y`;未在映射表里的表头列**丢弃**,表头首列必须是 Date,行宽与表头不一致、日期不是 M/D/YYYY、同日重复都响亮失败。CSV 实测倒序(新→旧),本层输出按 date 升序。空区间(如只有周末)返回成功空数组,不是失败。更新时点:每个业务日约 15:30 ET 后发布当日曲线(本轮未复测)。',
581
+ inputSchema: dateRangeInput,
582
+ outputSchema: { type: 'array', items: treasuryRow },
583
+ allowed: ['start_date', 'end_date'],
584
+ normalize: normalizeDateRange,
585
+ validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.date === 'string'),
586
+ execute: executeTreasury,
587
+ }),
588
+ createSource({
589
+ capability: 'nyfed_reference_rates',
590
+ cacheMaxAgeMs: 3_600_000,
591
+ name: 'get_nyfed_reference_rates',
592
+ summary: '纽约联储基准利率(SOFR/EFFR 等,日频)',
593
+ description: '获取纽约联储公布的美元基准利率(markets.newyorkfed.org,零 key、官方 JSON):`rate` 取 `sofr`/`tgcr`/`bgcr`(secured)或 `effr`/`obfr`(unsecured),走 `search.json?startDate&endDate` 区间查询。一行一个业务日;`effective_date` 是**美东业务日**(周末与假日没有行,空区间返回成功空数组)。⛔ 单位是**百分数原值**(3.94 读作 3.94%),`percent_rate` 与四个分位数字段都是百分数原值,`volume_billions` 单位是**十亿美元**(3158 = 3.158 万亿),不要按美元解读。`target_rate_from`/`target_rate_to` 只有 EFFR 有(目标区间),其余为 null。字段映射:effectiveDate→effective_date、type→rate_type(如 SOFR)、percentRate→percent_rate、percentPercentile1/25/75/99→percentile_1/25/75/99、targetRateFrom/To→target_rate_from/to、volumeInBillions→volume_billions、revisionIndicator→revision_indicator(空串→null)。⛔ 该接口按利率分别返回,不同利率的 `type` 不同;不要用 SOFR 的日期范围去推断 EFFR 是否发布。上游 `refRates` 缺失、行不是对象、effectiveDate 非 YYYY-MM-DD、同日重复都响亮失败;`refRates: []` 是合法空。本层输出按 effective_date 升序(上游实测倒序)。SOFR 自 2018-04-02 起,EFFR/OBFR/BGCR/TGCR 各自起点不同,更早日期为空是数据边界不是故障。对外展示需按纽约联储要求标注来源与取数日期。',
594
+ inputSchema: {
595
+ type: 'object',
596
+ properties: {
597
+ rate: { type: 'string', enum: NYFED_RATES, description: '利率:sofr/tgcr/bgcr/effr/obfr' },
598
+ start_date: { type: 'string', description: '起始日 YYYY-MM-DD(美东业务日,含端点)' },
599
+ end_date: { type: 'string', description: '截止日 YYYY-MM-DD(美东业务日,含端点)' },
600
+ },
601
+ required: ['rate', 'start_date', 'end_date'],
602
+ additionalProperties: false,
603
+ },
604
+ outputSchema: { type: 'array', items: nyfedRow },
605
+ allowed: ['rate', 'start_date', 'end_date'],
606
+ normalize: normalizeNyfed,
607
+ validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.effective_date === 'string'),
608
+ execute: executeNyfed,
609
+ }),
610
+ createSource({
611
+ capability: 'finra_short_volume',
612
+ cacheMaxAgeMs: 3_600_000,
613
+ name: 'get_finra_short_volume',
614
+ summary: 'FINRA 做空成交量(日频,全市场文件)',
615
+ description: '获取 FINRA 每日做空成交量(Reg SHO 日文件:`cdn.finra.org/equity/regsho/daily/CNMSshvol{YYYYMMDD}.txt`,零 key,Consolidated NMS 口径)。⛔ 上游是**整份全市场文件**(实测 2026-11-25:12,378 行 / 552KB),本层下载后在本地按 `symbols` 过滤,不改变上游事实;不传 `symbols` 就是全市场(行数大,慎用)。⛔ **成交量是小数**:实测 `AAPL` 为 short 9,758,284.19 / total 16,888,251.03,不要当整数股数四舍五入;单位是股。`market` 是交易所集合(实测 `B,Q,N`),不是单一市场。`trade_date` 是**美东业务日**:省略时从美东今天往回找最多 10 个自然日,取第一个已发布文件(收盘后才发布,所以当天常取到前一交易日);显式传日期但该日没有文件(周末/假日/尚未发布)时上游 403,本层**响亮失败**并说明,不返回空数组。文件表头固定为 `Date|Symbol|ShortVolume|ShortExemptVolume|TotalVolume|Market`,**末尾还有一行裸行数**(实测 2026-11-25 是 `12376`),本层把它当校验值:解析出的数据行数必须等于它,否则响亮失败;表头变化、行宽不是 6、日期不是 YYYYMMDD、数值非数字同样响亮失败。⛔ 来源条款含 non-commercial 限制,按研究口径使用,不宣称可商用;展示时标注 FINRA Reg SHO。',
616
+ inputSchema: {
617
+ type: 'object',
618
+ properties: {
619
+ trade_date: { type: 'string', description: '美东业务日 YYYY-MM-DD;省略则自动取最近已发布日' },
620
+ symbols: { type: 'array', items: { type: 'string' }, description: '可选:只保留这些美股代码(1–50 个)' },
621
+ },
622
+ required: [],
623
+ additionalProperties: false,
624
+ },
625
+ outputSchema: { type: 'array', items: finraShortVolumeRow },
626
+ allowed: ['trade_date', 'symbols'],
627
+ normalize: normalizeShortVolume,
628
+ validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.symbol === 'string' && typeof row.trade_date === 'string'),
629
+ execute: executeShortVolume,
630
+ }),
631
+ createSource({
632
+ capability: 'finra_short_interest',
633
+ cacheMaxAgeMs: 21_600_000,
634
+ name: 'get_finra_short_interest',
635
+ summary: 'FINRA 做空余额(双周,按结算日)',
636
+ description: '获取 FINRA 合并做空余额(consolidatedShortInterest,零 key,POST JSON)。`symbols` 必填 1–10 个;`settlement_date` 可选——**省略时自动发现最近已发布的结算日**(结算日是每月 15 日与月末,遇周末提前到前一个工作日;双周披露、约 8 个工作日滞后,本层从最近 3 个月候选日里由新到旧探测)。⛔ 上游 API **强制按 settlementDate 分区**:不给该日期做 EQUAL 过滤时排序会被拒绝(400),所以本层按「结算日 × 单票」逐次查询,不做全市场扫描。字段:current/previous_short_position(股)、change_previous(股)、change_percent(百分数原值)、average_daily_volume(股/日)、days_to_cover(日)、market_class_code、exchange_code、stock_split_flag、revision_flag、accounting_year_month(如 20261113)。⛔ 204 No Content = 该结算日没有该票记录(合法空),不是失败;某票在该结算日无记录时不返回该行。⛔ 结算日不是自然日期:**不要**用 `resolve_data_time_range` 生成它,省略参数让本能力自动发现。来源条款含 non-commercial 限制。',
637
+ inputSchema: {
638
+ type: 'object',
639
+ properties: {
640
+ symbols: { type: 'array', items: { type: 'string' }, description: '美股代码 1–10 个(如 AAPL)' },
641
+ settlement_date: { type: 'string', description: '结算日 YYYY-MM-DD(可选;省略自动取最近已发布结算日)' },
642
+ },
643
+ required: ['symbols'],
644
+ additionalProperties: false,
645
+ },
646
+ outputSchema: { type: 'array', items: finraShortInterestRow },
647
+ allowed: ['symbols', 'settlement_date'],
648
+ normalize: normalizeShortInterest,
649
+ validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.symbol === 'string' && typeof row.settlement_date === 'string'),
650
+ execute: executeShortInterest,
651
+ }),
652
+ ...createSecSources(),
653
+ ];
654
+ }