gloomberb 0.20.1 → 0.20.3

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 (675) hide show
  1. package/README.md +16 -26
  2. package/README.zh-CN.md +21 -65
  3. package/package.json +2 -1
  4. package/src/account/auth-form.tsx +13 -8
  5. package/src/account/auth-model.ts +20 -1
  6. package/src/account/upgrade-dialog.tsx +8 -4
  7. package/src/api-client/askg.ts +7 -1
  8. package/src/api-client/auth.ts +27 -0
  9. package/src/api-client/catalysts.ts +2 -0
  10. package/src/api-client/central-bank-rates.ts +5 -0
  11. package/src/api-client/company-kpis.ts +2 -1
  12. package/src/api-client/cot.ts +14 -2
  13. package/src/api-client/data.ts +20 -6
  14. package/src/api-client/debt-maturities.ts +45 -2
  15. package/src/api-client/earnings.ts +50 -5
  16. package/src/api-client/errors.ts +21 -11
  17. package/src/api-client/futures-curve.ts +17 -0
  18. package/src/api-client/index.ts +5 -1
  19. package/src/api-client/one-tap-reasons.ts +42 -0
  20. package/src/api-client/paths.ts +9 -1
  21. package/src/api-client/perps.ts +2 -1
  22. package/src/api-client/request.ts +3 -1
  23. package/src/api-client/research-activity.ts +16 -3
  24. package/src/api-client/social-mentions.ts +47 -0
  25. package/src/api-client/types/econ.ts +4 -0
  26. package/src/api-client/types/filings-and-calls.ts +3 -0
  27. package/src/api-client/types/search.ts +3 -0
  28. package/src/app/keybindings/chord.ts +153 -9
  29. package/src/app/keybindings/index.ts +1 -1
  30. package/src/app/keybindings/labels.ts +49 -6
  31. package/src/app/runtime/desktop-deeplink.ts +73 -8
  32. package/src/app.tsx +18 -2
  33. package/src/architecture/core-builtin-allowlist.json +1 -2
  34. package/src/architecture/pane-tabs-allowlist.json +2 -1
  35. package/src/architecture/shortcut-labels-allowlist.json +11 -0
  36. package/src/architecture/ui-literals-allowlist.json +8 -8
  37. package/src/brokers/broker-portfolio-sync.ts +1 -1
  38. package/src/cli/bank-section.ts +26 -12
  39. package/src/cli/command-options.ts +2 -1
  40. package/src/cli/commands/market.ts +372 -99
  41. package/src/cli/commands/options-chain.ts +23 -6
  42. package/src/cli/commands/overview.ts +13 -5
  43. package/src/cli/commands/plugins.ts +49 -18
  44. package/src/cli/commands/search.ts +25 -6
  45. package/src/cli/commands/ticker.ts +16 -9
  46. package/src/cli/desktop-pane-shot-browser.ts +47 -31
  47. package/src/cli/desktop-pane-shot.ts +15 -0
  48. package/src/cli/entry.ts +5 -0
  49. package/src/cli/export-source.ts +7 -1
  50. package/src/cli/freshness.ts +0 -16
  51. package/src/cli/fx-pair.ts +64 -12
  52. package/src/cli/fx-quote-rate.ts +192 -0
  53. package/src/cli/glossary.ts +100 -15
  54. package/src/cli/history-back-adjust.ts +122 -0
  55. package/src/cli/history-rows.ts +122 -34
  56. package/src/cli/index.ts +6 -35
  57. package/src/cli/known-gaps.ts +48 -6
  58. package/src/cli/listing-arg.ts +125 -21
  59. package/src/cli/name-entries.ts +26 -5
  60. package/src/cli/not-a-ticker.ts +6 -2
  61. package/src/cli/pane-functions/capabilities.ts +12 -1
  62. package/src/cli/pane-functions/catalog.ts +12 -2
  63. package/src/cli/pane-functions/dom.ts +4 -2
  64. package/src/cli/pane-functions/function-help.ts +23 -11
  65. package/src/cli/pane-functions/headless.ts +11 -6
  66. package/src/cli/pane-functions/index.ts +35 -4
  67. package/src/cli/pane-functions/market-session.ts +8 -3
  68. package/src/cli/pane-functions/resolver.ts +22 -12
  69. package/src/cli/pane-functions/screenshot-assessment.ts +15 -3
  70. package/src/cli/pane-functions/screenshot-payload.ts +166 -72
  71. package/src/cli/pane-functions/screenshot-render.ts +18 -2
  72. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  73. package/src/cli/quote-answer.ts +10 -0
  74. package/src/cli/report-tables.ts +22 -2
  75. package/src/cli/result.ts +7 -3
  76. package/src/cli/spreadsheet-hint.ts +43 -0
  77. package/src/cli/symbol-list.ts +58 -4
  78. package/src/cli/symbol-rows.ts +71 -4
  79. package/src/cli/ticker-resolution.ts +171 -21
  80. package/src/cli/unknown-command.ts +88 -0
  81. package/src/components/chart/composite/axis-overlays.tsx +13 -3
  82. package/src/components/chart/composite/composite-chart.tsx +8 -1
  83. package/src/components/chart/composite/format.ts +16 -1
  84. package/src/components/chart/composite/legend.tsx +4 -3
  85. package/src/components/chart/composite/panel-labels.ts +2 -1
  86. package/src/components/chart/composite/panel-surface.tsx +33 -4
  87. package/src/components/chart/composite/time-scale.ts +1 -1
  88. package/src/components/chart/composite/toolbar.tsx +8 -4
  89. package/src/components/chart/composite/types.ts +17 -1
  90. package/src/components/chart/composite/use-composite-chart-keyboard.ts +15 -5
  91. package/src/components/chart/composite/use-composite-viewport.ts +31 -8
  92. package/src/components/chart/static/scatter-chart-surface.tsx +25 -9
  93. package/src/components/chart-table/axis.ts +11 -0
  94. package/src/components/command-bar/assist/inventory.ts +3 -2
  95. package/src/components/command-bar/assist/model.ts +6 -1
  96. package/src/components/command-bar/commands/collection-list.ts +3 -2
  97. package/src/components/command-bar/commands/direct/index.ts +9 -1
  98. package/src/components/command-bar/commands/registry.ts +18 -0
  99. package/src/components/command-bar/pane-actions.ts +30 -13
  100. package/src/components/command-bar/panel/index.tsx +6 -3
  101. package/src/components/command-bar/panel/layout.ts +8 -1
  102. package/src/components/command-bar/panel/prompt-binding.ts +4 -0
  103. package/src/components/command-bar/panel/prompt-width.ts +34 -0
  104. package/src/components/command-bar/panel/state.ts +4 -0
  105. package/src/components/command-bar/panel/types.ts +3 -0
  106. package/src/components/command-bar/routes/header-market.ts +108 -0
  107. package/src/components/command-bar/routes/root/command-items.ts +5 -0
  108. package/src/components/command-bar/routes/root/provider-search.ts +190 -32
  109. package/src/components/command-bar/routes/root/results.ts +3 -0
  110. package/src/components/command-bar/routes/root/runtime.ts +28 -5
  111. package/src/components/command-bar/routes/root/search-providers.ts +3 -2
  112. package/src/components/command-bar/routes/root/search-report.ts +2 -2
  113. package/src/components/command-bar/routes/ticker-search/results.ts +53 -6
  114. package/src/components/command-bar/routing/list-state.ts +38 -0
  115. package/src/components/command-bar/selection-hint.ts +28 -0
  116. package/src/components/command-bar/surface/index.tsx +41 -3
  117. package/src/components/command-bar/view-model.ts +15 -0
  118. package/src/components/command-bar/workflow/ticker-listing-picker.ts +1 -0
  119. package/src/components/command-bar/workflow/tickers.ts +3 -2
  120. package/src/components/company-logo.tsx +22 -4
  121. package/src/components/data-table/export.ts +13 -8
  122. package/src/components/data-table/view.tsx +11 -2
  123. package/src/components/feed-data-table/stack-view.tsx +20 -6
  124. package/src/components/feedback-dialog.tsx +5 -2
  125. package/src/components/form-modal/field-row.tsx +3 -2
  126. package/src/components/form-modal/routes.ts +1 -0
  127. package/src/components/index.ts +1 -1
  128. package/src/components/input-search-bar.tsx +2 -2
  129. package/src/components/layout/double-escape-close.ts +8 -5
  130. package/src/components/layout/header.tsx +87 -47
  131. package/src/components/layout/market-summary.ts +323 -116
  132. package/src/components/layout/pane/footer/index.tsx +31 -9
  133. package/src/components/layout/pane/footer/model.ts +63 -21
  134. package/src/components/layout/pane/footer/registration.tsx +60 -1
  135. package/src/components/layout/pane/header-tabs.tsx +17 -3
  136. package/src/components/layout/pane/header.tsx +8 -4
  137. package/src/components/layout/pane/pane-tabs.tsx +57 -3
  138. package/src/components/layout/shell/active-drag.ts +38 -30
  139. package/src/components/layout/shell/chrome.ts +15 -15
  140. package/src/components/layout/shell/drag/index.ts +51 -21
  141. package/src/components/layout/shell/menu.ts +3 -5
  142. package/src/components/layout/shell/pane/actions.ts +4 -1
  143. package/src/components/layout/shell/pane/ask.ts +5 -2
  144. package/src/components/layout/status-bar.tsx +63 -57
  145. package/src/components/layout/status-widget-space.ts +8 -0
  146. package/src/components/markdown-editor.tsx +2 -2
  147. package/src/components/markdown-text.tsx +35 -10
  148. package/src/components/onboarding/account-step/form-panel.tsx +0 -3
  149. package/src/components/onboarding/first-run-workspace.ts +25 -23
  150. package/src/components/onboarding/onboarding-keyboard.ts +21 -7
  151. package/src/components/onboarding/onboarding-wizard.tsx +73 -13
  152. package/src/components/onboarding/portfolio-step/broker-fields-panel.tsx +0 -1
  153. package/src/components/onboarding/portfolio-step/positions-panel.tsx +3 -5
  154. package/src/components/onboarding/use-onboarding-broker-form.ts +2 -1
  155. package/src/components/onboarding/use-onboarding-progress.ts +11 -4
  156. package/src/components/onboarding/use-onboarding-upgrade.ts +3 -2
  157. package/src/components/onboarding/wizard-positions.ts +8 -1
  158. package/src/components/pane-notice-seen.ts +125 -0
  159. package/src/components/pane-settings-dialog/field-dialogs.tsx +2 -1
  160. package/src/components/pane-settings-dialog.tsx +7 -6
  161. package/src/components/price-sparkline/model.ts +26 -10
  162. package/src/components/sign-in-code-panel.tsx +3 -2
  163. package/src/components/speedometer-gauge/terminal.tsx +30 -9
  164. package/src/components/ticker/list-table-view.tsx +68 -7
  165. package/src/components/ui/button.tsx +13 -2
  166. package/src/components/ui/column-grid.tsx +18 -9
  167. package/src/components/ui/confirm-dialog.tsx +2 -1
  168. package/src/components/ui/data-table/index.tsx +5 -3
  169. package/src/components/ui/data-table/opentui/index.tsx +17 -6
  170. package/src/components/ui/data-table/types.ts +26 -0
  171. package/src/components/ui/delayed-mark.tsx +3 -2
  172. package/src/components/ui/external-link.tsx +4 -1
  173. package/src/components/ui/field-grid.tsx +1 -3
  174. package/src/components/ui/fields.tsx +7 -4
  175. package/src/components/ui/index.ts +2 -0
  176. package/src/components/ui/inline-quick-add.tsx +7 -2
  177. package/src/components/ui/key-hint-words.ts +153 -0
  178. package/src/components/ui/key-hints.tsx +73 -0
  179. package/src/components/ui/menu.tsx +3 -1
  180. package/src/components/ui/message-composer.tsx +2 -2
  181. package/src/components/ui/multi-select/dialog.tsx +10 -9
  182. package/src/components/ui/pane-link-chip.tsx +354 -0
  183. package/src/components/ui/query-bar.tsx +22 -13
  184. package/src/components/ui/ratio-bar.tsx +24 -1
  185. package/src/components/ui/select-button.tsx +2 -1
  186. package/src/components/ui/shortcut-hint.tsx +32 -4
  187. package/src/components/ui/table-layout.ts +81 -0
  188. package/src/components/ui/tabs.tsx +52 -6
  189. package/src/components/ui/text-prompt-dialog.tsx +2 -1
  190. package/src/components/use-pane-notice-footer.tsx +12 -4
  191. package/src/core/app-service-ports.ts +1 -1
  192. package/src/core/state/app/command-bar-launch.ts +3 -0
  193. package/src/data/config/store/normalize.ts +6 -0
  194. package/src/data/plugin-state-store.ts +44 -8
  195. package/src/docs/snapshot.json +172 -100
  196. package/src/i18n/es.ts +48 -6
  197. package/src/i18n/ja.ts +48 -5
  198. package/src/i18n/ko.ts +48 -5
  199. package/src/i18n/zh-cn.ts +48 -5
  200. package/src/i18n/zh-tw.ts +48 -5
  201. package/src/layout/pane-manager/gridlock-inference.ts +2 -1
  202. package/src/layout/pane-manager/gridlock.ts +58 -2
  203. package/src/layout-marketplace/api.ts +1 -0
  204. package/src/layout-marketplace/gallery.tsx +4 -3
  205. package/src/layout-marketplace/linked.ts +6 -4
  206. package/src/layout-marketplace/model.ts +3 -2
  207. package/src/market-data/bars-per-year.ts +27 -9
  208. package/src/market-data/coordinator/quotes.ts +22 -3
  209. package/src/market-data/futures-board.ts +80 -0
  210. package/src/market-data/futures-contract.ts +86 -34
  211. package/src/market-data/fx-closes.ts +5 -2
  212. package/src/market-data/hooks.tsx +23 -0
  213. package/src/market-data/market/change-basis.ts +74 -16
  214. package/src/market-data/market/dated-previous-close.ts +163 -47
  215. package/src/market-data/market/format.ts +33 -14
  216. package/src/market-data/market/freshness.ts +24 -7
  217. package/src/market-data/market/globex-day.ts +73 -0
  218. package/src/market-data/market/header-market.ts +154 -0
  219. package/src/market-data/market/index-level.ts +39 -1
  220. package/src/market-data/market/index-session-venues.ts +44 -0
  221. package/src/market-data/market/status.ts +7 -2
  222. package/src/market-data/market/venue-session.ts +72 -0
  223. package/src/market-data/model-dividend-yield.ts +23 -8
  224. package/src/market-data/options-alternatives.ts +39 -4
  225. package/src/market-data/published-apac-sessions.ts +40 -2
  226. package/src/market-data/quotes/export-identity.ts +76 -0
  227. package/src/market-data/quotes/freshness.ts +22 -0
  228. package/src/market-data/quotes/intraday-bar.ts +1 -1
  229. package/src/market-data/quotes/session-split.ts +28 -0
  230. package/src/market-data/quotes/time.ts +42 -1
  231. package/src/market-data/realized-volatility.ts +11 -7
  232. package/src/market-data/tax-equivalent.ts +145 -27
  233. package/src/plugins/builtin/account-management/pane.tsx +3 -3
  234. package/src/plugins/builtin/alerts/alert-engine.ts +12 -6
  235. package/src/plugins/builtin/alerts/alert-log.ts +6 -2
  236. package/src/plugins/builtin/alerts/calendar-events.ts +74 -12
  237. package/src/plugins/builtin/alerts/cli-forms.ts +11 -1
  238. package/src/plugins/builtin/alerts/cli-move.ts +234 -0
  239. package/src/plugins/builtin/alerts/cli.ts +224 -33
  240. package/src/plugins/builtin/alerts/command.ts +33 -6
  241. package/src/plugins/builtin/alerts/event-rows.ts +18 -4
  242. package/src/plugins/builtin/alerts/events-pane.tsx +6 -2
  243. package/src/plugins/builtin/alerts/events.ts +9 -0
  244. package/src/plugins/builtin/alerts/format.ts +40 -15
  245. package/src/plugins/builtin/alerts/headless.ts +31 -18
  246. package/src/plugins/builtin/alerts/history.ts +1 -0
  247. package/src/plugins/builtin/alerts/index.tsx +86 -12
  248. package/src/plugins/builtin/alerts/live.ts +2 -1
  249. package/src/plugins/builtin/alerts/move-checks.ts +155 -0
  250. package/src/plugins/builtin/alerts/move.ts +160 -0
  251. package/src/plugins/builtin/alerts/pane.tsx +52 -22
  252. package/src/plugins/builtin/alerts/price-text.ts +62 -0
  253. package/src/plugins/builtin/alerts/price.ts +17 -0
  254. package/src/plugins/builtin/alerts/quotes.ts +84 -3
  255. package/src/plugins/builtin/alerts/scheduled-check.ts +7 -1
  256. package/src/plugins/builtin/alerts/storage.ts +20 -7
  257. package/src/plugins/builtin/alerts/types.ts +13 -0
  258. package/src/plugins/builtin/analytics/account-returns.ts +1 -1
  259. package/src/plugins/builtin/analytics/index.tsx +10 -3
  260. package/src/plugins/builtin/analytics/pane-model.ts +1 -1
  261. package/src/plugins/builtin/analytics/risk-client.ts +64 -40
  262. package/src/plugins/builtin/analytics/risk-episodes.ts +440 -0
  263. package/src/plugins/builtin/analytics/risk-fx.ts +1 -1
  264. package/src/plugins/builtin/analytics/risk-headless.ts +44 -10
  265. package/src/plugins/builtin/analytics/risk-math.ts +1 -1
  266. package/src/plugins/builtin/analytics/risk-model.ts +183 -27
  267. package/src/plugins/builtin/analytics/risk-pane.tsx +216 -26
  268. package/src/plugins/builtin/analytics/sharpe-cadence.ts +1 -1
  269. package/src/plugins/builtin/backtest/engine.ts +4 -2
  270. package/src/plugins/builtin/backtest/format.ts +14 -0
  271. package/src/plugins/builtin/backtest/pane.tsx +3 -3
  272. package/src/plugins/builtin/backtest/report.ts +5 -3
  273. package/src/plugins/builtin/backtest/window.ts +3 -1
  274. package/src/plugins/builtin/broker-manager/add-request.ts +10 -1
  275. package/src/plugins/builtin/broker-manager/sign-in-end.ts +1 -1
  276. package/src/plugins/builtin/broker-trading/pane.tsx +20 -2
  277. package/src/plugins/builtin/buildout/company/flow.tsx +5 -5
  278. package/src/plugins/builtin/buildout/company/model.ts +14 -2
  279. package/src/plugins/builtin/catalysts/detail.tsx +2 -2
  280. package/src/plugins/builtin/catalysts/model.ts +7 -2
  281. package/src/plugins/builtin/catalysts/pane.tsx +2 -2
  282. package/src/plugins/builtin/central-bank-rates/client.ts +4 -0
  283. package/src/plugins/builtin/central-bank-rates/headless.ts +1 -1
  284. package/src/plugins/builtin/central-bank-rates/model.ts +18 -8
  285. package/src/plugins/builtin/central-bank-rates/pane.tsx +6 -3
  286. package/src/plugins/builtin/chart-composer/cli-options.ts +5 -0
  287. package/src/plugins/builtin/chart-composer/headless-schema.ts +17 -1
  288. package/src/plugins/builtin/chart-composer/headless.ts +2 -0
  289. package/src/plugins/builtin/chat/message/pane-chip.tsx +36 -208
  290. package/src/plugins/builtin/cloud/askg/answer-follow-ups.tsx +61 -0
  291. package/src/plugins/builtin/cloud/askg/answer-sources.tsx +102 -0
  292. package/src/plugins/builtin/cloud/askg/controller.ts +7 -1
  293. package/src/plugins/builtin/cloud/askg/host.ts +57 -0
  294. package/src/plugins/builtin/cloud/askg/model.ts +45 -5
  295. package/src/plugins/builtin/cloud/askg/pane.tsx +304 -25
  296. package/src/plugins/builtin/cloud/askg/protocol.ts +26 -1
  297. package/src/plugins/builtin/cloud/askg/sources.ts +466 -0
  298. package/src/plugins/builtin/cloud/one-tap/controller.ts +309 -0
  299. package/src/plugins/builtin/cloud/one-tap/google-identity.ts +142 -0
  300. package/src/plugins/builtin/cloud/one-tap/one-tap-prompt.tsx +101 -0
  301. package/src/plugins/builtin/cloud/plugin.tsx +7 -1
  302. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +9 -2
  303. package/src/plugins/builtin/company-kpis/client.ts +4 -3
  304. package/src/plugins/builtin/company-kpis/model.ts +34 -3
  305. package/src/plugins/builtin/correlation/index.tsx +39 -167
  306. package/src/plugins/builtin/correlation/matrix/grid.tsx +285 -0
  307. package/src/plugins/builtin/correlation/relationship/pane.tsx +6 -7
  308. package/src/plugins/builtin/correlation/relationship/view-model.ts +14 -5
  309. package/src/plugins/builtin/cot/client.ts +8 -3
  310. package/src/plugins/builtin/cot/headless.ts +65 -12
  311. package/src/plugins/builtin/cot/pane.tsx +11 -5
  312. package/src/plugins/builtin/crypto-board/headless.ts +82 -17
  313. package/src/plugins/builtin/crypto-board/index.tsx +24 -2
  314. package/src/plugins/builtin/crypto-board/model.ts +5 -2
  315. package/src/plugins/builtin/crypto-board/pane.tsx +4 -1
  316. package/src/plugins/builtin/debt-maturities/client.ts +111 -6
  317. package/src/plugins/builtin/debt-maturities/headless.ts +84 -1
  318. package/src/plugins/builtin/debt-maturities/model.ts +97 -14
  319. package/src/plugins/builtin/debt-maturities/pane.tsx +165 -15
  320. package/src/plugins/builtin/debt-maturities/series.ts +3 -1
  321. package/src/plugins/builtin/dividend-yield/client.ts +22 -6
  322. package/src/plugins/builtin/dividend-yield/headless.ts +113 -46
  323. package/src/plugins/builtin/dividend-yield/model.ts +5 -2
  324. package/src/plugins/builtin/dividend-yield/pane.tsx +6 -3
  325. package/src/plugins/builtin/dividend-yield/ranking-reads.ts +11 -4
  326. package/src/plugins/builtin/dividend-yield/ranking.ts +113 -18
  327. package/src/plugins/builtin/dividend-yield/types.ts +2 -0
  328. package/src/plugins/builtin/dividend-yield/view.ts +3 -0
  329. package/src/plugins/builtin/earnings/client.ts +40 -6
  330. package/src/plugins/builtin/earnings/fiscal-quarter.ts +54 -0
  331. package/src/plugins/builtin/earnings/headless.ts +47 -11
  332. package/src/plugins/builtin/earnings/history-model.ts +136 -24
  333. package/src/plugins/builtin/earnings/history-table.ts +42 -10
  334. package/src/plugins/builtin/earnings/history.tsx +23 -8
  335. package/src/plugins/builtin/earnings-ripple/client.ts +5 -2
  336. package/src/plugins/builtin/earnings-ripple/headless.ts +8 -3
  337. package/src/plugins/builtin/earnings-ripple/model.ts +21 -0
  338. package/src/plugins/builtin/earnings-ripple/pane.tsx +2 -3
  339. package/src/plugins/builtin/econ/calendar-model.ts +21 -3
  340. package/src/plugins/builtin/econ/detail-view.tsx +5 -3
  341. package/src/plugins/builtin/econ/figures.ts +13 -0
  342. package/src/plugins/builtin/econ/fred-catalog.ts +6 -3
  343. package/src/plugins/builtin/econ/index.tsx +10 -7
  344. package/src/plugins/builtin/econ/types.ts +5 -0
  345. package/src/plugins/builtin/econ-statistics/stats.ts +13 -5
  346. package/src/plugins/builtin/equity-screener/footer.ts +45 -0
  347. package/src/plugins/builtin/equity-screener/headless.ts +2 -1
  348. package/src/plugins/builtin/equity-screener/pane.tsx +4 -18
  349. package/src/plugins/builtin/equity-screener/ticker-check.tsx +2 -1
  350. package/src/plugins/builtin/filing-events/feed.ts +56 -18
  351. package/src/plugins/builtin/filing-events/pane.tsx +8 -2
  352. package/src/plugins/builtin/fixed-income/model.ts +1 -0
  353. package/src/plugins/builtin/futures/index.tsx +32 -10
  354. package/src/plugins/builtin/futures/model.ts +93 -6
  355. package/src/plugins/builtin/futures/returns.ts +29 -7
  356. package/src/plugins/builtin/futures/table.tsx +59 -17
  357. package/src/plugins/builtin/futures/use-front-returns.ts +32 -6
  358. package/src/plugins/builtin/futures-curve/client.ts +12 -2
  359. package/src/plugins/builtin/futures-curve/headless.ts +58 -17
  360. package/src/plugins/builtin/futures-curve/model.ts +114 -25
  361. package/src/plugins/builtin/futures-curve/pane.tsx +11 -6
  362. package/src/plugins/builtin/fx-matrix/amount.ts +132 -0
  363. package/src/plugins/builtin/fx-matrix/headless.ts +53 -13
  364. package/src/plugins/builtin/fx-matrix/index.tsx +205 -42
  365. package/src/plugins/builtin/fx-matrix/pairs.ts +10 -8
  366. package/src/plugins/builtin/fx-matrix/settings.ts +22 -1
  367. package/src/plugins/builtin/help/function-card.tsx +2 -1
  368. package/src/plugins/builtin/help/function-index.ts +1 -0
  369. package/src/plugins/builtin/help/index.tsx +68 -61
  370. package/src/plugins/builtin/holders/format.ts +7 -2
  371. package/src/plugins/builtin/holders/pane.tsx +11 -3
  372. package/src/plugins/builtin/holders/report-header.ts +5 -4
  373. package/src/plugins/builtin/holders/report-rows.ts +4 -1
  374. package/src/plugins/builtin/holders/treemap.tsx +5 -3
  375. package/src/plugins/builtin/insider/client.ts +31 -14
  376. package/src/plugins/builtin/insider/signals-model.ts +6 -12
  377. package/src/plugins/builtin/ipo-calendar/headless.ts +18 -7
  378. package/src/plugins/builtin/ipo-calendar/listing-ipo.ts +3 -1
  379. package/src/plugins/builtin/ipo-calendar/model.ts +28 -8
  380. package/src/plugins/builtin/ipo-calendar/pane.tsx +2 -1
  381. package/src/plugins/builtin/iv-history/headless.ts +1 -2
  382. package/src/plugins/builtin/iv-history/model.ts +33 -23
  383. package/src/plugins/builtin/iv-history/screen-pane.tsx +0 -3
  384. package/src/plugins/builtin/kelly-sizer/headless.ts +68 -16
  385. package/src/plugins/builtin/kelly-sizer/history.ts +37 -28
  386. package/src/plugins/builtin/kelly-sizer/pane.tsx +43 -10
  387. package/src/plugins/builtin/kelly-sizer/sections.tsx +7 -2
  388. package/src/plugins/builtin/kelly-sizer/units.ts +29 -0
  389. package/src/plugins/builtin/news/index.tsx +7 -13
  390. package/src/plugins/builtin/news/overview-headlines.tsx +117 -0
  391. package/src/plugins/builtin/news/ticker-news.ts +35 -0
  392. package/src/plugins/builtin/news/wire/news/detail-view.tsx +8 -6
  393. package/src/plugins/builtin/news/wire/news/row.ts +49 -0
  394. package/src/plugins/builtin/news/wire/news/table.tsx +9 -20
  395. package/src/plugins/builtin/options/analytics.ts +7 -2
  396. package/src/plugins/builtin/options/live-quotes.ts +6 -1
  397. package/src/plugins/builtin/options/table.ts +3 -2
  398. package/src/plugins/builtin/options/view.tsx +11 -9
  399. package/src/plugins/builtin/options-scenario/client.ts +3 -0
  400. package/src/plugins/builtin/options-scenario/headless.ts +1 -1
  401. package/src/plugins/builtin/perps/client.ts +5 -4
  402. package/src/plugins/builtin/perps/headless.ts +189 -123
  403. package/src/plugins/builtin/perps/index.tsx +3 -1
  404. package/src/plugins/builtin/perps/markets-section.tsx +2 -2
  405. package/src/plugins/builtin/perps/model.ts +9 -5
  406. package/src/plugins/builtin/perps/open-market.ts +4 -4
  407. package/src/plugins/builtin/perps/pane.tsx +2 -0
  408. package/src/plugins/builtin/perps/venue-markets.ts +3 -6
  409. package/src/plugins/builtin/portfolio-list/cell-version.ts +2 -0
  410. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +54 -11
  411. package/src/plugins/builtin/portfolio-list/cli/import-positions.ts +260 -0
  412. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +180 -0
  413. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +68 -22
  414. package/src/plugins/builtin/portfolio-list/cli/render.ts +82 -27
  415. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -3
  416. package/src/plugins/builtin/portfolio-list/grid.tsx +61 -15
  417. package/src/plugins/builtin/portfolio-list/headless.ts +128 -0
  418. package/src/plugins/builtin/portfolio-list/pane/data.ts +34 -1
  419. package/src/plugins/builtin/portfolio-list/pane/index.tsx +48 -4
  420. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +124 -0
  421. package/src/plugins/builtin/portfolio-list/pane/streaming.ts +15 -6
  422. package/src/plugins/builtin/portfolio-list/period-pnl.ts +179 -0
  423. package/src/plugins/builtin/portfolio-list/positions-import/dialog.tsx +445 -0
  424. package/src/plugins/builtin/portfolio-list/positions-import/index.tsx +255 -0
  425. package/src/plugins/builtin/portfolio-list/positions-import/lookup.ts +78 -0
  426. package/src/plugins/builtin/portfolio-list/positions-import/read-file.ts +32 -0
  427. package/src/plugins/builtin/portfolio-list/quick-add/index.tsx +186 -50
  428. package/src/plugins/builtin/portfolio-list/quick-add/resolution.ts +137 -11
  429. package/src/plugins/builtin/portfolio-list/settings.ts +25 -0
  430. package/src/plugins/builtin/portfolio-list/summary/index.tsx +16 -1
  431. package/src/plugins/builtin/portfolio-list/summary/totals.ts +7 -5
  432. package/src/plugins/builtin/portfolio-list/table.tsx +134 -9
  433. package/src/plugins/builtin/power/headless.ts +47 -9
  434. package/src/plugins/builtin/realized-vol/evidence.ts +33 -6
  435. package/src/plugins/builtin/realized-vol/fx-proxy.ts +135 -0
  436. package/src/plugins/builtin/realized-vol/headless.ts +44 -8
  437. package/src/plugins/builtin/realized-vol/model.ts +9 -5
  438. package/src/plugins/builtin/realized-vol/pane.tsx +49 -15
  439. package/src/plugins/builtin/research/relative-valuation-model.ts +8 -3
  440. package/src/plugins/builtin/research-search/article.ts +12 -2
  441. package/src/plugins/builtin/research-search/data.ts +5 -2
  442. package/src/plugins/builtin/research-search/document-view.tsx +1 -1
  443. package/src/plugins/builtin/research-search/model.ts +47 -3
  444. package/src/plugins/builtin/research-search/pane.tsx +3 -2
  445. package/src/plugins/builtin/reverse-dcf/model.ts +7 -4
  446. package/src/plugins/builtin/risk-factors/headless.ts +3 -2
  447. package/src/plugins/builtin/risk-factors/pane.tsx +5 -3
  448. package/src/plugins/builtin/scanner/flow-model.ts +17 -13
  449. package/src/plugins/builtin/scanner/flow-pane.tsx +8 -9
  450. package/src/plugins/builtin/scanner/flow-session.ts +2 -9
  451. package/src/plugins/builtin/sec/filing-display.tsx +0 -5
  452. package/src/plugins/builtin/sec/forms.ts +19 -0
  453. package/src/plugins/builtin/sec/headless.ts +55 -17
  454. package/src/plugins/builtin/sec/index.tsx +17 -7
  455. package/src/plugins/builtin/sec/model.ts +4 -1
  456. package/src/plugins/builtin/shared/earnings-calendar.ts +8 -3
  457. package/src/plugins/builtin/shared/earnings-report.ts +1 -1
  458. package/src/plugins/builtin/shared/fx-rate-freshness.ts +0 -35
  459. package/src/plugins/builtin/shared/market-cap-bands.ts +12 -0
  460. package/src/plugins/builtin/shared/report-freshness.ts +3 -1
  461. package/src/plugins/builtin/shared/use-quote-board.ts +47 -30
  462. package/src/plugins/builtin/shared/volatility/options.ts +63 -2
  463. package/src/plugins/builtin/social-mentions/headless.ts +72 -3
  464. package/src/plugins/builtin/social-mentions/index.tsx +8 -4
  465. package/src/plugins/builtin/social-mentions/lock-note.ts +6 -2
  466. package/src/plugins/builtin/social-mentions/outliers-client.ts +101 -0
  467. package/src/plugins/builtin/social-mentions/outliers-model.ts +162 -0
  468. package/src/plugins/builtin/social-mentions/outliers-names.ts +51 -0
  469. package/src/plugins/builtin/social-mentions/outliers.tsx +276 -0
  470. package/src/plugins/builtin/social-mentions/pane.tsx +32 -3
  471. package/src/plugins/builtin/supply-chain/graph-model.ts +7 -1
  472. package/src/plugins/builtin/supply-chain/graph-pane.tsx +2 -2
  473. package/src/plugins/builtin/supply-chain/headless.ts +20 -10
  474. package/src/plugins/builtin/supply-chain/model.ts +117 -20
  475. package/src/plugins/builtin/supply-chain/pane.tsx +22 -15
  476. package/src/plugins/builtin/supply-chain/row-evidence.tsx +1 -1
  477. package/src/plugins/builtin/thirteenf/api.ts +36 -2
  478. package/src/plugins/builtin/thirteenf/data.ts +4 -1
  479. package/src/plugins/builtin/thirteenf/headless.ts +14 -6
  480. package/src/plugins/builtin/thirteenf/model.ts +56 -1
  481. package/src/plugins/builtin/thirteenf/pane.tsx +8 -8
  482. package/src/plugins/builtin/thirteenf/report-notes.ts +11 -0
  483. package/src/plugins/builtin/thirteenf/table.ts +2 -1
  484. package/src/plugins/builtin/thirteenf/types.ts +6 -0
  485. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +23 -3
  486. package/src/plugins/builtin/ticker-detail/data-panes/returns-chart-model.ts +69 -0
  487. package/src/plugins/builtin/ticker-detail/data-panes/returns-chart.tsx +118 -0
  488. package/src/plugins/builtin/ticker-detail/data-panes/returns-model.ts +1 -1
  489. package/src/plugins/builtin/ticker-detail/data-panes/returns-pane.tsx +103 -40
  490. package/src/plugins/builtin/ticker-detail/financials/model.ts +5 -0
  491. package/src/plugins/builtin/ticker-detail/headless-schema.ts +12 -2
  492. package/src/plugins/builtin/ticker-detail/headless.ts +21 -59
  493. package/src/plugins/builtin/ticker-detail/index.tsx +5 -0
  494. package/src/plugins/builtin/ticker-detail/overview/components.tsx +15 -2
  495. package/src/plugins/builtin/ticker-detail/overview/model.ts +10 -6
  496. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +15 -0
  497. package/src/plugins/builtin/ticker-detail/overview/tax-equivalent.ts +69 -0
  498. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +52 -14
  499. package/src/plugins/builtin/ticker-detail/pane.tsx +95 -20
  500. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +47 -24
  501. package/src/plugins/builtin/ticker-detail/quote-monitor/export.ts +46 -0
  502. package/src/plugins/builtin/ticker-detail/quote-monitor/index.tsx +20 -1
  503. package/src/plugins/builtin/ticker-detail/quote-monitor/rows.ts +120 -0
  504. package/src/plugins/builtin/ticker-detail/research-groups.ts +89 -0
  505. package/src/plugins/builtin/ticker-detail/research-tabs.ts +1 -5
  506. package/src/plugins/builtin/ticker-detail/settings.ts +10 -9
  507. package/src/plugins/builtin/treasury-auctions/cache.ts +85 -19
  508. package/src/plugins/builtin/treasury-auctions/index.tsx +22 -11
  509. package/src/plugins/builtin/treasury-auctions/model.ts +23 -0
  510. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +128 -0
  511. package/src/plugins/builtin/volatility/charts.tsx +2 -2
  512. package/src/plugins/builtin/world-indices/client.ts +2 -0
  513. package/src/plugins/compat.ts +15 -0
  514. package/src/plugins/host-link.ts +6 -1
  515. package/src/plugins/host-resolver.ts +3 -2
  516. package/src/plugins/installer.ts +8 -3
  517. package/src/portfolio/column-values.ts +56 -12
  518. package/src/portfolio/futures-positions.ts +10 -2
  519. package/src/portfolio/listed-symbol.ts +78 -0
  520. package/src/portfolio/mutations.ts +4 -3
  521. package/src/portfolio/period-pnl.ts +119 -0
  522. package/src/portfolio/positions-import/describe.ts +89 -0
  523. package/src/portfolio/positions-import/parse.ts +682 -0
  524. package/src/portfolio/positions-import/plan.ts +295 -0
  525. package/src/portfolio/real-return.ts +172 -0
  526. package/src/{plugins/builtin/analytics/metrics.ts → portfolio/return-metrics.ts} +24 -11
  527. package/src/public/__snapshots__/public-api.test.ts.snap +2 -0
  528. package/src/react/jsx-dev-fallback.ts +62 -0
  529. package/src/renderers/browser/cloud-transport.ts +1 -1
  530. package/src/renderers/browser/config-host.ts +59 -16
  531. package/src/renderers/browser/deeplink-bridge.ts +8 -1
  532. package/src/renderers/browser/http-proxy-transport.ts +9 -2
  533. package/src/renderers/browser/main.tsx +5 -2
  534. package/src/renderers/browser/research-entry.ts +12 -0
  535. package/src/renderers/browser/ui-host.tsx +1 -0
  536. package/src/renderers/cloudflare/http-proxy.ts +9 -2
  537. package/src/renderers/cloudflare/proxy-session.ts +1 -0
  538. package/src/renderers/cloudflare/worker.ts +12 -3
  539. package/src/renderers/dom/boot-frame.ts +2 -2
  540. package/src/renderers/dom/data-table/row.tsx +4 -1
  541. package/src/renderers/dom/desktop/audio-player.tsx +2 -2
  542. package/src/renderers/dom/desktop/controls.tsx +5 -5
  543. package/src/renderers/dom/desktop/dialog-actions.tsx +62 -57
  544. package/src/renderers/dom/desktop/icons.tsx +4 -2
  545. package/src/renderers/dom/desktop/query-bar.tsx +23 -19
  546. package/src/renderers/dom/dom-host-providers.tsx +7 -2
  547. package/src/renderers/dom/dom-ui-host.tsx +3 -1
  548. package/src/renderers/dom/host/box.tsx +2 -2
  549. package/src/renderers/dom/host/input.tsx +17 -1
  550. package/src/renderers/dom/host/tabs.tsx +10 -1
  551. package/src/renderers/dom/key-event.ts +1 -0
  552. package/src/renderers/dom/styles.css +36 -13
  553. package/src/renderers/electrobun/bun/context-menu/click.ts +1 -0
  554. package/src/renderers/electrobun/bun/desktop/app-name.ts +1 -1
  555. package/src/renderers/electrobun/bun/desktop/backend.ts +1 -0
  556. package/src/renderers/electrobun/bun/desktop/capability-bridge.ts +5 -4
  557. package/src/renderers/electrobun/bun/desktop/host-requests.ts +5 -4
  558. package/src/renderers/electrobun/bun/desktop/http-fetch.ts +1 -0
  559. package/src/renderers/electrobun/bun/desktop/http-stream.ts +1 -1
  560. package/src/renderers/electrobun/bun/desktop/initialization.ts +3 -1
  561. package/src/renderers/electrobun/bun/desktop/install-records.ts +4 -1
  562. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +5 -2
  563. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +3 -1
  564. package/src/renderers/electrobun/bun/desktop/screen-setup-file.ts +9 -4
  565. package/src/renderers/electrobun/bun/desktop/update.ts +27 -13
  566. package/src/renderers/electrobun/bun/desktop/windows-script.ts +6 -2
  567. package/src/renderers/electrobun/bun/window/attention.ts +1 -0
  568. package/src/renderers/electrobun/bun/window/boot-frame.ts +1 -0
  569. package/src/renderers/electrobun/bun/window/create.ts +1 -0
  570. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +13 -8
  571. package/src/renderers/electrobun/bun/window/native-min-size.ts +1 -1
  572. package/src/renderers/electrobun/bun/window/remembered-frame.ts +1 -0
  573. package/src/renderers/electrobun/bun/window/windows-native.ts +3 -1
  574. package/src/renderers/electrobun/bun/window/windows-quit.ts +3 -1
  575. package/src/renderers/electrobun/view/app-badge-host.ts +2 -1
  576. package/src/renderers/electrobun/view/capability-subscription.ts +2 -1
  577. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +7 -10
  578. package/src/renderers/electrobun/view/cli-pane-shot-mutations.ts +36 -0
  579. package/src/renderers/electrobun/view/http-fetch.ts +2 -1
  580. package/src/renderers/electrobun/view/main.tsx +9 -4
  581. package/src/renderers/electrobun/view/remote/capability-invoker.ts +6 -3
  582. package/src/renderers/electrobun/view/remote/persistence.ts +63 -27
  583. package/src/renderers/electrobun/view/rpc-timeout.ts +1 -0
  584. package/src/renderers/electrobun/view/ui-host.tsx +3 -2
  585. package/src/renderers/electrobun/view/window-fullscreen.ts +3 -1
  586. package/src/renderers/opentui/browser-open.ts +2 -1
  587. package/src/renderers/opentui/dialog-host.tsx +1 -1
  588. package/src/renderers/opentui/host.tsx +2 -1
  589. package/src/renderers/opentui/interaction-performance.ts +3 -1
  590. package/src/renderers/opentui/start.tsx +2 -1
  591. package/src/renderers/opentui/terminal-media.ts +11 -6
  592. package/src/renderers/opentui/ui-host.tsx +5 -8
  593. package/src/shares/open.ts +22 -1
  594. package/src/shares/pane.ts +2 -1
  595. package/src/sources/gloomberb-cloud/fred-series.ts +12 -0
  596. package/src/sources/gloomberb-cloud/index.ts +31 -2
  597. package/src/sources/gloomberb-cloud/normalizers.ts +32 -3
  598. package/src/sources/provider-router/cached-routes.ts +19 -7
  599. package/src/state/pane-table-export-registry.ts +19 -6
  600. package/src/sync/analytics-payload.ts +194 -0
  601. package/src/sync/baseline.ts +19 -9
  602. package/src/sync/broker-identity.ts +171 -0
  603. package/src/sync/broker-instances.ts +137 -0
  604. package/src/sync/collections-contributor.ts +173 -0
  605. package/src/sync/config-contributor.ts +100 -0
  606. package/src/sync/config-merge.ts +229 -0
  607. package/src/sync/controller.ts +139 -28
  608. package/src/sync/core-contributors.ts +8 -1583
  609. package/src/sync/history-memo.ts +32 -0
  610. package/src/sync/layout-merge.ts +259 -0
  611. package/src/sync/sanitize.ts +114 -0
  612. package/src/sync/ticker-merge.ts +208 -0
  613. package/src/sync/ticker-payload.ts +81 -0
  614. package/src/sync/types.ts +15 -1
  615. package/src/telemetry/attention-setting.ts +1 -1
  616. package/src/telemetry/usage-counts.ts +16 -0
  617. package/src/test-support/preload.ts +9 -0
  618. package/src/theme/color-utils.ts +10 -0
  619. package/src/theme/colors.ts +9 -1
  620. package/src/theme/font-scale.ts +34 -3
  621. package/src/theme/series-colors.ts +44 -0
  622. package/src/theme/themes.ts +64 -16
  623. package/src/theme/tone-contrast.ts +40 -0
  624. package/src/theme/ui-tokens.ts +23 -3
  625. package/src/tickers/batched-lookups.ts +314 -8
  626. package/src/tickers/company-name-listing.ts +198 -14
  627. package/src/tickers/company-name.ts +37 -8
  628. package/src/tickers/list.ts +7 -0
  629. package/src/tickers/search/home-listing.ts +31 -9
  630. package/src/tickers/search/index.ts +13 -3
  631. package/src/tickers/search/listing-index.ts +558 -0
  632. package/src/tickers/search/major-listings.chunk.ts +10 -0
  633. package/src/tickers/search/major-listings.json +3346 -0
  634. package/src/tickers/search/ranking.ts +68 -1
  635. package/src/tickers/search/types.ts +4 -0
  636. package/src/tickers/search/upsert.ts +16 -1
  637. package/src/tickers/terminal-codes.ts +26 -1
  638. package/src/time-series/base-series.ts +18 -4
  639. package/src/time-series/calendar-month-returns.ts +47 -0
  640. package/src/time-series/currency-conversion.ts +130 -0
  641. package/src/time-series/hooks.ts +2 -0
  642. package/src/time-series/price-comparison.ts +34 -11
  643. package/src/time-series/resolve-context.ts +3 -0
  644. package/src/time-series/resolve.ts +14 -2
  645. package/src/time-series/spec.ts +1 -0
  646. package/src/time-series/studies/indicators.ts +7 -2
  647. package/src/time-series/studies/resolve.ts +1 -1
  648. package/src/time-series/types.ts +14 -0
  649. package/src/types/config.ts +8 -0
  650. package/src/types/data-provider.ts +28 -0
  651. package/src/types/financials.ts +38 -2
  652. package/src/types/headless.ts +23 -0
  653. package/src/ui/host.tsx +34 -3
  654. package/src/ui/index.tsx +1 -0
  655. package/src/utils/concurrency.ts +6 -0
  656. package/src/utils/currency-pair.ts +56 -4
  657. package/src/utils/datetime-format.ts +28 -3
  658. package/src/utils/decimal-comma.ts +9 -6
  659. package/src/utils/display-number.ts +15 -0
  660. package/src/utils/double-escape-close.ts +61 -16
  661. package/src/utils/exchanges.ts +32 -0
  662. package/src/utils/float32-price.ts +24 -0
  663. package/src/utils/forward-dividend.ts +81 -16
  664. package/src/utils/fundamentals.ts +41 -0
  665. package/src/utils/fx-market-hours.ts +11 -0
  666. package/src/utils/markdown.ts +4 -2
  667. package/src/utils/pasted-lines.ts +14 -0
  668. package/src/utils/plugin-proxy-hosts.json +2 -1
  669. package/src/utils/price-history.ts +7 -6
  670. package/src/utils/price-window.ts +2 -1
  671. package/src/utils/report-timing.ts +62 -0
  672. package/src/utils/sec-filings.ts +49 -0
  673. package/src/utils/sec.ts +4 -23
  674. package/src/utils/shortcut-labels.ts +6 -30
  675. package/src/utils/utc-time.ts +5 -0
@@ -0,0 +1,682 @@
1
+ /**
2
+ * Reads a broker's positions export (the CSV a brokerage's positions or
3
+ * holdings page downloads) into the positions it lists: shares, cost and,
4
+ * where the file has one, the purchase date. Fidelity, Schwab, Vanguard,
5
+ * E*TRADE and Merrill are recognised by their columns; any other file works
6
+ * when it has a Symbol (or Ticker) and a Quantity (or Shares) column.
7
+ *
8
+ * Rows that are not a holding of a security are left out: cash and money
9
+ * market sweeps, pending activity, totals, account titles and footers.
10
+ * Options and bonds are listed as skipped with the reason, never read as
11
+ * shares of a stock.
12
+ */
13
+ import { readCalendarDate } from "../../utils/calendar-date";
14
+ import { isCurrencyCode } from "../../utils/currency-pair";
15
+ import { normalizeHeldCurrencyCode, resolveCurrencyUnit } from "../../utils/currency-units";
16
+
17
+ export type PositionsLayoutId = "fidelity" | "schwab" | "vanguard" | "etrade" | "merrill" | "generic";
18
+
19
+ /** How each layout is named to the person importing it. */
20
+ export const POSITIONS_LAYOUT_NAMES: Readonly<Record<PositionsLayoutId, string>> = {
21
+ fidelity: "Fidelity positions export",
22
+ schwab: "Schwab positions export",
23
+ vanguard: "Vanguard holdings export",
24
+ etrade: "E*TRADE portfolio export",
25
+ merrill: "Merrill holdings export",
26
+ generic: "Positions table",
27
+ };
28
+
29
+ /** The broker exports recognised by their columns, in the order the help names them. */
30
+ export const POSITIONS_EXPORT_BROKERS = ["Fidelity", "Schwab", "Vanguard", "E*TRADE", "Merrill"] as const;
31
+
32
+ /** A holding the file lists, its rows of one symbol added up. */
33
+ export interface FilePosition {
34
+ /** The symbol as the file writes it, cleaned of marks (BRK/B reads BRK.B). */
35
+ symbol: string;
36
+ description: string | null;
37
+ /** Signed: a negative count is a short. */
38
+ shares: number;
39
+ /** Cost per share in `currency`, when the file gives a cost (per share, in total, or as value less gain). */
40
+ avgCost: number | null;
41
+ /** The cost's currency when the file says it (US brokers' exports are in USD); null for the listing's. */
42
+ currency: string | null;
43
+ /** YYYY-MM-DD; with several rows, the earliest. */
44
+ dateAcquired: string | null;
45
+ /** The file's lines (from 1) the position was read from. */
46
+ lines: number[];
47
+ }
48
+
49
+ /** Why a row is not imported: one of `SKIP_REASONS`, or a symbol that did not resolve to a listing. */
50
+ export type SkipKind = keyof typeof SKIP_REASONS | "lookup";
51
+
52
+ /** A row that names something but is not imported, and why. */
53
+ export interface SkippedFileRow {
54
+ line: number;
55
+ /** The symbol, else the description, as the file writes it. */
56
+ label: string;
57
+ reason: string;
58
+ kind: SkipKind;
59
+ /** The row's symbol, cleaned, when it has one: a holding of it is never removed by a replace. */
60
+ symbol: string | null;
61
+ }
62
+
63
+ export interface PositionsFile {
64
+ layout: PositionsLayoutId;
65
+ positions: FilePosition[];
66
+ skipped: SkippedFileRow[];
67
+ }
68
+
69
+ /** Why a file has no positions to import: no positions table, only activity, too many positions, or none. */
70
+ export type PositionsFileProblem = "no-table" | "activity" | "too-many" | "empty";
71
+
72
+ export class PositionsFileError extends Error {
73
+ constructor(message: string, readonly problem: PositionsFileProblem) {
74
+ super(message);
75
+ this.name = "PositionsFileError";
76
+ }
77
+ }
78
+
79
+ /** The largest export read: a brokerage's positions file is kilobytes, so anything bigger is the wrong file. */
80
+ export const MAX_POSITIONS_FILE_BYTES = 5 * 1024 * 1024;
81
+
82
+ /** The most positions one import takes: every symbol is looked up, and the preview lists each. */
83
+ export const MAX_IMPORT_POSITIONS = 1000;
84
+
85
+ /** The reasons a row is skipped, as they are shown. */
86
+ export const SKIP_REASONS = {
87
+ cash: "cash or money market",
88
+ pending: "pending activity",
89
+ option: "option",
90
+ bond: "bond or CD",
91
+ noTicker: "no ticker in the file",
92
+ notSymbol: "not a ticker symbol",
93
+ noShares: "no share count",
94
+ zero: "no shares held",
95
+ netZero: "rows net to zero shares",
96
+ currencies: "rows in different currencies",
97
+ } as const;
98
+
99
+ type Role =
100
+ | "symbol" | "description" | "quantity" | "costTotal" | "costPerShare" | "date"
101
+ | "currency" | "securityType" | "value" | "gain" | "cusip";
102
+
103
+ /** Header names each column goes by, lower case, with units ($, #, ($)) taken off. */
104
+ const ROLE_NAMES: Readonly<Record<Role, readonly string[]>> = {
105
+ symbol: ["symbol", "ticker", "ticker symbol", "symbol/cusip", "security symbol", "stock symbol", "trading symbol"],
106
+ description: [
107
+ "description", "security description", "investment name", "investment", "name", "security name", "fund name",
108
+ "fund", "holding", "holding name", "asset name", "company", "company name",
109
+ ],
110
+ quantity: [
111
+ "quantity", "qty", "shares", "units", "share quantity", "quantity held", "shares held", "shares/units",
112
+ "units held", "share balance", "shares owned", "number of shares", "no. of shares",
113
+ ],
114
+ costTotal: [
115
+ "cost basis total", "cost basis", "total cost basis", "total cost", "cost", "book value", "book cost",
116
+ "adjusted cost basis", "adjusted cost", "cost basis amount", "purchase value", "amount invested",
117
+ ],
118
+ costPerShare: [
119
+ "average cost basis", "avg cost basis", "average cost", "avg cost", "avg. cost", "average price", "avg price",
120
+ "average cost per share", "avg cost/share", "cost per share", "cost/share", "cost per unit", "unit cost",
121
+ "average unit cost", "price paid", "purchase price", "buy price", "entry price",
122
+ ],
123
+ date: [
124
+ "date acquired", "acquired", "acquisition date", "acquired date", "acquired on", "purchase date",
125
+ "date purchased", "open date", "date opened", "trade date", "date",
126
+ ],
127
+ currency: ["currency", "ccy", "cost currency", "position currency", "trading currency", "price currency"],
128
+ securityType: [
129
+ "security type", "asset type", "asset class", "security class", "investment type", "product type",
130
+ "asset category", "instrument type",
131
+ ],
132
+ value: ["current value", "market value", "mkt val", "market val", "value", "total value", "ending value", "position value"],
133
+ gain: [
134
+ "unrealized gain/loss", "unrealized gain/loss dollar", "total gain/loss dollar", "total gain/loss", "gain/loss",
135
+ "gain/loss dollar", "gain", "total gain", "unrealized gain", "unrealized p&l", "unrealized p/l",
136
+ ],
137
+ cusip: ["cusip", "cusip number"],
138
+ };
139
+
140
+ const ROLES = Object.keys(ROLE_NAMES) as Role[];
141
+
142
+ /** Columns of an activity export (trades, dividends, transfers): its rows are not holdings. */
143
+ const ACTIVITY_COLUMN = /transaction|^trans code$|^action$|^activity$|^side$|^buy\/sell$|^b\/s$|^trade type$|^order type$|^settlement date$|^process date$|^run date$/;
144
+ /** A plain Type column is a trade's side in a trade history, and a holding's account type (Cash, Margin) in Fidelity's positions. */
145
+ const TYPE_COLUMN = new Set(["type", "kind"]);
146
+ /** A trade's side or an activity's kind. Not Short: Fidelity's Type says a holding is short. */
147
+ const TRADE_SIDE = /^(?:buy|sell|bought|sold|you bought|you sold|b|s|buy to (?:open|close|cover)|sell (?:short|to (?:open|close))|short sell|dividend|reinvest(?:ment)?|interest|deposit|withdrawal|transfer)$/i;
148
+
149
+ /** The broker exports' default currency: their positions are in US dollars. */
150
+ const US_LAYOUTS: ReadonlySet<PositionsLayoutId> = new Set(["fidelity", "schwab", "vanguard", "etrade", "merrill"]);
151
+
152
+ /** A US brokerage's export, whose accounts hold US listings in US dollars. */
153
+ export function isUsBrokerLayout(layout: PositionsLayoutId): boolean {
154
+ return US_LAYOUTS.has(layout);
155
+ }
156
+
157
+ const TOTAL_ROW = /^(?:account|grand|positions|portfolio|overall)?\s*totals?\b|\btotals?:?$/i;
158
+ const PENDING_ROW = /^pending\b/i;
159
+ const CASH_SYMBOL = /^(?:cash|cash & cash investments|cash and cash investments|cash & money market|cash and money market|money market|money market funds?|core position|cash balance|sweep|bank sweep|fcash)$/i;
160
+ const CASH_TYPE = /^(?:cash|cash and money market|cash & money market|money market|sweep)\b/i;
161
+ const CASH_DESCRIPTION = /money market|cash reserves|held in money market|bank deposit|deposit program|deposit sweep|sweep program|insured deposit/i;
162
+ /** Fidelity ` -AAPL250117C200`, the OCC `AAPL 250117C00200000`, Schwab `AAPL 01/17/2025 200.00 C`, E*TRADE `AAPL Jan 17 '25 $200 Call`. */
163
+ const OPTION_SYMBOLS = [
164
+ /^-?[A-Z]{1,6}\d{6}[CP]\d+(?:\.\d+)?$/,
165
+ /^[A-Z]{1,6}\s*\d{6}[CP]\d{8}$/,
166
+ /^[A-Z./]{1,8} \d{1,2}\/\d{1,2}\/\d{2,4} \$?\d+(?:\.\d+)? [CP]$/,
167
+ /^[A-Z./]{1,8} [A-Z]{3} \d{1,2} '?\d{2,4} \$?\d+(?:\.\d+)? (?:CALL|PUT)$/,
168
+ ];
169
+ const OPTION_TYPE = /\boptions?\b/i;
170
+ const BOND_TYPE = /^(?:fixed income|bonds?|treasur(?:y|ies)|cds?|certificates? of deposit|brokered cds?|municipal(?: bonds?)?|corporate bonds?|government bonds?|agency bonds?)\b/i;
171
+ /** A CUSIP where a ticker should be: a security with no ticker, which a broker's export means a bond or CD. */
172
+ const CUSIP = /^[0-9]{3}[0-9A-Z]{5}[0-9]$/;
173
+ const SYMBOL = /^[A-Z0-9^][A-Z0-9.\-=^:]{0,19}$/;
174
+ /** A symbol cell with nothing else on its row, read as a ticker only when written as one: upper case and short. */
175
+ const LONE_TICKER = /^[A-Z][A-Z0-9.\-/]{0,9}$/;
176
+
177
+ /**
178
+ * The longest cell each reading looks at. A file can hold anything; past
179
+ * these lengths a cell is no column name, number, date or ticker, and is not
180
+ * searched, so no cell costs more than its length.
181
+ */
182
+ const MAX_HEADER_CELL = 80;
183
+ const MAX_NUMBER_CELL = 40;
184
+ const MAX_SYMBOL_CELL = 40;
185
+ const MAX_LABEL = 60;
186
+
187
+ function clip(text: string): string {
188
+ return text.length > MAX_LABEL ? `${text.slice(0, MAX_LABEL - 1).trimEnd()}…` : text;
189
+ }
190
+
191
+ function headerNames(cell: string): string[] {
192
+ if (cell.length > MAX_HEADER_CELL) return [];
193
+ const raw = cell.replace(/\s+/g, " ").trim().toLowerCase();
194
+ // A percent column (Gain %) is never a share count, a cost or a value.
195
+ if (!raw || raw.includes("%")) return [];
196
+ const names = new Set<string>();
197
+ const add = (value: string | undefined) => {
198
+ const name = (value ?? "").replace(/\(\s*[$#]\s*\)/g, "").replace(/[$#*:]/g, "").replace(/\s+/g, " ").trim();
199
+ if (name) names.add(name);
200
+ };
201
+ add(raw);
202
+ // Schwab: "Qty (Quantity)", "Mkt Val (Market Value)".
203
+ const paren = /^(.*?)\((.*)\)\s*$/.exec(raw);
204
+ if (paren) {
205
+ add(paren[1]);
206
+ add(paren[2]);
207
+ }
208
+ return [...names];
209
+ }
210
+
211
+ interface Header {
212
+ columns: Partial<Record<Role, number>>;
213
+ /** Every name the header's cells go by, for telling the layouts apart. */
214
+ names: Set<string>;
215
+ activity: boolean;
216
+ /** A plain Type column, which makes the table a trade history when it holds buys and sells. */
217
+ typeColumn: number | null;
218
+ }
219
+
220
+ /**
221
+ * Each role's column is the one with its most specific name, wherever it
222
+ * stands: Trade Date before Date, Average Cost before Cost. A column serves
223
+ * one role.
224
+ */
225
+ function assignRoles(cellNames: readonly (readonly string[])[]): Partial<Record<Role, number>> {
226
+ const columns: Partial<Record<Role, number>> = {};
227
+ const taken = new Set<number>();
228
+ for (const role of ROLES) {
229
+ let best = -1;
230
+ let bestRank = Infinity;
231
+ for (let index = 0; index < cellNames.length; index += 1) {
232
+ if (taken.has(index)) continue;
233
+ for (const name of cellNames[index]!) {
234
+ const rank = ROLE_NAMES[role].indexOf(name);
235
+ if (rank >= 0 && rank < bestRank) {
236
+ best = index;
237
+ bestRank = rank;
238
+ }
239
+ }
240
+ }
241
+ if (best >= 0) {
242
+ columns[role] = best;
243
+ taken.add(best);
244
+ }
245
+ }
246
+ return columns;
247
+ }
248
+
249
+ function readHeader(cells: readonly string[]): Header | null {
250
+ const filled = cells.filter((cell) => cell.trim());
251
+ if (filled.length < 2 || filled.some((cell) => readNumber(cell, false) !== null)) return null;
252
+ const cellNames = cells.map(headerNames);
253
+ const names = new Set(cellNames.flat());
254
+ const columns = assignRoles(cellNames);
255
+ const typeIndex = cellNames.findIndex((list) => list.some((name) => TYPE_COLUMN.has(name)));
256
+ const typeColumn = typeIndex >= 0 ? typeIndex : null;
257
+ // An activity table starts a section of its own, so its rows never read as holdings of the table above it.
258
+ if (filled.length >= 3 && [...names].some((name) => ACTIVITY_COLUMN.test(name))) return { columns, names, activity: true, typeColumn };
259
+ const holdings = (columns.symbol !== undefined || columns.description !== undefined) && columns.quantity !== undefined;
260
+ return holdings ? { columns, names, activity: false, typeColumn } : null;
261
+ }
262
+
263
+ function layoutOf(names: ReadonlySet<string>, schwabTitle: boolean): PositionsLayoutId {
264
+ const has = (name: string) => names.has(name);
265
+ if (has("account number") && has("last price") && has("current value")) return "fidelity";
266
+ if (has("investment name") && has("share price") && has("total value")) return "vanguard";
267
+ if (has("price paid") && has("last price")) return "etrade";
268
+ if (has("cob date") || (has("security description") && has("cusip") && has("account registration"))) return "merrill";
269
+ if (schwabTitle || (has("security type") && (has("mkt val") || has("market value")) && has("cost basis"))) return "schwab";
270
+ return "generic";
271
+ }
272
+
273
+ interface CsvRecord {
274
+ line: number;
275
+ cells: string[];
276
+ }
277
+
278
+ /** RFC 4180 records: quoted cells may hold the delimiter, doubled quotes and line breaks. */
279
+ function readRecords(text: string, delimiter: string): CsvRecord[] {
280
+ const records: CsvRecord[] = [];
281
+ let cells: string[] = [];
282
+ let cell = "";
283
+ let quoted = false;
284
+ let line = 1;
285
+ let start = 1;
286
+ const endCell = () => {
287
+ cells.push(cell.trim());
288
+ cell = "";
289
+ };
290
+ const endRecord = () => {
291
+ endCell();
292
+ records.push({ line: start, cells });
293
+ cells = [];
294
+ };
295
+ for (let index = 0; index < text.length; index += 1) {
296
+ const char = text[index]!;
297
+ if (quoted) {
298
+ if (char === "\"") {
299
+ if (text[index + 1] === "\"") {
300
+ cell += "\"";
301
+ index += 1;
302
+ } else {
303
+ quoted = false;
304
+ }
305
+ } else {
306
+ if (char === "\n") line += 1;
307
+ cell += char;
308
+ }
309
+ continue;
310
+ }
311
+ if (char === "\"") {
312
+ quoted = true;
313
+ } else if (char === delimiter) {
314
+ endCell();
315
+ } else if (char === "\n" || char === "\r") {
316
+ if (char === "\r" && text[index + 1] === "\n") index += 1;
317
+ endRecord();
318
+ line += 1;
319
+ start = line;
320
+ } else {
321
+ cell += char;
322
+ }
323
+ }
324
+ if (cell || cells.length > 0) endRecord();
325
+ return records;
326
+ }
327
+
328
+ /**
329
+ * A number as the exports write one: `$1,234.56`, `+$1.14`, `-$2.97`,
330
+ * `(1,234.56)`, `1,000`; with a decimal comma, `1.234,56`. Null for `--`,
331
+ * `n/a`, `Incomplete` and anything else that is not a number.
332
+ */
333
+ function readNumber(text: string, decimalComma: boolean): number | null {
334
+ if (text.length > MAX_NUMBER_CELL) return null;
335
+ let value = text.trim();
336
+ if (!value) return null;
337
+ let negative = false;
338
+ if (/^\(.*\)$/.test(value)) {
339
+ negative = true;
340
+ value = value.slice(1, -1).trim();
341
+ }
342
+ value = value.replace(/[$€£¥\s]/g, "");
343
+ if (value.startsWith("+")) value = value.slice(1);
344
+ if (value.startsWith("-")) {
345
+ negative = !negative;
346
+ value = value.slice(1);
347
+ }
348
+ if (decimalComma) {
349
+ if (!/^\d{1,3}(?:\.\d{3})+(?:,\d+)?$|^\d*(?:,\d+)?$/.test(value)) return null;
350
+ value = value.replace(/\./g, "").replace(",", ".");
351
+ } else {
352
+ if (!/^\d{1,3}(?:,\d{3})+(?:\.\d*)?$|^\d*\.?\d*$/.test(value)) return null;
353
+ value = value.replace(/,/g, "");
354
+ }
355
+ if (!/\d/.test(value)) return null;
356
+ const number = Number(value);
357
+ if (!Number.isFinite(number)) return null;
358
+ return negative ? -number : number;
359
+ }
360
+
361
+ /** No date is longer: a longer cell is not one, and is not searched. */
362
+ const MAX_DATE_CELL = 40;
363
+ const SLASHED_DATE = /^(\d{1,2})\/(\d{1,2})\/(\d{2}|\d{4})$/;
364
+
365
+ /**
366
+ * A purchase date as YYYY-MM-DD. A slashed date is read month first
367
+ * (1/15/2025) or, in a file that writes the day first, day first
368
+ * (15/1/2025); a part over 12 says which it is either way. A day after today
369
+ * is no purchase date.
370
+ */
371
+ function readFileDate(text: string, now: Date, dayFirst: boolean): string | null {
372
+ if (text.length > MAX_DATE_CELL) return null;
373
+ const value = text.trim().split(/\s+(?=\d{1,2}:\d{2})/)[0] ?? "";
374
+ if (!value) return null;
375
+ const slashed = SLASHED_DATE.exec(value);
376
+ let date: string | null;
377
+ if (slashed) {
378
+ const [first, second] = [Number(slashed[1]), Number(slashed[2])];
379
+ const year = slashed[3]!.length === 2 ? 2000 + Number(slashed[3]) : Number(slashed[3]);
380
+ const [month, day] = first > 12 || (dayFirst && second <= 12) ? [second, first] : [first, second];
381
+ date = readCalendarDate(`${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`);
382
+ } else {
383
+ date = readCalendarDate(value);
384
+ }
385
+ return date && date <= now.toISOString().slice(0, 10) ? date : null;
386
+ }
387
+
388
+ function readCurrency(text: string): string | null {
389
+ const raw = text.trim();
390
+ if (!raw || raw.length > 8) return null;
391
+ const code = normalizeHeldCurrencyCode(raw);
392
+ // Pence (GBp, GBX) are a unit of the pound, kept as the file writes them.
393
+ if (resolveCurrencyUnit(code).divisor !== 1) return code;
394
+ return /^[A-Z]{3}$/.test(code) && isCurrencyCode(code) ? code : null;
395
+ }
396
+
397
+ /** The symbol cleaned of the marks exports add: Fidelity's `**` core money market, Schwab's `BRK/B`. */
398
+ function cleanSymbol(text: string): string {
399
+ // Too long for a ticker: kept as written, so it is skipped as not one.
400
+ if (text.length > MAX_SYMBOL_CELL) return text.trim().toUpperCase();
401
+ const symbol = text.trim().replace(/\*+$/, "").toUpperCase();
402
+ if (!symbol || /^-+$/.test(symbol) || /^n\/?a$/i.test(symbol)) return "";
403
+ return symbol.replace(/\//g, ".");
404
+ }
405
+
406
+ interface ReadRow {
407
+ line: number;
408
+ symbol: string;
409
+ description: string | null;
410
+ shares: number;
411
+ avgCost: number | null;
412
+ currency: string | null;
413
+ dateAcquired: string | null;
414
+ }
415
+
416
+ type RowReading = { kind: "position"; row: ReadRow } | { kind: "skipped"; skipped: SkippedFileRow } | { kind: "ignored" };
417
+
418
+ interface RowOptions {
419
+ decimalComma: boolean;
420
+ dayFirst: boolean;
421
+ defaultCurrency: string | null;
422
+ now: Date;
423
+ }
424
+
425
+ function readRow(record: CsvRecord, header: Header, options: RowOptions): RowReading {
426
+ const { cells, line } = record;
427
+ const cell = (role: Role) => {
428
+ const index = header.columns[role];
429
+ return index === undefined ? "" : (cells[index] ?? "").trim();
430
+ };
431
+ const filled = cells.filter((value) => value.trim() && !/^-+$/.test(value.trim()));
432
+ const rawSymbol = cell("symbol");
433
+ // Blank rows, account titles ("Individual ...321") and footers fill one cell at most. A ticker
434
+ // alone (KO with -- for its shares) is a holding the file could not count, skipped as one.
435
+ if (filled.length < 2 && !(filled.length === 1 && filled[0] === rawSymbol && LONE_TICKER.test(rawSymbol))) return { kind: "ignored" };
436
+ const description = cell("description") || null;
437
+ const type = cell("securityType");
438
+ const lead = rawSymbol || filled[0]!.trim();
439
+ if (TOTAL_ROW.test(lead) || (!rawSymbol && description && TOTAL_ROW.test(description))) return { kind: "ignored" };
440
+ const symbol = cleanSymbol(rawSymbol);
441
+ const label = clip((symbol ? rawSymbol : description) || lead);
442
+ const skip = (kind: keyof typeof SKIP_REASONS): RowReading => ({
443
+ kind: "skipped",
444
+ skipped: { line, label, reason: SKIP_REASONS[kind], kind, symbol: symbol && symbol.length <= MAX_SYMBOL_CELL ? symbol : null },
445
+ });
446
+ if (PENDING_ROW.test(rawSymbol) || (!rawSymbol && description && PENDING_ROW.test(description))) return skip("pending");
447
+ const upper = rawSymbol.trim().toUpperCase();
448
+ if (/\*\*$/.test(rawSymbol) || CASH_SYMBOL.test(rawSymbol) || CASH_TYPE.test(type) || (description && CASH_DESCRIPTION.test(description))) {
449
+ return skip("cash");
450
+ }
451
+ if (OPTION_TYPE.test(type) || OPTION_SYMBOLS.some((pattern) => pattern.test(upper))
452
+ || (description && /\b(?:call|put)\b/i.test(description) && /\d/.test(upper) && upper.length > 6)) {
453
+ return skip("option");
454
+ }
455
+ const coupon = !!description && /\d(?:\.\d+)?\s*%/.test(description) && /\b\d{1,2}\/\d{1,2}\/\d{2,4}\b/.test(description);
456
+ if (BOND_TYPE.test(type) || CUSIP.test(symbol) || (!symbol && coupon)) return skip("bond");
457
+ if (!symbol) return skip("noTicker");
458
+ if (!SYMBOL.test(symbol)) return skip("notSymbol");
459
+ const shares = readNumber(cell("quantity"), options.decimalComma);
460
+ if (shares === null) return skip("noShares");
461
+ if (shares === 0) return skip("zero");
462
+ const magnitude = Math.abs(shares);
463
+ const perShare = readNumber(cell("costPerShare"), options.decimalComma);
464
+ const total = readNumber(cell("costTotal"), options.decimalComma);
465
+ const value = readNumber(cell("value"), options.decimalComma);
466
+ const gain = readNumber(cell("gain"), options.decimalComma);
467
+ // Merrill gives no cost column: the cost is the value less the unrealized gain.
468
+ const avgCost = perShare !== null && perShare !== 0 ? Math.abs(perShare)
469
+ : total !== null && total !== 0 ? tidy(Math.abs(total) / magnitude)
470
+ : value !== null && gain !== null && value - gain !== 0 ? tidy(Math.abs(value - gain) / magnitude)
471
+ : null;
472
+ return {
473
+ kind: "position",
474
+ row: {
475
+ line,
476
+ symbol,
477
+ description,
478
+ shares,
479
+ avgCost,
480
+ currency: readCurrency(cell("currency")) ?? options.defaultCurrency,
481
+ dateAcquired: readFileDate(cell("date"), options.now, options.dayFirst),
482
+ },
483
+ };
484
+ }
485
+
486
+ /** Drops the float noise of a sum (0.1 + 0.2) without losing a digit the file wrote. */
487
+ function tidy(value: number): number {
488
+ return Number(value.toPrecision(15));
489
+ }
490
+
491
+ /** Several accounts or lots of one symbol are one position: shares added up, cost by shares, the earliest date. */
492
+ function mergeRows(rows: readonly ReadRow[]): { position: FilePosition } | { skipped: SkippedFileRow[] } {
493
+ const first = rows[0]!;
494
+ const skipAll = (kind: SkipKind, reason: string) => ({
495
+ skipped: rows.map((row) => ({ line: row.line, label: row.symbol, reason, kind, symbol: row.symbol })),
496
+ });
497
+ const currencies = new Set(rows.map((row) => row.currency ?? ""));
498
+ if (currencies.size > 1) return skipAll("currencies", `${SKIP_REASONS.currencies} (${[...currencies].map((code) => code || "none").join(", ")})`);
499
+ const shares = tidy(rows.reduce((sum, row) => sum + row.shares, 0));
500
+ if (shares === 0) return skipAll("netZero", SKIP_REASONS.netZero);
501
+ const held = rows.reduce((sum, row) => sum + Math.abs(row.shares), 0);
502
+ const costed = rows.every((row) => row.avgCost !== null);
503
+ const avgCost = rows.length === 1 ? first.avgCost
504
+ : costed ? tidy(rows.reduce((sum, row) => sum + row.avgCost! * Math.abs(row.shares), 0) / held) : null;
505
+ const dates = rows.map((row) => row.dateAcquired).filter((date): date is string => !!date).sort();
506
+ return {
507
+ position: {
508
+ symbol: first.symbol,
509
+ description: rows.find((row) => row.description)?.description ?? null,
510
+ shares,
511
+ avgCost,
512
+ currency: first.currency,
513
+ dateAcquired: dates[0] ?? null,
514
+ lines: rows.map((row) => row.line),
515
+ },
516
+ };
517
+ }
518
+
519
+ interface Section {
520
+ header: Header;
521
+ records: CsvRecord[];
522
+ }
523
+
524
+ function readSections(records: readonly CsvRecord[]): { sections: Section[]; schwabTitle: boolean } {
525
+ const sections: Section[] = [];
526
+ let schwabTitle = false;
527
+ let current: Section | null = null;
528
+ for (const record of records) {
529
+ if (/^positions for\b/i.test(record.cells[0] ?? "")) schwabTitle = true;
530
+ const header = readHeader(record.cells);
531
+ if (header) {
532
+ current = { header, records: [] };
533
+ sections.push(current);
534
+ continue;
535
+ }
536
+ current?.records.push(record);
537
+ }
538
+ return { sections, schwabTitle };
539
+ }
540
+
541
+ function pickDelimiter(text: string): { delimiter: string; records: CsvRecord[] } {
542
+ let fallback: { delimiter: string; records: CsvRecord[] } | null = null;
543
+ for (const delimiter of [",", "\t", ";"]) {
544
+ const records = readRecords(text, delimiter);
545
+ fallback ??= { delimiter, records };
546
+ if (records.some((record) => readHeader(record.cells))) return { delimiter, records };
547
+ }
548
+ return fallback!;
549
+ }
550
+
551
+ const NUMBER_ROLES: readonly Role[] = ["quantity", "costTotal", "costPerShare", "value", "gain"];
552
+ /** Numbers only a decimal comma reads: 12,5, 0,125, 1,2345, 1.234,56, 1.234.567. */
553
+ const DECIMAL_COMMA_ONLY = /^\d+,\d{1,2}$|^0,\d+$|^\d+,\d{4,}$|^\d{1,3}(?:\.\d{3})+,\d+$|^\d{1,3}(?:\.\d{3}){2,}$/;
554
+ /** Numbers only a decimal point reads: 12.5, 0.125, 1.2345, 1,234.56, 1,234,567. */
555
+ const DECIMAL_POINT_ONLY = /^\d*\.\d{1,2}$|^0\.\d+$|^\d*\.\d{4,}$|^\d{1,3}(?:,\d{3})+\.\d+$|^\d{1,3}(?:,\d{3}){2,}$/;
556
+
557
+ function numberBody(cell: string): string {
558
+ return cell.trim().replace(/^\((.*)\)$/, "$1").replace(/[$€£¥\s]/g, "").replace(/^[+-]/, "");
559
+ }
560
+
561
+ /**
562
+ * Whether a file split by tabs or semicolons writes its numbers with a
563
+ * decimal comma (1.234,56). Only a number no decimal point could mean says
564
+ * so: 1,500 is read as fifteen hundred, as a US export means it, unless the
565
+ * file also writes 12,5 or 1.234,56 and never 12.50.
566
+ */
567
+ function usesDecimalComma(delimiter: string, sections: readonly Section[]): boolean {
568
+ if (delimiter === ",") return false;
569
+ let comma = false;
570
+ for (const section of sections) {
571
+ const indexes = NUMBER_ROLES.flatMap((role) => section.header.columns[role] ?? []);
572
+ for (const record of section.records) {
573
+ for (const index of indexes) {
574
+ const body = numberBody(record.cells[index] ?? "");
575
+ if (!body) continue;
576
+ if (DECIMAL_POINT_ONLY.test(body)) return false;
577
+ if (DECIMAL_COMMA_ONLY.test(body)) comma = true;
578
+ }
579
+ }
580
+ }
581
+ return comma;
582
+ }
583
+
584
+ /**
585
+ * Whether the file's slashed dates put the day first. A part over 12 says
586
+ * which; a file whose dates never do follows its numbers (a decimal comma
587
+ * writes the day first) and its currencies (a table in none of them USD).
588
+ */
589
+ function writesDayFirst(sections: readonly Section[], decimalComma: boolean, layout: PositionsLayoutId): boolean {
590
+ let dayFirst = false;
591
+ let monthFirst = false;
592
+ let usd = false;
593
+ let otherCurrency = false;
594
+ for (const section of sections) {
595
+ const { date, currency } = section.header.columns;
596
+ for (const record of section.records) {
597
+ const slashed = date === undefined ? null : SLASHED_DATE.exec((record.cells[date] ?? "").trim().split(/\s/)[0] ?? "");
598
+ if (slashed) {
599
+ if (Number(slashed[1]) > 12) dayFirst = true;
600
+ if (Number(slashed[2]) > 12) monthFirst = true;
601
+ }
602
+ const code = currency === undefined ? null : readCurrency(record.cells[currency] ?? "");
603
+ if (code === "USD") usd = true;
604
+ else if (code) otherCurrency = true;
605
+ }
606
+ }
607
+ if (dayFirst !== monthFirst) return dayFirst;
608
+ return decimalComma || (layout === "generic" && otherCurrency && !usd);
609
+ }
610
+
611
+ /** A table whose Type column holds buys and sells is a trade history, whatever its other columns. */
612
+ function listsTrades(section: Section): boolean {
613
+ const index = section.header.typeColumn;
614
+ if (index === null) return false;
615
+ const values = section.records.map((record) => (record.cells[index] ?? "").trim()).filter(Boolean);
616
+ return values.length > 0 && values.filter((value) => TRADE_SIDE.test(value)).length * 2 >= values.length;
617
+ }
618
+
619
+ /**
620
+ * A file's bytes as text: UTF-16 by its byte order mark (Excel's Unicode
621
+ * text) or its zero bytes, UTF-8, else Windows-1252 (Excel's CSV on Windows).
622
+ */
623
+ export function decodePositionsFile(bytes: Uint8Array): string {
624
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(bytes.subarray(2));
625
+ if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(bytes.subarray(2));
626
+ if (bytes.length >= 4 && bytes[0] !== 0 && bytes[1] === 0 && bytes[2] !== 0 && bytes[3] === 0) return new TextDecoder("utf-16le").decode(bytes);
627
+ if (bytes.length >= 4 && bytes[0] === 0 && bytes[1] !== 0 && bytes[2] === 0 && bytes[3] !== 0) return new TextDecoder("utf-16be").decode(bytes);
628
+ try {
629
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
630
+ } catch {
631
+ return new TextDecoder("windows-1252").decode(bytes);
632
+ }
633
+ }
634
+
635
+ /**
636
+ * The positions a broker's export lists, and the rows it names that are not
637
+ * imported with the reason. Throws `PositionsFileError` when the file has no
638
+ * positions table: no header row with a symbol (or a fund name) and a share
639
+ * count, or only an activity history.
640
+ */
641
+ export function parsePositionsFile(text: string, now = new Date()): PositionsFile {
642
+ const { delimiter, records } = pickDelimiter(text.replace(/^\uFEFF/, ""));
643
+ const { sections, schwabTitle } = readSections(records);
644
+ const holdings = sections.filter((section) => !section.header.activity && !listsTrades(section));
645
+ if (holdings.length === 0) {
646
+ throw sections.length > 0
647
+ ? new PositionsFileError("This is an activity history (trades and transfers), not a positions export. Download the positions or holdings page instead.", "activity")
648
+ : new PositionsFileError("No positions table found: the file needs a header row with a Symbol (or Ticker) column and a Quantity (or Shares) column.", "no-table");
649
+ }
650
+ const layout = layoutOf(holdings[0]!.header.names, schwabTitle);
651
+ const decimalComma = usesDecimalComma(delimiter, holdings);
652
+ const options: RowOptions = {
653
+ decimalComma,
654
+ dayFirst: writesDayFirst(holdings, decimalComma, layout),
655
+ defaultCurrency: US_LAYOUTS.has(layout) ? "USD" : null,
656
+ now,
657
+ };
658
+ const skipped: SkippedFileRow[] = [];
659
+ const bySymbol = new Map<string, ReadRow[]>();
660
+ for (const section of holdings) {
661
+ for (const record of section.records) {
662
+ const reading = readRow(record, section.header, options);
663
+ if (reading.kind === "skipped") skipped.push(reading.skipped);
664
+ if (reading.kind !== "position") continue;
665
+ const rows = bySymbol.get(reading.row.symbol) ?? [];
666
+ rows.push(reading.row);
667
+ bySymbol.set(reading.row.symbol, rows);
668
+ }
669
+ }
670
+ if (bySymbol.size > MAX_IMPORT_POSITIONS) {
671
+ throw new PositionsFileError(`The file lists ${bySymbol.size.toLocaleString("en-US")} positions, and an import takes at most ${MAX_IMPORT_POSITIONS.toLocaleString("en-US")}. Import each account's export on its own.`, "too-many");
672
+ }
673
+ const positions: FilePosition[] = [];
674
+ for (const rows of bySymbol.values()) {
675
+ const merged = mergeRows(rows);
676
+ if ("position" in merged) positions.push(merged.position);
677
+ else skipped.push(...merged.skipped);
678
+ }
679
+ if (positions.length === 0 && skipped.length === 0) throw new PositionsFileError("The positions table has no rows.", "empty");
680
+ skipped.sort((left, right) => left.line - right.line);
681
+ return { layout, positions, skipped };
682
+ }