margin-mcp 0.10.1__py3-none-any.whl

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 (65) hide show
  1. margin/__init__.py +3 -0
  2. margin/analysis/__init__.py +1 -0
  3. margin/analysis/calculations.py +241 -0
  4. margin/analysis/company.py +313 -0
  5. margin/analysis/facts.py +371 -0
  6. margin/analysis/presentation.py +152 -0
  7. margin/analysis/product_reports.py +167 -0
  8. margin/analysis/ratios.py +266 -0
  9. margin/analysis/reporting.py +247 -0
  10. margin/analysis/service.py +177 -0
  11. margin/analysis/units.py +95 -0
  12. margin/core/__init__.py +0 -0
  13. margin/core/company_finance.py +513 -0
  14. margin/core/config.py +64 -0
  15. margin/core/contracts.py +55 -0
  16. margin/core/registry.py +363 -0
  17. margin/core/service.py +1040 -0
  18. margin/core/validation.py +81 -0
  19. margin/evidence/__init__.py +0 -0
  20. margin/evidence/results.py +113 -0
  21. margin/evidence/review_sources.py +111 -0
  22. margin/evidence/sanitize.py +141 -0
  23. margin/finance/__init__.py +1 -0
  24. margin/finance/dcf.py +221 -0
  25. margin/interfaces/__init__.py +0 -0
  26. margin/interfaces/agent/__init__.py +1 -0
  27. margin/interfaces/agent/__main__.py +3 -0
  28. margin/interfaces/agent/backend.py +62 -0
  29. margin/interfaces/agent/cli.py +202 -0
  30. margin/interfaces/agent/client.py +231 -0
  31. margin/interfaces/agent/local_config.py +38 -0
  32. margin/interfaces/mcp/__init__.py +1 -0
  33. margin/interfaces/mcp/__main__.py +3 -0
  34. margin/interfaces/mcp/backend.py +267 -0
  35. margin/interfaces/mcp/bridge.py +126 -0
  36. margin/interfaces/mcp/policy.py +41 -0
  37. margin/interfaces/mcp/profiles.py +317 -0
  38. margin/interfaces/mcp/recording.py +62 -0
  39. margin/interfaces/mcp/server.py +835 -0
  40. margin/interfaces/mcp/tools.py +414 -0
  41. margin/interfaces/workbench/__init__.py +0 -0
  42. margin/interfaces/workbench/app.py +275 -0
  43. margin/interfaces/workbench/static/app.js +771 -0
  44. margin/interfaces/workbench/static/favicon.svg +1 -0
  45. margin/interfaces/workbench/static/index.html +91 -0
  46. margin/interfaces/workbench/static/style.css +207 -0
  47. margin/policy/__init__.py +0 -0
  48. margin/policy/ledger.py +74 -0
  49. margin/protocols/__init__.py +1 -0
  50. margin/protocols/handoffs.py +69 -0
  51. margin/protocols/review_flow.py +279 -0
  52. margin/protocols/schemas.py +185 -0
  53. margin/protocols/service.py +812 -0
  54. margin/providers/__init__.py +0 -0
  55. margin/providers/bharatstock.py +62 -0
  56. margin/providers/drishti.py +304 -0
  57. margin/providers/synthetic.py +264 -0
  58. margin/resources/__init__.py +0 -0
  59. margin/resources/drishti-contracts.json +1414 -0
  60. margin_mcp-0.10.1.dist-info/METADATA +200 -0
  61. margin_mcp-0.10.1.dist-info/RECORD +65 -0
  62. margin_mcp-0.10.1.dist-info/WHEEL +5 -0
  63. margin_mcp-0.10.1.dist-info/entry_points.txt +5 -0
  64. margin_mcp-0.10.1.dist-info/licenses/LICENSE +21 -0
  65. margin_mcp-0.10.1.dist-info/top_level.txt +1 -0
margin/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Margin: local Indian financial research interfaces."""
2
+
3
+ __version__ = "0.10.1"
@@ -0,0 +1 @@
1
+ """Local fact preparation and deterministic financial analysis; no provider I/O."""
@@ -0,0 +1,241 @@
1
+ """Pure financial comparisons. Decimal outputs are strings, not binary floats."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, timedelta
6
+ from decimal import Decimal, localcontext
7
+
8
+ from margin.analysis.facts import (
9
+ MONEY_UNITS,
10
+ TTM_FLOW_METRICS,
11
+ VERSION,
12
+ check_compatibility,
13
+ decimal,
14
+ fact,
15
+ wire,
16
+ )
17
+ from margin.core.contracts import DomainError
18
+
19
+
20
+ def result(name, inputs, values=None, issues=(), status=None):
21
+ return wire(
22
+ {
23
+ "function": name,
24
+ "function_version": VERSION,
25
+ "status": status or ("incomplete" if issues else "success"),
26
+ "inputs": inputs,
27
+ "values": values or {},
28
+ "issues": list(issues),
29
+ "precision": "34 significant digits; exact decimal strings; displayed rounding is separate",
30
+ "warnings": ["Input validity and arithmetic do not independently verify source facts."],
31
+ }
32
+ )
33
+
34
+
35
+ def compare_periods(previous, current):
36
+ a, b = fact(previous), fact(current)
37
+ issues = check_compatibility([previous, current])["issues"]
38
+ if a["period_end"] and b["period_end"] and a["period_end"] >= b["period_end"]:
39
+ issues.append("Current reporting period must follow the previous period.")
40
+ if issues:
41
+ return result("finance.compare_periods", [a, b], issues=issues)
42
+ with localcontext() as ctx:
43
+ ctx.prec = 34
44
+ delta = b["value"] - a["value"]
45
+ percent = delta / a["value"] * 100 if a["value"] > 0 else None
46
+ output = result(
47
+ "finance.compare_periods",
48
+ [a, b],
49
+ {
50
+ "absolute_change": delta,
51
+ "percentage_change": percent,
52
+ "unit": a["unit"],
53
+ "formula": "(current - previous) / previous * 100",
54
+ "formulas": {
55
+ "absolute_change": "current - previous",
56
+ "percentage_change": "(current - previous) / previous * 100",
57
+ },
58
+ },
59
+ issues=["Percentage growth is not meaningful for a nonpositive baseline."]
60
+ if percent is None
61
+ else (),
62
+ status="not_meaningful" if percent is None else "success",
63
+ )
64
+
65
+ if not a.get("period_start") or not b.get("period_start"):
66
+ output["warnings"].append(
67
+ "Period starts are unknown; comparison uses declared period types/ends. Review stub periods and reporting-duration changes."
68
+ )
69
+ return output
70
+
71
+
72
+ def calculate_margins(profit, revenue):
73
+ a, b = fact(profit), fact(revenue)
74
+ issues = check_compatibility([profit, revenue], "ratio")["issues"]
75
+ if (
76
+ a["metric"]
77
+ not in {
78
+ "net_profit",
79
+ "net_profit_attributable_to_owners",
80
+ "profit_from_continuing_operations",
81
+ "operating_profit",
82
+ "ebitda",
83
+ "gross_profit",
84
+ "ebit",
85
+ }
86
+ or b["metric"] != "revenue"
87
+ ):
88
+ issues.append("Select an explicitly defined profit measure and revenue.")
89
+ if a["unit"] not in MONEY_UNITS:
90
+ issues.append("Profit/revenue must use an established monetary scale.")
91
+ if (
92
+ a["metric"] in {"net_profit", "net_profit_attributable_to_owners"}
93
+ and a.get("source", {}).get("continuing_profit_differs") is True
94
+ ):
95
+ issues.append(
96
+ "Group/owners profit differs in scope from continuing profit; select aligned continuing profit or establish reporting scope before calculating a margin."
97
+ )
98
+ if issues:
99
+ return result("finance.calculate_margins", [a, b], issues=issues)
100
+ if b["value"] <= 0:
101
+ return result(
102
+ "finance.calculate_margins",
103
+ [a, b],
104
+ issues=["Positive revenue is required."],
105
+ status="not_meaningful",
106
+ )
107
+ with localcontext() as ctx:
108
+ ctx.prec = 34
109
+ margin = a["value"] / b["value"] * 100
110
+ return result(
111
+ "finance.calculate_margins",
112
+ [a, b],
113
+ {
114
+ "margin_percent": margin,
115
+ "profit_definition": a["definition"],
116
+ "formula": "profit / revenue * 100",
117
+ },
118
+ )
119
+
120
+
121
+ def calculate_cashflow_metrics(cfo, capex):
122
+ a, b = fact(cfo), fact(capex)
123
+ issues = check_compatibility([cfo, capex], "ratio")["issues"]
124
+ if (
125
+ a["metric"] != "cash_flow_operating"
126
+ or b["metric"] != "capex"
127
+ or a["unit"] not in MONEY_UNITS
128
+ ):
129
+ issues.append("Select operating cash flow and explicitly defined monetary capex.")
130
+ if issues:
131
+ return result("finance.calculate_cashflow_metrics", [a, b], issues=issues)
132
+ if b["value"] < 0:
133
+ raise DomainError(
134
+ "invalid_input",
135
+ "Capex must be supplied as a positive outflow; review the source sign convention.",
136
+ )
137
+ with localcontext() as ctx:
138
+ ctx.prec = 34
139
+ values = {
140
+ "cfo_minus_capex": a["value"] - b["value"],
141
+ "capex_coverage": a["value"] / b["value"] if b["value"] else None,
142
+ "unit": a["unit"],
143
+ "definition": "Reported CFO minus cash capex; not automatically FCFF.",
144
+ }
145
+ return result("finance.calculate_cashflow_metrics", [a, b], values)
146
+
147
+
148
+ def calculate_cagr(previous, current, years):
149
+ a, b = fact(previous), fact(current)
150
+ duration = decimal(years, "years")
151
+ if not Decimal(1) / 366 <= duration <= 100:
152
+ raise DomainError(
153
+ "invalid_input",
154
+ "CAGR requires an explicit duration of at least one day and at most 100 years.",
155
+ )
156
+ issues = check_compatibility([previous, current])["issues"]
157
+ if a["period_end"] and b["period_end"]:
158
+ days = (date.fromisoformat(b["period_end"]) - date.fromisoformat(a["period_end"])).days
159
+ if days <= 0 or abs(Decimal(days) / Decimal("365.25") - duration) > Decimal("0.02"):
160
+ issues.append(
161
+ "Explicit elapsed years do not match the reporting-period endpoints (seven-day tolerance)."
162
+ )
163
+ if issues:
164
+ return result("finance.calculate_cagr", [a, b], issues=issues)
165
+ if a["value"] <= 0 or b["value"] <= 0:
166
+ return result(
167
+ "finance.calculate_cagr",
168
+ [a, b],
169
+ issues=["CAGR requires positive endpoints."],
170
+ status="not_meaningful",
171
+ )
172
+ with localcontext() as ctx:
173
+ ctx.prec = 34
174
+ growth = ((b["value"] / a["value"]) ** (Decimal(1) / duration) - 1) * 100
175
+ return result(
176
+ "finance.calculate_cagr",
177
+ [a, b],
178
+ {
179
+ "cagr_percent": growth,
180
+ "years": duration,
181
+ "formula": "((current / previous) ** (1 / years) - 1) * 100",
182
+ },
183
+ )
184
+
185
+
186
+ def calculate_ttm(facts):
187
+ if not isinstance(facts, list) or len(facts) != 4:
188
+ raise DomainError("invalid_input", "TTM needs exactly four explicit quarterly flow facts.")
189
+ items = [fact(v) for v in facts]
190
+ issues = check_compatibility(facts, "ttm")["issues"]
191
+ if any(
192
+ v["metric"] not in TTM_FLOW_METRICS
193
+ or v["period_type"] != "quarterly"
194
+ or v["unit"] not in MONEY_UNITS
195
+ for v in items
196
+ ):
197
+ issues.append(
198
+ "TTM accepts monetary quarterly flows, not EPS, ratios, balance-sheet stocks or cumulative YTD data."
199
+ )
200
+ if any(not v.get("period_start") for v in items):
201
+ issues.append("All four quarterly start dates must be established; dates are not inferred.")
202
+ if any(
203
+ v.get("source", {}).get("reported_period_days") is not None
204
+ or v.get("source", {}).get("filed_period_days") is not None
205
+ for v in items
206
+ ):
207
+ issues.append(
208
+ "Longer or provider-derived reporting periods require separate review before TTM."
209
+ )
210
+ if issues:
211
+ return result("finance.calculate_ttm", items, issues=issues)
212
+ items.sort(key=lambda v: v["period_end"])
213
+ for index, value in enumerate(items):
214
+ start, end = (
215
+ date.fromisoformat(value["period_start"]),
216
+ date.fromisoformat(value["period_end"]),
217
+ )
218
+ if not 80 <= (end - start).days <= 100:
219
+ issues.append(
220
+ "Each observation must span a single quarter, not a YTD cumulative period."
221
+ )
222
+ if index and start != date.fromisoformat(items[index - 1]["period_end"]) + timedelta(
223
+ days=1
224
+ ):
225
+ issues.append("Quarterly observations overlap or have a gap.")
226
+ if issues:
227
+ return result("finance.calculate_ttm", items, issues=issues)
228
+ with localcontext() as ctx:
229
+ ctx.prec = 34
230
+ total = sum(v["value"] for v in items)
231
+ return result(
232
+ "finance.calculate_ttm",
233
+ items,
234
+ {
235
+ "total": total,
236
+ "unit": items[0]["unit"],
237
+ "period_start": items[0]["period_start"],
238
+ "period_end": items[-1]["period_end"],
239
+ "formula": "sum of four non-overlapping quarterly flows",
240
+ },
241
+ )
@@ -0,0 +1,313 @@
1
+ """Bounded company calculations over one explicit retained financial response."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ from datetime import date
7
+ from decimal import Decimal, localcontext
8
+
9
+ from jsonschema import Draft202012Validator, ValidationError
10
+
11
+ from margin.analysis.facts import (
12
+ FIELDS,
13
+ MONEY_UNITS,
14
+ STOCK_FIELDS,
15
+ TTM_FLOW_METRICS,
16
+ prepare_financial_facts,
17
+ )
18
+ from margin.analysis.service import calculate, obj
19
+ from margin.core.contracts import DomainError
20
+
21
+ FUNCTIONS = {
22
+ "finance.company_data_readiness": "Which fields support profitability, cash-conversion and liquidity across groups in ONE financial response; no forecast assumptions or numeric report rows",
23
+ "finance.company_balance_sheet_metrics": "Liquidity and borrowings; current-assets-less-inventories ratio is not a fully adjusted quick ratio",
24
+ "finance.company_cash_conversion": "CFO ratios and capex intensity; not days-based cash-conversion-cycle metrics",
25
+ "finance.company_profitability": "Defined group/owners/operating/EBITDA margins",
26
+ "finance.company_margins": "Latest-period continuing-profit margin when supplied, otherwise reported group-profit margin with scope caveat",
27
+ "finance.company_cashflow_metrics": "Latest-period operating cash flow minus capex and coverage",
28
+ "finance.company_growth": "Absolute and percentage change between the latest two returned periods; not a TTM sum",
29
+ "finance.company_cagr": "CAGR between two returned annual endpoints",
30
+ "finance.company_ttm": "Sum of four eligible quarterly flows, not growth or balance-sheet stocks; requires continuity",
31
+ }
32
+ SCHEMA = obj(
33
+ {
34
+ "ticker": {"type": "string", "pattern": r"^[A-Za-z0-9][A-Za-z0-9&_.-]{0,39}$"},
35
+ "exchange": {"enum": ["NSE", "BSE"]},
36
+ "period_type": {"enum": ["annual", "quarterly"]},
37
+ "basis": {"enum": ["consolidated", "standalone"]},
38
+ "money_unit": {"enum": ["auto", None, *MONEY_UNITS]},
39
+ "metric": {"enum": list(FIELDS)},
40
+ "source_operation_id": {"type": "string", "minLength": 1, "maxLength": 100},
41
+ "source_run_id": {"type": ["string", "null"], "maxLength": 100},
42
+ }
43
+ )
44
+
45
+
46
+ def default_period(function):
47
+ return "quarterly" if function == "finance.company_ttm" else "annual"
48
+
49
+
50
+ def function_constraints():
51
+ return [
52
+ {
53
+ "if": {"properties": {"function": {"const": name}}, "required": ["function"]},
54
+ "then": {"properties": properties},
55
+ }
56
+ for name, properties in [
57
+ (
58
+ "finance.company_ttm",
59
+ {
60
+ "period_type": {"const": "quarterly"},
61
+ "metric": {"enum": [m for m in FIELDS if m in TTM_FLOW_METRICS]},
62
+ },
63
+ ),
64
+ ("finance.company_cagr", {"period_type": {"const": "annual"}}),
65
+ ]
66
+ ]
67
+
68
+
69
+ def planning_capabilities():
70
+ properties = {
71
+ k: copy.deepcopy(v)
72
+ for k, v in SCHEMA["properties"].items()
73
+ if k not in {"source_run_id", "source_operation_id"}
74
+ }
75
+ properties.update(
76
+ source=obj(
77
+ {
78
+ "run_id": {"type": "string", "minLength": 1, "maxLength": 100},
79
+ "operation_id": {"type": "string", "minLength": 1, "maxLength": 100},
80
+ }
81
+ ),
82
+ fetch_missing={"type": "boolean", "default": False},
83
+ )
84
+ rows = []
85
+ for name, description in FUNCTIONS.items():
86
+ inputs = copy.deepcopy(properties)
87
+ inputs["period_type"]["default"] = default_period(name)
88
+ if name in {"finance.company_ttm", "finance.company_cagr"}:
89
+ inputs["period_type"]["enum"] = [default_period(name)]
90
+ if name == "finance.company_ttm":
91
+ inputs["metric"]["enum"] = [m for m in FIELDS if m in TTM_FLOW_METRICS]
92
+ rows.append(
93
+ {
94
+ "function": name,
95
+ "description": description,
96
+ "planning_schema": obj(
97
+ inputs | {"function": {"const": name}}, ["function", "ticker", "exchange"]
98
+ ),
99
+ "defaults": {
100
+ "period_type": default_period(name),
101
+ "basis": "consolidated",
102
+ "money_unit": "auto",
103
+ "metric": "revenue",
104
+ "fetch_missing": False,
105
+ },
106
+ "note": "Reuse a matching retained source or explicitly preview one missing financials request.",
107
+ }
108
+ )
109
+ return rows
110
+
111
+
112
+ def validate(function, arguments):
113
+ if not isinstance(function, str) or function not in FUNCTIONS:
114
+ raise DomainError("unknown_function", "Choose a supported company financial function.")
115
+ try:
116
+ Draft202012Validator(SCHEMA).validate(arguments)
117
+ except ValidationError:
118
+ raise DomainError(
119
+ "invalid_input", "Check the company financial function arguments."
120
+ ) from None
121
+ if function == "finance.company_cagr" and arguments["period_type"] != "annual":
122
+ raise DomainError("invalid_input", "Company CAGR requires annual financials.")
123
+ if function == "finance.company_ttm" and arguments["period_type"] != "quarterly":
124
+ raise DomainError("invalid_input", "Company TTM requires quarterly financials.")
125
+ if (
126
+ function == "finance.company_ttm"
127
+ and arguments.get("metric", "revenue") not in TTM_FLOW_METRICS
128
+ ):
129
+ raise DomainError(
130
+ "invalid_input",
131
+ "TTM requires monetary quarterly flows, not EPS, ratios or balance-sheet stocks.",
132
+ )
133
+
134
+
135
+ def calculate_company(function, arguments, source):
136
+ validate(function, arguments)
137
+ selectors = source.get("receipt", {}).get("arguments", {})
138
+ if any(selectors.get(k) != arguments[k] for k in ("ticker", "exchange", "period_type")):
139
+ raise DomainError(
140
+ "incompatible_source", "Financial source belongs to a different listing or period type."
141
+ )
142
+ prepared = prepare_financial_facts(source, arguments["money_unit"])
143
+ facts = [
144
+ f
145
+ for f in prepared["facts"]
146
+ if f["basis"] == arguments["basis"]
147
+ and f["source"]["reported_period_type"] == arguments["period_type"]
148
+ ]
149
+ dates = sorted({f["period_end"] for f in facts if f["period_end"]}, reverse=True)
150
+ issues = []
151
+
152
+ def pick(metric, end):
153
+ matches = [f for f in facts if f["metric"] == metric and f["period_end"] == end]
154
+ if len(matches) != 1:
155
+ issues.append(
156
+ f"Need one unambiguous {metric} observation for {end} / {arguments['basis']}."
157
+ )
158
+ return None
159
+ return matches[0]
160
+
161
+ needed = 4 if function.endswith("_ttm") else 2 if function.endswith(("_growth", "_cagr")) else 1
162
+ if len(dates) < needed:
163
+ issues.append(
164
+ f"Need {needed} returned {arguments['basis']} {arguments['period_type']} periods; found {len(dates)}. No extra pages were fetched."
165
+ )
166
+ inputs = {}
167
+ target = None
168
+ if not issues and function.endswith("_data_readiness"):
169
+ checks = {}
170
+ for name in FUNCTIONS:
171
+ if (
172
+ name == function
173
+ or (name.endswith("_ttm") and arguments["period_type"] != "quarterly")
174
+ or (name.endswith("_cagr") and arguments["period_type"] != "annual")
175
+ ):
176
+ continue
177
+ try:
178
+ assessed = calculate_company(name, arguments, source)
179
+ except DomainError as exc:
180
+ if exc.code != "invalid_input":
181
+ raise
182
+ checks[name] = {"status": "incomplete", "issues": [exc.message]}
183
+ continue
184
+ checks[name] = {
185
+ k: assessed[k] for k in ["status", "issues", "components"] if k in assessed
186
+ }
187
+ missing = sorted(
188
+ {f["metric"] for f in facts if f["period_end"] == dates[0] and f["value"] is None}
189
+ )
190
+ output = {
191
+ "status": "success",
192
+ "issues": [],
193
+ "values": {
194
+ "periods_returned": dates,
195
+ "null_fields_latest_period": missing,
196
+ "calculation_readiness": checks,
197
+ "valuation_readiness": {
198
+ "status": "needs_explicit_inputs",
199
+ "required": [
200
+ "reviewed EBIT definition",
201
+ "tax rate",
202
+ "noncash operating working-capital changes",
203
+ "FCFF forecasts",
204
+ "WACC",
205
+ "terminal growth",
206
+ "debt/cash/equity bridge",
207
+ "diluted share count for per-share output",
208
+ ],
209
+ "note": "Reported operating profit is not automatically EBIT; historical cash flow is not a forecast.",
210
+ },
211
+ },
212
+ }
213
+ elif not issues:
214
+ if function.endswith(("_balance_sheet_metrics", "_cash_conversion", "_profitability")):
215
+ target = "finance.calculate_" + function.removeprefix("finance.company_")
216
+ metrics = (
217
+ set(STOCK_FIELDS)
218
+ if function.endswith("_balance_sheet_metrics")
219
+ else {"revenue", "net_profit", "cash_flow_operating", "capex"}
220
+ if function.endswith("_cash_conversion")
221
+ else {
222
+ "revenue",
223
+ "net_profit",
224
+ "profit_from_continuing_operations",
225
+ "net_profit_attributable_to_owners",
226
+ "operating_profit",
227
+ "ebitda",
228
+ }
229
+ )
230
+ inputs = {
231
+ "facts": [
232
+ f for f in facts if f["period_end"] == dates[0] and f["metric"] in metrics
233
+ ]
234
+ }
235
+ if not inputs["facts"]:
236
+ issues.append("No eligible fields returned for this metric group.")
237
+ elif function.endswith("_margins"):
238
+ target = "finance.calculate_margins"
239
+ continuing = [
240
+ f
241
+ for f in facts
242
+ if f["metric"] == "profit_from_continuing_operations"
243
+ and f["period_end"] == dates[0]
244
+ and f["value"] is not None
245
+ ]
246
+ inputs = {
247
+ "profit": pick(
248
+ "profit_from_continuing_operations" if continuing else "net_profit", dates[0]
249
+ ),
250
+ "revenue": pick("revenue", dates[0]),
251
+ }
252
+ elif function.endswith("_cashflow_metrics"):
253
+ target = "finance.calculate_cashflow_metrics"
254
+ inputs = {
255
+ "cfo": pick("cash_flow_operating", dates[0]),
256
+ "capex": pick("capex", dates[0]),
257
+ }
258
+ elif function.endswith("_ttm"):
259
+ target = "finance.calculate_ttm"
260
+ inputs = {"facts": [pick(arguments["metric"], end) for end in dates[:4]]}
261
+ else:
262
+ target = (
263
+ "finance.calculate_cagr"
264
+ if function.endswith("_cagr")
265
+ else "finance.compare_periods"
266
+ )
267
+ inputs = {
268
+ "previous": pick(arguments["metric"], dates[1]),
269
+ "current": pick(arguments["metric"], dates[0]),
270
+ }
271
+ if function.endswith("_cagr"):
272
+ current, previous = date.fromisoformat(dates[0]), date.fromisoformat(dates[1])
273
+ anniversary = (current.month, current.day) == (previous.month, previous.day)
274
+ with localcontext() as context:
275
+ context.prec = 34
276
+ inputs["years"] = str(
277
+ Decimal(current.year - previous.year)
278
+ if anniversary
279
+ else Decimal((current - previous).days) / Decimal("365.25")
280
+ )
281
+ if not function.endswith("_data_readiness") or issues:
282
+ output = (
283
+ calculate(target, inputs)
284
+ if not issues
285
+ else {"status": "incomplete", "issues": issues, "values": {}}
286
+ )
287
+ output["calculation_function"] = target
288
+ output["function"] = function
289
+ output["function_version"] = "1.0"
290
+ output["selection"] = {
291
+ k: arguments[k]
292
+ for k in ("ticker", "exchange", "period_type", "basis", "metric", "money_unit")
293
+ }
294
+ output["source"] = {
295
+ "run_id": arguments["source_run_id"],
296
+ "operation_id": source["operation_id"],
297
+ "retrieved_at": source["receipt"].get("retrieved_at"),
298
+ "verification": "unverified",
299
+ }
300
+ output["warnings"] = [
301
+ *output.get("warnings", []),
302
+ *prepared["warnings"],
303
+ "Latest means latest within this bounded response; not independently established as the latest filing.",
304
+ ]
305
+ if function.endswith("_cagr"):
306
+ output["warnings"].append(
307
+ "CAGR duration uses exact calendar-anniversary years when endpoints share month/day; otherwise actual days / 365.25, explicitly a day-count convention."
308
+ )
309
+ if function.endswith("_cagr"):
310
+ output["warnings"].append(
311
+ "Elapsed years are derived from returned endpoint dates / 365.25; two annual endpoints are not a long-term growth history."
312
+ )
313
+ return output