gloomberb 0.20.6 → 0.20.7

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 (67) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/fund-facts.ts +20 -4
  3. package/src/api-client/socket.ts +4 -4
  4. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  5. package/src/cli/commands/market.ts +33 -17
  6. package/src/cli/commands/search.ts +19 -3
  7. package/src/cli/desktop-pane-shot.ts +61 -0
  8. package/src/cli/pane-functions/dom.ts +4 -4
  9. package/src/cli/pane-functions/freshness.ts +38 -5
  10. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  11. package/src/cli/quote-answer.ts +57 -1
  12. package/src/cli/result.ts +17 -0
  13. package/src/docs/snapshot.json +55 -16
  14. package/src/i18n/es.ts +2 -0
  15. package/src/i18n/ja.ts +2 -0
  16. package/src/i18n/ko.ts +2 -0
  17. package/src/i18n/zh-cn.ts +2 -0
  18. package/src/i18n/zh-tw.ts +2 -0
  19. package/src/market-data/market/change-basis.ts +49 -8
  20. package/src/market-data/market/dated-previous-close.ts +133 -10
  21. package/src/market-data/market/freshness.ts +18 -6
  22. package/src/market-data/market/status.ts +9 -1
  23. package/src/market-data/published-nse-sessions.ts +16 -1
  24. package/src/market-data/quotes/freshness.ts +15 -0
  25. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  26. package/src/plugins/builtin/alerts/cli.ts +22 -9
  27. package/src/plugins/builtin/alerts/headless.ts +1 -1
  28. package/src/plugins/builtin/alerts/index.tsx +5 -1
  29. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  30. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  31. package/src/plugins/builtin/holders/headless.ts +5 -4
  32. package/src/plugins/builtin/holders/pane.tsx +7 -3
  33. package/src/plugins/builtin/holders/report-header.ts +23 -0
  34. package/src/plugins/builtin/members/client.ts +1 -1
  35. package/src/plugins/builtin/members/headless.ts +2 -0
  36. package/src/plugins/builtin/members/model.ts +10 -8
  37. package/src/plugins/builtin/members/pane.tsx +4 -1
  38. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  39. package/src/plugins/builtin/portfolio-list/cli/render.ts +66 -23
  40. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  41. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  42. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  43. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  44. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  45. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  46. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  47. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  48. package/src/portfolio/column-values.ts +3 -0
  49. package/src/portfolio/valuation-basis.ts +23 -1
  50. package/src/state/hooks/quote-streaming.ts +14 -6
  51. package/src/tickers/instrument-kind.ts +22 -1
  52. package/src/tickers/search/index.ts +5 -0
  53. package/src/tickers/terminal-codes.ts +17 -5
  54. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  55. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  56. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  57. package/src/time-series/fundamentals/period-points.ts +104 -0
  58. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  59. package/src/time-series/fundamentals/series.ts +164 -0
  60. package/src/time-series/fundamentals/source-statements.ts +177 -0
  61. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  62. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  63. package/src/time-series/fundamentals/statement.ts +114 -0
  64. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  65. package/src/time-series/fundamentals.ts +18 -1407
  66. package/src/types/financials.ts +9 -0
  67. package/src/utils/debug-log.ts +29 -0
@@ -0,0 +1,154 @@
1
+ // Picks the statement fields a metric reads (shares, cash, EPS, free cash flow) and the dependencies that date it.
2
+ import type { FinancialStatement } from "../../types/financials";
3
+ import { completeAvailability, statementFieldAvailability } from "../../utils/financial-statements";
4
+ import { hasStatementGap } from "../../utils/statement-gaps";
5
+ import { isFiniteNumber } from "../../utils/guards";
6
+ import { type InternalStatement, type NumericStatementField, statementNumber } from "./statement";
7
+
8
+ export function ratio(numerator: unknown, denominator: unknown): number | null {
9
+ return isFiniteNumber(numerator) && isFiniteNumber(denominator) && denominator !== 0
10
+ ? numerator / denominator
11
+ : null;
12
+ }
13
+
14
+ export function freeCashFlow(statement: FinancialStatement): { value: number | null; derived: boolean } {
15
+ if (isFiniteNumber(statement.freeCashFlow)) return { value: statement.freeCashFlow, derived: false };
16
+ if (isFiniteNumber(statement.operatingCashFlow) && isFiniteNumber(statement.capitalExpenditure)) {
17
+ return { value: statement.operatingCashFlow + statement.capitalExpenditure, derived: true };
18
+ }
19
+ return { value: null, derived: false };
20
+ }
21
+
22
+ type SelectedStatementField = {
23
+ field: NumericStatementField;
24
+ value: number;
25
+ };
26
+
27
+ function selectStatementField(
28
+ statement: FinancialStatement,
29
+ fields: readonly NumericStatementField[],
30
+ accepts: (value: number) => boolean = () => true,
31
+ ): SelectedStatementField | null {
32
+ for (const field of fields) {
33
+ const value = statementNumber(statement, field);
34
+ if (value !== null && accepts(value)) return { field, value };
35
+ }
36
+ return null;
37
+ }
38
+
39
+ export function selectedShares(statement: FinancialStatement): SelectedStatementField | null {
40
+ return selectStatementField(
41
+ statement,
42
+ ["dilutedShares", "basicShares", "ordinarySharesNumber", "shareIssued"],
43
+ (value) => value > 0,
44
+ );
45
+ }
46
+
47
+ export function selectedCash(statement: FinancialStatement): SelectedStatementField | null {
48
+ return selectStatementField(statement, [
49
+ "cashCashEquivalentsAndShortTermInvestments",
50
+ "cashAndCashEquivalents",
51
+ ]);
52
+ }
53
+
54
+ export function selectedEps(
55
+ statement: InternalStatement,
56
+ ): { value: number; dependencies: NumericStatementField[] } | null {
57
+ if (statement.epsBasis?.status === "unresolved" || hasStatementGap(statement, "eps")) return null;
58
+ if (isFiniteNumber(statement.eps)) {
59
+ return { value: statement.eps, dependencies: ["eps"] };
60
+ }
61
+ if (statement.__timeSeriesIncompleteCommonIncome || statement.__timeSeriesIncompleteAverageShares
62
+ || statement.unavailableFields?.includes("netIncomeCommonStockholders")) return null;
63
+ const shares = selectedShares(statement);
64
+ const income = selectStatementField(statement, ["netIncomeCommonStockholders", "netIncome"]);
65
+ if (!shares || !income) return null;
66
+ return {
67
+ value: income.value / shares.value,
68
+ dependencies: [income.field, shares.field],
69
+ };
70
+ }
71
+
72
+ function uniqueDependencies(
73
+ fields: Array<NumericStatementField | null | undefined>,
74
+ ): NumericStatementField[] {
75
+ return [...new Set(fields.filter((field): field is NumericStatementField => !!field))];
76
+ }
77
+
78
+ function metricDependencies(metric: string, statement: FinancialStatement): NumericStatementField[] {
79
+ if (metric === "grossMargin") return ["grossProfit", "totalRevenue"];
80
+ if (metric === "operatingMargin") return ["operatingIncome", "totalRevenue"];
81
+ if (metric === "netMargin") return ["netIncome", "totalRevenue"];
82
+ if (metric === "freeCashFlowMargin") {
83
+ return isFiniteNumber(statement.freeCashFlow)
84
+ ? ["freeCashFlow", "totalRevenue"]
85
+ : ["operatingCashFlow", "capitalExpenditure", "totalRevenue"];
86
+ }
87
+ if (metric === "freeCashFlow") {
88
+ return isFiniteNumber(statement.freeCashFlow)
89
+ ? ["freeCashFlow"]
90
+ : ["operatingCashFlow", "capitalExpenditure"];
91
+ }
92
+ if (metric === "trailingPE") return selectedEps(statement)?.dependencies ?? ["eps"];
93
+ if (metric === "priceSales") {
94
+ return uniqueDependencies(["totalRevenue", selectedShares(statement)?.field]);
95
+ }
96
+ if (metric === "evSales") {
97
+ return uniqueDependencies([
98
+ "totalRevenue",
99
+ selectedShares(statement)?.field,
100
+ "totalDebt",
101
+ selectedCash(statement)?.field,
102
+ ]);
103
+ }
104
+ if (metric === "evEbitda") {
105
+ return uniqueDependencies([
106
+ "ebitda",
107
+ selectedShares(statement)?.field,
108
+ "totalDebt",
109
+ selectedCash(statement)?.field,
110
+ ]);
111
+ }
112
+ if (metric === "priceFcf") {
113
+ return uniqueDependencies([
114
+ ...(isFiniteNumber(statement.freeCashFlow)
115
+ ? ["freeCashFlow" as const]
116
+ : ["operatingCashFlow" as const, "capitalExpenditure" as const]),
117
+ selectedShares(statement)?.field,
118
+ ]);
119
+ }
120
+ return [metric as NumericStatementField];
121
+ }
122
+
123
+ export function metricAvailability(statement: FinancialStatement, metric: string): string | undefined {
124
+ const dependencies = metricDependencies(metric, statement);
125
+ return completeAvailability(dependencies.map((field) => statementFieldAvailability(statement, field)));
126
+ }
127
+
128
+ export function fundamentalValue(
129
+ statement: InternalStatement,
130
+ metric: string,
131
+ ): { value: number | null; derived: boolean } {
132
+ if (metric === "grossMargin") {
133
+ const value = ratio(statement.grossProfit, statement.totalRevenue);
134
+ return { value: value === null ? null : value * 100, derived: true };
135
+ }
136
+ if (metric === "operatingMargin") {
137
+ const value = ratio(statement.operatingIncome, statement.totalRevenue);
138
+ return { value: value === null ? null : value * 100, derived: true };
139
+ }
140
+ if (metric === "netMargin") {
141
+ const value = ratio(statement.netIncome, statement.totalRevenue);
142
+ return { value: value === null ? null : value * 100, derived: true };
143
+ }
144
+ if (metric === "freeCashFlow" || metric === "freeCashFlowMargin") {
145
+ const fcf = freeCashFlow(statement);
146
+ if (metric === "freeCashFlow") return fcf;
147
+ const value = ratio(fcf.value, statement.totalRevenue);
148
+ return { value: value === null ? null : value * 100, derived: true };
149
+ }
150
+ const value = statementNumber(statement, metric as NumericStatementField);
151
+ const derived = statement.__timeSeriesTtm === true
152
+ || statement.__timeSeriesDerivedFields?.includes(metric as NumericStatementField) === true;
153
+ return { value, derived };
154
+ }
@@ -0,0 +1,124 @@
1
+ // Merges the statements a source reports for one fiscal period into a single row.
2
+ import type { FinancialStatement } from "../../types/financials";
3
+ import { areNearbyFinancialPeriodEnds, completeAvailability, statementFieldAvailability } from "../../utils/financial-statements";
4
+ import { copyIncomeField, incomeFieldKnowledgeDate, incomeFieldOwner, isIncomeStatementField } from "../../utils/income-statement";
5
+ import { hasStatementGap, mergeStatementGaps } from "../../utils/statement-gaps";
6
+ import {
7
+ completeStatementAvailability,
8
+ type InternalStatement,
9
+ NUMERIC_STATEMENT_FIELDS,
10
+ type NumericStatementField,
11
+ statementNumber,
12
+ } from "./statement";
13
+
14
+ function statementAvailabilityScore(statement: FinancialStatement): number {
15
+ return Object.values(statement.fieldAvailability ?? {})
16
+ .filter((value) => Number.isFinite(Date.parse(value)))
17
+ .length + (Number.isFinite(Date.parse(statement.availableAt ?? "")) ? 1 : 0);
18
+ }
19
+
20
+ interface StatementFieldCandidate {
21
+ statement: InternalStatement;
22
+ value: number;
23
+ availableAt?: string;
24
+ derived: boolean;
25
+ }
26
+
27
+ function selectFieldCandidate(candidates: StatementFieldCandidate[]): StatementFieldCandidate {
28
+ const reported = candidates.filter((candidate) => !candidate.derived);
29
+ const qualityCandidates = reported.length > 0 ? reported : candidates;
30
+ const dated = qualityCandidates.filter((candidate) => (
31
+ Number.isFinite(Date.parse(candidate.availableAt ?? ""))
32
+ ));
33
+ const chronological = [...(dated.length > 0 ? dated : qualityCandidates)].sort((left, right) => (
34
+ Date.parse(left.availableAt ?? "") - Date.parse(right.availableAt ?? "")
35
+ || left.statement.date.localeCompare(right.statement.date)
36
+ ));
37
+ let selected = chronological[0]!;
38
+ for (const candidate of chronological.slice(1)) {
39
+ if (!Object.is(candidate.value, selected.value)) selected = candidate;
40
+ }
41
+ return selected;
42
+ }
43
+
44
+ function periodDateSource(statements: readonly InternalStatement[]): InternalStatement {
45
+ return [...statements].sort((left, right) => {
46
+ const availabilityDifference = statementAvailabilityScore(right) - statementAvailabilityScore(left);
47
+ return availabilityDifference || left.date.localeCompare(right.date);
48
+ })[0]!;
49
+ }
50
+
51
+ function mergeStatementPeriodGroup(statements: readonly InternalStatement[]): InternalStatement {
52
+ const dateSource = periodDateSource(statements);
53
+ const merged: InternalStatement = { date: dateSource.date, currency: dateSource.currency };
54
+ const compatibleStatements = statements.filter((statement) => statement.currency === dateSource.currency);
55
+ const derivedFields: NumericStatementField[] = [];
56
+ const fieldAvailability: Record<string, string> = {};
57
+ const record = merged as unknown as Record<string, unknown>;
58
+
59
+ for (const field of NUMERIC_STATEMENT_FIELDS) {
60
+ // A gap declared for the period is never filled from another report.
61
+ if (!isIncomeStatementField(field) && compatibleStatements.some((statement) => hasStatementGap(statement, field))) continue;
62
+ if (isIncomeStatementField(field)) {
63
+ const qualified = compatibleStatements.filter(statement => statement.date === dateSource.date && incomeFieldOwner(field, statement));
64
+ if (qualified.length) {
65
+ const owner = [...qualified].sort((left, right) => incomeFieldKnowledgeDate(right, field).localeCompare(incomeFieldKnowledgeDate(left, field)))[0]!;
66
+ copyIncomeField(merged, owner, field);
67
+ const availability = statementFieldAvailability(owner, field);
68
+ if (typeof merged[field] === "number" && availability) fieldAvailability[field] = availability;
69
+ continue;
70
+ }
71
+ }
72
+ const candidates = compatibleStatements.flatMap((statement): StatementFieldCandidate[] => {
73
+ if (isIncomeStatementField(field) && statement.date !== dateSource.date
74
+ && incomeFieldOwner(field, statement)) return [];
75
+ const value = statementNumber(statement, field);
76
+ if (value === null) return [];
77
+ return [{
78
+ statement,
79
+ value,
80
+ availableAt: statementFieldAvailability(statement, field),
81
+ derived: statement.__timeSeriesDerivedFields?.includes(field) === true,
82
+ }];
83
+ });
84
+ const verifiedEps = field === "eps" ? candidates.filter((candidate) => candidate.statement.epsBasis?.status === "split-adjusted") : [];
85
+ const unresolvedEps = field === "eps" ? compatibleStatements.find((statement) => statement.epsBasis?.status === "unresolved") : undefined;
86
+ if (unresolvedEps && verifiedEps.length === 0) {
87
+ merged.epsBasis = unresolvedEps.epsBasis;
88
+ continue;
89
+ }
90
+ if (candidates.length === 0) continue;
91
+ const selected = selectFieldCandidate(verifiedEps.length ? verifiedEps : candidates);
92
+ record[field] = selected.value;
93
+ if (field === "eps" && selected.statement.epsBasis) merged.epsBasis = selected.statement.epsBasis;
94
+ if (selected.availableAt) fieldAvailability[field] = selected.availableAt;
95
+ if (selected.derived) derivedFields.push(field);
96
+ }
97
+
98
+ mergeStatementGaps(merged, compatibleStatements);
99
+ merged.fieldAvailability = fieldAvailability;
100
+ merged.availableAt = completeStatementAvailability(merged);
101
+ if (NUMERIC_STATEMENT_FIELDS.every(field => statementNumber(merged, field) === null)) {
102
+ // Even an empty statement can establish when a missing period became
103
+ // known. Its empty field map still cannot date any numeric metric.
104
+ merged.availableAt = completeAvailability([dateSource.availableAt]);
105
+ }
106
+ if (derivedFields.length > 0) merged.__timeSeriesDerivedFields = derivedFields;
107
+ return merged;
108
+ }
109
+
110
+ export function mergeStatementsByPeriod(
111
+ statements: readonly FinancialStatement[],
112
+ ): InternalStatement[] {
113
+ const groups: InternalStatement[][] = [];
114
+ const sorted = [...statements].sort((left, right) => left.date.localeCompare(right.date));
115
+ for (const statement of sorted) {
116
+ const lastGroup = groups.at(-1);
117
+ if (lastGroup && areNearbyFinancialPeriodEnds(lastGroup[0]!.date, statement.date)) {
118
+ lastGroup.push(statement as InternalStatement);
119
+ } else groups.push([statement as InternalStatement]);
120
+ }
121
+ return groups
122
+ .map(mergeStatementPeriodGroup)
123
+ .sort((left, right) => left.date.localeCompare(right.date));
124
+ }
@@ -0,0 +1,114 @@
1
+ // Statement field names, the numeric field lists and the accessors every fundamentals module reads a statement through.
2
+ import type { FinancialStatement } from "../../types/financials";
3
+ import { completeAvailability, statementFieldAvailability } from "../../utils/financial-statements";
4
+ import { isFiniteNumber } from "../../utils/guards";
5
+
6
+ export type NumericStatementField =
7
+ | "totalRevenue"
8
+ | "grossProfit"
9
+ | "operatingIncome"
10
+ | "netIncome"
11
+ | "netIncomeIncludingNoncontrollingInterests"
12
+ | "netIncomeCommonStockholders"
13
+ | "ebitda"
14
+ | "depreciationAndAmortization"
15
+ | "operatingCashFlow"
16
+ | "capitalExpenditure"
17
+ | "freeCashFlow"
18
+ | "eps"
19
+ | "totalAssets"
20
+ | "cashAndCashEquivalents"
21
+ | "cashCashEquivalentsAndShortTermInvestments"
22
+ | "totalDebt"
23
+ | "totalEquity"
24
+ | "basicShares"
25
+ | "dilutedShares"
26
+ | "shareIssued"
27
+ | "ordinarySharesNumber";
28
+
29
+ export type InternalStatement = FinancialStatement & {
30
+ __timeSeriesDerivedFields?: NumericStatementField[];
31
+ __timeSeriesTtm?: boolean;
32
+ __timeSeriesIncompleteCommonIncome?: boolean;
33
+ __timeSeriesIncompleteAverageShares?: boolean;
34
+ };
35
+
36
+ export const DAY_MS = 24 * 60 * 60 * 1_000;
37
+
38
+ export const QUARTERLY_FLOW_FIELDS: readonly NumericStatementField[] = [
39
+ "totalRevenue",
40
+ "grossProfit",
41
+ "operatingIncome",
42
+ "netIncome",
43
+ "netIncomeIncludingNoncontrollingInterests",
44
+ "ebitda",
45
+ "depreciationAndAmortization",
46
+ "operatingCashFlow",
47
+ "capitalExpenditure",
48
+ "freeCashFlow",
49
+ ];
50
+
51
+ export const QUARTERLY_SNAPSHOT_FIELDS: readonly NumericStatementField[] = [
52
+ "totalAssets",
53
+ "cashAndCashEquivalents",
54
+ "cashCashEquivalentsAndShortTermInvestments",
55
+ "totalDebt",
56
+ "totalEquity",
57
+ "shareIssued",
58
+ "ordinarySharesNumber",
59
+ ];
60
+
61
+ export const QUARTERLY_AVERAGE_FIELDS: readonly NumericStatementField[] = ["basicShares", "dilutedShares"];
62
+
63
+ // Reported common-income allocations and EPS may be summed for TTM, but
64
+ // independently determined annual values cannot establish a missing quarter.
65
+ // A trailing year across a fiscal Q4 without EPS reads that year's own EPS.
66
+ export const TTM_SUM_FIELDS: readonly NumericStatementField[] = [...QUARTERLY_FLOW_FIELDS, "netIncomeCommonStockholders", "eps"];
67
+
68
+ export const NUMERIC_STATEMENT_FIELDS: readonly NumericStatementField[] = [
69
+ ...QUARTERLY_FLOW_FIELDS,
70
+ ...QUARTERLY_SNAPSHOT_FIELDS,
71
+ ...QUARTERLY_AVERAGE_FIELDS,
72
+ "netIncomeCommonStockholders",
73
+ "eps",
74
+ ];
75
+
76
+ export function validDate(value: unknown): Date | null {
77
+ if (value instanceof Date) {
78
+ return Number.isFinite(value.getTime()) ? new Date(value.getTime()) : null;
79
+ }
80
+ if (typeof value !== "string" && typeof value !== "number") return null;
81
+ const parsed = new Date(value);
82
+ return Number.isFinite(parsed.getTime()) ? parsed : null;
83
+ }
84
+
85
+ export function statementTime(statement: FinancialStatement): number {
86
+ return Date.parse(statement.date);
87
+ }
88
+
89
+ export function statementNumber(statement: FinancialStatement, field: NumericStatementField): number | null {
90
+ if (field === "eps" && statement.epsBasis?.status === "unresolved") return null;
91
+ const value = statement[field];
92
+ return isFiniteNumber(value) ? value : null;
93
+ }
94
+
95
+ export function setStatementNumber(
96
+ statement: InternalStatement,
97
+ field: NumericStatementField,
98
+ value: number,
99
+ availableAt?: string,
100
+ ): void {
101
+ (statement as unknown as Record<string, unknown>)[field] = value;
102
+ statement.__timeSeriesDerivedFields = [
103
+ ...new Set([...(statement.__timeSeriesDerivedFields ?? []), field]),
104
+ ];
105
+ statement.fieldAvailability = { ...statement.fieldAvailability };
106
+ if (availableAt) statement.fieldAvailability[field] = availableAt;
107
+ else delete statement.fieldAvailability[field];
108
+ }
109
+
110
+ export function completeStatementAvailability(statement: InternalStatement): string | undefined {
111
+ return completeAvailability(NUMERIC_STATEMENT_FIELDS
112
+ .filter((field) => statementNumber(statement, field) !== null)
113
+ .map((field) => statementFieldAvailability(statement, field)));
114
+ }
@@ -0,0 +1,50 @@
1
+ // Prices a statement-based multiple at a given price, and says whether a statement has the inputs for one.
2
+ import type { FinancialStatement } from "../../types/financials";
3
+ import { hasStatementGap } from "../../utils/statement-gaps";
4
+ import { isFiniteNumber } from "../../utils/guards";
5
+ import type { InternalStatement } from "./statement";
6
+ import { freeCashFlow, ratio, selectedCash, selectedEps, selectedShares } from "./statement-fields";
7
+
8
+ export function hasValuationInputs(statement: InternalStatement, metric: string): boolean {
9
+ if (metric === "trailingPE") {
10
+ return hasStatementGap(statement, "eps") || statement.epsBasis?.status === "unresolved"
11
+ || statement.__timeSeriesIncompleteCommonIncome === true
12
+ || statement.__timeSeriesIncompleteAverageShares === true
13
+ || selectedEps(statement) !== null;
14
+ }
15
+ if (!selectedShares(statement)) return false;
16
+ if (metric === "priceSales") return isFiniteNumber(statement.totalRevenue);
17
+ if (metric === "priceFcf") return freeCashFlow(statement).value !== null;
18
+ if (!isFiniteNumber(statement.totalDebt) || !selectedCash(statement)) return false;
19
+ return metric === "evSales" ? isFiniteNumber(statement.totalRevenue)
20
+ : metric === "evEbitda" && isFiniteNumber(statement.ebitda);
21
+ }
22
+
23
+ export function valuationAtPrice(
24
+ statement: FinancialStatement,
25
+ metric: string,
26
+ price: number,
27
+ checkingInputs = false,
28
+ ): number | null {
29
+ const shares = selectedShares(statement);
30
+ const marketCap = shares ? price * shares.value : null;
31
+ const cash = selectedCash(statement)?.value;
32
+ const debt = statement.totalDebt;
33
+ // Unknown balance-sheet inputs are not zero balances. Avoid manufacturing
34
+ // an EV multiple from market capitalization alone when coverage is sparse.
35
+ const enterpriseValue = marketCap !== null && isFiniteNumber(debt) && isFiniteNumber(cash)
36
+ ? marketCap + debt - cash
37
+ : null;
38
+ if (metric === "trailingPE") {
39
+ const eps = selectedEps(statement)?.value;
40
+ return eps && eps > 0 ? price / eps : null;
41
+ }
42
+ if (metric === "priceSales") return ratio(marketCap, statement.totalRevenue);
43
+ // The probe at price=1 checks input coverage, not the historical EV sign.
44
+ if (!checkingInputs && enterpriseValue !== null && enterpriseValue < 0 && (metric === "evSales" || metric === "evEbitda")) return null;
45
+ if (metric === "evSales") return ratio(enterpriseValue, statement.totalRevenue);
46
+ // Over EBITDA at or below zero the multiple means nothing (N/M), as a P/E over a loss.
47
+ if (metric === "evEbitda") return isFiniteNumber(statement.ebitda) && statement.ebitda > 0 ? ratio(enterpriseValue, statement.ebitda) : null;
48
+ if (metric === "priceFcf") return ratio(marketCap, freeCashFlow(statement).value);
49
+ return null;
50
+ }