gloomberb 0.20.13 → 0.20.16

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 (275) hide show
  1. package/package.json +2 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +22 -4
  3. package/src/account/auth-dialog.tsx +22 -4
  4. package/src/account/auth-form.tsx +6 -1
  5. package/src/account/checkout-handoff.tsx +7 -14
  6. package/src/account/device-signin-dialog.tsx +35 -24
  7. package/src/api-client/crypto-markets.ts +10 -0
  8. package/src/api-client/errors.ts +3 -1
  9. package/src/api-client/index.ts +54 -0
  10. package/src/api-client/install-experiments.ts +8 -7
  11. package/src/api-client/money-markets.ts +7 -0
  12. package/src/api-client/paths.ts +2 -1
  13. package/src/api-client/product-waitlist.ts +63 -0
  14. package/src/api-client/request.ts +16 -4
  15. package/src/api-client/types/billing.ts +45 -0
  16. package/src/api-client/yearly-plan.ts +132 -0
  17. package/src/app/global-shortcuts.ts +5 -3
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  20. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  21. package/src/app/since-last-visit/keys.ts +26 -0
  22. package/src/app/since-last-visit/model.ts +266 -0
  23. package/src/app/since-last-visit/strip.tsx +193 -0
  24. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  25. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  26. package/src/app.tsx +15 -0
  27. package/src/architecture/floating-promise-allowlist.json +0 -1
  28. package/src/brokers/signed-in/sign-in-dialog.tsx +38 -38
  29. package/src/cli/commands/market.ts +103 -27
  30. package/src/cli/commands/overview.ts +18 -4
  31. package/src/cli/commands/system.ts +29 -1
  32. package/src/cli/commands/ticker.ts +12 -5
  33. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  34. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  35. package/src/cli/desktop-pane-shot-view.ts +3 -7
  36. package/src/cli/desktop-pane-shot.ts +26 -28
  37. package/src/cli/errors.ts +3 -1
  38. package/src/cli/freshness.ts +7 -2
  39. package/src/cli/glossary.ts +10 -5
  40. package/src/cli/help.ts +1 -0
  41. package/src/cli/helpers.ts +8 -16
  42. package/src/cli/history-export.ts +4 -0
  43. package/src/cli/history-rows.ts +24 -0
  44. package/src/cli/index.ts +4 -0
  45. package/src/cli/known-gaps.ts +2 -2
  46. package/src/cli/listing-arg.ts +79 -11
  47. package/src/cli/not-a-ticker.ts +4 -0
  48. package/src/cli/options.ts +29 -1
  49. package/src/cli/pane-functions/catalog.ts +70 -12
  50. package/src/cli/pane-functions/function-help.ts +1 -1
  51. package/src/cli/pane-functions/headless.ts +68 -3
  52. package/src/cli/pane-functions/index.ts +2 -2
  53. package/src/cli/pane-functions/options.ts +7 -0
  54. package/src/cli/pane-functions/resolver.ts +104 -15
  55. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  56. package/src/cli/report-tables.ts +20 -5
  57. package/src/cli/result.ts +22 -4
  58. package/src/cli/shot-temp-dir.ts +30 -0
  59. package/src/cli/suffixed-listing-rows.ts +11 -0
  60. package/src/cli/symbol-args.ts +5 -3
  61. package/src/cli/symbol-list.ts +23 -10
  62. package/src/cli/symbol-rows.ts +135 -3
  63. package/src/cli/treasury-yields.ts +15 -1
  64. package/src/components/chart/composite/composite-chart.tsx +3 -3
  65. package/src/components/chart/composite/format.ts +2 -1
  66. package/src/components/chart/composite/panel-surface/axis-markers.ts +133 -0
  67. package/src/components/chart/composite/panel-surface/level-labels.tsx +78 -0
  68. package/src/components/chart/composite/panel-surface/overlays.ts +108 -0
  69. package/src/components/chart/composite/panel-surface/pan-coast.ts +54 -0
  70. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +138 -0
  71. package/src/components/chart/composite/panel-surface/panel-levels.ts +47 -0
  72. package/src/components/chart/composite/panel-surface/plot-gestures.ts +403 -0
  73. package/src/components/chart/composite/panel-surface/plot-pointer.ts +65 -0
  74. package/src/components/chart/composite/panel-surface/plot-wheel.ts +102 -0
  75. package/src/components/chart/composite/panel-surface/pointer.ts +12 -0
  76. package/src/components/chart/composite/panel-surface/props.ts +79 -0
  77. package/src/components/chart/composite/panel-surface/tool-readout.ts +151 -0
  78. package/src/components/chart/composite/panel-surface/value-axis-gestures.ts +152 -0
  79. package/src/components/chart/composite/panel-surface.tsx +81 -1177
  80. package/src/components/command-bar/commands/collection-list.ts +1 -0
  81. package/src/components/command-bar/commands/direct/index.ts +31 -8
  82. package/src/components/command-bar/commands/registry.ts +7 -0
  83. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  84. package/src/components/command-bar/routes/root/results.ts +19 -2
  85. package/src/components/command-bar/routes/root/runtime.ts +3 -2
  86. package/src/components/command-bar/routes/root/selection.ts +3 -2
  87. package/src/components/command-bar/routes/root/shortcuts.ts +15 -0
  88. package/src/components/company-logo.tsx +10 -3
  89. package/src/components/data-table/sections.ts +6 -1
  90. package/src/components/layout/pane/title.ts +16 -6
  91. package/src/components/layout/shell/index.tsx +5 -1
  92. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  93. package/src/components/pane-settings-dialog/tui.tsx +6 -3
  94. package/src/components/pane-settings-dialog.tsx +2 -1
  95. package/src/components/pane-template-wizard.tsx +2 -0
  96. package/src/components/ticker/badge/format.ts +12 -3
  97. package/src/components/ticker/badge/index.tsx +9 -3
  98. package/src/components/ticker/list-table-view.tsx +119 -17
  99. package/src/components/ui/choice-dialog.tsx +1 -1
  100. package/src/components/ui/confirm-dialog.tsx +3 -2
  101. package/src/components/ui/data-table/display-columns.ts +16 -0
  102. package/src/components/ui/data-table/index.tsx +40 -9
  103. package/src/components/ui/data-table/types.ts +14 -0
  104. package/src/components/ui/frame.tsx +7 -3
  105. package/src/components/ui/icon.tsx +4 -2
  106. package/src/components/ui/list-view.tsx +8 -0
  107. package/src/components/ui/number-prompt-dialog.tsx +2 -1
  108. package/src/components/use-pane-notice-footer.tsx +3 -1
  109. package/src/core/state/app/layout-reducer.ts +3 -1
  110. package/src/core/state/app/layout.ts +2 -2
  111. package/src/data/config/layout.ts +14 -0
  112. package/src/data/config/store/normalize.ts +11 -1
  113. package/src/docs/snapshot.json +2 -2
  114. package/src/i18n/es.ts +39 -0
  115. package/src/i18n/ja.ts +39 -0
  116. package/src/i18n/ko.ts +39 -0
  117. package/src/i18n/zh-cn.ts +39 -0
  118. package/src/i18n/zh-tw.ts +39 -0
  119. package/src/layout/pane-follow.ts +141 -4
  120. package/src/layout/pane-layout-move.ts +10 -7
  121. package/src/layout/ticker-navigation.ts +13 -19
  122. package/src/layout/ticker-retarget.ts +3 -2
  123. package/src/market-data/market/format.ts +35 -1
  124. package/src/market-data/market/index-level.ts +19 -0
  125. package/src/market-data/quotes/contributions.ts +13 -0
  126. package/src/market-data/quotes/export-identity.ts +36 -1
  127. package/src/market-data/quotes/resolution.ts +16 -0
  128. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  129. package/src/plugins/builtin/account-management/model.ts +2 -0
  130. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  131. package/src/plugins/builtin/account-management/password-dialog.tsx +2 -2
  132. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  133. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  134. package/src/plugins/builtin/analytics/risk-client.ts +12 -2
  135. package/src/plugins/builtin/analytics/risk-headless.ts +66 -6
  136. package/src/plugins/builtin/analytics/risk-math.ts +23 -6
  137. package/src/plugins/builtin/analytics/risk-model.ts +20 -9
  138. package/src/plugins/builtin/analytics/risk-pane.tsx +2 -2
  139. package/src/plugins/builtin/awards/pane.tsx +6 -8
  140. package/src/plugins/builtin/changelog/index.tsx +6 -44
  141. package/src/plugins/builtin/changelog/versions.ts +17 -68
  142. package/src/plugins/builtin/chart-composer/catalog-inventory.ts +5 -2
  143. package/src/plugins/builtin/chart-composer/editor.tsx +1 -0
  144. package/src/plugins/builtin/chart-composer/pane.tsx +1 -1
  145. package/src/plugins/builtin/chart-composer/quick-add.tsx +4 -1
  146. package/src/plugins/builtin/chart-composer/series-catalog.ts +17 -1
  147. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  148. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  149. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  150. package/src/plugins/builtin/cloud/thesis/module.tsx +2 -0
  151. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +6 -2
  152. package/src/plugins/builtin/cpi/headless.ts +6 -1
  153. package/src/plugins/builtin/cpi/model.ts +17 -0
  154. package/src/plugins/builtin/cpi/pane.tsx +4 -2
  155. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  156. package/src/plugins/builtin/crypto-board/headless.ts +10 -2
  157. package/src/plugins/builtin/crypto-board/model.ts +89 -11
  158. package/src/plugins/builtin/crypto-board/pane.tsx +20 -5
  159. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  160. package/src/plugins/builtin/dividend-yield/client.ts +24 -2
  161. package/src/plugins/builtin/dividend-yield/headless.ts +4 -2
  162. package/src/plugins/builtin/dividend-yield/ranking.ts +2 -1
  163. package/src/plugins/builtin/dividend-yield/view.ts +5 -1
  164. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  165. package/src/plugins/builtin/earnings/board.tsx +36 -16
  166. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  167. package/src/plugins/builtin/earnings/history-table.ts +9 -1
  168. package/src/plugins/builtin/earnings/index.tsx +1 -1
  169. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  170. package/src/plugins/builtin/earnings-ripple/index.tsx +2 -0
  171. package/src/plugins/builtin/econ/calendar-model.ts +17 -1
  172. package/src/plugins/builtin/econ/fred-catalog.ts +33 -4
  173. package/src/plugins/builtin/econ-statistics/headless.ts +21 -0
  174. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  175. package/src/plugins/builtin/exposure/index.tsx +1 -1
  176. package/src/plugins/builtin/macro-day/headless.ts +21 -10
  177. package/src/plugins/builtin/macro-day/model.ts +42 -3
  178. package/src/plugins/builtin/macro-day/pane.tsx +26 -8
  179. package/src/plugins/builtin/macro-day/releases.ts +24 -1
  180. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  181. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  182. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  183. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  184. package/src/plugins/builtin/money-markets/client.ts +4 -1
  185. package/src/plugins/builtin/money-markets/headless.ts +15 -4
  186. package/src/plugins/builtin/money-markets/index.tsx +1 -1
  187. package/src/plugins/builtin/money-markets/pane.tsx +7 -1
  188. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  189. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  190. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -2
  191. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +61 -11
  192. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +11 -3
  193. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  194. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +178 -17
  195. package/src/plugins/builtin/portfolio-list/headless.ts +33 -6
  196. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  197. package/src/plugins/builtin/portfolio-list/pane/index.tsx +95 -18
  198. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +24 -6
  199. package/src/plugins/builtin/portfolio-list/period-pnl.ts +16 -1
  200. package/src/plugins/builtin/portfolio-list/summary/index.tsx +4 -1
  201. package/src/plugins/builtin/portfolio-list/summary/totals.ts +6 -4
  202. package/src/plugins/builtin/portfolio-list/table.tsx +38 -16
  203. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  204. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  205. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  206. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  207. package/src/plugins/builtin/shared/cloud-upgrade.ts +4 -2
  208. package/src/plugins/builtin/shared/cpi-year-gap.ts +67 -0
  209. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  210. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  211. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  212. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +45 -2
  213. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  214. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  215. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  216. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  217. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  218. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  219. package/src/plugins/builtin/ticker-detail/headless.ts +280 -35
  220. package/src/plugins/builtin/ticker-detail/overview/components.tsx +4 -5
  221. package/src/plugins/builtin/ticker-detail/overview/model.ts +9 -2
  222. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +10 -2
  223. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  224. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  225. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  226. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  227. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  228. package/src/portfolio/collection-name.ts +2 -1
  229. package/src/portfolio/column-values.ts +34 -12
  230. package/src/portfolio/listed-symbol.ts +4 -2
  231. package/src/portfolio/period-pnl.ts +51 -1
  232. package/src/portfolio/suffixed-listings.ts +3 -1
  233. package/src/portfolio/watchlist-groups.ts +212 -0
  234. package/src/react/ticker-source.ts +3 -1
  235. package/src/renderers/dom/dialog-host.tsx +5 -5
  236. package/src/renderers/dom/styles.css +7 -0
  237. package/src/renderers/electrobun/view/remote/capability-invoker.ts +1 -1
  238. package/src/renderers/opentui/dialog-host.tsx +3 -4
  239. package/src/sources/gloomberb-cloud/normalizers.ts +5 -0
  240. package/src/sources/provider-router/history.ts +5 -2
  241. package/src/state/app/bootstrap.ts +11 -0
  242. package/src/state/app/context/index.tsx +6 -0
  243. package/src/sync/collections-contributor.ts +5 -2
  244. package/src/sync/config-merge.ts +10 -2
  245. package/src/sync/sanitize.ts +28 -0
  246. package/src/telemetry/usage-counts.ts +17 -0
  247. package/src/test-support/plugin-persistence.ts +12 -0
  248. package/src/tickers/company-name-listing.ts +4 -3
  249. package/src/tickers/company-name.ts +19 -1
  250. package/src/tickers/instrument-coverage.ts +27 -0
  251. package/src/tickers/search/home-listing.ts +38 -1
  252. package/src/tickers/search/index.ts +3 -2
  253. package/src/tickers/search/ranking.ts +21 -2
  254. package/src/time-series/base-series.ts +4 -0
  255. package/src/time-series/chart-seed.ts +1 -1
  256. package/src/time-series/financial-period-coverage.ts +4 -12
  257. package/src/time-series/parsed-history-cache.ts +1 -1
  258. package/src/time-series/resolve.ts +1 -1
  259. package/src/time-series/types.ts +5 -2
  260. package/src/time-series/use-chart-resolution.ts +6 -1
  261. package/src/types/config.ts +32 -0
  262. package/src/types/financials.ts +13 -0
  263. package/src/types/headless.ts +7 -0
  264. package/src/types/plugin-context.ts +5 -0
  265. package/src/types/ticker.ts +14 -0
  266. package/src/ui/ascii-font.ts +1 -4
  267. package/src/ui/dialog-stack.ts +17 -0
  268. package/src/ui/dialog.tsx +6 -2
  269. package/src/utils/async-deadline.ts +2 -2
  270. package/src/utils/crypto-pair.ts +9 -0
  271. package/src/utils/csv.ts +44 -5
  272. package/src/utils/exchanges.ts +13 -0
  273. package/src/utils/financial-statements.ts +60 -3
  274. package/src/utils/futures-generic.ts +17 -0
  275. package/src/utils/trailing-dividend.ts +13 -3
@@ -0,0 +1,359 @@
1
+ import { useCallback, useEffect, useRef, useState, type Ref } from "react";
2
+ import {
3
+ apiClient,
4
+ yearlyRefusalCode,
5
+ type CloudYearlyOffer,
6
+ type CloudYearlyPlanStatus,
7
+ type CloudYearlyResult,
8
+ type CloudYearlyReview,
9
+ } from "../../../api-client";
10
+ import { Button, FieldLabel, KeyValueRow } from "../../../components";
11
+ import { t, tf } from "../../../i18n";
12
+ import { colors } from "../../../theme/colors";
13
+ import { Box, Text, TextAttributes, useRendererHost, type BoxRenderable } from "../../../ui";
14
+ import { formatDetailDate, formatShortDate } from "../../../utils/datetime-format";
15
+
16
+ /**
17
+ * The Pro tab's offer to move a monthly Pro subscription to yearly billing:
18
+ * the offer, the exact review of the charge, and the outcome, all inline.
19
+ * The server decides who may switch and what it costs; the row never says a
20
+ * switch is done before the server reports it paid.
21
+ */
22
+
23
+ /** Exact cents, as on an invoice: $567.29, $630.00. */
24
+ function formatExactUsd(cents: number): string {
25
+ return `$${(cents / 100).toFixed(2)}`;
26
+ }
27
+
28
+ /** Whole dollars when exact, for the offer line: $630, $210. */
29
+ function formatOfferUsd(cents: number): string {
30
+ return cents % 100 === 0 ? `$${cents / 100}` : formatExactUsd(cents);
31
+ }
32
+
33
+ function yearlyOfferText(offer: CloudYearlyOffer): string {
34
+ return tf("Yearly is {yearly} a year, {savings} less than twelve monthly payments of {monthly} ({twelve}).", {
35
+ yearly: formatOfferUsd(offer.yearlyAmount),
36
+ savings: formatOfferUsd(offer.savingsAmount),
37
+ monthly: formatOfferUsd(offer.monthlyAmount),
38
+ twelve: formatOfferUsd(offer.twelveMonthlyAmount),
39
+ });
40
+ }
41
+
42
+ /** What the server's refusals mean here, in the app's language. */
43
+ function refusalMessage(code: string | null): string {
44
+ switch (code) {
45
+ case "review_changed": return t("The total changed since you reviewed it. Review it again.");
46
+ case "review_expired": return t("This total has expired. Review it again.");
47
+ case "review_invalid": return t("This review is no longer valid. Review the switch again.");
48
+ case "busy": return t("Your switch is already going through. Refresh in a moment.");
49
+ case "pending": return t("Your switch to yearly is waiting for its payment.");
50
+ case "unavailable": return t("Yearly billing can't be set up for this plan here. Your plan is unchanged.");
51
+ case "failed": return t("The switch didn't go through and your plan is unchanged. Try again in a minute.");
52
+ default: return t("We couldn't confirm the switch. Refresh your account before trying again.");
53
+ }
54
+ }
55
+
56
+ export type YearlyPlanView =
57
+ | { kind: "hidden" }
58
+ | { kind: "offer"; offer: CloudYearlyOffer }
59
+ | { kind: "review"; review: CloudYearlyReview }
60
+ | { kind: "pending"; invoiceUrl: string | null; expiresAt: string | null }
61
+ | { kind: "result"; result: CloudYearlyResult };
62
+
63
+ /**
64
+ * `onReviewOpened` runs in the same update that shows the review, so the
65
+ * caller can move the keyboard to Not Now before any render has the payment
66
+ * active.
67
+ */
68
+ export function useYearlyPlan(enabled: boolean, sessionMarker: string, onSwitched: () => void, onReviewOpened: () => void) {
69
+ const renderer = useRendererHost();
70
+ const [status, setStatus] = useState<CloudYearlyPlanStatus | null>(null);
71
+ const [review, setReview] = useState<CloudYearlyReview | null>(null);
72
+ const [result, setResult] = useState<CloudYearlyResult | null>(null);
73
+ const [busy, setBusy] = useState<"review" | "confirm" | "invoice" | null>(null);
74
+ const [message, setMessage] = useState<string | null>(null);
75
+ const generation = useRef(0);
76
+ // One confirmation at a time, whatever presses arrive while it is out.
77
+ const confirming = useRef(false);
78
+
79
+ const load = useCallback(async (current: number) => {
80
+ try {
81
+ const next = await apiClient.getCloudYearlyPlan();
82
+ if (generation.current !== current) return;
83
+ setStatus(next);
84
+ // A payment the row was waiting on is now the server's status to tell.
85
+ setResult((shown) => shown?.state === "switched" ? shown : null);
86
+ } catch {
87
+ // Intentional ignore: without an answer the row stays hidden; the plan is unchanged.
88
+ if (generation.current === current) setStatus(null);
89
+ }
90
+ }, []);
91
+
92
+ useEffect(() => {
93
+ const current = ++generation.current;
94
+ setStatus(null);
95
+ setReview(null);
96
+ setBusy(null);
97
+ setMessage(null);
98
+ if (enabled) void load(current).catch(() => setStatus(null));
99
+ else setResult((shown) => shown?.state === "switched" ? shown : null);
100
+ return () => { generation.current++; };
101
+ }, [enabled, sessionMarker, load]);
102
+
103
+ const openReview = useCallback(async () => {
104
+ if (busy) return;
105
+ const current = generation.current;
106
+ setBusy("review");
107
+ setMessage(null);
108
+ try {
109
+ const next = await apiClient.previewCloudYearlyPlan();
110
+ if (generation.current === current) {
111
+ // One batched update: a key held down never finds Pay active on open.
112
+ setReview(next);
113
+ onReviewOpened();
114
+ }
115
+ } catch (error) {
116
+ if (generation.current !== current) return;
117
+ const code = yearlyRefusalCode(error);
118
+ setMessage(code ? refusalMessage(code) : t("Couldn't work out the yearly total. Try again in a minute."));
119
+ if (code) await load(current);
120
+ } finally {
121
+ if (generation.current === current) setBusy(null);
122
+ }
123
+ }, [busy, load, onReviewOpened]);
124
+
125
+ const confirm = useCallback(async () => {
126
+ if (!review || confirming.current) return;
127
+ confirming.current = true;
128
+ const current = generation.current;
129
+ setBusy("confirm");
130
+ setMessage(null);
131
+ try {
132
+ const answer = await apiClient.confirmCloudYearlyPlan(review.token);
133
+ if (generation.current !== current) return;
134
+ setReview(null);
135
+ setResult(answer);
136
+ if (answer.state === "switched") onSwitched();
137
+ } catch (error) {
138
+ if (generation.current !== current) return;
139
+ const code = yearlyRefusalCode(error);
140
+ setMessage(refusalMessage(code));
141
+ // A total that moved or ran out: show the new one, never charge the old.
142
+ if (code !== "busy") {
143
+ setReview(null);
144
+ await load(current);
145
+ }
146
+ } finally {
147
+ confirming.current = false;
148
+ if (generation.current === current) setBusy(null);
149
+ }
150
+ }, [load, onSwitched, review]);
151
+
152
+ const dismiss = useCallback(() => {
153
+ if (busy === "confirm") return;
154
+ setReview(null);
155
+ setMessage(null);
156
+ }, [busy]);
157
+
158
+ const pendingUrl = result?.state === "payment_required"
159
+ ? result.invoiceUrl
160
+ : status?.state === "pending" ? status.invoiceUrl : null;
161
+ const openInvoice = useCallback(async () => {
162
+ if (!pendingUrl || busy) return;
163
+ const current = generation.current;
164
+ setBusy("invoice");
165
+ try {
166
+ const opened = await renderer.openExternal(pendingUrl);
167
+ if (generation.current === current) {
168
+ setMessage(opened === false ? t("Could not open invoice payment. Try again.") : t("Invoice opened in your browser."));
169
+ }
170
+ } catch {
171
+ if (generation.current === current) setMessage(t("Could not open invoice payment. Try again."));
172
+ } finally {
173
+ if (generation.current === current) setBusy(null);
174
+ }
175
+ }, [busy, pendingUrl, renderer]);
176
+
177
+ let view: YearlyPlanView = { kind: "hidden" };
178
+ if (result) view = { kind: "result", result };
179
+ else if (review) view = { kind: "review", review };
180
+ else if (status?.state === "pending") view = { kind: "pending", invoiceUrl: status.invoiceUrl, expiresAt: status.expiresAt };
181
+ else if (status?.state === "available") view = { kind: "offer", offer: status.offer };
182
+ if (!enabled && view.kind !== "result") view = { kind: "hidden" };
183
+
184
+ /** What Enter on the row's first action does now, if anything. */
185
+ const primary = view.kind === "offer"
186
+ ? () => { void openReview().catch(() => setMessage(t("Couldn't work out the yearly total. Try again in a minute."))); }
187
+ : view.kind === "review"
188
+ ? () => { void confirm().catch(() => setMessage(refusalMessage(null))); }
189
+ : pendingUrl && (view.kind === "pending" || view.kind === "result")
190
+ ? () => { void openInvoice().catch(() => setMessage(t("Could not open invoice payment. Try again."))); }
191
+ : null;
192
+
193
+ return { view, busy, message, primary, dismiss, reviewing: view.kind === "review" };
194
+ }
195
+
196
+ function ReviewLines({ review, width }: { review: CloudYearlyReview; width: number }) {
197
+ const lineWidth = Math.max(24, Math.min(width, 56));
198
+ return (
199
+ <Box flexDirection="column" width={lineWidth}>
200
+ <KeyValueRow
201
+ label={tf("Yearly Pro, today to {date}", { date: formatShortDate(review.renewsAt) })}
202
+ value={formatExactUsd(review.yearlyAmount)}
203
+ width={lineWidth}
204
+ align="right"
205
+ emphasis={false}
206
+ />
207
+ <KeyValueRow
208
+ label={t("Credit for the rest of this month")}
209
+ value={review.credit > 0 ? `-${formatExactUsd(review.credit)}` : formatExactUsd(0)}
210
+ width={lineWidth}
211
+ align="right"
212
+ emphasis={false}
213
+ />
214
+ {review.tax > 0 ? (
215
+ <KeyValueRow label={t("Tax")} value={formatExactUsd(review.tax)} width={lineWidth} align="right" emphasis={false} />
216
+ ) : null}
217
+ {review.balanceApplied > 0 ? (
218
+ <KeyValueRow label={t("Account credit")} value={`-${formatExactUsd(review.balanceApplied)}`} width={lineWidth} align="right" emphasis={false} />
219
+ ) : null}
220
+ <KeyValueRow label={t("Due today")} value={formatExactUsd(review.amountDue)} width={lineWidth} align="right" />
221
+ </Box>
222
+ );
223
+ }
224
+
225
+ function renewalText(review: CloudYearlyReview): string {
226
+ const params = { amount: formatExactUsd(review.renewalAmount), date: formatShortDate(review.renewsAt) };
227
+ return review.renewalTaxed
228
+ ? tf("Then {amount} a year plus tax, renewing {date}.", params)
229
+ : tf("Then {amount} a year, renewing {date}.", params);
230
+ }
231
+
232
+ function PaymentNeeded({ expiresAt }: { expiresAt: string | null }) {
233
+ return (
234
+ <Text fg={colors.text} wrapMode="word">
235
+ {[
236
+ t("Your switch to yearly needs the payment confirmed. You stay on monthly billing until it is paid."),
237
+ expiresAt ? tf("Unpaid by {date}, the switch is dropped.", { date: formatDetailDate(expiresAt) }) : "",
238
+ ].filter(Boolean).join(" ")}
239
+ </Text>
240
+ );
241
+ }
242
+
243
+ function resultText(result: Extract<CloudYearlyResult, { state: "switched" | "processing" }>): string {
244
+ if (result.state === "processing") return t("Your payment is processing. You move to yearly billing once it clears.");
245
+ return [
246
+ t("You're on yearly billing."),
247
+ result.amountPaid !== null ? tf("Paid {amount} today.", { amount: formatExactUsd(result.amountPaid) }) : "",
248
+ result.renewsAt ? tf("Renews {date} at {amount}.", { date: formatShortDate(result.renewsAt), amount: formatExactUsd(result.renewalAmount) }) : "",
249
+ ].filter(Boolean).join(" ");
250
+ }
251
+
252
+ /**
253
+ * The row as it draws for one state. Two actions while reviewing: the
254
+ * payment, and Not Now, which the keyboard lands on first so a second Enter
255
+ * never pays by itself.
256
+ */
257
+ export function YearlyPlanRow({
258
+ view,
259
+ busy,
260
+ message,
261
+ width,
262
+ labelWidth,
263
+ primaryActive,
264
+ dismissActive,
265
+ primaryRef,
266
+ dismissRef,
267
+ onPrimary,
268
+ onDismiss,
269
+ onFocusPrimary,
270
+ onFocusDismiss,
271
+ }: {
272
+ view: YearlyPlanView;
273
+ busy: "review" | "confirm" | "invoice" | null;
274
+ message: string | null;
275
+ width: number;
276
+ labelWidth: number;
277
+ primaryActive: boolean;
278
+ dismissActive: boolean;
279
+ primaryRef?: Ref<BoxRenderable>;
280
+ dismissRef?: Ref<BoxRenderable>;
281
+ onPrimary: (() => void) | null;
282
+ onDismiss: () => void;
283
+ onFocusPrimary: () => void;
284
+ onFocusDismiss: () => void;
285
+ }) {
286
+ if (view.kind === "hidden" && !message) return null;
287
+ const bodyWidth = Math.max(20, width - labelWidth - 1);
288
+ const pendingUrl = view.kind === "pending"
289
+ ? view.invoiceUrl
290
+ : view.kind === "result" && view.result.state === "payment_required" ? view.result.invoiceUrl : null;
291
+ return (
292
+ <Box flexDirection="row" gap={1}>
293
+ <FieldLabel label={t("Yearly")} active={primaryActive || dismissActive} width={labelWidth} />
294
+ <Box flexDirection="column" flexShrink={1} minWidth={0} gap={1} width={bodyWidth}>
295
+ {view.kind === "offer" ? (
296
+ <>
297
+ <Text fg={colors.text} wrapMode="word">{yearlyOfferText(view.offer)}</Text>
298
+ <Box ref={primaryRef} flexDirection="row" onMouseDown={onFocusPrimary}>
299
+ <Button
300
+ label={busy === "review" ? t("Loading...") : t("Review Yearly")}
301
+ active={primaryActive}
302
+ disabled={!!busy}
303
+ onPress={() => onPrimary?.()}
304
+ />
305
+ </Box>
306
+ </>
307
+ ) : null}
308
+ {view.kind === "review" ? (
309
+ <>
310
+ <Text fg={colors.text} attributes={TextAttributes.BOLD}>{t("Switch to yearly billing")}</Text>
311
+ <ReviewLines review={view.review} width={bodyWidth} />
312
+ <Text fg={colors.textDim} wrapMode="word">
313
+ {`${renewalText(view.review)} ${t("Your saved payment method is charged today, and your plan stays monthly until it is paid.")}`}
314
+ </Text>
315
+ <Box flexDirection="row" gap={1}>
316
+ <Box ref={primaryRef} flexDirection="row" onMouseDown={onFocusPrimary}>
317
+ <Button
318
+ label={busy === "confirm"
319
+ ? t("Switching...")
320
+ : view.review.amountDue > 0
321
+ ? tf("Pay {amount} and Switch", { amount: formatExactUsd(view.review.amountDue) })
322
+ : t("Switch to Yearly")}
323
+ variant="primary"
324
+ active={primaryActive}
325
+ disabled={!!busy}
326
+ onPress={() => onPrimary?.()}
327
+ />
328
+ </Box>
329
+ <Box ref={dismissRef} flexDirection="row" onMouseDown={onFocusDismiss}>
330
+ <Button
331
+ label={t("Not Now")}
332
+ active={dismissActive}
333
+ disabled={busy === "confirm"}
334
+ onPress={onDismiss}
335
+ />
336
+ </Box>
337
+ </Box>
338
+ </>
339
+ ) : null}
340
+ {view.kind === "pending" ? <PaymentNeeded expiresAt={view.expiresAt} /> : null}
341
+ {view.kind === "result" && view.result.state === "payment_required" ? <PaymentNeeded expiresAt={view.result.expiresAt} /> : null}
342
+ {view.kind === "result" && view.result.state !== "payment_required" ? (
343
+ <Text fg={colors.text} wrapMode="word">{resultText(view.result)}</Text>
344
+ ) : null}
345
+ {pendingUrl ? (
346
+ <Box ref={primaryRef} flexDirection="row" onMouseDown={onFocusPrimary}>
347
+ <Button
348
+ label={busy === "invoice" ? t("Opening...") : t("Confirm Payment")}
349
+ active={primaryActive}
350
+ disabled={!!busy}
351
+ onPress={() => onPrimary?.()}
352
+ />
353
+ </Box>
354
+ ) : null}
355
+ {message ? <Text fg={colors.textDim} wrapMode="word">{message}</Text> : null}
356
+ </Box>
357
+ </Box>
358
+ );
359
+ }
@@ -8,7 +8,8 @@ import type {
8
8
  } from "../../../api-client/types";
9
9
  import { createPluginCache } from "../../../data/plugin-cache";
10
10
  import { loadCloudResource } from "../shared/cloud-resource";
11
- import { canonicalExchange, normalizeSymbol } from "../../../utils/exchanges";
11
+ import { canonicalExchange, normalizeSymbol, storedKeyListing } from "../../../utils/exchanges";
12
+ import type { TickerRecord } from "../../../types/ticker";
12
13
  import { resolveCurrencyUnit } from "../../../utils/currency-units";
13
14
  import type { PricePoint } from "../../../types/financials";
14
15
  import { resolveDatedReturns, type DatedReturn } from "../../../portfolio/return-metrics";
@@ -67,6 +68,8 @@ interface RiskMarketHistory {
67
68
  fxBridged?: string[];
68
69
  } | null;
69
70
  error: string | null;
71
+ /** Set when its daily closes did not load (the service failed or did not answer), which asked again they may. */
72
+ loadFailed?: true;
70
73
  }
71
74
  export interface RiskMarketSnapshot {
72
75
  histories: RiskMarketHistory[];
@@ -113,6 +116,9 @@ export const RISK_FACTOR_INSTRUMENTS: RiskInstrument[] = [
113
116
  ].map(([symbol, exchange]) => ({ symbol: symbol!, exchange: exchange! }));
114
117
  /** US equity venues quote only in USD, so the listing venue alone establishes currency. */
115
118
  const US_LISTING_VENUES = new Set(["NASDAQ", "NYSE", "AMEX", "ARCA", "BATS", "CBOE"]);
119
+ /** A held row as the listing its history is read for: `ES3:XSES` is ES3 on SGX, never a symbol the service does not know. */
120
+ export const riskInstrumentOf = (ticker: Pick<TickerRecord, "metadata">): RiskInstrument =>
121
+ storedKeyListing(ticker.metadata.ticker, ticker.metadata.exchange);
116
122
  export const riskInstrumentId = (instrument: RiskInstrument) =>
117
123
  `${canonicalExchange(instrument.exchange)}:${normalizeSymbol(instrument.symbol)}`;
118
124
  const message = (error: unknown) =>
@@ -650,9 +656,13 @@ export async function fetchPortfolioRiskMarket(
650
656
  entry = histories[index]!,
651
657
  conversion = conversions.get(instruments[index]![0]),
652
658
  { instrument, quote } = entry;
659
+ // Whether its closes' request failed, which asked again may answer; an answer without them, or a pair's FX, is a reason.
660
+ let requesting = false;
653
661
  try {
654
662
  const fxCloses = conversion ? await fxHistory(conversion) : null;
663
+ requesting = true;
655
664
  const response = await historyOf(instrument.symbol, instrument.exchange || quote?.listingExchangeName || "");
665
+ requesting = false;
656
666
  const { latestClose, fxBridged, ...resolved } = validateRiskHistory(
657
667
  response,
658
668
  instrument,
@@ -687,7 +697,7 @@ export async function fetchPortfolioRiskMarket(
687
697
  };
688
698
  } catch (error) {
689
699
  if (isAccessDenied(error) || signal?.aborted) throw error;
690
- histories[index] = { ...entry, error: message(error) };
700
+ histories[index] = { ...entry, error: message(error), ...(requesting ? { loadFailed: true as const } : {}) };
691
701
  }
692
702
  }
693
703
  }),
@@ -1,7 +1,7 @@
1
1
  import { portfolioSectorReport } from "./risk-sectors";
2
2
  import { loadPortfolioOptionBook } from "./risk-options";
3
3
  import type { HeadlessPaneDefinition } from "../../../types/plugin";
4
- import { fetchPortfolioRiskMarket, RISK_HISTORY_LIMIT } from "./risk-client";
4
+ import { fetchPortfolioRiskMarket, riskInstrumentOf, RISK_HISTORY_LIMIT } from "./risk-client";
5
5
  import { parsePortfolioRiskEvidence } from "./risk-evidence";
6
6
  import { cloudEpisodeReader, fetchRiskEpisodeHistory, onceEpisodeReader, riskEpisodeTargets } from "./risk-episodes";
7
7
  import { describeCollections } from "../../../portfolio/collection-name";
@@ -71,6 +71,51 @@ function emptyPortfolioHint(name: string, listed: readonly string[]): string {
71
71
  + `then their shares with gloom portfolio position set ${portfolio} AAPL 10 150.`;
72
72
  }
73
73
 
74
+ /**
75
+ * Why a view of PORT has no rows, in one line, as its section says it in
76
+ * place of a bare "No data.": what it needs, and where the trustee's question
77
+ * is answered instead. Performance reads the account's own history, which a
78
+ * book entered by hand has none of; its P&L over a period is `portfolio show
79
+ * --from`.
80
+ */
81
+ function riskSectionEmpty(
82
+ view: RiskView,
83
+ { name, brokerLinked, unvaluedOptions, failedHistories }: {
84
+ name: string; brokerLinked: boolean; unvaluedOptions: boolean;
85
+ /** Holdings whose daily closes did not load: the reason a view of returns is empty, not what the book holds. */
86
+ failedHistories: readonly string[];
87
+ },
88
+ ): string {
89
+ if (failedHistories.length > 0 && !RISK_OWN_DATA_VIEWS.has(view)) return failedClosesText(failedHistories);
90
+ switch (view) {
91
+ case "performance":
92
+ return `No account history${brokerLinked ? " from its broker" : ""} (daily values and flows) to measure. `
93
+ + `For P&L over a period: gloom portfolio show ${shellWord(name)} --from <date>.`;
94
+ case "attribution":
95
+ return "No sector weights and returns for this account and its benchmark; import them with --evidence.";
96
+ case "greeks":
97
+ return unvaluedOptions ? "No option position in this portfolio could be valued." : "No option positions in this portfolio.";
98
+ case "correlation":
99
+ return "Needs two holdings with 60 daily returns each.";
100
+ default:
101
+ return "No holding has the daily closes this view needs.";
102
+ }
103
+ }
104
+
105
+ /** Views read from the account's own records or option positions, not from its holdings' daily closes. */
106
+ const RISK_OWN_DATA_VIEWS: ReadonlySet<RiskView> = new Set(["performance", "attribution", "greeks"]);
107
+
108
+ /** The holdings whose daily closes did not load, for an empty view's reason. */
109
+ function failedHistories(coverage: RiskCoverage | undefined): string[] {
110
+ return (coverage?.leftOut ?? []).filter((line) => line.historyFailed).map((line) => line.symbol);
111
+ }
112
+
113
+ /** "Daily closes did not load for US02, US03 and 4 more; try again in a moment." */
114
+ function failedClosesText(symbols: readonly string[]): string {
115
+ const more = symbols.length > 3 ? ` and ${symbols.length - 3} more` : "";
116
+ return `Daily closes did not load for ${symbols.slice(0, 3).join(", ")}${more}; try again in a moment.`;
117
+ }
118
+
74
119
  /** Rows of one view in the compact result; the pane and reports keep every row. */
75
120
  const COMPACT_ROW_LIMIT = 100;
76
121
  /** The correlation view is every pair of holdings; the compact result keeps the strongest. */
@@ -127,7 +172,11 @@ function coverageSummary(coverage: RiskCoverage, limit = Infinity) {
127
172
  function coverageLine(coverage: RiskCoverage | undefined): { error?: string; note?: string } {
128
173
  const shortfall = riskCoverageShortfall(coverage);
129
174
  // No estimate at all is a failure; an estimate that leaves holdings out is a caveat.
130
- if (shortfall) return { error: `Basket estimates unavailable: ${shortfall.title} ${shortfall.message}`.trim() };
175
+ if (shortfall) {
176
+ // Closes that did not load are why, which asked again may not be.
177
+ const failed = failedHistories(coverage);
178
+ return { error: [`Basket estimates unavailable: ${shortfall.title} ${shortfall.message}`.trim(), ...failed.length ? [failedClosesText(failed)] : []].join(" ") };
179
+ }
131
180
  const line = coverage?.leftOut.length ? riskCoverageLine(coverage) : null;
132
181
  return line ? { note: `${line[0]!.toUpperCase()}${line.slice(1)}; metadata.coverage lists each with its reason.` } : {};
133
182
  }
@@ -307,7 +356,8 @@ export const portfolioRiskHeadless: HeadlessPaneDefinition<"bundle"> = {
307
356
  // go unused. A bigger book waits for the basket, so it reads no closes it does not replay.
308
357
  const warming = wantsEpisodes && tickers.length <= EPISODE_WARM_LIMIT
309
358
  ? fetchRiskEpisodeHistory(
310
- tickers.map((ticker) => ({ instrument: { symbol: ticker.metadata.ticker, exchange: ticker.metadata.exchange }, currency: null })),
359
+ // With the currency each is saved in, so the FX closes the replay converts at are read alongside, not after.
360
+ tickers.map((ticker) => ({ instrument: riskInstrumentOf(ticker), currency: ticker.metadata.currency || null })),
311
361
  local.portfolio.currency, episodeReader, ctx.signal,
312
362
  ).catch(() => {
313
363
  // Intentional ignore: the replayed load below reads the same closes and reports their failures.
@@ -335,7 +385,7 @@ export const portfolioRiskHeadless: HeadlessPaneDefinition<"bundle"> = {
335
385
  : loadPortfolioOptionBook(tickers, local.portfolio),
336
386
  ]);
337
387
  const episodeTargets = wantsEpisodes
338
- ? riskEpisodeTargets(prices, tickers.map((ticker) => ({ symbol: ticker.metadata.ticker, exchange: ticker.metadata.exchange })))
388
+ ? riskEpisodeTargets(prices, tickers.map(riskInstrumentOf))
339
389
  : [];
340
390
  const episodes = episodeTargets.length
341
391
  ? await fetchRiskEpisodeHistory(episodeTargets, local.portfolio.currency, episodeReader, ctx.signal)
@@ -406,7 +456,13 @@ export const portfolioRiskHeadless: HeadlessPaneDefinition<"bundle"> = {
406
456
  complete,
407
457
  errors: model.warnings,
408
458
  notes: [...riskCoverageNotices(model.coverage), ...model.notes.filter((note) => note !== fallback)],
409
- sections: shown.map(({ view, rows }) => ({ title: view, columns: RISK_COLUMNS, rows })),
459
+ // A view with nothing to show says why in one line.
460
+ sections: shown.map(({ view, rows }) => ({ title: view, columns: RISK_COLUMNS, rows, ...(rows.length === 0 ? { empty: riskSectionEmpty(view, {
461
+ name: local.portfolio.name,
462
+ brokerLinked: !!(local.portfolio.brokerId || local.portfolio.brokerInstanceId),
463
+ unvaluedOptions: (model.greeks?.warnings.length ?? 0) > 0,
464
+ failedHistories: failedHistories(model.coverage),
465
+ }) } : {}) })),
410
466
  metadata: { coverage: coverageSummary(model.coverage), model, benchmark: model.benchmark, window: model.window,
411
467
  notices: [...(shortfall ? [shortfall] : []), ...notices] },
412
468
  };
@@ -426,7 +482,11 @@ export const portfolioRiskHeadless: HeadlessPaneDefinition<"bundle"> = {
426
482
  complete: result.complete,
427
483
  ...(errors.length ? { errors } : {}),
428
484
  ...(notes.length ? { notes } : {}),
429
- sections: [{ title: view, columns: RISK_COLUMNS, rows: rows.map(displayRow) }],
485
+ sections: [{ title: view, columns: RISK_COLUMNS, rows: rows.map(displayRow), ...(rows.length === 0 ? { empty: riskSectionEmpty(view, {
486
+ name: model.portfolio.name, brokerLinked: !!(model.portfolio.brokerId || model.portfolio.brokerInstanceId),
487
+ unvaluedOptions: (model.greeks?.warnings.length ?? 0) > 0,
488
+ failedHistories: failedHistories(model.coverage),
489
+ }) } : {}) }],
430
490
  metadata: {
431
491
  portfolio: {
432
492
  id: model.portfolio.id,
@@ -106,12 +106,13 @@ function byInterval(series: readonly DatedReturn[]): Map<string, number> {
106
106
  }
107
107
  return index;
108
108
  }
109
- /** Matched start and end dates prevent pairing a multi-session return with a daily one. */
110
- export function regressReturns(
111
- asset: readonly DatedReturn[],
112
- factor: readonly DatedReturn[],
113
- minimum = 60,
114
- ): Regression | null {
109
+ /**
110
+ * The asset's returns over the same start and end dates as the factor's, in
111
+ * the asset's order, the latest `window` of them when given. The window is
112
+ * taken after matching: two series that end on different days (a US close
113
+ * today, a Singapore close yesterday) still pair their latest common returns.
114
+ */
115
+ function matchReturns(asset: readonly DatedReturn[], factor: readonly DatedReturn[], window?: number) {
115
116
  const other = byInterval(factor);
116
117
  const sample: DatedReturn[] = [],
117
118
  x: number[] = [],
@@ -124,6 +125,22 @@ export function regressReturns(
124
125
  x.push(matched);
125
126
  y.push(point.value);
126
127
  }
128
+ const from = window == null ? 0 : Math.max(0, sample.length - window);
129
+ return { sample: sample.slice(from), x: x.slice(from), y: y.slice(from) };
130
+ }
131
+ /** How many daily returns two series share, by start and end date. */
132
+ export const matchedReturnCount = (asset: readonly DatedReturn[], factor: readonly DatedReturn[]) =>
133
+ matchReturns(asset, factor).sample.length;
134
+ /**
135
+ * Matched start and end dates prevent pairing a multi-session return with a
136
+ * daily one. `window`: the latest so many matched returns, else every one.
137
+ */
138
+ export function regressReturns(
139
+ asset: readonly DatedReturn[],
140
+ factor: readonly DatedReturn[],
141
+ { window, minimum = 60 }: { window?: number; minimum?: number } = {},
142
+ ): Regression | null {
143
+ const { sample, x, y } = matchReturns(asset, factor, window);
127
144
  if (sample.length < minimum) return null;
128
145
  const meanX = x.reduce((a, b) => a + b, 0) / x.length,
129
146
  meanY = y.reduce((a, b) => a + b, 0) / y.length;