@v587d/capital-generation 2.28.0 → 2.30.0
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.
- package/CHANGELOG.md +59 -0
- package/README.md +5 -4
- package/THIRD_PARTY_NOTICES.md +16 -0
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/collector-runtime.js +56 -1
- package/lib/data-collector/catalog-taxonomy.d.ts +1 -1
- package/lib/data-collector/catalog-taxonomy.js +33 -0
- package/lib/data-collector/tools.js +7 -7
- package/lib/host-version.d.ts +9 -0
- package/lib/host-version.js +57 -0
- package/lib/python-runtime/errors.d.ts +1 -1
- package/lib/python-runtime/errors.js +2 -0
- package/lib/python-runtime/manager.d.ts +28 -1
- package/lib/python-runtime/manager.js +141 -5
- package/lib/python-runtime/probe.d.ts +24 -0
- package/lib/python-runtime/probe.js +66 -50
- package/lib/runtime-entry.js +8 -0
- package/lib/sources/csindex-http.d.ts +4 -0
- package/lib/sources/csindex-http.js +233 -0
- package/lib/sources/eastmoney-http.js +1504 -1
- package/lib/sources/fuyao-rest.js +168 -8
- package/lib/sources/official-http.d.ts +4 -0
- package/lib/sources/official-http.js +477 -0
- package/lib/sources/python-remote.d.ts +25 -0
- package/lib/sources/python-remote.js +461 -0
- package/lib/sources/sina-http.d.ts +2 -0
- package/lib/sources/sina-http.js +484 -0
- package/lib/sources/tencent-http.js +23 -8
- package/lib/sources/ths-http.d.ts +2 -0
- package/lib/sources/ths-http.js +514 -0
- package/lib/time/tools.js +19 -0
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/sources.d.ts +7 -0
- package/lib/web-retriever/sources.js +46 -21
- package/lib/web-retriever/throttle.d.ts +8 -0
- package/lib/web-retriever/throttle.js +13 -0
- package/lib/web-retriever/tools.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +6 -3
- package/preset/capital-generation/agent.patch.yml +7 -5
- package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +16 -16
- package/python/scripts/baostock_stock_basic.py +129 -0
- package/python/scripts/baostock_valuation_history.py +141 -0
- package/python/scripts/pbc_social_financing.py +291 -0
- package/python/vendor/baostock/LICENSE +19 -0
- package/python/vendor/baostock/__init__.py +42 -0
- package/python/vendor/baostock/common/__init__.py +0 -0
- package/python/vendor/baostock/common/contants.py +189 -0
- package/python/vendor/baostock/common/context.py +4 -0
- package/python/vendor/baostock/corpreport/__init__.py +0 -0
- package/python/vendor/baostock/corpreport/corp_performance.py +202 -0
- package/python/vendor/baostock/data/__init__.py +0 -0
- package/python/vendor/baostock/data/messageheader.py +17 -0
- package/python/vendor/baostock/data/msg.py +21 -0
- package/python/vendor/baostock/data/resultset.py +200 -0
- package/python/vendor/baostock/demo/__init__.py +0 -0
- package/python/vendor/baostock/demo/demo_A_stock_5mk-data.py +34 -0
- package/python/vendor/baostock/demo/demo_A_stock_k_data.py +36 -0
- package/python/vendor/baostock/demo/demo_AllStock.py +27 -0
- package/python/vendor/baostock/demo/demo_Balance_data.py +22 -0
- package/python/vendor/baostock/demo/demo_CashFlow_data.py +22 -0
- package/python/vendor/baostock/demo/demo_Dividend_data.py +35 -0
- package/python/vendor/baostock/demo/demo_Dupont_data.py +25 -0
- package/python/vendor/baostock/demo/demo_Forecast_report.py +24 -0
- package/python/vendor/baostock/demo/demo_Growth_data.py +22 -0
- package/python/vendor/baostock/demo/demo_Index_k_data.py +39 -0
- package/python/vendor/baostock/demo/demo_Operation_data.py +22 -0
- package/python/vendor/baostock/demo/demo_PerformanceExpress_report.py +25 -0
- package/python/vendor/baostock/demo/demo_Profit_data.py +22 -0
- package/python/vendor/baostock/demo/demo_TradeDates.py +27 -0
- package/python/vendor/baostock/demo/demo_adjust_factor_data.py +23 -0
- package/python/vendor/baostock/demo/demo_assignDayData.py +23 -0
- package/python/vendor/baostock/demo/demo_daily_adjust_factor_data.py +28 -0
- package/python/vendor/baostock/demo/demo_daily_k_4_AStock.py +28 -0
- package/python/vendor/baostock/demo/demo_daily_k_4_ETF.py +28 -0
- package/python/vendor/baostock/demo/demo_depositRate_data.py +26 -0
- package/python/vendor/baostock/demo/demo_hs300_stocks.py +26 -0
- package/python/vendor/baostock/demo/demo_loanRate_data.py +26 -0
- package/python/vendor/baostock/demo/demo_moneySupplyDataMonth_data.py +26 -0
- package/python/vendor/baostock/demo/demo_moneySupplyDataYear_data.py +26 -0
- package/python/vendor/baostock/demo/demo_requiredReserveRatio_data.py +26 -0
- package/python/vendor/baostock/demo/demo_set_API_key.py +37 -0
- package/python/vendor/baostock/demo/demo_stockBasic_data.py +27 -0
- package/python/vendor/baostock/demo/demo_stock_Valuation_indicator_data.py +34 -0
- package/python/vendor/baostock/demo/demo_stock_industry.py +26 -0
- package/python/vendor/baostock/demo/demo_sz50stocks.py +26 -0
- package/python/vendor/baostock/demo/demo_zz500_stock.py +26 -0
- package/python/vendor/baostock/evaluation/__init__.py +0 -0
- package/python/vendor/baostock/evaluation/season_index.py +758 -0
- package/python/vendor/baostock/login/__init__.py +0 -0
- package/python/vendor/baostock/login/loginout.py +230 -0
- package/python/vendor/baostock/macroscopic/__init__.py +0 -0
- package/python/vendor/baostock/macroscopic/economic_data.py +723 -0
- package/python/vendor/baostock/metadata/__init__.py +0 -0
- package/python/vendor/baostock/metadata/stock_metadata.py +207 -0
- package/python/vendor/baostock/security/__init__.py +0 -0
- package/python/vendor/baostock/security/history.py +265 -0
- package/python/vendor/baostock/security/sectorinfo.py +1024 -0
- package/python/vendor/baostock/util/__init__.py +0 -0
- package/python/vendor/baostock/util/socketutil.py +97 -0
- package/python/vendor/baostock/util/stringutil.py +83 -0
- package/python/vendor/et_xmlfile/LICENSE +23 -0
- package/python/vendor/et_xmlfile/LICENSE.python +298 -0
- package/python/vendor/et_xmlfile/__init__.py +8 -0
- package/python/vendor/et_xmlfile/incremental_tree.py +917 -0
- package/python/vendor/et_xmlfile/xmlfile.py +158 -0
- package/python/vendor/openpyxl/LICENSE +23 -0
- package/python/vendor/openpyxl/__init__.py +19 -0
- package/python/vendor/openpyxl/_constants.py +13 -0
- package/python/vendor/openpyxl/cell/__init__.py +4 -0
- package/python/vendor/openpyxl/cell/_writer.py +136 -0
- package/python/vendor/openpyxl/cell/cell.py +332 -0
- package/python/vendor/openpyxl/cell/read_only.py +136 -0
- package/python/vendor/openpyxl/cell/rich_text.py +202 -0
- package/python/vendor/openpyxl/cell/text.py +184 -0
- package/python/vendor/openpyxl/chart/_3d.py +105 -0
- package/python/vendor/openpyxl/chart/__init__.py +19 -0
- package/python/vendor/openpyxl/chart/_chart.py +199 -0
- package/python/vendor/openpyxl/chart/area_chart.py +106 -0
- package/python/vendor/openpyxl/chart/axis.py +401 -0
- package/python/vendor/openpyxl/chart/bar_chart.py +144 -0
- package/python/vendor/openpyxl/chart/bubble_chart.py +67 -0
- package/python/vendor/openpyxl/chart/chartspace.py +195 -0
- package/python/vendor/openpyxl/chart/data_source.py +246 -0
- package/python/vendor/openpyxl/chart/descriptors.py +43 -0
- package/python/vendor/openpyxl/chart/error_bar.py +62 -0
- package/python/vendor/openpyxl/chart/label.py +127 -0
- package/python/vendor/openpyxl/chart/layout.py +74 -0
- package/python/vendor/openpyxl/chart/legend.py +75 -0
- package/python/vendor/openpyxl/chart/line_chart.py +129 -0
- package/python/vendor/openpyxl/chart/marker.py +90 -0
- package/python/vendor/openpyxl/chart/picture.py +35 -0
- package/python/vendor/openpyxl/chart/pie_chart.py +177 -0
- package/python/vendor/openpyxl/chart/pivot.py +65 -0
- package/python/vendor/openpyxl/chart/plotarea.py +162 -0
- package/python/vendor/openpyxl/chart/print_settings.py +57 -0
- package/python/vendor/openpyxl/chart/radar_chart.py +55 -0
- package/python/vendor/openpyxl/chart/reader.py +32 -0
- package/python/vendor/openpyxl/chart/reference.py +124 -0
- package/python/vendor/openpyxl/chart/scatter_chart.py +53 -0
- package/python/vendor/openpyxl/chart/series.py +197 -0
- package/python/vendor/openpyxl/chart/series_factory.py +41 -0
- package/python/vendor/openpyxl/chart/shapes.py +89 -0
- package/python/vendor/openpyxl/chart/stock_chart.py +54 -0
- package/python/vendor/openpyxl/chart/surface_chart.py +119 -0
- package/python/vendor/openpyxl/chart/text.py +78 -0
- package/python/vendor/openpyxl/chart/title.py +76 -0
- package/python/vendor/openpyxl/chart/trendline.py +98 -0
- package/python/vendor/openpyxl/chart/updown_bars.py +31 -0
- package/python/vendor/openpyxl/chartsheet/__init__.py +3 -0
- package/python/vendor/openpyxl/chartsheet/chartsheet.py +107 -0
- package/python/vendor/openpyxl/chartsheet/custom.py +61 -0
- package/python/vendor/openpyxl/chartsheet/properties.py +28 -0
- package/python/vendor/openpyxl/chartsheet/protection.py +41 -0
- package/python/vendor/openpyxl/chartsheet/publish.py +58 -0
- package/python/vendor/openpyxl/chartsheet/relation.py +97 -0
- package/python/vendor/openpyxl/chartsheet/views.py +51 -0
- package/python/vendor/openpyxl/comments/__init__.py +4 -0
- package/python/vendor/openpyxl/comments/author.py +21 -0
- package/python/vendor/openpyxl/comments/comment_sheet.py +211 -0
- package/python/vendor/openpyxl/comments/comments.py +62 -0
- package/python/vendor/openpyxl/comments/shape_writer.py +112 -0
- package/python/vendor/openpyxl/compat/__init__.py +54 -0
- package/python/vendor/openpyxl/compat/abc.py +8 -0
- package/python/vendor/openpyxl/compat/numbers.py +43 -0
- package/python/vendor/openpyxl/compat/product.py +17 -0
- package/python/vendor/openpyxl/compat/singleton.py +40 -0
- package/python/vendor/openpyxl/compat/strings.py +25 -0
- package/python/vendor/openpyxl/descriptors/__init__.py +58 -0
- package/python/vendor/openpyxl/descriptors/base.py +272 -0
- package/python/vendor/openpyxl/descriptors/container.py +41 -0
- package/python/vendor/openpyxl/descriptors/excel.py +112 -0
- package/python/vendor/openpyxl/descriptors/namespace.py +12 -0
- package/python/vendor/openpyxl/descriptors/nested.py +129 -0
- package/python/vendor/openpyxl/descriptors/sequence.py +136 -0
- package/python/vendor/openpyxl/descriptors/serialisable.py +240 -0
- package/python/vendor/openpyxl/descriptors/slots.py +18 -0
- package/python/vendor/openpyxl/drawing/__init__.py +4 -0
- package/python/vendor/openpyxl/drawing/colors.py +435 -0
- package/python/vendor/openpyxl/drawing/connector.py +144 -0
- package/python/vendor/openpyxl/drawing/drawing.py +92 -0
- package/python/vendor/openpyxl/drawing/effect.py +407 -0
- package/python/vendor/openpyxl/drawing/fill.py +425 -0
- package/python/vendor/openpyxl/drawing/geometry.py +584 -0
- package/python/vendor/openpyxl/drawing/graphic.py +177 -0
- package/python/vendor/openpyxl/drawing/image.py +65 -0
- package/python/vendor/openpyxl/drawing/line.py +144 -0
- package/python/vendor/openpyxl/drawing/picture.py +144 -0
- package/python/vendor/openpyxl/drawing/properties.py +174 -0
- package/python/vendor/openpyxl/drawing/relation.py +17 -0
- package/python/vendor/openpyxl/drawing/spreadsheet_drawing.py +382 -0
- package/python/vendor/openpyxl/drawing/text.py +717 -0
- package/python/vendor/openpyxl/drawing/xdr.py +33 -0
- package/python/vendor/openpyxl/formatting/__init__.py +3 -0
- package/python/vendor/openpyxl/formatting/formatting.py +114 -0
- package/python/vendor/openpyxl/formatting/rule.py +291 -0
- package/python/vendor/openpyxl/formula/__init__.py +3 -0
- package/python/vendor/openpyxl/formula/tokenizer.py +446 -0
- package/python/vendor/openpyxl/formula/translate.py +166 -0
- package/python/vendor/openpyxl/packaging/__init__.py +3 -0
- package/python/vendor/openpyxl/packaging/core.py +115 -0
- package/python/vendor/openpyxl/packaging/custom.py +289 -0
- package/python/vendor/openpyxl/packaging/extended.py +137 -0
- package/python/vendor/openpyxl/packaging/interface.py +56 -0
- package/python/vendor/openpyxl/packaging/manifest.py +194 -0
- package/python/vendor/openpyxl/packaging/relationship.py +158 -0
- package/python/vendor/openpyxl/packaging/workbook.py +185 -0
- package/python/vendor/openpyxl/pivot/__init__.py +1 -0
- package/python/vendor/openpyxl/pivot/cache.py +965 -0
- package/python/vendor/openpyxl/pivot/fields.py +326 -0
- package/python/vendor/openpyxl/pivot/record.py +111 -0
- package/python/vendor/openpyxl/pivot/table.py +1261 -0
- package/python/vendor/openpyxl/reader/__init__.py +1 -0
- package/python/vendor/openpyxl/reader/drawings.py +71 -0
- package/python/vendor/openpyxl/reader/excel.py +349 -0
- package/python/vendor/openpyxl/reader/strings.py +44 -0
- package/python/vendor/openpyxl/reader/workbook.py +133 -0
- package/python/vendor/openpyxl/styles/__init__.py +11 -0
- package/python/vendor/openpyxl/styles/alignment.py +62 -0
- package/python/vendor/openpyxl/styles/borders.py +103 -0
- package/python/vendor/openpyxl/styles/builtins.py +1397 -0
- package/python/vendor/openpyxl/styles/cell_style.py +206 -0
- package/python/vendor/openpyxl/styles/colors.py +172 -0
- package/python/vendor/openpyxl/styles/differential.py +95 -0
- package/python/vendor/openpyxl/styles/fills.py +224 -0
- package/python/vendor/openpyxl/styles/fonts.py +113 -0
- package/python/vendor/openpyxl/styles/named_styles.py +282 -0
- package/python/vendor/openpyxl/styles/numbers.py +200 -0
- package/python/vendor/openpyxl/styles/protection.py +17 -0
- package/python/vendor/openpyxl/styles/proxy.py +62 -0
- package/python/vendor/openpyxl/styles/styleable.py +151 -0
- package/python/vendor/openpyxl/styles/stylesheet.py +274 -0
- package/python/vendor/openpyxl/styles/table.py +94 -0
- package/python/vendor/openpyxl/utils/__init__.py +17 -0
- package/python/vendor/openpyxl/utils/bound_dictionary.py +26 -0
- package/python/vendor/openpyxl/utils/cell.py +240 -0
- package/python/vendor/openpyxl/utils/dataframe.py +87 -0
- package/python/vendor/openpyxl/utils/datetime.py +140 -0
- package/python/vendor/openpyxl/utils/escape.py +43 -0
- package/python/vendor/openpyxl/utils/exceptions.py +34 -0
- package/python/vendor/openpyxl/utils/formulas.py +24 -0
- package/python/vendor/openpyxl/utils/indexed_list.py +49 -0
- package/python/vendor/openpyxl/utils/inference.py +60 -0
- package/python/vendor/openpyxl/utils/protection.py +22 -0
- package/python/vendor/openpyxl/utils/units.py +108 -0
- package/python/vendor/openpyxl/workbook/__init__.py +4 -0
- package/python/vendor/openpyxl/workbook/_writer.py +197 -0
- package/python/vendor/openpyxl/workbook/child.py +166 -0
- package/python/vendor/openpyxl/workbook/defined_name.py +189 -0
- package/python/vendor/openpyxl/workbook/external_link/__init__.py +3 -0
- package/python/vendor/openpyxl/workbook/external_link/external.py +190 -0
- package/python/vendor/openpyxl/workbook/external_reference.py +18 -0
- package/python/vendor/openpyxl/workbook/function_group.py +36 -0
- package/python/vendor/openpyxl/workbook/properties.py +151 -0
- package/python/vendor/openpyxl/workbook/protection.py +163 -0
- package/python/vendor/openpyxl/workbook/smart_tags.py +56 -0
- package/python/vendor/openpyxl/workbook/views.py +155 -0
- package/python/vendor/openpyxl/workbook/web.py +98 -0
- package/python/vendor/openpyxl/workbook/workbook.py +438 -0
- package/python/vendor/openpyxl/worksheet/__init__.py +1 -0
- package/python/vendor/openpyxl/worksheet/_read_only.py +190 -0
- package/python/vendor/openpyxl/worksheet/_reader.py +472 -0
- package/python/vendor/openpyxl/worksheet/_write_only.py +160 -0
- package/python/vendor/openpyxl/worksheet/_writer.py +390 -0
- package/python/vendor/openpyxl/worksheet/cell_range.py +512 -0
- package/python/vendor/openpyxl/worksheet/cell_watch.py +34 -0
- package/python/vendor/openpyxl/worksheet/controls.py +107 -0
- package/python/vendor/openpyxl/worksheet/copier.py +70 -0
- package/python/vendor/openpyxl/worksheet/custom.py +35 -0
- package/python/vendor/openpyxl/worksheet/datavalidation.py +202 -0
- package/python/vendor/openpyxl/worksheet/dimensions.py +306 -0
- package/python/vendor/openpyxl/worksheet/drawing.py +14 -0
- package/python/vendor/openpyxl/worksheet/errors.py +93 -0
- package/python/vendor/openpyxl/worksheet/filters.py +486 -0
- package/python/vendor/openpyxl/worksheet/formula.py +51 -0
- package/python/vendor/openpyxl/worksheet/header_footer.py +270 -0
- package/python/vendor/openpyxl/worksheet/hyperlink.py +46 -0
- package/python/vendor/openpyxl/worksheet/merge.py +141 -0
- package/python/vendor/openpyxl/worksheet/ole.py +133 -0
- package/python/vendor/openpyxl/worksheet/page.py +174 -0
- package/python/vendor/openpyxl/worksheet/pagebreak.py +94 -0
- package/python/vendor/openpyxl/worksheet/picture.py +8 -0
- package/python/vendor/openpyxl/worksheet/print_settings.py +184 -0
- package/python/vendor/openpyxl/worksheet/properties.py +97 -0
- package/python/vendor/openpyxl/worksheet/protection.py +120 -0
- package/python/vendor/openpyxl/worksheet/related.py +17 -0
- package/python/vendor/openpyxl/worksheet/scenario.py +105 -0
- package/python/vendor/openpyxl/worksheet/smart_tag.py +78 -0
- package/python/vendor/openpyxl/worksheet/table.py +385 -0
- package/python/vendor/openpyxl/worksheet/views.py +155 -0
- package/python/vendor/openpyxl/worksheet/worksheet.py +907 -0
- package/python/vendor/openpyxl/writer/__init__.py +1 -0
- package/python/vendor/openpyxl/writer/excel.py +295 -0
- package/python/vendor/openpyxl/writer/theme.py +291 -0
- package/python/vendor/openpyxl/xml/__init__.py +42 -0
- package/python/vendor/openpyxl/xml/constants.py +129 -0
- package/python/vendor/openpyxl/xml/functions.py +87 -0
- package/watchlist/package.json +1 -1
|
@@ -1,15 +1,43 @@
|
|
|
1
|
-
import { chmod, mkdir, rename, rm, stat } from 'node:fs/promises';
|
|
1
|
+
import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { join, resolve } from 'node:path';
|
|
4
|
-
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
5
|
import { PythonRuntimeError, isPythonRuntimeError, messageOf } from './errors.js';
|
|
6
6
|
import { withInstallLock } from './lock.js';
|
|
7
7
|
import { normalizePackNames, packTarget } from './manifest.js';
|
|
8
8
|
import { availableBytes, directoryBytes, exists, isInside, lockRoot, packRoot, readJson, readyFileShape, readyPath, removeStaleStaging, resolveDshHome, runtimeRoot, safeRelative, stagingRoot, storeRoot, writeJsonAtomic, } from './paths.js';
|
|
9
|
-
import { findPnpmCli } from './platform.js';
|
|
9
|
+
import { findPnpmCli, pythonFlags } from './platform.js';
|
|
10
10
|
import { classifyPnpmFailure, installArgs, runPnpm, writeInstallProject } from './pnpm.js';
|
|
11
|
-
import { probePython } from './probe.js';
|
|
11
|
+
import { probePython, runWorkerProcess } from './probe.js';
|
|
12
|
+
import { pythonChildEnv } from './child-env.js';
|
|
12
13
|
const PACK_ORDER = ['base', 'parquet'];
|
|
14
|
+
/** Fixed data scripts live in the repo (never model-supplied code); ids map 1:1 to `python/scripts/<id>.py`. */
|
|
15
|
+
const DATA_SCRIPT_DIR = fileURLToPath(new URL('../../python/scripts', import.meta.url));
|
|
16
|
+
/** Pure-Python packages for those scripts; absolute so the child never depends on cwd. */
|
|
17
|
+
const PYTHON_VENDOR_DIR = fileURLToPath(new URL('../../python/vendor', import.meta.url));
|
|
18
|
+
const DATA_SCRIPT_ID = /^[a-z0-9_]+$/u;
|
|
19
|
+
const DATA_RUN_DIR = 'data-runs';
|
|
20
|
+
const DIAGNOSTIC_TAIL_CHARS = 2_000;
|
|
21
|
+
function recordOf(value) {
|
|
22
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
|
|
23
|
+
}
|
|
24
|
+
function diagnosticTail(...values) {
|
|
25
|
+
const text = values.map((value) => value?.trim() ?? '').filter((value) => value !== '').join('\n');
|
|
26
|
+
if (text === '')
|
|
27
|
+
return undefined;
|
|
28
|
+
return text.length <= DIAGNOSTIC_TAIL_CHARS ? text : `…${text.slice(-DIAGNOSTIC_TAIL_CHARS)}`;
|
|
29
|
+
}
|
|
30
|
+
/** Scripts print one concise stderr line; it beats the worker's generic "analysis.py exited with N". */
|
|
31
|
+
function lastStderrLine(value) {
|
|
32
|
+
const line = (value ?? '').split(/\r?\n/u).map((item) => item.trim()).filter((item) => item !== '').at(-1);
|
|
33
|
+
if (line === undefined)
|
|
34
|
+
return undefined;
|
|
35
|
+
return line.length <= 500 ? line : `…${line.slice(-500)}`;
|
|
36
|
+
}
|
|
37
|
+
function failureDiagnostics(worker, failure) {
|
|
38
|
+
const traceback = typeof failure?.traceback === 'string' ? failure.traceback : undefined;
|
|
39
|
+
return diagnosticTail(worker.stderr, worker.stdout, traceback);
|
|
40
|
+
}
|
|
13
41
|
function nowIso(now) {
|
|
14
42
|
return now().toISOString();
|
|
15
43
|
}
|
|
@@ -49,6 +77,7 @@ export class PythonRuntimeManager {
|
|
|
49
77
|
now;
|
|
50
78
|
runPnpm;
|
|
51
79
|
probePython;
|
|
80
|
+
runWorker;
|
|
52
81
|
jobs = new Map();
|
|
53
82
|
activeJobId;
|
|
54
83
|
pnpmInvocation;
|
|
@@ -66,6 +95,7 @@ export class PythonRuntimeManager {
|
|
|
66
95
|
this.now = options.now ?? (() => new Date());
|
|
67
96
|
this.runPnpm = options.runPnpm ?? runPnpm;
|
|
68
97
|
this.probePython = options.probePython ?? probePython;
|
|
98
|
+
this.runWorker = options.runWorkerProcess ?? runWorkerProcess;
|
|
69
99
|
}
|
|
70
100
|
targetId() {
|
|
71
101
|
if (this.target.target === null || !this.target.supported) {
|
|
@@ -456,6 +486,112 @@ export class PythonRuntimeManager {
|
|
|
456
486
|
}
|
|
457
487
|
return report;
|
|
458
488
|
}
|
|
489
|
+
/** Base pack must be installed and intact; a missing runtime is a call-time failure, never a boot gate. */
|
|
490
|
+
async resolveDataRuntime() {
|
|
491
|
+
try {
|
|
492
|
+
return await this.resolve(['base']);
|
|
493
|
+
}
|
|
494
|
+
catch (error) {
|
|
495
|
+
if (isPythonRuntimeError(error) && (error.code === 'runtime-not-ready' || error.code === 'pack-invalid' || error.code === 'unsupported-platform')) {
|
|
496
|
+
throw new PythonRuntimeError('data-runtime-not-ready', undefined, error.message);
|
|
497
|
+
}
|
|
498
|
+
throw error;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/** Quote a JSON value for a script's `input.json`: no `undefined`, no non-finite numbers. */
|
|
502
|
+
static serializeParams(params) {
|
|
503
|
+
return JSON.stringify(params ?? {});
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Run one fixed repo data script in an isolated run directory and return the rows it wrote.
|
|
507
|
+
*
|
|
508
|
+
* The child only ever sees a copied repo script and `input.json`; its whole working set lives under
|
|
509
|
+
* `<cacheRoot>/data-runs/<script>-<uuid>/` and is removed afterwards. `python/vendor` rides along as
|
|
510
|
+
* an extra `--site-packages` entry so no pip/venv/pack is involved.
|
|
511
|
+
*/
|
|
512
|
+
async runDataScript(options) {
|
|
513
|
+
const script = typeof options?.script === 'string' ? options.script : '';
|
|
514
|
+
if (!DATA_SCRIPT_ID.test(script)) {
|
|
515
|
+
throw new PythonRuntimeError('invalid-request', `固定数据脚本名不合法:${JSON.stringify(script)}`);
|
|
516
|
+
}
|
|
517
|
+
const scriptFile = `${script}.py`;
|
|
518
|
+
let source;
|
|
519
|
+
try {
|
|
520
|
+
source = await readFile(join(DATA_SCRIPT_DIR, scriptFile), 'utf8');
|
|
521
|
+
}
|
|
522
|
+
catch (error) {
|
|
523
|
+
throw new PythonRuntimeError('pack-invalid', `固定数据脚本缺失:${scriptFile}(${messageOf(error)})`);
|
|
524
|
+
}
|
|
525
|
+
const timeoutMs = options?.timeoutMs ?? this.manifest.limits.probeTimeoutMs;
|
|
526
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
|
|
527
|
+
throw new PythonRuntimeError('invalid-request', 'timeoutMs 必须是正整数。');
|
|
528
|
+
}
|
|
529
|
+
const signal = options?.signal;
|
|
530
|
+
const handle = await this.resolveDataRuntime();
|
|
531
|
+
const runRoot = join(this.cacheRoot, DATA_RUN_DIR);
|
|
532
|
+
const runDir = join(runRoot, `${script}-${randomUUID()}`);
|
|
533
|
+
const homeDir = join(runDir, 'home');
|
|
534
|
+
const tempDir = join(runDir, 'tmp');
|
|
535
|
+
try {
|
|
536
|
+
await mkdir(runRoot, { recursive: true, mode: 0o700 });
|
|
537
|
+
await removeStaleStaging(runRoot);
|
|
538
|
+
await mkdir(runDir, { recursive: true, mode: 0o700 });
|
|
539
|
+
await mkdir(homeDir, { recursive: true, mode: 0o700 });
|
|
540
|
+
await mkdir(tempDir, { recursive: true, mode: 0o700 });
|
|
541
|
+
await writeFile(join(runDir, scriptFile), source, { encoding: 'utf8', mode: 0o600 });
|
|
542
|
+
await writeFile(join(runDir, 'request.json'), JSON.stringify({ script: scriptFile, args: [] }), 'utf8');
|
|
543
|
+
await writeFile(join(runDir, 'input.json'), PythonRuntimeManager.serializeParams(options?.params), 'utf8');
|
|
544
|
+
const sitePackages = [...handle.sitePackages];
|
|
545
|
+
if (await exists(PYTHON_VENDOR_DIR))
|
|
546
|
+
sitePackages.push(PYTHON_VENDOR_DIR);
|
|
547
|
+
const env = pythonChildEnv({ pythonDir: dirname(handle.python), homeDir, tempDir, baseEnv: process.env });
|
|
548
|
+
const args = [
|
|
549
|
+
...pythonFlags,
|
|
550
|
+
this.workerPath,
|
|
551
|
+
'run',
|
|
552
|
+
...sitePackages.flatMap((item) => ['--site-packages', item]),
|
|
553
|
+
'--run-dir',
|
|
554
|
+
runDir,
|
|
555
|
+
];
|
|
556
|
+
const worker = await this.runWorker({
|
|
557
|
+
python: handle.python,
|
|
558
|
+
args,
|
|
559
|
+
cwd: runDir,
|
|
560
|
+
env,
|
|
561
|
+
timeoutMs,
|
|
562
|
+
...(signal === undefined ? {} : { signal }),
|
|
563
|
+
});
|
|
564
|
+
if (worker.spawnError !== undefined) {
|
|
565
|
+
throw new PythonRuntimeError('script-failed', `启动 Python 失败:${worker.spawnError}`, diagnosticTail(worker.stderr));
|
|
566
|
+
}
|
|
567
|
+
if (worker.timedOut)
|
|
568
|
+
throw new PythonRuntimeError('timeout', `Python 数据脚本超时(${scriptFile})。`, diagnosticTail(worker.stderr));
|
|
569
|
+
if (worker.aborted)
|
|
570
|
+
throw new PythonRuntimeError('cancelled', undefined, diagnosticTail(worker.stderr));
|
|
571
|
+
const executed = recordOf(await readJson(join(runDir, 'result.json')));
|
|
572
|
+
if (executed === undefined) {
|
|
573
|
+
throw new PythonRuntimeError('script-failed', `数据脚本没有写出 result.json(退出码 ${String(worker.code)})。`, diagnosticTail(worker.stderr || worker.stdout));
|
|
574
|
+
}
|
|
575
|
+
const failure = recordOf(executed.error);
|
|
576
|
+
if (executed.ok !== true) {
|
|
577
|
+
const workerMessage = typeof failure?.message === 'string' && failure.message.trim() !== '' ? failure.message.trim() : undefined;
|
|
578
|
+
const message = lastStderrLine(worker.stderr) ?? workerMessage ?? `数据脚本退出码 ${String(worker.code)}。`;
|
|
579
|
+
throw new PythonRuntimeError('script-failed', message, failureDiagnostics(worker, failure));
|
|
580
|
+
}
|
|
581
|
+
const output = recordOf(await readJson(join(runDir, 'out.json')));
|
|
582
|
+
if (output === undefined || !Array.isArray(output.rows)) {
|
|
583
|
+
throw new PythonRuntimeError('script-failed', `数据脚本没有写出 out.json({"rows":[...]})。`, diagnosticTail(worker.stderr));
|
|
584
|
+
}
|
|
585
|
+
return {
|
|
586
|
+
rows: output.rows,
|
|
587
|
+
pythonVersion: typeof executed.python === 'string' ? executed.python : handle.pythonVersion,
|
|
588
|
+
durationMs: typeof executed.durationMs === 'number' && Number.isFinite(executed.durationMs) ? executed.durationMs : 0,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
finally {
|
|
592
|
+
await rm(runDir, { recursive: true, force: true }).catch(() => undefined);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
459
595
|
async resolve(packs = ['base']) {
|
|
460
596
|
const names = normalizePackNames(packs);
|
|
461
597
|
const target = this.targetId();
|
|
@@ -9,5 +9,29 @@ export interface ProbeOptions {
|
|
|
9
9
|
signal?: AbortSignal;
|
|
10
10
|
env?: Record<string, string | undefined>;
|
|
11
11
|
}
|
|
12
|
+
export interface WorkerProcessOptions {
|
|
13
|
+
python: string;
|
|
14
|
+
/** Full argv after the interpreter path: worker script, subcommand and its flags. */
|
|
15
|
+
args: string[];
|
|
16
|
+
cwd: string;
|
|
17
|
+
env: Record<string, string>;
|
|
18
|
+
timeoutMs: number;
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}
|
|
21
|
+
export interface WorkerProcessResult {
|
|
22
|
+
code: number | null;
|
|
23
|
+
stdout: string;
|
|
24
|
+
stderr: string;
|
|
25
|
+
timedOut: boolean;
|
|
26
|
+
aborted: boolean;
|
|
27
|
+
/** Set when the child could not be started at all; no exit code exists in that case. */
|
|
28
|
+
spawnError?: string;
|
|
29
|
+
}
|
|
30
|
+
export type WorkerProcessRunner = (options: WorkerProcessOptions) => Promise<WorkerProcessResult>;
|
|
31
|
+
/**
|
|
32
|
+
* Spawn the private interpreter once. Timeout kills the whole child tree, abort behaves the same
|
|
33
|
+
* without becoming an error here: callers map the flags to their own `timeout` / `cancelled` codes.
|
|
34
|
+
*/
|
|
35
|
+
export declare function runWorkerProcess(options: WorkerProcessOptions): Promise<WorkerProcessResult>;
|
|
12
36
|
/** Run the private interpreter once and require its self-check JSON. */
|
|
13
37
|
export declare function probePython(options: ProbeOptions): Promise<ProbeReport>;
|
|
@@ -3,6 +3,54 @@ import { mkdir } from 'node:fs/promises';
|
|
|
3
3
|
import { PythonRuntimeError } from './errors.js';
|
|
4
4
|
import { pythonChildEnv } from './child-env.js';
|
|
5
5
|
import { detachedChild, killTree, pythonFlags } from './platform.js';
|
|
6
|
+
/** Tail kept per stream; probes and scripts only ever surface the end of a traceback. */
|
|
7
|
+
const OUTPUT_LIMIT = 64 * 1024;
|
|
8
|
+
/**
|
|
9
|
+
* Spawn the private interpreter once. Timeout kills the whole child tree, abort behaves the same
|
|
10
|
+
* without becoming an error here: callers map the flags to their own `timeout` / `cancelled` codes.
|
|
11
|
+
*/
|
|
12
|
+
export async function runWorkerProcess(options) {
|
|
13
|
+
return await new Promise((resolvePromise) => {
|
|
14
|
+
let stdout = '';
|
|
15
|
+
let stderr = '';
|
|
16
|
+
let timedOut = false;
|
|
17
|
+
let settled = false;
|
|
18
|
+
const child = spawn(options.python, options.args, {
|
|
19
|
+
cwd: options.cwd,
|
|
20
|
+
env: options.env,
|
|
21
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
22
|
+
windowsHide: true,
|
|
23
|
+
detached: detachedChild,
|
|
24
|
+
});
|
|
25
|
+
const timer = setTimeout(() => {
|
|
26
|
+
timedOut = true;
|
|
27
|
+
void killTree(child.pid, child, 'SIGTERM');
|
|
28
|
+
setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 2_000).unref?.();
|
|
29
|
+
}, options.timeoutMs);
|
|
30
|
+
timer.unref?.();
|
|
31
|
+
const abort = () => { void killTree(child.pid, child, 'SIGTERM'); };
|
|
32
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
33
|
+
const finish = (code) => {
|
|
34
|
+
if (settled)
|
|
35
|
+
return;
|
|
36
|
+
settled = true;
|
|
37
|
+
clearTimeout(timer);
|
|
38
|
+
options.signal?.removeEventListener('abort', abort);
|
|
39
|
+
resolvePromise({ code, stdout, stderr, timedOut, aborted: options.signal?.aborted === true });
|
|
40
|
+
};
|
|
41
|
+
child.stdout?.on('data', (chunk) => { stdout = (stdout + chunk.toString('utf8')).slice(-OUTPUT_LIMIT); });
|
|
42
|
+
child.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-OUTPUT_LIMIT); });
|
|
43
|
+
child.once('error', (error) => {
|
|
44
|
+
if (settled)
|
|
45
|
+
return;
|
|
46
|
+
settled = true;
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
options.signal?.removeEventListener('abort', abort);
|
|
49
|
+
resolvePromise({ code: null, stdout, stderr, timedOut, aborted: options.signal?.aborted === true, spawnError: String(error) });
|
|
50
|
+
});
|
|
51
|
+
child.once('close', (code) => finish(code));
|
|
52
|
+
});
|
|
53
|
+
}
|
|
6
54
|
function parseReport(output) {
|
|
7
55
|
const line = output.split(/\r?\n/u).map((item) => item.trim()).filter(Boolean).at(-1);
|
|
8
56
|
if (line === undefined)
|
|
@@ -47,55 +95,23 @@ export async function probePython(options) {
|
|
|
47
95
|
'probe',
|
|
48
96
|
...options.sitePackages.flatMap((path) => ['--site-packages', path]),
|
|
49
97
|
];
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
env,
|
|
58
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
59
|
-
windowsHide: true,
|
|
60
|
-
detached: detachedChild,
|
|
61
|
-
});
|
|
62
|
-
const timer = setTimeout(() => {
|
|
63
|
-
timedOut = true;
|
|
64
|
-
void killTree(child.pid, child, 'SIGTERM');
|
|
65
|
-
setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 2_000).unref?.();
|
|
66
|
-
}, options.timeoutMs);
|
|
67
|
-
timer.unref?.();
|
|
68
|
-
const abort = () => { void killTree(child.pid, child, 'SIGTERM'); };
|
|
69
|
-
options.signal?.addEventListener('abort', abort, { once: true });
|
|
70
|
-
const finish = (code) => {
|
|
71
|
-
if (settled)
|
|
72
|
-
return;
|
|
73
|
-
settled = true;
|
|
74
|
-
clearTimeout(timer);
|
|
75
|
-
options.signal?.removeEventListener('abort', abort);
|
|
76
|
-
if (timedOut)
|
|
77
|
-
return reject(new PythonRuntimeError('timeout', 'Python probe 超时。', stderr));
|
|
78
|
-
if (options.signal?.aborted === true)
|
|
79
|
-
return reject(new PythonRuntimeError('cancelled', undefined, stderr));
|
|
80
|
-
if (code !== 0)
|
|
81
|
-
return reject(new PythonRuntimeError('probe-failed', `Python probe 退出码 ${String(code)}。`, stderr || stdout));
|
|
82
|
-
try {
|
|
83
|
-
resolvePromise(parseReport(stdout));
|
|
84
|
-
}
|
|
85
|
-
catch (error) {
|
|
86
|
-
reject(error);
|
|
87
|
-
}
|
|
88
|
-
};
|
|
89
|
-
child.stdout?.on('data', (chunk) => { stdout = (stdout + chunk.toString('utf8')).slice(-64 * 1024); });
|
|
90
|
-
child.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-64 * 1024); });
|
|
91
|
-
child.once('error', (error) => {
|
|
92
|
-
if (settled)
|
|
93
|
-
return;
|
|
94
|
-
settled = true;
|
|
95
|
-
clearTimeout(timer);
|
|
96
|
-
options.signal?.removeEventListener('abort', abort);
|
|
97
|
-
reject(new PythonRuntimeError('probe-failed', `启动 Python 失败:${String(error)}`));
|
|
98
|
-
});
|
|
99
|
-
child.once('close', (code) => finish(code));
|
|
98
|
+
const result = await runWorkerProcess({
|
|
99
|
+
python: options.python,
|
|
100
|
+
args,
|
|
101
|
+
cwd: options.tempDir,
|
|
102
|
+
env,
|
|
103
|
+
timeoutMs: options.timeoutMs,
|
|
104
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
100
105
|
});
|
|
106
|
+
if (result.spawnError !== undefined) {
|
|
107
|
+
throw new PythonRuntimeError('probe-failed', `启动 Python 失败:${result.spawnError}`);
|
|
108
|
+
}
|
|
109
|
+
if (result.timedOut)
|
|
110
|
+
throw new PythonRuntimeError('timeout', 'Python probe 超时。', result.stderr);
|
|
111
|
+
if (result.aborted)
|
|
112
|
+
throw new PythonRuntimeError('cancelled', undefined, result.stderr);
|
|
113
|
+
if (result.code !== 0) {
|
|
114
|
+
throw new PythonRuntimeError('probe-failed', `Python probe 退出码 ${String(result.code)}。`, result.stderr || result.stdout);
|
|
115
|
+
}
|
|
116
|
+
return parseReport(result.stdout);
|
|
101
117
|
}
|
package/lib/runtime-entry.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
|
+
import { detectDshVersion, unverifiedHostWarning } from './host-version.js';
|
|
1
2
|
import { capitalSharedRuntime } from './runtime.js';
|
|
2
3
|
export const name = 'capital-runtime';
|
|
3
4
|
export function apply(ctx) {
|
|
5
|
+
// `engines.dsh` already keeps an out-of-window host from importing this package; reaching here on
|
|
6
|
+
// an unverified version means "same minor, untested patch" and users need one line to paste into an
|
|
7
|
+
// issue. `ctx.logger` is buffered into boot diagnostics only (no terminal exporter), so this goes
|
|
8
|
+
// to stderr directly.
|
|
9
|
+
const hostWarning = unverifiedHostWarning(detectDshVersion());
|
|
10
|
+
if (hostWarning !== undefined)
|
|
11
|
+
console.warn(hostWarning);
|
|
4
12
|
ctx.provide('capitalChartRuntime', capitalSharedRuntime(ctx));
|
|
5
13
|
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/** 中证指数官网 csindex-home JSON:指数 PE(TTM) 日序列。官网 JSON 没有 PB/静态 PE/股息率,
|
|
2
|
+
* 那些只在 oss-ch 的 {code}indicator.xls 里,本仓无 xls 解析依赖,所以这一能力只承诺 pe_ttm。 */
|
|
3
|
+
import { buildDataKey } from '../data-collector/hub.js';
|
|
4
|
+
import { getDataTimeContract } from '../time/tools.js';
|
|
5
|
+
import { createRequestThrottle } from '../net/throttle.js';
|
|
6
|
+
const PE_HISTORY_URL = 'https://www.csindex.com.cn/csindex-home/perf/indexCsiDsPe';
|
|
7
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
8
|
+
/** Upstream indexCode is case-sensitive: h30374 answers an empty list while H30374 has rows. */
|
|
9
|
+
const INDEX_CODE_PATTERN = /^(?:\d{6}|H\d{5})$/;
|
|
10
|
+
/** Daily series: a 1h cache only has to beat the publish cadence. */
|
|
11
|
+
const DAILY_CACHE_MS = 3_600_000;
|
|
12
|
+
const MAX_COUNT = 10_000;
|
|
13
|
+
const REQUEST_INTERVAL_MS = 500;
|
|
14
|
+
/** Upstream injects an anchor row at the requested start when it is not a published date; asking a
|
|
15
|
+
* week earlier keeps that row out of our window (any positive lookback works). */
|
|
16
|
+
const START_LOOKBACK_DAYS = 7;
|
|
17
|
+
const throttle = createRequestThrottle(REQUEST_INTERVAL_MS);
|
|
18
|
+
function isRecord(value) {
|
|
19
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
function sourceError(message, code = 'csindex_invalid_response') {
|
|
22
|
+
const error = new Error(message);
|
|
23
|
+
error.code = code;
|
|
24
|
+
return error;
|
|
25
|
+
}
|
|
26
|
+
function assertKnown(params, allowed) {
|
|
27
|
+
for (const key of Object.keys(params)) {
|
|
28
|
+
if (!allowed.includes(key))
|
|
29
|
+
throw new Error(`unsupported parameter: ${key} (allowed: ${allowed.join(', ')})`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function isCalendarDate(value) {
|
|
33
|
+
if (!DATE_PATTERN.test(value))
|
|
34
|
+
return false;
|
|
35
|
+
const parsed = new Date(`${value}T00:00:00Z`);
|
|
36
|
+
return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
|
|
37
|
+
}
|
|
38
|
+
function parameterDate(value, name) {
|
|
39
|
+
if (typeof value !== 'string' || !isCalendarDate(value.trim()))
|
|
40
|
+
throw new Error(`parameter ${name} must be a valid YYYY-MM-DD date`);
|
|
41
|
+
return value.trim();
|
|
42
|
+
}
|
|
43
|
+
/** Uppercase before the request: lowercase codes are a silent empty list upstream (measured). */
|
|
44
|
+
function parameterIndexCode(value) {
|
|
45
|
+
if (typeof value !== 'string')
|
|
46
|
+
throw new Error('parameter index_code must be a string');
|
|
47
|
+
const code = value.trim().toUpperCase();
|
|
48
|
+
if (!INDEX_CODE_PATTERN.test(code))
|
|
49
|
+
throw new Error(`parameter index_code must be a 6-character CSI index code like 000300 or H30374, got ${JSON.stringify(value)}`);
|
|
50
|
+
return code;
|
|
51
|
+
}
|
|
52
|
+
function normalizePeHistory(params) {
|
|
53
|
+
if (!isRecord(params))
|
|
54
|
+
throw new Error('params must be an object');
|
|
55
|
+
assertKnown(params, ['index_code', 'start_date', 'end_date', 'count']);
|
|
56
|
+
const index_code = parameterIndexCode(params.index_code);
|
|
57
|
+
const start_date = parameterDate(params.start_date, 'start_date');
|
|
58
|
+
const end_date = parameterDate(params.end_date, 'end_date');
|
|
59
|
+
// Upstream answers an empty list for a reversed range; reject it as a parameter error instead.
|
|
60
|
+
if (start_date > end_date)
|
|
61
|
+
throw new Error('parameter start_date must not be later than end_date');
|
|
62
|
+
if (params.count === undefined)
|
|
63
|
+
return { index_code, start_date, end_date };
|
|
64
|
+
if (typeof params.count !== 'number' || !Number.isSafeInteger(params.count) || params.count < 1 || params.count > MAX_COUNT) {
|
|
65
|
+
throw new Error(`parameter count must be an integer from 1 to ${MAX_COUNT}`);
|
|
66
|
+
}
|
|
67
|
+
return { index_code, start_date, end_date, count: params.count };
|
|
68
|
+
}
|
|
69
|
+
async function getJson(url, signal, label) {
|
|
70
|
+
signal.throwIfAborted();
|
|
71
|
+
return throttle(async () => {
|
|
72
|
+
let response;
|
|
73
|
+
try {
|
|
74
|
+
response = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' }, signal });
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (error instanceof Error && error.name === 'AbortError')
|
|
78
|
+
throw error;
|
|
79
|
+
throw sourceError(`${label} request failed: ${error instanceof Error ? error.message : String(error)}`, 'csindex_http_error');
|
|
80
|
+
}
|
|
81
|
+
const text = await response.text();
|
|
82
|
+
if (!response.ok)
|
|
83
|
+
throw sourceError(`${label} returned HTTP ${response.status}`, 'csindex_http_error');
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(text);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
throw sourceError(`${label} returned non-JSON: ${JSON.stringify(text.slice(0, 120))}`, 'csindex_invalid_response');
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/** Upstream gives calendar dates as YYYYMMDD text in a weekday series (weekends absent). */
|
|
93
|
+
function upstreamDate(value, label) {
|
|
94
|
+
if (typeof value !== 'string' || !/^\d{8}$/.test(value))
|
|
95
|
+
throw sourceError(`${label} is not a YYYYMMDD date: ${JSON.stringify(String(value ?? ''))}`);
|
|
96
|
+
const text = `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`;
|
|
97
|
+
if (!isCalendarDate(text))
|
|
98
|
+
throw sourceError(`${label} is not a valid date: ${value}`);
|
|
99
|
+
return text;
|
|
100
|
+
}
|
|
101
|
+
function shiftDays(date, days) {
|
|
102
|
+
return new Date(Date.parse(`${date}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10);
|
|
103
|
+
}
|
|
104
|
+
const peHistoryRow = {
|
|
105
|
+
type: 'object',
|
|
106
|
+
properties: {
|
|
107
|
+
index_code: { type: 'string', description: '6 位中证指数代码(H 开头的字母代码原样保留,如 H30374)' },
|
|
108
|
+
index_name: { type: 'string', description: '指数中文简称(上游 indexName,如 沪深300)' },
|
|
109
|
+
date: { type: 'string', description: '数据日期 YYYY-MM-DD(北京时间日期;上游按工作日发布,节假日未剔除)' },
|
|
110
|
+
pe_ttm: { type: 'number', description: '滚动市盈率(倍),上游字段 peg;本能力不提供静态 PE / PB / 股息率' },
|
|
111
|
+
},
|
|
112
|
+
required: ['index_code', 'index_name', 'date', 'pe_ttm'],
|
|
113
|
+
additionalProperties: false,
|
|
114
|
+
};
|
|
115
|
+
const peHistoryOutput = { type: 'array', items: peHistoryRow };
|
|
116
|
+
const peHistoryInput = {
|
|
117
|
+
type: 'object',
|
|
118
|
+
properties: {
|
|
119
|
+
index_code: { type: 'string', description: '6 位中证指数代码,如 000300、000905、H30374;小写会自动转大写(上游区分大小写)' },
|
|
120
|
+
start_date: { type: 'string', description: '起始日期 YYYY-MM-DD(闭区间)' },
|
|
121
|
+
end_date: { type: 'string', description: '截止日期 YYYY-MM-DD(闭区间)' },
|
|
122
|
+
count: { type: 'integer', minimum: 1, maximum: MAX_COUNT, description: '只保留区间内最近 N 行(本地截断,默认返回区间全部)' },
|
|
123
|
+
},
|
|
124
|
+
required: ['index_code', 'start_date', 'end_date'],
|
|
125
|
+
additionalProperties: false,
|
|
126
|
+
};
|
|
127
|
+
function isPeHistoryRow(row) {
|
|
128
|
+
return isRecord(row)
|
|
129
|
+
&& typeof row.index_code === 'string' && INDEX_CODE_PATTERN.test(row.index_code)
|
|
130
|
+
&& typeof row.index_name === 'string' && row.index_name.length > 0
|
|
131
|
+
&& typeof row.date === 'string' && isCalendarDate(row.date)
|
|
132
|
+
&& typeof row.pe_ttm === 'number' && Number.isFinite(row.pe_ttm);
|
|
133
|
+
}
|
|
134
|
+
async function executePeHistory(params, signal) {
|
|
135
|
+
const indexCode = String(params.index_code);
|
|
136
|
+
const startDate = String(params.start_date);
|
|
137
|
+
const endDate = String(params.end_date);
|
|
138
|
+
const url = new URL(PE_HISTORY_URL);
|
|
139
|
+
url.searchParams.set('indexCode', indexCode);
|
|
140
|
+
url.searchParams.set('startDate', shiftDays(startDate, -START_LOOKBACK_DAYS).replaceAll('-', ''));
|
|
141
|
+
url.searchParams.set('endDate', endDate.replaceAll('-', ''));
|
|
142
|
+
const label = `CSIndex index PE ${indexCode}`;
|
|
143
|
+
const payload = await getJson(url.toString(), signal, label);
|
|
144
|
+
if (!isRecord(payload))
|
|
145
|
+
throw sourceError(`${label} response is not an object`);
|
|
146
|
+
// Missing indexCode answers HTTP 200 with code 500 and data null; keep that a failure, not an empty series.
|
|
147
|
+
if (payload.success !== true || String(payload.code ?? '') !== '200') {
|
|
148
|
+
throw sourceError(`${label} failed: ${String(payload.msg ?? 'unknown upstream error')} (code ${String(payload.code ?? 'unknown')})`, 'csindex_upstream_error');
|
|
149
|
+
}
|
|
150
|
+
if (!Array.isArray(payload.data))
|
|
151
|
+
throw sourceError(`${label} response lost the data array`);
|
|
152
|
+
const rows = [];
|
|
153
|
+
const seen = new Map();
|
|
154
|
+
let indexName;
|
|
155
|
+
for (const record of payload.data) {
|
|
156
|
+
if (!isRecord(record))
|
|
157
|
+
throw sourceError(`${label} contains a non-object row`);
|
|
158
|
+
const date = upstreamDate(record.tradeDate, `${label} tradeDate`);
|
|
159
|
+
// The lookback window answers real rows before start_date too; only the requested window is output.
|
|
160
|
+
if (date < startDate)
|
|
161
|
+
continue;
|
|
162
|
+
// A row past end_date means the upstream range filter was dropped; refuse instead of quietly widening.
|
|
163
|
+
if (date > endDate)
|
|
164
|
+
throw sourceError(`${label} returned ${date} outside the requested ${startDate}..${endDate}`);
|
|
165
|
+
const name = typeof record.indexName === 'string' ? record.indexName.trim() : '';
|
|
166
|
+
if (name.length === 0)
|
|
167
|
+
throw sourceError(`${label} ${date} has an empty indexName`);
|
|
168
|
+
if (indexName === undefined)
|
|
169
|
+
indexName = name;
|
|
170
|
+
else if (name !== indexName)
|
|
171
|
+
throw sourceError(`${label} mixed index names ${JSON.stringify(indexName)} and ${JSON.stringify(name)} in one response`);
|
|
172
|
+
const pe = record.peg;
|
|
173
|
+
if (typeof pe !== 'number' || !Number.isFinite(pe))
|
|
174
|
+
throw sourceError(`${label} ${date} has a non-numeric peg: ${JSON.stringify(String(pe ?? ''))}`);
|
|
175
|
+
// Same (date, index_code) twice is deduplicated; a second value for one key is a shape change.
|
|
176
|
+
const key = `${date}|${indexCode}`;
|
|
177
|
+
const previous = seen.get(key);
|
|
178
|
+
if (previous !== undefined) {
|
|
179
|
+
if (previous !== pe)
|
|
180
|
+
throw sourceError(`${label} repeats ${date} with conflicting peg ${previous} vs ${pe}`);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
seen.set(key, pe);
|
|
184
|
+
rows.push({ index_code: indexCode, index_name: name, date, pe_ttm: pe });
|
|
185
|
+
}
|
|
186
|
+
rows.sort((left, right) => String(left.date).localeCompare(String(right.date)));
|
|
187
|
+
const limited = typeof params.count === 'number' ? rows.slice(-params.count) : rows;
|
|
188
|
+
return { data: limited, schema: peHistoryOutput };
|
|
189
|
+
}
|
|
190
|
+
function createSource(options) {
|
|
191
|
+
const schema = {
|
|
192
|
+
capability: options.capability,
|
|
193
|
+
time_contract: getDataTimeContract(options.capability),
|
|
194
|
+
name: options.name,
|
|
195
|
+
source: `http:csindex.${options.capability}`,
|
|
196
|
+
data_key: buildDataKey('csindex', 'http', options.capability),
|
|
197
|
+
source_label: 'csindex',
|
|
198
|
+
paginated: false,
|
|
199
|
+
cacheMaxAgeMs: DAILY_CACHE_MS,
|
|
200
|
+
rowShape: { rootArray: true },
|
|
201
|
+
summary: options.summary,
|
|
202
|
+
description: options.description,
|
|
203
|
+
input_schema: options.inputSchema,
|
|
204
|
+
output_schema: options.outputSchema,
|
|
205
|
+
};
|
|
206
|
+
const normalize = (params) => {
|
|
207
|
+
if (!isRecord(params))
|
|
208
|
+
throw new Error('params must be an object');
|
|
209
|
+
return options.normalize(params);
|
|
210
|
+
};
|
|
211
|
+
return {
|
|
212
|
+
schema,
|
|
213
|
+
normalizeParams: normalize,
|
|
214
|
+
validateOutput: options.validateOutput,
|
|
215
|
+
execute: async (request, signal) => options.execute(normalize(request.params), signal),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
export function createCsindexSources() {
|
|
219
|
+
return [
|
|
220
|
+
createSource({
|
|
221
|
+
capability: 'csindex_index_valuation',
|
|
222
|
+
name: 'get_csindex_index_valuation',
|
|
223
|
+
summary: '中证指数滚动市盈率 PE(TTM) 日序列(官网 JSON)',
|
|
224
|
+
description: '按指数代码与日期区间获取中证指数官网发布的**指数滚动市盈率(PE TTM)日序列**(csindex-home indexCsiDsPe JSON,零 key)。一行一个 (指数, 日期),date 升序;响应无分页,单次可一次取满全历史(实测 2011→2026 共 3824 行 / 324 KB,未观察到区间长度上限),只要少量就用 count 或窄区间。实测覆盖中证/上证系列(2026-11-22 复核):000300 从 2011-06-28 起 3824 行、000905 从 2011-06-28 起 3822 行、H30374 从 2015-05-12 起 3006 行、932000 从 2023-06-13 起、000001 上证指数同源;非中证指数(如创业板指 399006)返回空数组。⛔ **本能力只提供 pe_ttm,不提供 PB、不提供静态市盈率、不提供股息率**:官网 JSON 只有滚动 PE 一列(上游字段名 peg,与官网「指数估值」页 PE(TTM) 同列;实测 2026-11-20 沪深300 = 13.09,与官网数据服务页一致);静态 PE 与股息率只存在于 oss-ch 的 {code}indicator.xls(P/E1、P/E2、D/P1、D/P2),本仓没有 xls 解析依赖,别把 pe_ttm 当 PB 或股息率用。时间轴:date 是上游按**工作日**发布的日期(实测全序列周末 0 行、节假日不剔除——2026-10-01/02、10-05..07 都有值,2026-01-01/02 也有值),不是交易所交易日历,不要拿它当交易日或用来校准交易日。⛔ 上游**请求起点补行**:startDate 不是发布日时会在该日期补一行(值复制其后第一行,实测 startDate=2026-11-14 周六补出 13.05);本层把请求起点前移 7 天再按 [start_date, end_date] 闭区间本地裁剪,输出里不会出现补出来的周末/虚构行。新鲜度:实测 2026-11-22(周日)查询主流指数最新到 2026-11-20(周五);**不同指数更新不同步**——实测 H30374 最新只到 2026-11-19,比 000300 晚一个工作日,跨指数同日比较前先对齐到共同日期;更新发生在收盘后(本轮未在交易日盘中复核具体时刻),盘中不要期待当日数据,按 1 小时缓存。空数组 = 区间内没有数据(未来日期/未覆盖指数/区间无发布行),是合法空结果不是取数失败,不要重试;上游 code 非 200 或 HTTP 非 200 才是失败。参数:index_code 必填(6 位数字或 H+5 位数字;上游 indexCode **区分大小写**,实测小写 h30374 直接回空数组,本层先转大写);start_date/end_date 必填,闭区间 YYYY-MM-DD,区间写反在参数层拒绝(上游对写反的区间回空数组);count 可选,只保留区间内最近 N 行(本地截断,不改变服务端请求)。⛔ (date, index_code) 已去重;同一主键出现不同 pe_ttm 判上游结构异常并响亮失败,不静默取一个。pe_ttm 是倍数原值,未四舍五入;Dataset 的 captured_at 才是采集时刻。',
|
|
225
|
+
inputSchema: peHistoryInput,
|
|
226
|
+
outputSchema: peHistoryOutput,
|
|
227
|
+
allowed: ['index_code', 'start_date', 'end_date', 'count'],
|
|
228
|
+
normalize: normalizePeHistory,
|
|
229
|
+
validateOutput: (data) => Array.isArray(data) && data.every(isPeHistoryRow),
|
|
230
|
+
execute: executePeHistory,
|
|
231
|
+
}),
|
|
232
|
+
];
|
|
233
|
+
}
|