@gloom-sh/terminal 0.19.5 → 0.19.6

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 (208) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +86 -25
  3. package/src/api-client/equity-screener.ts +23 -0
  4. package/src/app/pane-runtime/index.tsx +2 -0
  5. package/src/app/pane-runtime/plugin-bindings.ts +10 -1
  6. package/src/app.tsx +63 -16
  7. package/src/cli/commands/market.ts +149 -10
  8. package/src/cli/commands/search.ts +21 -3
  9. package/src/cli/commands/ticker.ts +74 -33
  10. package/src/cli/glossary.ts +3 -3
  11. package/src/cli/known-gaps.ts +8 -0
  12. package/src/cli/listing-arg.ts +12 -0
  13. package/src/cli/pane-functions/capabilities.ts +2 -0
  14. package/src/cli/pane-functions/catalog.ts +22 -4
  15. package/src/cli/pane-functions/function-help.ts +8 -5
  16. package/src/cli/pane-functions/headless.ts +4 -3
  17. package/src/cli/pane-functions/resolver.ts +75 -2
  18. package/src/cli/quote-answer.ts +9 -0
  19. package/src/cli/symbol-list.ts +54 -2
  20. package/src/cli/symbol-rows.ts +14 -2
  21. package/src/cli/ticker-resolution.ts +89 -20
  22. package/src/components/chart/composite/axis-overlays.tsx +60 -27
  23. package/src/components/chart/composite/composite-chart.tsx +118 -63
  24. package/src/components/chart/composite/cursor-source.ts +111 -0
  25. package/src/components/chart/composite/format.ts +168 -6
  26. package/src/components/chart/composite/legend.tsx +8 -4
  27. package/src/components/chart/composite/panel-labels.ts +20 -1
  28. package/src/components/chart/composite/panel-surface.tsx +201 -92
  29. package/src/components/chart/composite/price-axis-labels.tsx +92 -46
  30. package/src/components/chart/composite/price-series.ts +31 -8
  31. package/src/components/chart/composite/scene.ts +154 -59
  32. package/src/components/chart/composite/series-axis-tags.tsx +4 -2
  33. package/src/components/chart/composite/time-axis.ts +13 -5
  34. package/src/components/chart/composite/time-scale.ts +211 -56
  35. package/src/components/chart/composite/types.ts +11 -1
  36. package/src/components/chart/composite/use-composite-chart-keyboard.ts +32 -12
  37. package/src/components/chart/curve/curve-surface.tsx +5 -2
  38. package/src/components/chart/curve/model.ts +4 -1
  39. package/src/components/chart/native/use-bitmap-metrics.ts +81 -0
  40. package/src/components/chart/static/series.ts +3 -0
  41. package/src/components/command-bar/commands/collection-list.ts +81 -0
  42. package/src/components/command-bar/commands/direct/index.ts +6 -0
  43. package/src/components/command-bar/commands/registry.ts +8 -0
  44. package/src/components/command-bar/layout-items/current-layout.ts +22 -1
  45. package/src/components/command-bar/layout-items/focused-pane.ts +22 -1
  46. package/src/components/command-bar/pane-templates/items.ts +19 -3
  47. package/src/components/command-bar/pane-templates/workflow.ts +5 -0
  48. package/src/components/command-bar/routes/root/results.ts +23 -3
  49. package/src/components/command-bar/routes/root/selection.ts +4 -2
  50. package/src/components/command-bar/routes/root/shortcut-feedback.ts +1 -1
  51. package/src/components/command-bar/routes/root/shortcut-items.ts +3 -4
  52. package/src/components/command-bar/routes/root/shortcuts.ts +58 -14
  53. package/src/components/command-bar/routes/root/ticker-first.ts +32 -0
  54. package/src/components/command-bar/surface/environment.ts +2 -0
  55. package/src/components/command-bar/view-model.ts +7 -0
  56. package/src/components/command-bar/workflow/ops.ts +2 -1
  57. package/src/components/command-bar/workflow/tickers.ts +20 -0
  58. package/src/components/layout/shell/menu.ts +15 -1
  59. package/src/components/layout/shell/pane/actions.ts +4 -0
  60. package/src/components/layout/shell/ticker-link-menu.ts +12 -3
  61. package/src/components/layout/status-bar.tsx +20 -0
  62. package/src/components/onboarding/onboarding-keyboard.ts +5 -1
  63. package/src/components/onboarding/onboarding-wizard.tsx +15 -4
  64. package/src/components/onboarding/portfolio-step/positions-panel.tsx +8 -5
  65. package/src/components/onboarding/use-onboarding-progress.ts +20 -1
  66. package/src/components/price-sparkline/view.tsx +14 -6
  67. package/src/components/ticker/badge/index.tsx +8 -4
  68. package/src/components/ticker/badge/list.tsx +23 -7
  69. package/src/components/ui/column-grid.tsx +8 -2
  70. package/src/components/ui/data-table/opentui/model.ts +4 -1
  71. package/src/components/ui/tabs.tsx +5 -2
  72. package/src/core/state/app/layout.ts +18 -3
  73. package/src/core/state/app/state.ts +2 -0
  74. package/src/core/state/app/types.ts +5 -0
  75. package/src/data/config/layout.ts +3 -0
  76. package/src/data/config/store/normalize.ts +39 -4
  77. package/src/i18n/es.ts +10 -0
  78. package/src/i18n/ja.ts +10 -0
  79. package/src/i18n/ko.ts +10 -0
  80. package/src/i18n/zh-cn.ts +10 -0
  81. package/src/i18n/zh-tw.ts +10 -0
  82. package/src/layout/pane-manager/floating-placement.ts +7 -4
  83. package/src/layout/pane-manager/floating.ts +5 -2
  84. package/src/market-data/bond-funds.ts +19 -0
  85. package/src/market-data/futures-contract.ts +14 -3
  86. package/src/market-data/market/freshness.ts +18 -0
  87. package/src/market-data/market/status.ts +15 -2
  88. package/src/plugins/builtin/bond-calculator/headless.ts +2 -1
  89. package/src/plugins/builtin/bond-calculator/index.tsx +1 -1
  90. package/src/plugins/builtin/bond-calculator/model.ts +14 -5
  91. package/src/plugins/builtin/bond-calculator/pane.tsx +1 -1
  92. package/src/plugins/builtin/buildout/cells.tsx +25 -45
  93. package/src/plugins/builtin/buildout/detail/company.tsx +3 -3
  94. package/src/plugins/builtin/buildout/detail/index.tsx +1 -1
  95. package/src/plugins/builtin/buildout/detail/intel.tsx +4 -7
  96. package/src/plugins/builtin/buildout/detail/site.tsx +4 -4
  97. package/src/plugins/builtin/buildout/detail/ui.tsx +39 -38
  98. package/src/plugins/builtin/buildout/format.ts +23 -1
  99. package/src/plugins/builtin/buildout/model/types.ts +1 -0
  100. package/src/plugins/builtin/buildout/pane/index.tsx +2 -8
  101. package/src/plugins/builtin/buildout/table-model.ts +12 -4
  102. package/src/plugins/builtin/cds/headless.ts +1 -0
  103. package/src/plugins/builtin/cds/index.tsx +1 -1
  104. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  105. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +28 -3
  106. package/src/plugins/builtin/correlation/headless.ts +3 -2
  107. package/src/plugins/builtin/crypto-board/pane.tsx +5 -4
  108. package/src/plugins/builtin/debt-maturities/headless.ts +11 -2
  109. package/src/plugins/builtin/debt-maturities/model.ts +66 -0
  110. package/src/plugins/builtin/debt-maturities/pane.tsx +23 -4
  111. package/src/plugins/builtin/earnings-ripple/pane.tsx +1 -1
  112. package/src/plugins/builtin/econ/calendar-model.ts +28 -6
  113. package/src/plugins/builtin/equity-screener/client.ts +1 -1
  114. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +4 -16
  115. package/src/plugins/builtin/equity-screener/headless.ts +4 -2
  116. package/src/plugins/builtin/equity-screener/ideas.ts +67 -3
  117. package/src/plugins/builtin/equity-screener/model.ts +180 -12
  118. package/src/plugins/builtin/equity-screener/pane.tsx +52 -12
  119. package/src/plugins/builtin/equity-screener/screen-check.ts +7 -4
  120. package/src/plugins/builtin/equity-screener/watchlist.ts +33 -0
  121. package/src/plugins/builtin/futures-curve/client.ts +19 -0
  122. package/src/plugins/builtin/futures-curve/headless.ts +52 -13
  123. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  124. package/src/plugins/builtin/futures-curve/model.ts +77 -6
  125. package/src/plugins/builtin/futures-curve/pane.tsx +19 -3
  126. package/src/plugins/builtin/macro-day/client.ts +41 -0
  127. package/src/plugins/builtin/macro-day/headless.ts +19 -9
  128. package/src/plugins/builtin/macro-day/model.ts +3 -1
  129. package/src/plugins/builtin/market-movers/index.tsx +4 -3
  130. package/src/plugins/builtin/mna/distress/headless.ts +1 -0
  131. package/src/plugins/builtin/perps/pane.tsx +3 -1
  132. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +17 -0
  133. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +2 -1
  134. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
  135. package/src/plugins/builtin/rate-path/headless.ts +24 -10
  136. package/src/plugins/builtin/research/event-model.ts +10 -3
  137. package/src/plugins/builtin/research/events-headless.ts +20 -2
  138. package/src/plugins/builtin/sec/fund-facts.ts +17 -1
  139. package/src/plugins/builtin/sec/index.tsx +1 -1
  140. package/src/plugins/builtin/shared/members-menu.tsx +103 -38
  141. package/src/plugins/builtin/short-interest/publications-model.ts +22 -1
  142. package/src/plugins/builtin/short-interest/publications-pane.tsx +13 -4
  143. package/src/plugins/builtin/short-interest/watch-model.ts +1 -1
  144. package/src/plugins/builtin/time-sales/pane.tsx +3 -2
  145. package/src/plugins/builtin/trace-bonds/client.ts +7 -4
  146. package/src/plugins/builtin/trace-bonds/index.tsx +1 -1
  147. package/src/plugins/builtin/volatility/client.ts +6 -1
  148. package/src/plugins/builtin/volatility/headless.ts +0 -1
  149. package/src/plugins/builtin/yield-curve/curves.ts +15 -0
  150. package/src/plugins/builtin/yield-curve/headless.ts +6 -1
  151. package/src/plugins/builtin/yield-curve/index.tsx +5 -8
  152. package/src/plugins/host-modules.ts +22 -3
  153. package/src/plugins/host-smoke.ts +6 -3
  154. package/src/portfolio/collection-name.ts +19 -0
  155. package/src/renderers/browser/http-proxy-transport.ts +78 -8
  156. package/src/renderers/cloudflare/http-proxy.ts +13 -2
  157. package/src/renderers/cloudflare/proxy-session.ts +47 -24
  158. package/src/renderers/cloudflare/worker.ts +15 -2
  159. package/src/renderers/desktop/geometry.ts +279 -0
  160. package/src/renderers/desktop/screen-setup.ts +246 -0
  161. package/src/renderers/desktop/sequential-window-host.ts +179 -0
  162. package/src/renderers/desktop/test-utils.ts +71 -0
  163. package/src/renderers/desktop/window-controller.ts +433 -0
  164. package/src/renderers/desktop/window-host.ts +70 -0
  165. package/src/renderers/desktop/window-layouts.ts +630 -0
  166. package/src/renderers/dom/data-frames.ts +15 -4
  167. package/src/renderers/electrobun/bun/application-menu/click.ts +1 -0
  168. package/src/renderers/electrobun/bun/application-menu/index.ts +4 -1
  169. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +19 -8
  170. package/src/renderers/electrobun/bun/desktop/backend.ts +320 -19
  171. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +83 -61
  172. package/src/renderers/electrobun/bun/desktop/host-requests.ts +4 -14
  173. package/src/renderers/electrobun/bun/desktop/initialization.ts +30 -11
  174. package/src/renderers/electrobun/bun/desktop/screen-setup-file.ts +55 -0
  175. package/src/renderers/electrobun/bun/desktop/state-broadcaster.ts +44 -8
  176. package/src/renderers/electrobun/bun/desktop/workspace/index.ts +298 -97
  177. package/src/renderers/electrobun/bun/desktop/workspace/requests.ts +44 -6
  178. package/src/renderers/electrobun/bun/index.ts +4 -97
  179. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +306 -0
  180. package/src/renderers/electrobun/bun/window/focus.ts +0 -25
  181. package/src/renderers/electrobun/bun/window/remembered-frame.ts +4 -82
  182. package/src/renderers/electrobun/shared/protocol.ts +44 -2
  183. package/src/renderers/electrobun/view/backend-rpc.ts +15 -0
  184. package/src/renderers/electrobun/view/desktop/window/bridge.ts +63 -3
  185. package/src/renderers/electrobun/view/main.tsx +13 -7
  186. package/src/series/fred-argument.ts +17 -0
  187. package/src/sources/provider-router/financial-routes.ts +7 -1
  188. package/src/state/app/context/index.tsx +16 -2
  189. package/src/state/desktop-windows.ts +63 -0
  190. package/src/sync/other-window-tabs.ts +62 -0
  191. package/src/tickers/company-name-listing.ts +23 -3
  192. package/src/tickers/listing-fate.ts +147 -1
  193. package/src/tickers/terminal-codes.ts +5 -0
  194. package/src/time-series/types.ts +6 -0
  195. package/src/types/config.ts +10 -1
  196. package/src/types/desktop-window.ts +71 -2
  197. package/src/types/financials.ts +4 -0
  198. package/src/types/headless.ts +19 -0
  199. package/src/types/plugin.ts +6 -0
  200. package/src/ui/index.tsx +14 -13
  201. package/src/ui/same-props.ts +58 -0
  202. package/src/utils/cli-output.ts +33 -4
  203. package/src/utils/format.ts +7 -2
  204. package/src/utils/futures-generic.ts +12 -0
  205. package/src/utils/http-proxy-upstream.ts +6 -2
  206. package/src/utils/plugin-proxy-hosts.json +0 -4
  207. package/src/utils/plugin-proxy-hosts.ts +22 -0
  208. package/src/utils/sec-filings.ts +7 -1
@@ -4,6 +4,8 @@ import { colors } from "../../../theme/colors";
4
4
  import { displayWidth, MISSING_VALUE } from "../../../utils/format";
5
5
  import { fetchEconCalendar } from "./calendar-source";
6
6
  import { parseEconFigure } from "./figures";
7
+ import { resolveFredMapping } from "./fred-series-map";
8
+ import { STATS } from "../econ-statistics/stats";
7
9
  import { isAllDayEvent, type EconEvent, type EconImpact } from "./types";
8
10
 
9
11
  const CACHE_KIND = "calendar";
@@ -277,17 +279,37 @@ function publisherNames(source: EconEvent["source"]): string[] {
277
279
  return [source.name, initials, site].map(compactName).filter(Boolean);
278
280
  }
279
281
 
282
+ /** ECST's names for each FRED series it charts, compacted: PAYEMS is Nonfarm Payrolls, nfp and the jobs report. */
283
+ let statNames: ReadonlyMap<string, readonly string[]> | null = null;
284
+
285
+ function statNamesOf(seriesId: string): readonly string[] {
286
+ statNames ??= STATS.reduce((names, stat) => names.set(stat.seriesId,
287
+ [...names.get(stat.seriesId) ?? [], ...[stat.label, ...stat.aliases ?? [], ...stat.keywords ?? []].map(compactName).filter(Boolean)]),
288
+ new Map<string, string[]>());
289
+ return statNames.get(seriesId) ?? [];
290
+ }
291
+
292
+ /**
293
+ * The names a row is searched by, compacted: the feed's own and the one the
294
+ * calendar shows, then what ECST calls the series the release is of
295
+ * (Non-Farm Employment Change is also nonfarm payrolls, nfp and the jobs report).
296
+ */
297
+ function eventSearchNames(event: Pick<EconEvent, "country" | "event" | "actual" | "forecast" | "prior">): string[] {
298
+ const series = resolveFredMapping(event.event, event.country)?.seriesId;
299
+ return [...[event.event, econEventName(event)].map(compactName), ...series ? statNamesOf(series) : []];
300
+ }
301
+
280
302
  /**
281
- * Whether a row carries every word of `query` in its name or its publisher's,
282
- * case, spaces and punctuation aside: `nonfarm` finds Non Farm Payrolls and
283
- * Non-Farm Employment Change, `fed funds` the Federal Funds Rate, and `usda`
284
- * every row the U.S. Department of Agriculture publishes. The name shown and
285
- * the feed's own are both read.
303
+ * Whether a row carries every word of `query` in one of its names or its
304
+ * publisher's, case, spaces and hyphens aside: `nonfarm` finds Non Farm
305
+ * Payrolls and Non-Farm Employment Change, `nfp` and `jobs report` the
306
+ * latter by ECST's names for it, `fed funds` the Federal Funds Rate, and
307
+ * `usda` every row the U.S. Department of Agriculture publishes.
286
308
  */
287
309
  export function matchesEventSearch(event: Pick<EconEvent, "country" | "event" | "actual" | "forecast" | "prior" | "source">, query: string): boolean {
288
310
  const words = query.split(/\s+/).map(compactName).filter(Boolean);
289
311
  if (words.length === 0) return true;
290
- const names = [event.event, econEventName(event)].map(compactName);
312
+ const names = eventSearchNames(event);
291
313
  const publisher = publisherNames(event.source);
292
314
  return names.some((name) => words.every((word) => name.includes(word) || publisher.some((text) => text.includes(word))));
293
315
  }
@@ -21,7 +21,7 @@ const savedPath = (id: string) => `saved/${encodeURIComponent(id)}`;
21
21
  export const screenerApi = {
22
22
  query: (query: ScreenQuery, signal?: AbortSignal, client: ScreenerClient = apiClient) =>
23
23
  client.equityScreener<ScreenPayload>("query", json("POST", query, { signal })),
24
- fields: (signal?: AbortSignal) => apiClient.equityScreener<ScreenFieldsResponse>("fields?include=social,research,attention,hiring-apps,kpis,volatility,dividends,technical,option-volatility,ownership,quality", { signal }),
24
+ fields: (signal?: AbortSignal) => apiClient.equityScreener<ScreenFieldsResponse>("fields?include=social,research,attention,hiring-apps,kpis,volatility,dividends,technical,option-volatility,ownership,quality,scores,grades", { signal }),
25
25
  export: (definition: ScreenDefinition, snapshotId: string) =>
26
26
  apiClient.equityScreener<ScreenExportResponse>("export", json("POST", { ...definition, snapshotId }, { headers: { Accept: "application/json" } })),
27
27
  saved: async (signal?: AbortSignal, client: ScreenerClient = apiClient) =>
@@ -13,7 +13,7 @@ import type {
13
13
  ScreenFieldDefinition,
14
14
  ScreenOperator,
15
15
  } from "../../../api-client/equity-screener";
16
- import { parseCriterion } from "./model";
16
+ import { criterionInputText, criterionValueHint, criterionValueLabel, parseCriterion } from "./model";
17
17
 
18
18
  export function CriterionEditor({
19
19
  fields,
@@ -40,13 +40,7 @@ export function CriterionEditor({
40
40
  const [operator, setOperator] = useState<ScreenOperator>(
41
41
  value?.op ?? field.operators[0]!,
42
42
  );
43
- const [text, setText] = useState(
44
- value && "value" in value
45
- ? Array.isArray(value.value)
46
- ? value.value.join(", ")
47
- : String(value.value)
48
- : "",
49
- );
43
+ const [text, setText] = useState(criterionInputText(value));
50
44
  const [error, setError] = useState<string | null>(null);
51
45
  const [active, setActive] = useState("field");
52
46
  const fieldControl = useRef<SelectControl>(null),
@@ -138,16 +132,10 @@ export function CriterionEditor({
138
132
  />
139
133
  {!["present", "missing"].includes(operator) ? (
140
134
  <TextField
141
- label={`Value${field.unit ? ` (${field.unit})` : ""}`}
135
+ label={criterionValueLabel(field)}
142
136
  value={text}
143
137
  onChange={setText}
144
- placeholder={
145
- operator === "between"
146
- ? "minimum, maximum"
147
- : operator === "in"
148
- ? "comma-separated values"
149
- : "threshold, e.g. 25 or 10B"
150
- }
138
+ placeholder={criterionValueHint(field, operator)}
151
139
  width={Math.min(45, width - 4)}
152
140
  focused={focused && active === "value"}
153
141
  onMouseDown={() => setActive("value")}
@@ -14,7 +14,7 @@ import { buildQuoteKey } from "../../../market-data/selectors";
14
14
  import type { Quote } from "../../../types/financials";
15
15
  import { formatCurrency, formatPercentRaw } from "../../../utils/format";
16
16
  import { fetchSavedScreens, fetchScreen, fetchScreenCheck } from "./client";
17
- import { SCREEN_IDEAS, screenIdea } from "./ideas";
17
+ import { ideaMetricSetting, SCREEN_IDEAS, screenIdea } from "./ideas";
18
18
  import { checkRows, screenCheckSummary, screenCheckTicker } from "./screen-check";
19
19
  import { overlayScreenQuotes, screenExtendedSessions, sortLiveScreenRows } from "./live";
20
20
  import {
@@ -252,6 +252,8 @@ export const equityScreenerHeadless: HeadlessPaneDefinition<"bundle"> = {
252
252
  "Technical fields (RSI, moving averages, MACD and golden crosses, new highs and lows, Bollinger width) read US listings' completed daily sessions: they describe the last close, not the session in progress. A days-since field counts trading days, 0 at the last session.",
253
253
  "Shares outstanding, float, short % of float and institutional ownership cover US filers: the 10-K or 10-Q cover count, the stored statistics float, the FINRA settlement, the 13F quarter. The source does not say when it measured the float, so float and short % of float are partial, dated by when the statistics were retrieved (within 30 days) and never above the dated shares outstanding. A stale or inconsistent input leaves a field unavailable with its reason. Institutional ownership is over the balance-sheet count at the 13F quarter end; over 100% is partial with its reason.",
254
254
  "ROIC, FCF yield, net debt / EBITDA and debt / equity read FA's latest annual column: the trailing four quarters, or the fiscal year when those quarters are it. Revenue and EPS CAGRs run from the latest fiscal year back 3 or 5 years, both years from the stored statements or both from the SEC filings (US filers), never one of each. Forward growth is the consensus EE shows for the fiscal year in progress. N/M where FA prints it: EBITDA, equity, invested capital or a base year at or below zero.",
255
+ "Piotroski F-score compares the latest two fiscal years; Altman Z, the Graham number, Lynch fair value, earnings yield and return on capital read FA's latest annual column at today's price and market cap, each dated by its period end. N/M where the score is not defined: Altman Z, the Magic Formula and an unclassified balance sheet's F-score for banks and insurers, the Graham number and Lynch value over a loss. Magic Formula rank and RS rating rank the covered US listings, not the whole market. Streak years run to the first stored year at most, read as at least that many; the distribution history covers about ten years. S&P 500 and Dow membership read the IVV and DIA holdings MEMB reads, 1 for a member.",
256
+ "Value, Growth, Profitability, Momentum and Revisions grades rank a few of these fields within the company's sector, every currency together, and print F to A+ (stored 1 to 13, so B+ or better is gte 10); a company's share classes and lines are graded once, on its most traded line, and a sector with fewer than 20 companies that have them ranks against every company, and the Reason says so. A grade needs two of its inputs; an N/M input is left out. The composite averages the grades' percentiles with equal weights (three grades or more), ranks the averages across every company and prints 1 to 5 with its label: Top, Strong, Neutral, Weak or Bottom, its nearest whole number.",
255
257
  ],
256
258
  },
257
259
  async load(args, ctx) {
@@ -303,7 +305,7 @@ export const equityScreenerHeadless: HeadlessPaneDefinition<"bundle"> = {
303
305
  }
304
306
  const limit = typeof args.options.limit === "number" ? args.options.limit : SCREEN_PAGE_ROWS;
305
307
  const data = await fetchScreenRows(definition, limit, ctx);
306
- const metrics = readMetrics(args.options.metric == null ? preset?.metric ?? "marketCap" : String(args.options.metric));
308
+ const metrics = readMetrics(args.options.metric == null ? preset ? ideaMetricSetting(preset) : "marketCap" : String(args.options.metric));
307
309
  const metric = metrics[0]!;
308
310
  // Last, Chg% and market cap are the regular session, as `quote` and the
309
311
  // pane read each row's quote; an extended print is a column of its own.
@@ -1,10 +1,12 @@
1
- import type { NumericField, ScreenCriterion, ScreenDefinition } from "../../../api-client/equity-screener";
1
+ import { LETTER_GRADE_FIELDS, type NumericField, type ScreenCriterion, type ScreenDefinition } from "../../../api-client/equity-screener";
2
2
 
3
- /** A ready screen in the Ideas tab and `--preset`: its definition and the metric it leads with. */
3
+ /** A ready screen in the Ideas tab and `--preset`: its definition, the metric it leads with and any it shows beside. */
4
4
  export interface ScreenIdea {
5
5
  id: string;
6
6
  name: string;
7
7
  metric: NumericField;
8
+ /** Columns after the metric, as `--metric` adds them. */
9
+ others?: readonly NumericField[];
8
10
  definition: ScreenDefinition;
9
11
  }
10
12
 
@@ -16,16 +18,19 @@ const idea = (
16
18
  name: string,
17
19
  criteria: ScreenCriterion[],
18
20
  sort: ScreenDefinition["sort"] & { field: NumericField },
21
+ others?: readonly NumericField[],
19
22
  ): ScreenIdea => ({
20
23
  id,
21
24
  name,
22
25
  metric: sort.field,
26
+ ...(others ? { others } : {}),
23
27
  definition: { version: 1, currency: "USD", criteria: [...criteria, TRADED], sort },
24
28
  });
25
29
 
26
30
  /**
27
31
  * Technical ideas, read at the last completed session, then fundamental ones, read on `FA`'s bases (the trailing four
28
- * quarters, or the latest fiscal year when those quarters are that year) and `EE`'s consensus.
32
+ * quarters, or the latest fiscal year when those quarters are that year) and `EE`'s consensus, then the classic
33
+ * scores and the grades. Each keeps to companies above $2B.
29
34
  */
30
35
  export const SCREEN_IDEAS: ScreenIdea[] = [
31
36
  idea("oversold-uptrend", "Oversold in an uptrend", [
@@ -72,7 +77,66 @@ export const SCREEN_IDEAS: ScreenIdea[] = [
72
77
  { field: "forwardPE", op: "lte", value: 20 },
73
78
  { field: "roicPercent", op: "gte", value: 10 },
74
79
  ], { field: "forwardEpsGrowthPercent", direction: "desc" }),
80
+ // Classic scores. Piotroski's F-score of 8 or 9, his high group, among cheaper companies: he scored the cheapest
81
+ // fifth by book to market, and a P/B of 2x or less keeps to cheaper names. Highest score first.
82
+ idea("piotroski", "Piotroski 8-9", [
83
+ { field: "piotroskiFScore", op: "gte", value: 8 },
84
+ { field: "priceToBook", op: "lte", value: 2 },
85
+ ], { field: "piotroskiFScore", direction: "desc" }),
86
+ // Greenblatt's Magic Formula: earnings yield and return on capital ranked over the covered US listings, the two
87
+ // ranks summed and ranked again. The top 100 hold about 50 companies above $2B; banks, insurers and utilities are
88
+ // left out, as he left them out. Best rank first.
89
+ idea("magic-formula", "Magic Formula top", [
90
+ { field: "magicFormulaRank", op: "lte", value: 100 },
91
+ ], { field: "magicFormulaRank", direction: "asc" }),
92
+ // An Altman Z of 3 or more, above his 2.99 safe zone, at a trailing P/E of 15x or less, about the market's long-run
93
+ // multiple. Cheapest first.
94
+ idea("altman-safe-value", "Altman safe and cheap", [
95
+ { field: "altmanZScore", op: "gte", value: 3 },
96
+ { field: "trailingPE", op: "lte", value: 15 },
97
+ ], { field: "trailingPE", direction: "asc" }),
98
+ // A price at or below the Graham number, sqrt(22.5 x EPS x book value per share), with ten profitable years in a
99
+ // row, Graham's test of earnings stability for the defensive investor. Furthest below first.
100
+ idea("graham-number", "Below the Graham number", [
101
+ { field: "grahamUpsidePercent", op: "gte", value: 0 },
102
+ { field: "profitableYears", op: "gte", value: 10 },
103
+ ], { field: "grahamUpsidePercent", direction: "desc" }),
104
+ // A price at or below Lynch's fair value, EPS times its five-year growth rate, so a PEG of 1 or less, with debt no
105
+ // larger than equity, as Lynch preferred. Most upside first.
106
+ idea("lynch-value", "Below Lynch fair value", [
107
+ { field: "lynchUpsidePercent", op: "gte", value: 0 },
108
+ { field: "debtToEquity", op: "lte", value: 1 },
109
+ ], { field: "lynchUpsidePercent", direction: "desc" }),
110
+ // Five years or more of higher trailing dividends, a yield of 2% or more and a payout of 75% or less of earnings,
111
+ // room to keep raising. The stored distribution history runs about ten years, so a longer record reads as at
112
+ // least that. Fastest 3-year dividend growth first.
113
+ idea("dividend-growers", "Dividend growers", [
114
+ { field: "dividendGrowthYears", op: "gte", value: 5 },
115
+ { field: "dividendYieldPercent", op: "gte", value: 2 },
116
+ { field: "payoutRatioPercent", op: "lte", value: 75 },
117
+ ], { field: "dividendGrowth3YPercent", direction: "desc" }),
118
+ // An RS rating of 90 or more, a 1Y total return in the top tenth of US listings, within 15% of the 52-week high, as
119
+ // IBD looks for leaders near their highs. Highest rating first.
120
+ idea("rs-leaders", "RS leaders", [
121
+ { field: "rsRating", op: "gte", value: 90 },
122
+ { field: "fromHigh52WPercent", op: "gte", value: -15 },
123
+ ], { field: "rsRating", direction: "desc" }),
124
+ // Ten profitable fiscal years in a row, five years or more of higher revenue, and ROIC of 15% or more. Longest
125
+ // revenue growth first.
126
+ idea("compounders", "Steady compounders", [
127
+ { field: "profitableYears", op: "gte", value: 10 },
128
+ { field: "revenueGrowthYears", op: "gte", value: 5 },
129
+ { field: "roicPercent", op: "gte", value: 15 },
130
+ ], { field: "revenueGrowthYears", direction: "desc" }),
131
+ // Grades: the composite of the five sector-relative grades at 4.5 or more, its Top label, which the ranking keeps
132
+ // to an eighth of the graded listings, with the five grades beside it. Highest composite first.
133
+ idea("top-grades", "Top grades", [
134
+ { field: "gradeComposite", op: "gte", value: 4.5 },
135
+ ], { field: "gradeComposite", direction: "desc" }, LETTER_GRADE_FIELDS),
75
136
  ];
76
137
 
138
+ /** The metric setting an idea opens with: its metric, then the columns it shows beside it (`--metric` form). */
139
+ export const ideaMetricSetting = (entry: ScreenIdea): string => [entry.metric, ...(entry.others ?? [])].join(",");
140
+
77
141
  export const screenIdea = (id: string | undefined): ScreenIdea | undefined =>
78
142
  SCREEN_IDEAS.find((entry) => entry.id === id);
@@ -3,12 +3,16 @@ import {
3
3
  DIVIDEND_FIELDS,
4
4
  HIRING_APP_FIELDS,
5
5
  CATEGORY_FIELDS,
6
+ GRADE_FIELDS,
7
+ LETTER_GRADE_FIELDS,
6
8
  NUMERIC_FIELDS,
7
9
  OPTION_VOLATILITY_FIELDS,
8
10
  OWNERSHIP_FIELDS,
9
11
  QUALITY_FIELDS,
10
12
  RESEARCH_FIELDS,
11
13
  KPI_FIELDS,
14
+ MEMBERSHIP_FIELDS,
15
+ SCORE_FIELDS,
12
16
  SOCIAL_FIELDS,
13
17
  TECHNICAL_FIELDS,
14
18
  VOLATILITY_FIELDS,
@@ -137,6 +141,31 @@ export const SHORT_LABELS: Record<NumericField, string> = {
137
141
  epsCagr5YPercent: "EPS CAGR 5Y%",
138
142
  forwardRevenueGrowthPercent: "FWD REV GR%",
139
143
  forwardEpsGrowthPercent: "FWD EPS GR%",
144
+ piotroskiFScore: "F-SCORE",
145
+ altmanZScore: "ALTMAN Z",
146
+ grahamNumber: "GRAHAM #",
147
+ grahamUpsidePercent: "GRAHAM UPS%",
148
+ lynchFairValue: "LYNCH FV",
149
+ lynchUpsidePercent: "LYNCH UPS%",
150
+ earningsYieldPercent: "EBIT/EV%",
151
+ returnOnCapitalPercent: "ROC%",
152
+ magicFormulaRank: "MAGIC RANK",
153
+ totalReturn1YPercent: "1Y TR%",
154
+ rsRating: "RS RATING",
155
+ profitableYears: "PROFIT YRS",
156
+ revenueGrowthYears: "REV GR YRS",
157
+ dividendGrowthYears: "DIV GR YRS",
158
+ sp500Member: "S&P 500",
159
+ dowMember: "DOW",
160
+ // Letter grades, F to A+, and the composite with its label.
161
+ valueGrade: "VALUE",
162
+ growthGrade: "GROWTH",
163
+ profitabilityGrade: "PROFIT",
164
+ momentumGrade: "MOMENTUM",
165
+ revisionsGrade: "REVISIONS",
166
+ gradeComposite: "COMPOSITE",
167
+ nextYearEpsRevision30dPercent: "NXT EPS REV%",
168
+ revenueRevision30dPercent: "REVENUE REV%",
140
169
  hiringOpenRoles: "OPEN ROLES",
141
170
  hiringNetAddsWeek: "NET ROLES/WK",
142
171
  hiringRemotePercent: "REMOTE%",
@@ -161,14 +190,51 @@ const SIGNED = new Set<NumericField>(["hiringNetAddsWeek", "hiringZScore", "appR
161
190
  "iv30Change1d", "iv30Change5d",
162
191
  "revenueCagr3YPercent", "revenueCagr5YPercent", "epsCagr3YPercent", "epsCagr5YPercent",
163
192
  "forwardRevenueGrowthPercent", "forwardEpsGrowthPercent",
193
+ "totalReturn1YPercent", "grahamUpsidePercent", "lynchUpsidePercent",
194
+ "nextYearEpsRevision30dPercent", "revenueRevision30dPercent",
164
195
  ]);
165
- /** Moves whose sign is the news: they take the sign colour. */
196
+ /** Moves whose sign is the news: they take the sign colour. A fair value's upside reads as the analysts' does. */
166
197
  export const SIGN_COLORED = new Set<NumericField>(["changePercent", ...RETURNS, "epsRevision30dPercent", "analystUpsidePercent",
167
- "priceVsSma20Percent", "priceVsSma50Percent", "priceVsSma200Percent"]);
198
+ "priceVsSma20Percent", "priceVsSma50Percent", "priceVsSma200Percent",
199
+ "totalReturn1YPercent", "grahamUpsidePercent", "lynchUpsidePercent",
200
+ "nextYearEpsRevision30dPercent", "revenueRevision30dPercent"]);
201
+ const LETTER_GRADES = new Set<NumericField>(LETTER_GRADE_FIELDS);
202
+ /** Fields that print as a grade, a letter or the composite with its label, never as a number and a unit. */
203
+ export const GRADE_DISPLAY_FIELDS: ReadonlySet<string> = new Set<string>([...LETTER_GRADE_FIELDS, "gradeComposite"]);
204
+ /** A grade's letter by its value: 1 is F, 13 is A+. */
205
+ const GRADE_LETTERS = ["F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A", "A+"] as const;
206
+ /** The composite's labels from the score each starts at: its nearest whole number. */
207
+ const COMPOSITE_BANDS = [
208
+ { from: 4.5, label: "Top" },
209
+ { from: 3.5, label: "Strong" },
210
+ { from: 2.5, label: "Neutral" },
211
+ { from: 1.5, label: "Weak" },
212
+ { from: 1, label: "Bottom" },
213
+ ] as const;
214
+ const gradeLetter = (value: number): string | null =>
215
+ Number.isInteger(value) ? GRADE_LETTERS[value - 1] ?? null : null;
216
+ const compositeLabel = (score: number): string =>
217
+ (COMPOSITE_BANDS.find((band) => score >= band.from) ?? COMPOSITE_BANDS.at(-1)!).label;
218
+ /**
219
+ * The number a cell's sign colour reads, or null for a field without one: a move is its own sign, and a grade the side
220
+ * of the middle it falls on, B- and up above it and D+ and down below, Strong and Top above the composite's middle and
221
+ * Weak and Bottom below. So every grade reads in the colours a move does, in every view that shows it.
222
+ */
223
+ export function screenSignValue(field: NumericField, value: number | null): number | null {
224
+ if (value == null || !Number.isFinite(value)) return null;
225
+ if (SIGN_COLORED.has(field)) return Math.abs(value) < 0.05 ? 0 : value;
226
+ if (LETTER_GRADES.has(field)) return value >= 8 ? 1 : value <= 4 ? -1 : 0;
227
+ if (field === "gradeComposite") return value >= 3.5 ? 1 : value < 2.5 ? -1 : 0;
228
+ return null;
229
+ }
168
230
  const COUNTS = new Set<NumericField>(["appRatingCountGrowth7d", "hiringNetAddsWeek", "hiringOpenRoles", "attentionResearchUnits", "insiderPurchases90d", "insiderSales90d", "institutionalHolders", "institutionalNewHolders", "institutionalExits", "ivRank", "ivPercentile", "hvRank",
169
231
  "macdBullishCrossDays", "macdBearishCrossDays", "goldenCrossDays", "deathCrossDays",
170
- "newHigh20dDays", "newLow20dDays", "newHigh52wDays", "newLow52wDays", "bollingerWidthPercentile"]);
171
- const MONETARY = new Set<NumericField>(["price", "marketCap", "kpiArr", "kpiRpo", "kpiCrpo", "kpiGmv", "kpiBacklog"]);
232
+ "newHigh20dDays", "newLow20dDays", "newHigh52wDays", "newLow52wDays", "bollingerWidthPercentile",
233
+ "piotroskiFScore", "magicFormulaRank", "rsRating", "profitableYears", "revenueGrowthYears", "dividendGrowthYears"]);
234
+ const MONETARY = new Set<NumericField>(["price", "marketCap", "kpiArr", "kpiRpo", "kpiCrpo", "kpiGmv", "kpiBacklog", "grahamNumber", "lynchFairValue"]);
235
+ /** Prices and scores read to two decimals, as the quote and beta are. */
236
+ const HUNDREDTHS = new Set<NumericField>(["price", "beta", "altmanZScore", "grahamNumber", "lynchFairValue"]);
237
+ const MEMBERSHIP = new Set<NumericField>(MEMBERSHIP_FIELDS);
172
238
  /** Shown after the screen's own criteria when the pane has room. */
173
239
  const CONTEXT_FIELDS: NumericField[] = ["marketCap", "price", "changePercent", "trailingPE", "revenueGrowthPercent", "operatingMarginPercent", "dividendYieldPercent"];
174
240
 
@@ -178,7 +244,10 @@ export function formatScreenValue(field: NumericField, value: number | null): st
178
244
  if (DAILY_COUNTS.has(field)) return value < 1_000 ? value.toFixed(0) : formatCompact(value, { fixedDecimals: true });
179
245
  if (RATIOS.has(field)) return `${value.toFixed(1)}x`;
180
246
  if (COUNTS.has(field)) return formatNumber(value, 0);
181
- if (field === "price" || field === "beta") return formatNumber(value, 2);
247
+ if (MEMBERSHIP.has(field)) return value === 1 ? "Yes" : "No";
248
+ if (LETTER_GRADES.has(field)) return gradeLetter(value) ?? "--";
249
+ if (field === "gradeComposite") return `${formatNumber(value, 2)} ${compositeLabel(value)}`;
250
+ if (HUNDREDTHS.has(field)) return formatNumber(value, 2);
182
251
  // A value that rounds to zero prints 0.0, never -0.0.
183
252
  const fixed = Math.abs(value) < 0.05 ? "0.0" : formatNumber(value, 1);
184
253
  return SIGNED.has(field) && value > 0 && fixed !== "0.0" ? `+${fixed}` : fixed;
@@ -189,6 +258,36 @@ export function formatScreenMetric(field: NumericField, metric: Pick<ScreenMetri
189
258
  return metric.value == null && metric.notMeaningful ? formatPriceEarnings(NOT_MEANINGFUL) : formatScreenValue(field, metric.value);
190
259
  }
191
260
 
261
+ /** A metric as a company's detail prints it: with its unit, but a grade or the composite reads as itself (B+, 4.72 Top). */
262
+ export function screenDetailValue(field: NumericField, metric: Pick<ScreenMetric, "value" | "notMeaningful" | "unit">): string {
263
+ // A missing value is just "--", without the unit it would have had; N/M says so.
264
+ if (metric.value == null) return metric.notMeaningful ? formatScreenMetric(field, metric) : formatScreenValue(field, null);
265
+ const text = formatScreenValue(field, metric.value);
266
+ if (GRADE_DISPLAY_FIELDS.has(field)) return text;
267
+ // A count of one is singular: 1 year, 1 day.
268
+ const unit = metric.value === 1 && COUNT_UNITS.has(metric.unit) ? metric.unit.slice(0, -1) : metric.unit;
269
+ return unit ? `${text} ${unit}` : text;
270
+ }
271
+ const COUNT_UNITS: ReadonlySet<string> = new Set(["years", "days", "sessions", "weeks", "months"]);
272
+
273
+ /** The note a grade on a company's other line leads with, naming the line it was graded on (the server's text). */
274
+ const COMPANY_NOTE = /^One company with \S+, its primary line: graded once, on that line's figures\.\s*/;
275
+ /**
276
+ * A grade's reason split into the company note, which every grade of the line repeats and the detail says once, and
277
+ * what is this grade's own (its peers, an N/M or stale input), null when nothing is left.
278
+ */
279
+ export function splitGradeReason(reason: string | null): { company: string | null; own: string | null } {
280
+ const match = reason == null ? null : COMPANY_NOTE.exec(reason);
281
+ if (!match) return { company: null, own: reason };
282
+ return { company: match[0].trim(), own: reason!.slice(match[0].length).trim() || null };
283
+ }
284
+
285
+ /** Where a grade ranks, from its source without the letter it leads with: `percentile 82.4 among 412 Technology listings, from ...`. */
286
+ export function gradeRankText(metric: Pick<ScreenMetric, "source">): string | null {
287
+ const text = metric.source?.replace(/^[^:]{1,12}:\s*/, "").trim();
288
+ return text ? text : null;
289
+ }
290
+
192
291
  /**
193
292
  * A row's dividend yield basis, in the words `ticker` and `DVD` use. Gloom
194
293
  * Cloud serves each row's statistics yield as it is stated, forward for most
@@ -254,8 +353,9 @@ export function screenColumnLabel(field: NumericField, ytdBase: string | null, f
254
353
  return form === "compact" ? `YTD% ${ytdBase}` : `YTD% vs ${ytdBase}${form === "report" ? " close" : ""}`;
255
354
  }
256
355
 
257
- /** Prices get room for a separated six-figure quote (757,398.00). */
258
- export const columnWidth = (field: NumericField, label = SHORT_LABELS[field]) => Math.max(field === "price" ? 10 : 8, label.length);
356
+ /** Prices get room for a separated six-figure quote (757,398.00), the composite for its label (3.36 Neutral). */
357
+ export const columnWidth = (field: NumericField, label = SHORT_LABELS[field]) =>
358
+ Math.max(field === "price" ? 10 : field === "gradeComposite" ? 12 : 8, label.length);
259
359
 
260
360
  export const DEFAULT_SCREEN: ScreenDefinition = {
261
361
  version: 1,
@@ -393,6 +493,30 @@ export const screenLabel = (field: string) =>
393
493
  epsCagr5YPercent: "EPS CAGR 5Y %",
394
494
  forwardRevenueGrowthPercent: "Forward revenue growth %",
395
495
  forwardEpsGrowthPercent: "Forward EPS growth %",
496
+ piotroskiFScore: "Piotroski F-score",
497
+ altmanZScore: "Altman Z-score",
498
+ grahamNumber: "Graham number",
499
+ grahamUpsidePercent: "Graham number upside %",
500
+ lynchFairValue: "Lynch fair value",
501
+ lynchUpsidePercent: "Lynch fair value upside %",
502
+ earningsYieldPercent: "Earnings yield (EBIT / EV) %",
503
+ returnOnCapitalPercent: "Return on capital (Greenblatt) %",
504
+ magicFormulaRank: "Magic Formula rank",
505
+ totalReturn1YPercent: "1Y total return %",
506
+ rsRating: "RS rating",
507
+ profitableYears: "Profitable years",
508
+ revenueGrowthYears: "Revenue growth years",
509
+ dividendGrowthYears: "Dividend growth years",
510
+ sp500Member: "S&P 500 member",
511
+ dowMember: "Dow member",
512
+ valueGrade: "Value grade",
513
+ growthGrade: "Growth grade",
514
+ profitabilityGrade: "Profitability grade",
515
+ momentumGrade: "Momentum grade",
516
+ revisionsGrade: "Revisions grade",
517
+ gradeComposite: "Grade composite",
518
+ nextYearEpsRevision30dPercent: "Next FY EPS revision 30D %",
519
+ revenueRevision30dPercent: "Revenue revision 30D %",
396
520
  hiringOpenRoles: "Hiring open roles",
397
521
  hiringNetAddsWeek: "Net open roles per week",
398
522
  hiringRemotePercent: "Remote roles %",
@@ -431,9 +555,11 @@ export function parseCriterion(
431
555
  value: values,
432
556
  };
433
557
  }
434
- const values = text.split(",").map(parseThreshold);
558
+ const values = text.split(",").map((part) => parseGradeThreshold(field.id, part) ?? parseThreshold(part));
435
559
  if (values.some((value) => value === null))
436
- throw new Error("Enter a finite numeric threshold, such as 25 or 10B.");
560
+ throw new Error(LETTER_GRADES.has(field.id as NumericField)
561
+ ? "Enter a grade from F to A+, such as B+."
562
+ : "Enter a finite numeric threshold, such as 25 or 10B.");
437
563
  if (operator === "between") {
438
564
  if (values.length !== 2 || Number(values[0]) > Number(values[1]))
439
565
  throw new Error("Enter minimum, maximum in ascending order.");
@@ -454,6 +580,34 @@ export function parseCriterion(
454
580
  value: Number(values[0]),
455
581
  };
456
582
  }
583
+ /** A grade typed as its letter (`b+`, `A`), or the composite as its label (`Strong` is 3.5); null for anything else. */
584
+ function parseGradeThreshold(field: string, text: string): number | null {
585
+ const typed = text.trim().toUpperCase();
586
+ if (LETTER_GRADES.has(field as NumericField)) {
587
+ const index = (GRADE_LETTERS as readonly string[]).indexOf(typed);
588
+ return index >= 0 ? index + 1 : null;
589
+ }
590
+ if (field === "gradeComposite") return COMPOSITE_BANDS.find((band) => band.label.toUpperCase() === typed)?.from ?? null;
591
+ return null;
592
+ }
593
+ /** A criterion's value as the editor shows it: a grade as its letter, a range as `min, max`. */
594
+ export function criterionInputText(criterion: ScreenCriterion | null): string {
595
+ if (!criterion || !("value" in criterion)) return "";
596
+ const shown = (value: string | number) => typeof value === "number" && LETTER_GRADES.has(criterion.field as NumericField)
597
+ ? gradeLetter(value) ?? String(value) : String(value);
598
+ return Array.isArray(criterion.value) ? criterion.value.map(shown).join(", ") : shown(criterion.value);
599
+ }
600
+ /** What the value field asks for: the grade's range for a grade, else the field's unit. */
601
+ export function criterionValueLabel(field: Pick<ScreenFieldDefinition, "id" | "unit">): string {
602
+ const unit = LETTER_GRADES.has(field.id as NumericField) ? "F to A+" : field.unit;
603
+ return `Value${unit ? ` (${unit})` : ""}`;
604
+ }
605
+ /** An example value: a letter for a grade, a score or label for the composite. */
606
+ export function criterionValueHint(field: Pick<ScreenFieldDefinition, "id">, operator: ScreenOperator): string {
607
+ if (LETTER_GRADES.has(field.id as NumericField)) return operator === "between" ? "lowest, highest grade, e.g. B, A+" : "grade, e.g. B+";
608
+ if (field.id === "gradeComposite") return operator === "between" ? "minimum, maximum, e.g. 3.5, 5" : "score or label, e.g. 3.5 or Strong";
609
+ return operator === "between" ? "minimum, maximum" : operator === "in" ? "comma-separated values" : "threshold, e.g. 25 or 10B";
610
+ }
457
611
  const SCALE: Record<string, number> = { k: 1e3, m: 1e6, b: 1e9, t: 1e12 };
458
612
  /** A plain number or one with a k/M/B/T scale suffix: 25, -0.5, 1e6, 10B. */
459
613
  export function parseThreshold(text: string): number | null {
@@ -479,6 +633,15 @@ export function criterionText(criterion: ScreenCriterion): string {
479
633
  };
480
634
  const value = !("value" in criterion)
481
635
  ? ""
636
+ // Membership is 1 or 0: `S&P 500 member = yes`.
637
+ : MEMBERSHIP.has(criterion.field as NumericField) && typeof criterion.value === "number" && [0, 1].includes(criterion.value)
638
+ ? ` ${criterion.value === 1 ? "yes" : "no"}`
639
+ // A grade reads as its letter: `Value grade >= B+`.
640
+ : LETTER_GRADES.has(criterion.field as NumericField)
641
+ ? ` ${criterionInputText(criterion)}`
642
+ // The composite names the label a threshold starts: `Grade composite >= 4.5 (Top)`.
643
+ : criterion.field === "gradeComposite" && typeof criterion.value === "number"
644
+ ? ` ${thresholdText(criterion.value)}${COMPOSITE_BANDS.some((band) => band.from === criterion.value && band.from > 1) ? ` (${compositeLabel(criterion.value)})` : ""}`
482
645
  : Array.isArray(criterion.value)
483
646
  ? ` ${criterion.value.map((item) => (typeof item === "number" ? thresholdText(item) : item)).join(", ")}`
484
647
  : ` ${thresholdText(criterion.value)}`;
@@ -488,6 +651,8 @@ export function criterionText(criterion: ScreenCriterion): string {
488
651
  const OBSERVED_SUBSET_FIELDS: readonly string[] = ["insiderPurchases90d", "insiderSales90d"];
489
652
  const NUMERIC_OPERATORS: ScreenOperator[] = ["gte", "lte", "gt", "lt", "eq", "between", "present", "missing"];
490
653
  const OBSERVED_SUBSET_OPERATORS: ScreenOperator[] = ["gte", "gt", "present", "missing"];
654
+ /** Index membership is 1 or 0: equal to one, or there or not. */
655
+ const MEMBERSHIP_OPERATORS: ScreenOperator[] = ["eq", "present", "missing"];
491
656
  const CATEGORY_OPERATORS: ScreenOperator[] = ["in", "present", "missing"];
492
657
 
493
658
  /**
@@ -513,6 +678,7 @@ function unknownFieldText(field: unknown): string {
513
678
  /** The operators a definition may use on a field, or null for a field screens do not have. */
514
679
  function screenFieldOperators(field: string): ScreenOperator[] | null {
515
680
  if (OBSERVED_SUBSET_FIELDS.includes(field)) return [...OBSERVED_SUBSET_OPERATORS];
681
+ if ((MEMBERSHIP_FIELDS as readonly string[]).includes(field)) return [...MEMBERSHIP_OPERATORS];
516
682
  if ((NUMERIC_FIELDS as readonly string[]).includes(field)) return [...NUMERIC_OPERATORS];
517
683
  if ((CATEGORY_FIELDS as readonly string[]).includes(field)) return [...CATEGORY_OPERATORS];
518
684
  return null;
@@ -530,6 +696,8 @@ export function screenDefinitionSyntax(): string {
530
696
  `Operators by field: numeric fields (the --metric values) take ${single.join(", ")} with one number,`,
531
697
  "between with [min, max], present and missing with no value;",
532
698
  `${OBSERVED_SUBSET_FIELDS.join(" and ")} take only ${OBSERVED_SUBSET_OPERATORS.join(", ")};`,
699
+ `${MEMBERSHIP_FIELDS.join(" and ")} take only ${MEMBERSHIP_OPERATORS.join(", ")}, eq with 1 for a member or 0;`,
700
+ `the grades (${LETTER_GRADE_FIELDS.join(", ")}) are numbers from 1 (F) to 13 (A+), so B+ or better is gte 10, and gradeComposite runs from 1 to 5 (4.5 and up is Top);`,
533
701
  `category fields (${CATEGORY_FIELDS.join(", ")}) take in with an array of 1-25 names, present, missing.`,
534
702
  ].join(" ");
535
703
  }
@@ -706,9 +874,9 @@ export function validateScreenPayload(value: unknown): ScreenPayload {
706
874
  throw new Error("Invalid screener listing identity.");
707
875
  ids.add(screenRowId(row));
708
876
  for (const field of NUMERIC_FIELDS) {
709
- // A server from before social, research, volatility, dividend, technical, option volatility, ownership or quality
710
- // fields omits them; they read as unavailable. A Pro field it left out was held back from this caller.
711
- if (!row.metrics[field] && ([...SOCIAL_FIELDS, ...RESEARCH_FIELDS, ...VOLATILITY_FIELDS, ...TECHNICAL_FIELDS, ...OPTION_VOLATILITY_FIELDS, ...OWNERSHIP_FIELDS, ...QUALITY_FIELDS, ...ATTENTION_FIELDS, ...HIRING_APP_FIELDS, ...KPI_FIELDS, ...DIVIDEND_FIELDS] as readonly string[]).includes(field))
877
+ // A server from before social, research, volatility, dividend, technical, option volatility, ownership, quality,
878
+ // score or grade fields omits them; they read as unavailable. A Pro field it left out was held back from this caller.
879
+ if (!row.metrics[field] && ([...SOCIAL_FIELDS, ...RESEARCH_FIELDS, ...VOLATILITY_FIELDS, ...TECHNICAL_FIELDS, ...OPTION_VOLATILITY_FIELDS, ...OWNERSHIP_FIELDS, ...QUALITY_FIELDS, ...SCORE_FIELDS, ...GRADE_FIELDS, ...ATTENTION_FIELDS, ...HIRING_APP_FIELDS, ...KPI_FIELDS, ...DIVIDEND_FIELDS] as readonly string[]).includes(field))
712
880
  row.metrics[field] = PRO_FIELDS.has(field) ? withheldMetric() : unavailableMetric();
713
881
  const metric = row.metrics[field];
714
882
  if (