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.
- package/package.json +1 -1
- package/src/api-client/fund-facts.ts +20 -4
- package/src/api-client/socket.ts +4 -4
- package/src/architecture/shortcut-labels-allowlist.json +1 -0
- package/src/cli/commands/market.ts +33 -17
- package/src/cli/commands/search.ts +19 -3
- package/src/cli/desktop-pane-shot.ts +61 -0
- package/src/cli/pane-functions/dom.ts +4 -4
- package/src/cli/pane-functions/freshness.ts +38 -5
- package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
- package/src/cli/quote-answer.ts +57 -1
- package/src/cli/result.ts +17 -0
- package/src/docs/snapshot.json +55 -16
- package/src/i18n/es.ts +2 -0
- package/src/i18n/ja.ts +2 -0
- package/src/i18n/ko.ts +2 -0
- package/src/i18n/zh-cn.ts +2 -0
- package/src/i18n/zh-tw.ts +2 -0
- package/src/market-data/market/change-basis.ts +49 -8
- package/src/market-data/market/dated-previous-close.ts +133 -10
- package/src/market-data/market/freshness.ts +18 -6
- package/src/market-data/market/status.ts +9 -1
- package/src/market-data/published-nse-sessions.ts +16 -1
- package/src/market-data/quotes/freshness.ts +15 -0
- package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
- package/src/plugins/builtin/alerts/cli.ts +22 -9
- package/src/plugins/builtin/alerts/headless.ts +1 -1
- package/src/plugins/builtin/alerts/index.tsx +5 -1
- package/src/plugins/builtin/alerts/metric-command.ts +1 -1
- package/src/plugins/builtin/holders/fund-holders.ts +22 -1
- package/src/plugins/builtin/holders/headless.ts +5 -4
- package/src/plugins/builtin/holders/pane.tsx +7 -3
- package/src/plugins/builtin/holders/report-header.ts +23 -0
- package/src/plugins/builtin/members/client.ts +1 -1
- package/src/plugins/builtin/members/headless.ts +2 -0
- package/src/plugins/builtin/members/model.ts +10 -8
- package/src/plugins/builtin/members/pane.tsx +4 -1
- package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
- package/src/plugins/builtin/portfolio-list/cli/render.ts +66 -23
- package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
- package/src/plugins/builtin/portfolio-list/income.ts +46 -22
- package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
- package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
- package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
- package/src/plugins/builtin/sec/fund-facts.ts +25 -5
- package/src/plugins/builtin/shared/report-freshness.ts +15 -6
- package/src/plugins/builtin/supply-chain/model.ts +18 -6
- package/src/portfolio/column-values.ts +3 -0
- package/src/portfolio/valuation-basis.ts +23 -1
- package/src/state/hooks/quote-streaming.ts +14 -6
- package/src/tickers/instrument-kind.ts +22 -1
- package/src/tickers/search/index.ts +5 -0
- package/src/tickers/terminal-codes.ts +17 -5
- package/src/time-series/fundamentals/current-valuation.ts +244 -0
- package/src/time-series/fundamentals/historical-valuation.ts +99 -0
- package/src/time-series/fundamentals/metric-ids.ts +61 -0
- package/src/time-series/fundamentals/period-points.ts +104 -0
- package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
- package/src/time-series/fundamentals/series.ts +164 -0
- package/src/time-series/fundamentals/source-statements.ts +177 -0
- package/src/time-series/fundamentals/statement-fields.ts +154 -0
- package/src/time-series/fundamentals/statement-merge.ts +124 -0
- package/src/time-series/fundamentals/statement.ts +114 -0
- package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
- package/src/time-series/fundamentals.ts +18 -1407
- package/src/types/financials.ts +9 -0
- package/src/utils/debug-log.ts +29 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Derives fiscal fourth quarters from their year and builds trailing-twelve-month statements.
|
|
2
|
+
import type { FinancialStatement } from "../../types/financials";
|
|
3
|
+
import { areNearbyFinancialPeriodEnds, completeAvailability, statementFieldAvailability } from "../../utils/financial-statements";
|
|
4
|
+
import { hasStatementGap } from "../../utils/statement-gaps";
|
|
5
|
+
import { trailingEpsAcrossFiscalYearEnd } from "../../utils/trailing-eps";
|
|
6
|
+
import { isFiniteNumber } from "../../utils/guards";
|
|
7
|
+
import {
|
|
8
|
+
completeStatementAvailability,
|
|
9
|
+
DAY_MS,
|
|
10
|
+
type InternalStatement,
|
|
11
|
+
type NumericStatementField,
|
|
12
|
+
QUARTERLY_AVERAGE_FIELDS,
|
|
13
|
+
QUARTERLY_FLOW_FIELDS,
|
|
14
|
+
QUARTERLY_SNAPSHOT_FIELDS,
|
|
15
|
+
setStatementNumber,
|
|
16
|
+
statementNumber,
|
|
17
|
+
statementTime,
|
|
18
|
+
TTM_SUM_FIELDS,
|
|
19
|
+
} from "./statement";
|
|
20
|
+
import { mergeStatementsByPeriod } from "./statement-merge";
|
|
21
|
+
|
|
22
|
+
/** Internal calendar bucket for selecting adjacent inputs, not an issuer fiscal label. */
|
|
23
|
+
function calendarQuarterBucket(date: string): string {
|
|
24
|
+
const parsedYear = Number(date.slice(0, 4));
|
|
25
|
+
let year = Number.isFinite(parsedYear) ? parsedYear : 0;
|
|
26
|
+
|
|
27
|
+
let month = Number(date.slice(5, 7));
|
|
28
|
+
const day = Number(date.slice(8, 10));
|
|
29
|
+
if (Number.isFinite(month) && Number.isFinite(day) && day <= 7 && (month - 1) % 3 === 0) {
|
|
30
|
+
month -= 1;
|
|
31
|
+
if (month === 0) {
|
|
32
|
+
month = 12;
|
|
33
|
+
year -= 1;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const quarter = Number.isFinite(month) && month > 0 ? Math.ceil(month / 3) : 0;
|
|
37
|
+
return quarter > 0 && year > 0 ? `${year} Q${quarter}` : date;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface PrecedingQuarterInput {
|
|
41
|
+
date: string;
|
|
42
|
+
time: number;
|
|
43
|
+
value: number;
|
|
44
|
+
availableAt?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function precedingQuarterInputs(
|
|
48
|
+
quarterlyStatements: readonly FinancialStatement[],
|
|
49
|
+
annualStatement: FinancialStatement,
|
|
50
|
+
field: NumericStatementField,
|
|
51
|
+
): PrecedingQuarterInput[] {
|
|
52
|
+
const annualTime = statementTime(annualStatement);
|
|
53
|
+
if (!Number.isFinite(annualTime)) return [];
|
|
54
|
+
|
|
55
|
+
const annualCategory = calendarQuarterBucket(annualStatement.date);
|
|
56
|
+
const byCategory = new Map<string, PrecedingQuarterInput>();
|
|
57
|
+
for (const statement of quarterlyStatements) {
|
|
58
|
+
if (statement.currency !== annualStatement.currency) continue;
|
|
59
|
+
const time = statementTime(statement);
|
|
60
|
+
if (!Number.isFinite(time) || time >= annualTime || annualTime - time > 370 * DAY_MS) continue;
|
|
61
|
+
const category = calendarQuarterBucket(statement.date);
|
|
62
|
+
if (category === annualCategory) continue;
|
|
63
|
+
const value = statementNumber(statement, field);
|
|
64
|
+
if (value === null) continue;
|
|
65
|
+
const previous = byCategory.get(category);
|
|
66
|
+
if (!previous || statement.date.localeCompare(previous.date) > 0) {
|
|
67
|
+
byCategory.set(category, {
|
|
68
|
+
date: statement.date,
|
|
69
|
+
time,
|
|
70
|
+
value,
|
|
71
|
+
availableAt: statementFieldAvailability(statement, field),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return [...byCategory.values()]
|
|
77
|
+
.sort((left, right) => right.time - left.time)
|
|
78
|
+
.slice(0, 3)
|
|
79
|
+
.sort((left, right) => left.time - right.time);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Completes additive fiscal Q4 flows from the annual total and three reported
|
|
84
|
+
* quarters. EPS and weighted-average shares require reported quarter values;
|
|
85
|
+
* neither is an additive flow. Snapshots come from the annual balance sheet. Derived
|
|
86
|
+
* values become available only after the annual total and every quarterly
|
|
87
|
+
* input used in the derivation are public.
|
|
88
|
+
*/
|
|
89
|
+
export function deriveQuarterlyStatements(
|
|
90
|
+
quarterlyStatements: readonly FinancialStatement[],
|
|
91
|
+
annualStatements: readonly FinancialStatement[],
|
|
92
|
+
): FinancialStatement[] {
|
|
93
|
+
const mergedQuarterly = mergeStatementsByPeriod(quarterlyStatements);
|
|
94
|
+
const byDate = new Map(mergedQuarterly.map((statement) => [statement.date, { ...statement }]));
|
|
95
|
+
|
|
96
|
+
for (const annualStatement of mergeStatementsByPeriod(annualStatements)) {
|
|
97
|
+
let target: InternalStatement = byDate.get(annualStatement.date) ?? { date: annualStatement.date, currency: annualStatement.currency };
|
|
98
|
+
if (target.currency !== annualStatement.currency) continue;
|
|
99
|
+
let changed = false;
|
|
100
|
+
|
|
101
|
+
for (const field of QUARTERLY_FLOW_FIELDS) {
|
|
102
|
+
// A line unavailable for the fourth quarter stays a gap: the full year
|
|
103
|
+
// minus the other quarters would recreate the value a source withheld.
|
|
104
|
+
if (hasStatementGap(target, field) || mergedQuarterly.some((statement) => (
|
|
105
|
+
areNearbyFinancialPeriodEnds(statement.date, annualStatement.date) && hasStatementGap(statement, field)
|
|
106
|
+
))) continue;
|
|
107
|
+
if (statementNumber(target, field) !== null) continue;
|
|
108
|
+
const annualValue = statementNumber(annualStatement, field);
|
|
109
|
+
if (annualValue === null) continue;
|
|
110
|
+
const previousInputs = precedingQuarterInputs(mergedQuarterly, annualStatement, field);
|
|
111
|
+
if (previousInputs.length !== 3) continue;
|
|
112
|
+
const inputTimes = [...previousInputs.map((input) => input.time), statementTime(annualStatement)];
|
|
113
|
+
if (inputTimes.some((time, index) => index > 0 && (time - inputTimes[index - 1]! < 60 * DAY_MS || time - inputTimes[index - 1]! > 120 * DAY_MS))) continue;
|
|
114
|
+
const derived = annualValue - previousInputs.reduce((sum, input) => sum + input.value, 0);
|
|
115
|
+
if (!Number.isFinite(derived)) continue;
|
|
116
|
+
const availableAt = completeAvailability([
|
|
117
|
+
statementFieldAvailability(annualStatement, field),
|
|
118
|
+
...previousInputs.map((input) => input.availableAt),
|
|
119
|
+
]);
|
|
120
|
+
setStatementNumber(target, field, derived, availableAt);
|
|
121
|
+
changed = true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
for (const field of QUARTERLY_SNAPSHOT_FIELDS) {
|
|
125
|
+
if (statementNumber(target, field) !== null) continue;
|
|
126
|
+
const annualValue = statementNumber(annualStatement, field);
|
|
127
|
+
if (annualValue === null) continue;
|
|
128
|
+
const availableAt = statementFieldAvailability(annualStatement, field);
|
|
129
|
+
setStatementNumber(target, field, annualValue, availableAt);
|
|
130
|
+
changed = true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (changed) {
|
|
134
|
+
target.availableAt = completeStatementAvailability(target);
|
|
135
|
+
byDate.set(target.date, target);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return mergeStatementsByPeriod([...byDate.values()]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function buildTtmStatements(
|
|
143
|
+
statements: readonly FinancialStatement[],
|
|
144
|
+
annualStatements: readonly FinancialStatement[],
|
|
145
|
+
): InternalStatement[] {
|
|
146
|
+
const sorted = mergeStatementsByPeriod(statements);
|
|
147
|
+
const annual = mergeStatementsByPeriod(annualStatements);
|
|
148
|
+
const result: InternalStatement[] = [];
|
|
149
|
+
for (let index = 3; index < sorted.length; index += 1) {
|
|
150
|
+
const window = sorted.slice(index - 3, index + 1);
|
|
151
|
+
const latest = window.at(-1)!;
|
|
152
|
+
const times = window.map(statementTime);
|
|
153
|
+
if (new Set(window.map((statement) => statement.currency)).size > 1
|
|
154
|
+
|| times.some((time, index) => !Number.isFinite(time) || (index > 0 && (time - times[index - 1]! < 60 * DAY_MS || time - times[index - 1]! > 120 * DAY_MS)))) {
|
|
155
|
+
// Retain the known period as a gap. Removing an incomplete window joins
|
|
156
|
+
// the last usable TTM observation to the first recovered one.
|
|
157
|
+
result.push({ date: latest.date, currency: latest.currency, availableAt: latest.availableAt,
|
|
158
|
+
__timeSeriesTtm: true });
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const ttm: InternalStatement = {
|
|
163
|
+
date: latest.date,
|
|
164
|
+
currency: latest.currency,
|
|
165
|
+
fieldAvailability: {},
|
|
166
|
+
__timeSeriesTtm: true,
|
|
167
|
+
__timeSeriesDerivedFields: [],
|
|
168
|
+
};
|
|
169
|
+
const unresolvedEps = window.find((statement) => statement.epsBasis?.status === "unresolved");
|
|
170
|
+
if (unresolvedEps) ttm.epsBasis = unresolvedEps.epsBasis;
|
|
171
|
+
const commonIncomeCount = window.filter((statement) => isFiniteNumber(statement.netIncomeCommonStockholders)).length;
|
|
172
|
+
// Known common claims in some quarters cannot be ignored by substituting
|
|
173
|
+
// aggregate income for the entire window or only its missing quarters.
|
|
174
|
+
if ((commonIncomeCount > 0 && commonIncomeCount < window.length)
|
|
175
|
+
|| window.some(statement => statement.unavailableFields?.includes("netIncomeCommonStockholders"))) ttm.__timeSeriesIncompleteCommonIncome = true;
|
|
176
|
+
const hasAverageShareInputs = window.some(statement => QUARTERLY_AVERAGE_FIELDS
|
|
177
|
+
.some(field => statementNumber(statement, field) !== null));
|
|
178
|
+
const hasCompleteAverageShares = QUARTERLY_AVERAGE_FIELDS.some(field => window.every(statement => {
|
|
179
|
+
const value = statementNumber(statement, field);
|
|
180
|
+
return value !== null && value > 0;
|
|
181
|
+
}));
|
|
182
|
+
// A missing quarter cannot replace a known weighted-period denominator
|
|
183
|
+
// with a year-end ordinary/issued-share snapshot. Capitalization may still
|
|
184
|
+
// use the snapshot; this guard is specific to the fallback earnings ratio.
|
|
185
|
+
if (hasAverageShareInputs && !hasCompleteAverageShares) ttm.__timeSeriesIncompleteAverageShares = true;
|
|
186
|
+
|
|
187
|
+
for (const field of [...TTM_SUM_FIELDS, ...QUARTERLY_AVERAGE_FIELDS]) {
|
|
188
|
+
const values = window.map((statement) => statementNumber(statement, field));
|
|
189
|
+
if (!values.every((value): value is number => value !== null)) continue;
|
|
190
|
+
if (QUARTERLY_AVERAGE_FIELDS.includes(field) && !values.every(value => value > 0)) continue;
|
|
191
|
+
(ttm as unknown as Record<string, unknown>)[field] = values.reduce((sum, value) => sum + value, 0)
|
|
192
|
+
/ (QUARTERLY_AVERAGE_FIELDS.includes(field) ? 4 : 1);
|
|
193
|
+
ttm.__timeSeriesDerivedFields!.push(field);
|
|
194
|
+
const availableAt = completeAvailability(window.map((statement) => (
|
|
195
|
+
statementFieldAvailability(statement, field)
|
|
196
|
+
)));
|
|
197
|
+
if (availableAt) ttm.fieldAvailability![field] = availableAt;
|
|
198
|
+
}
|
|
199
|
+
// A fiscal Q4 the 10-K reports only inside its year: the year's EPS plus the quarters since, less the same quarters a year earlier.
|
|
200
|
+
const acrossYearEnd = statementNumber(ttm, "eps") === null && !unresolvedEps
|
|
201
|
+
? trailingEpsAcrossFiscalYearEnd(window, sorted, annual, "eps") : null;
|
|
202
|
+
if (acrossYearEnd) {
|
|
203
|
+
ttm.eps = acrossYearEnd.value;
|
|
204
|
+
ttm.__timeSeriesDerivedFields!.push("eps");
|
|
205
|
+
const availableAt = completeAvailability(acrossYearEnd.inputs.map((statement) => statementFieldAvailability(statement, "eps")));
|
|
206
|
+
if (availableAt) ttm.fieldAvailability!.eps = availableAt;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
for (const field of QUARTERLY_SNAPSHOT_FIELDS) {
|
|
210
|
+
const value = statementNumber(latest, field);
|
|
211
|
+
if (value === null) continue;
|
|
212
|
+
(ttm as unknown as Record<string, unknown>)[field] = value;
|
|
213
|
+
const availableAt = statementFieldAvailability(latest, field);
|
|
214
|
+
if (availableAt) ttm.fieldAvailability![field] = availableAt;
|
|
215
|
+
}
|
|
216
|
+
ttm.availableAt = completeStatementAvailability(ttm) ?? latest.availableAt;
|
|
217
|
+
result.push(ttm);
|
|
218
|
+
}
|
|
219
|
+
return result;
|
|
220
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Extracts a fundamental or valuation series from a ticker's financials, with the warnings and issues that explain it.
|
|
2
|
+
import type { TickerFinancials } from "../../types/financials";
|
|
3
|
+
import { fiscalYearEndMonth } from "../../utils/fiscal-period";
|
|
4
|
+
import { canonicalTimeSeriesFieldId, getTimeSeriesField } from "../field-catalog";
|
|
5
|
+
import { dailyForwardPeHistory, forwardPeHistory, realizedNtmPeHistory } from "../forward-valuation";
|
|
6
|
+
import { reportingCurrencySeries } from "../reporting-currency";
|
|
7
|
+
import { createValuationCurrencyContext } from "../valuation-currency";
|
|
8
|
+
import { valuationPriceAtOrBefore, valuationQuoteIssue, type ValuationPriceIssue } from "../valuation-price";
|
|
9
|
+
import type { SecuritySeriesSource, TimeSeriesPoint } from "../types";
|
|
10
|
+
import { isBankOrInsurerIndustry } from "../../utils/ebitda";
|
|
11
|
+
import { currentDerivedValuationPoint, currentValuationStatements, providerCurrentValuationPoint } from "./current-valuation";
|
|
12
|
+
import { dailyStatementValuation, dailyValuationFallbackPeriod, historicalValuation } from "./historical-valuation";
|
|
13
|
+
import { FUNDAMENTAL_IDS, QUOTE_DERIVED_VALUATION_IDS, VALUATION_IDS, valuationSeriesUsesLiveQuote } from "./metric-ids";
|
|
14
|
+
import { dedupeFundamentalPeriods, pointForStatement } from "./period-points";
|
|
15
|
+
import { sourceStatements } from "./source-statements";
|
|
16
|
+
import { fundamentalValue, metricAvailability } from "./statement-fields";
|
|
17
|
+
import { valuationAtPrice } from "./valuation-multiples";
|
|
18
|
+
|
|
19
|
+
/** Extracts the selected statement snapshot, retaining known availability dates without reconstructing prior vintages. */
|
|
20
|
+
export function extractFundamentalSeries(
|
|
21
|
+
financials: TickerFinancials | null,
|
|
22
|
+
source: SecuritySeriesSource,
|
|
23
|
+
): TimeSeriesPoint[] {
|
|
24
|
+
if (!financials) return [];
|
|
25
|
+
const canonicalId = canonicalTimeSeriesFieldId(source.fieldId);
|
|
26
|
+
const [namespace, metric = ""] = canonicalId.split(".");
|
|
27
|
+
if (namespace === "fundamental" && FUNDAMENTAL_IDS.has(metric)) {
|
|
28
|
+
const selected = sourceStatements(financials, source.period);
|
|
29
|
+
const yearEndMonth = fiscalYearEndMonth(financials.annualStatements);
|
|
30
|
+
let hasObservation = false;
|
|
31
|
+
const points = selected.statements.flatMap((statement) => {
|
|
32
|
+
const result = fundamentalValue(statement, metric);
|
|
33
|
+
if (result.value !== null) hasObservation = true;
|
|
34
|
+
const point = pointForStatement(
|
|
35
|
+
statement,
|
|
36
|
+
metric,
|
|
37
|
+
result.value,
|
|
38
|
+
selected.period,
|
|
39
|
+
source.timestampMode,
|
|
40
|
+
result.derived,
|
|
41
|
+
yearEndMonth,
|
|
42
|
+
);
|
|
43
|
+
return point ? [point] : [];
|
|
44
|
+
});
|
|
45
|
+
if (!hasObservation) return [];
|
|
46
|
+
const deduped = dedupeFundamentalPeriods(points);
|
|
47
|
+
return getTimeSeriesField(canonicalId)?.unit.startsWith("currency")
|
|
48
|
+
? reportingCurrencySeries(deduped, financials.financialCurrency).points : deduped;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (namespace !== "valuation" || !VALUATION_IDS.has(metric)) return [];
|
|
52
|
+
// A bank's or an insurer's EBITDA measures nothing: its EV/EBITDA is N/M throughout (valuationNotMeaningful).
|
|
53
|
+
if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return [];
|
|
54
|
+
const fallback = dailyValuationFallbackPeriod(financials, source);
|
|
55
|
+
if (fallback) return extractFundamentalSeries(financials, { ...source, period: fallback });
|
|
56
|
+
if (source.period === "daily" && metric !== "realizedNtmPE") {
|
|
57
|
+
if (metric !== "forwardPE") return dailyStatementValuation(financials, metric, source.instrument.exchange);
|
|
58
|
+
const points = dailyForwardPeHistory(financials, createValuationCurrencyContext(financials), source.instrument.exchange);
|
|
59
|
+
if (points.some((point) => point.value !== null)) return points;
|
|
60
|
+
const current = providerCurrentValuationPoint(financials, metric);
|
|
61
|
+
return current ? [current] : [];
|
|
62
|
+
}
|
|
63
|
+
if (metric === "forwardPE") {
|
|
64
|
+
const points = forwardPeHistory(financials, createValuationCurrencyContext(financials));
|
|
65
|
+
if (points.length > 0) return points;
|
|
66
|
+
// Without an estimate history the provider's own figure is all there is.
|
|
67
|
+
const current = providerCurrentValuationPoint(financials, metric);
|
|
68
|
+
return current ? [current] : [];
|
|
69
|
+
}
|
|
70
|
+
if (metric === "realizedNtmPE") {
|
|
71
|
+
return realizedNtmPeHistory(financials, createValuationCurrencyContext(financials));
|
|
72
|
+
}
|
|
73
|
+
if (metric === "pegRatio") {
|
|
74
|
+
const current = providerCurrentValuationPoint(financials, metric);
|
|
75
|
+
return current ? [current] : [];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const selected = sourceStatements(financials, source.period, metric);
|
|
79
|
+
const currencies = createValuationCurrencyContext(financials);
|
|
80
|
+
const yearEndMonth = fiscalYearEndMonth(financials.annualStatements);
|
|
81
|
+
let hasHistoricalObservation = false;
|
|
82
|
+
const historical = selected.statements.flatMap((statement) => {
|
|
83
|
+
const historical = historicalValuation(financials, statement, metric, currencies);
|
|
84
|
+
if (historical !== null) hasHistoricalObservation = true;
|
|
85
|
+
const point = pointForStatement(
|
|
86
|
+
statement,
|
|
87
|
+
metric,
|
|
88
|
+
historical?.value ?? null,
|
|
89
|
+
selected.period,
|
|
90
|
+
source.timestampMode,
|
|
91
|
+
true,
|
|
92
|
+
yearEndMonth,
|
|
93
|
+
);
|
|
94
|
+
if (point && historical?.integrity) point.provenance = { ...point.provenance, priceHistoryIntegrity: historical.integrity };
|
|
95
|
+
if (point && historical?.issue) point.provenance = { ...point.provenance,
|
|
96
|
+
valuationPriceIssues: [{ ...historical.issue, affectedAt: point.date.toISOString() }] };
|
|
97
|
+
return point ? [point] : [];
|
|
98
|
+
});
|
|
99
|
+
const current = currentDerivedValuationPoint(financials, currentValuationStatements(financials, selected, metric), metric, currencies);
|
|
100
|
+
if (!hasHistoricalObservation && !current) return [];
|
|
101
|
+
const dedupedHistorical = dedupeFundamentalPeriods(historical);
|
|
102
|
+
// Publication timestamps can be shared by distinct fiscal periods. Their
|
|
103
|
+
// period identities were deduplicated above; a gap must not overwrite a
|
|
104
|
+
// different period's usable observation released on the same date.
|
|
105
|
+
return (current ? [...dedupedHistorical, current] : dedupedHistorical).sort((left, right) => (
|
|
106
|
+
left.date.getTime() - right.date.getTime() || left.observedAt.getTime() - right.observedAt.getTime()
|
|
107
|
+
));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The period a fundamental series asks for that its company reports no figure
|
|
112
|
+
* of, though it reports annual ones: `quarterly` for an issuer that reports
|
|
113
|
+
* twice a year. Null for any other series, and when the annual figures are as
|
|
114
|
+
* missing as the quarterly ones.
|
|
115
|
+
*/
|
|
116
|
+
export function unreportedStatementPeriod(
|
|
117
|
+
financials: TickerFinancials,
|
|
118
|
+
source: SecuritySeriesSource,
|
|
119
|
+
): "quarterly" | null {
|
|
120
|
+
if (source.period !== "quarterly" || !canonicalTimeSeriesFieldId(source.fieldId).startsWith("fundamental.")) return null;
|
|
121
|
+
return extractFundamentalSeries(financials, { ...source, period: "annual" }).length > 0 ? "quarterly" : null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function fundamentalSeriesUsesAvailabilityFallback(
|
|
125
|
+
financials: TickerFinancials | null,
|
|
126
|
+
source: SecuritySeriesSource,
|
|
127
|
+
): boolean {
|
|
128
|
+
if (!financials || source.timestampMode === "period-end") return false;
|
|
129
|
+
// A gap has no value to place, so it has no date to fall back for.
|
|
130
|
+
const points = extractFundamentalSeries(financials, source);
|
|
131
|
+
return points.some((point) => point.value != null && point.availableAt === undefined);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Explains withheld currency-dependent values through chart and export metadata. */
|
|
135
|
+
export function valuationCurrencyWarning(financials: TickerFinancials, source: SecuritySeriesSource): string | undefined {
|
|
136
|
+
const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
|
|
137
|
+
if (namespace !== "valuation" || !QUOTE_DERIVED_VALUATION_IDS.has(metric)) return undefined;
|
|
138
|
+
const selected = sourceStatements(financials, source.period, metric);
|
|
139
|
+
return createValuationCurrencyContext(financials).warning(selected.statements.filter((row) => (
|
|
140
|
+
valuationAtPrice(row, metric, 1) !== null
|
|
141
|
+
)));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Structured failures preserve source values independently of the chart's ratios. */
|
|
145
|
+
export function valuationPriceIssues(financials: TickerFinancials, source: SecuritySeriesSource): ValuationPriceIssue[] {
|
|
146
|
+
if (source.period === "daily" && canonicalTimeSeriesFieldId(source.fieldId).startsWith("valuation.")) {
|
|
147
|
+
return extractFundamentalSeries(financials, source).flatMap((point) => point.provenance?.valuationPriceIssues ?? []);
|
|
148
|
+
}
|
|
149
|
+
if (!valuationSeriesUsesLiveQuote(source.fieldId)) return [];
|
|
150
|
+
const metric = canonicalTimeSeriesFieldId(source.fieldId).split(".")[1]!;
|
|
151
|
+
const currencies = createValuationCurrencyContext(financials);
|
|
152
|
+
const selected = sourceStatements(financials, source.period, metric);
|
|
153
|
+
const rows = selected.statements.filter((row) => (
|
|
154
|
+
currencies.priceInStatementUnits(row, 1) !== null && valuationAtPrice(row, metric, 1) !== null
|
|
155
|
+
));
|
|
156
|
+
if (!rows.length) return [];
|
|
157
|
+
const quoteIssue = valuationQuoteIssue(financials.quote);
|
|
158
|
+
const issues = rows.flatMap((row) => {
|
|
159
|
+
const price = valuationPriceAtOrBefore(financials.priceHistory, metricAvailability(row, metric) ?? row.date);
|
|
160
|
+
const date = pointForStatement(row, metric, null, selected.period, source.timestampMode, true, null)?.date;
|
|
161
|
+
return price?.issue && date ? [{ ...price.issue, affectedAt: date.toISOString() }] : [];
|
|
162
|
+
});
|
|
163
|
+
return [...(quoteIssue ? [quoteIssue] : []), ...new Map(issues.map((issue) => [JSON.stringify(issue), issue])).values()];
|
|
164
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Chooses the statements a series is read from for a period and metric: annual, quarterly, trailing, or dated at release.
|
|
2
|
+
import type { FinancialStatement, TickerFinancials } from "../../types/financials";
|
|
3
|
+
import { areNearbyFinancialPeriodEnds, statementFieldAvailability } from "../../utils/financial-statements";
|
|
4
|
+
import { hasStatementGap } from "../../utils/statement-gaps";
|
|
5
|
+
import { statementAtRelease } from "../valuation-releases";
|
|
6
|
+
import type { SeriesPeriod } from "../types";
|
|
7
|
+
import { isFiniteNumber } from "../../utils/guards";
|
|
8
|
+
import { buildTtmStatements, deriveQuarterlyStatements } from "./quarterly-ttm";
|
|
9
|
+
import {
|
|
10
|
+
completeStatementAvailability,
|
|
11
|
+
type InternalStatement,
|
|
12
|
+
NUMERIC_STATEMENT_FIELDS,
|
|
13
|
+
QUARTERLY_SNAPSHOT_FIELDS,
|
|
14
|
+
statementNumber,
|
|
15
|
+
} from "./statement";
|
|
16
|
+
import { selectedShares } from "./statement-fields";
|
|
17
|
+
import { mergeStatementsByPeriod } from "./statement-merge";
|
|
18
|
+
import { hasValuationInputs } from "./valuation-multiples";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A split restates EPS onto the new share count, and SEC history dates the
|
|
22
|
+
* restated figure by the filing that evidenced the split. The earnings were
|
|
23
|
+
* known at the original filing; price history is split-adjusted the same way,
|
|
24
|
+
* so a multiple of the restated figure steps when it was first filed. The
|
|
25
|
+
* EPS series itself keeps the restatement's date: its value is the restated one.
|
|
26
|
+
*/
|
|
27
|
+
export function knownWhenFiled(row: FinancialStatement): FinancialStatement {
|
|
28
|
+
const filed = row.epsBasis?.status === "split-adjusted" ? row.epsBasis.originalFiled : undefined;
|
|
29
|
+
if (!filed || !Number.isFinite(Date.parse(filed))) return row;
|
|
30
|
+
const current = statementFieldAvailability(row, "eps");
|
|
31
|
+
if (current && Date.parse(current) <= Date.parse(filed)) return row;
|
|
32
|
+
return { ...row, fieldAvailability: { ...row.fieldAvailability, eps: filed } };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The statements a multiple is priced from, each restated EPS dated by its first filing. */
|
|
36
|
+
export function valuationStatements(financials: TickerFinancials): { quarterly: FinancialStatement[]; annual: FinancialStatement[] } {
|
|
37
|
+
return { quarterly: financials.quarterlyStatements.map(knownWhenFiled), annual: financials.annualStatements.map(knownWhenFiled) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A fiscal fourth quarter's EPS stated without a filing date of its own (a
|
|
42
|
+
* 10-K states the year, the results release the quarter) was public once its
|
|
43
|
+
* year's filing was, so it is dated by that filing. The daily P/E of the
|
|
44
|
+
* quarters after it then sums the same four quarters PEB and the headline EPS
|
|
45
|
+
* (TTM) sum (time-series/filed-trailing-eps), rather than reading the quarter
|
|
46
|
+
* from the year and landing a cent of rounding away from them. The window that
|
|
47
|
+
* ends with the year takes the year's own EPS (fiscalYearEpsAtYearEnd).
|
|
48
|
+
*/
|
|
49
|
+
function fourthQuarterEpsAtYearFiling(row: FinancialStatement, annual: readonly FinancialStatement[]): FinancialStatement {
|
|
50
|
+
if (!isFiniteNumber(row.eps) || hasStatementGap(row, "eps") || statementFieldAvailability(row, "eps")) return row;
|
|
51
|
+
const year = annual.find((candidate) => candidate.currency === row.currency && areNearbyFinancialPeriodEnds(candidate.date, row.date));
|
|
52
|
+
const filed = year && isFiniteNumber(year.eps) ? statementFieldAvailability(year, "eps") : undefined;
|
|
53
|
+
return filed ? { ...row, fieldAvailability: { ...row.fieldAvailability, eps: filed } } : row;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* At a fiscal year end the filed year's diluted EPS is the daily trailing
|
|
58
|
+
* figure, as PEB and the headline EPS (TTM) read it (filed-trailing-eps): four
|
|
59
|
+
* quarters need not add up to their year (3.90 for the year beside four
|
|
60
|
+
* quarters of 1.00), so their sum stands only where the year gives no dated EPS.
|
|
61
|
+
*/
|
|
62
|
+
function fiscalYearEpsAtYearEnd(statements: readonly InternalStatement[], annual: readonly FinancialStatement[]): InternalStatement[] {
|
|
63
|
+
return statements.map((statement) => {
|
|
64
|
+
const year = annual.find((row) => row.currency === statement.currency && areNearbyFinancialPeriodEnds(row.date, statement.date));
|
|
65
|
+
const eps = year && !hasStatementGap(year, "eps") ? statementNumber(year, "eps") : null;
|
|
66
|
+
if (!year || eps === null) return statement;
|
|
67
|
+
const { epsBasis: _sum, ...rest } = statement;
|
|
68
|
+
const fieldAvailability = { ...statement.fieldAvailability };
|
|
69
|
+
const filed = statementFieldAvailability(year, "eps");
|
|
70
|
+
if (filed) fieldAvailability.eps = filed;
|
|
71
|
+
else delete fieldAvailability.eps;
|
|
72
|
+
const next: InternalStatement = {
|
|
73
|
+
...rest, eps, fieldAvailability, ...(year.epsBasis ? { epsBasis: year.epsBasis } : {}),
|
|
74
|
+
__timeSeriesDerivedFields: [...new Set([...(statement.__timeSeriesDerivedFields ?? []), "eps" as const])],
|
|
75
|
+
};
|
|
76
|
+
next.availableAt = completeStatementAvailability(next) ?? statement.availableAt;
|
|
77
|
+
return next;
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** An undated vendor value cannot block a derivation from dated filings. */
|
|
82
|
+
function datedValuationStatement(statement: FinancialStatement): FinancialStatement {
|
|
83
|
+
const dated = { ...statement };
|
|
84
|
+
for (const field of NUMERIC_STATEMENT_FIELDS) {
|
|
85
|
+
if (!statementFieldAvailability(statement, field)) delete dated[field];
|
|
86
|
+
}
|
|
87
|
+
return dated;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function normalizeFundamentalPeriod(period: SeriesPeriod | undefined): "annual" | "quarterly" | "ttm" | "auto" {
|
|
91
|
+
return period === "annual" || period === "quarterly" || period === "ttm" ? period : "auto";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function sourceStatements(
|
|
95
|
+
financials: TickerFinancials,
|
|
96
|
+
period: SeriesPeriod | undefined,
|
|
97
|
+
valuationMetric?: string,
|
|
98
|
+
exchange?: string,
|
|
99
|
+
): { statements: InternalStatement[]; period: "annual" | "quarterly" | "ttm" } {
|
|
100
|
+
const normalized = normalizeFundamentalPeriod(period);
|
|
101
|
+
let known = valuationMetric
|
|
102
|
+
? valuationStatements(financials)
|
|
103
|
+
: { quarterly: financials.quarterlyStatements, annual: financials.annualStatements };
|
|
104
|
+
if (period === "daily" && valuationMetric) {
|
|
105
|
+
const releases = financials.earningsReleases ?? [];
|
|
106
|
+
const venue = financials.quote?.listingExchangeName || financials.quote?.exchangeName || exchange;
|
|
107
|
+
known = { quarterly: known.quarterly.map(row => statementAtRelease(row, releases, venue)),
|
|
108
|
+
annual: known.annual.map(row => statementAtRelease(row, releases, venue)) };
|
|
109
|
+
const annualRows = known.annual;
|
|
110
|
+
known = { ...known, quarterly: known.quarterly.map((row) => fourthQuarterEpsAtYearFiling(row, annualRows)) };
|
|
111
|
+
known = { quarterly: known.quarterly.map(datedValuationStatement), annual: known.annual.map(datedValuationStatement) };
|
|
112
|
+
// A later comparative quarter may repeat a year-end balance sheet that
|
|
113
|
+
// the annual filing already published. Only identical, same-currency
|
|
114
|
+
// snapshots can inherit that earlier evidence; changed values cannot.
|
|
115
|
+
known.quarterly = known.quarterly.map((statement) => {
|
|
116
|
+
const dated = { ...statement, fieldAvailability: Object.fromEntries(NUMERIC_STATEMENT_FIELDS.flatMap((field) => {
|
|
117
|
+
const availableAt = statementFieldAvailability(statement, field);
|
|
118
|
+
return availableAt ? [[field, availableAt]] : [];
|
|
119
|
+
})) };
|
|
120
|
+
for (const annual of known.annual) {
|
|
121
|
+
if (annual.currency !== dated.currency || !areNearbyFinancialPeriodEnds(annual.date, dated.date)) continue;
|
|
122
|
+
for (const field of QUARTERLY_SNAPSHOT_FIELDS) {
|
|
123
|
+
const value = statementNumber(dated, field);
|
|
124
|
+
const earlier = statementFieldAvailability(annual, field);
|
|
125
|
+
const current = statementFieldAvailability(dated, field);
|
|
126
|
+
if (value !== null && value === statementNumber(annual, field) && earlier
|
|
127
|
+
&& (!current || Date.parse(earlier) < Date.parse(current))) {
|
|
128
|
+
dated.fieldAvailability[field] = earlier;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return dated;
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const quarterly = deriveQuarterlyStatements(known.quarterly, known.annual);
|
|
136
|
+
if (period === "daily" && valuationMetric) {
|
|
137
|
+
// Sparse or loss-making quarters are gaps, not permission to substitute
|
|
138
|
+
// an older annual denominator. Annual-only issuers retain their years.
|
|
139
|
+
if (!known.quarterly.length) return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
|
|
140
|
+
const statements = fiscalYearEpsAtYearEnd(buildTtmStatements(quarterly, known.annual), known.annual);
|
|
141
|
+
// Capitalization uses the latest reported share count, not an average
|
|
142
|
+
// of four quarters. Keep TTM average shares for the income/EPS fallback.
|
|
143
|
+
if (valuationMetric !== "trailingPE") for (const statement of statements) {
|
|
144
|
+
const latest = quarterly.find((row) => row.date === statement.date);
|
|
145
|
+
const year = known.annual.find((row) => areNearbyFinancialPeriodEnds(row.date, statement.date));
|
|
146
|
+
const shareRow = latest && selectedShares(latest) ? latest : year;
|
|
147
|
+
for (const field of ["dilutedShares", "basicShares", "ordinarySharesNumber", "shareIssued"] as const) {
|
|
148
|
+
delete statement[field];
|
|
149
|
+
delete statement.fieldAvailability?.[field];
|
|
150
|
+
if (shareRow?.[field] !== undefined) {
|
|
151
|
+
statement[field] = shareRow[field];
|
|
152
|
+
const availableAt = statementFieldAvailability(shareRow, field);
|
|
153
|
+
if (availableAt) (statement.fieldAvailability ??= {})[field] = availableAt;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return { statements, period: "ttm" };
|
|
158
|
+
}
|
|
159
|
+
if (normalized === "annual") {
|
|
160
|
+
return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
|
|
161
|
+
}
|
|
162
|
+
if (normalized === "ttm" || valuationMetric) {
|
|
163
|
+
const ttm = buildTtmStatements(quarterly, known.annual);
|
|
164
|
+
if (normalized === "ttm" && ttm.length > 0) return { statements: ttm, period: "ttm" };
|
|
165
|
+
if (valuationMetric && ttm.some((statement) => hasValuationInputs(statement, valuationMetric))) {
|
|
166
|
+
return { statements: ttm, period: "ttm" };
|
|
167
|
+
}
|
|
168
|
+
if (normalized === "ttm") return { statements: [], period: "ttm" };
|
|
169
|
+
if (valuationMetric) {
|
|
170
|
+
return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (normalized === "quarterly" || (normalized === "auto" && quarterly.length > 0)) {
|
|
174
|
+
return { statements: quarterly, period: "quarterly" };
|
|
175
|
+
}
|
|
176
|
+
return { statements: mergeStatementsByPeriod(known.annual), period: "annual" };
|
|
177
|
+
}
|