stock-analysis-plugin 0.2.11 → 0.2.13
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/README.md +234 -382
- package/docs/mcp.md +60 -0
- package/hermes/__init__.py +35 -0
- package/hermes/plugin.yaml +132 -0
- package/hermes/schemas.py +6 -0
- package/hermes/tools.py +647 -0
- package/mcp_host/__init__.py +1 -0
- package/mcp_host/__main__.py +3 -0
- package/mcp_host/server.py +222 -0
- package/package.json +7 -1
- package/pi/index.ts +52 -2906
- package/scripts/cli-json.mjs +23 -0
- package/scripts/exec-process.mjs +89 -0
- package/scripts/setup-python.mjs +37 -4
- package/scripts/tool-calls.mjs +493 -0
- package/skills/bull-trend/SKILL.md +2 -2
- package/skills/bull-trend/references/fat-tails.md +76 -3
- package/skills/bull-trend/scripts/tail_analysis.py +92 -3
- package/skills/event-driven/SKILL.md +2 -2
- package/skills/growth-quality/SKILL.md +1 -1
- package/skills/market-review/SKILL.md +1 -0
- package/skills/stock-analysis/SKILL.md +12 -7
- package/skills/stock-analysis/references/stateless-analysis.md +9 -1
- package/skills/stock-screener/SKILL.md +1 -1
- package/skills/strategy-backtest/SKILL.md +1 -1
- package/tools/_cache.py +13 -0
- package/tools/_subproc.py +46 -0
- package/tools/alert_rules.py +2 -2
- package/tools/backtest.py +3 -3
- package/tools/capabilities.py +33 -9
- package/tools/cli_budgets.json +1 -0
- package/tools/credit_data.py +293 -0
- package/tools/diagnostics.py +3 -4
- package/tools/gather.py +2 -6
- package/tools/import_parser.py +3 -4
- package/tools/lixinger.py +119 -27
- package/tools/market_regime.py +5 -2
- package/tools/market_review.py +5 -6
- package/tools/name_resolver.py +45 -33
- package/tools/report_renderer.py +3 -3
- package/tools/requirements.txt +5 -4
- package/tools/risk_screening.py +3 -2
- package/tools/screener.py +41 -30
- package/tools/search_intel.py +79 -10
- package/tools/sec_edgar.py +268 -1
- package/tools/sec_holders.py +6 -0
- package/tools/signal_tracker.py +5 -5
- package/tools/stateless_analysis.py +132 -19
- package/tools/stock_data.py +1020 -817
- package/tools/tiaa_disclosures.py +4 -0
- package/tools/tool_schemas.json +2734 -0
- package/tools/trading_calendar.py +65 -30
- package/tools/value_data.py +423 -175
- package/tools/watchlist.py +43 -5
package/tools/sec_edgar.py
CHANGED
|
@@ -19,6 +19,7 @@ from _cache import DAY, WEEK, cached
|
|
|
19
19
|
from _subproc import utf8_stdio
|
|
20
20
|
|
|
21
21
|
_last_request = 0.0
|
|
22
|
+
SEC_MIN_INTERVAL = 0.5
|
|
22
23
|
|
|
23
24
|
|
|
24
25
|
def identity():
|
|
@@ -31,7 +32,7 @@ def identity():
|
|
|
31
32
|
def sec_get(url, as_json=True, stream=False):
|
|
32
33
|
global _last_request
|
|
33
34
|
agent = identity()
|
|
34
|
-
time.sleep(max(0,
|
|
35
|
+
time.sleep(max(0, SEC_MIN_INTERVAL - (time.monotonic() - _last_request)))
|
|
35
36
|
_last_request = time.monotonic()
|
|
36
37
|
try:
|
|
37
38
|
response = requests.get(
|
|
@@ -282,6 +283,272 @@ def form4(cik, filing):
|
|
|
282
283
|
return rows
|
|
283
284
|
|
|
284
285
|
|
|
286
|
+
# Announcement categories mapped to SEC form types; categories without an SEC equivalent are rejected.
|
|
287
|
+
FILING_FORMS = {
|
|
288
|
+
"annual": {"10-K", "10-K/A", "20-F", "20-F/A", "40-F", "40-F/A"},
|
|
289
|
+
"quarterly": {"10-Q", "10-Q/A"},
|
|
290
|
+
"current": {"8-K", "8-K/A", "6-K", "6-K/A"},
|
|
291
|
+
"issuance": {"S-1", "S-1/A", "S-3", "S-3/A", "F-1", "F-1/A", "F-3", "F-3/A", "424B2", "424B3", "424B4", "424B5"},
|
|
292
|
+
"reduction": {"144"},
|
|
293
|
+
"inquiry": {"UPLOAD", "CORRESP"},
|
|
294
|
+
}
|
|
295
|
+
FILING_FORMS["all"] = set().union(*FILING_FORMS.values()) | {"DEF 14A", "DEFA14A"}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
DCF_CONCEPTS = {
|
|
299
|
+
"revenue": ("Revenues", "RevenueFromContractWithCustomerExcludingAssessedTax", "SalesRevenueNet"),
|
|
300
|
+
"operating_income": ("OperatingIncomeLoss",),
|
|
301
|
+
"pretax_income": (
|
|
302
|
+
"IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest",
|
|
303
|
+
"IncomeLossFromContinuingOperationsBeforeIncomeTaxesMinorityInterestAndIncomeLossFromEquityMethodInvestments",
|
|
304
|
+
),
|
|
305
|
+
"income_tax": ("IncomeTaxExpenseBenefit",),
|
|
306
|
+
"operating_cash_flow": ("NetCashProvidedByUsedInOperatingActivities",),
|
|
307
|
+
"capital_expenditure": ("PaymentsToAcquirePropertyPlantAndEquipment",),
|
|
308
|
+
"depreciation_amortization": ("DepreciationDepletionAndAmortization", "DepreciationAndAmortization"),
|
|
309
|
+
"diluted_shares": ("WeightedAverageNumberOfDilutedSharesOutstanding",),
|
|
310
|
+
}
|
|
311
|
+
DCF_INSTANTS = {
|
|
312
|
+
"cash": ("CashAndCashEquivalentsAtCarryingValue",),
|
|
313
|
+
"minority_interest": ("MinorityInterest",),
|
|
314
|
+
}
|
|
315
|
+
DEBT_CONCEPTS = (
|
|
316
|
+
"LongTermDebt",
|
|
317
|
+
"LongTermDebtCurrent",
|
|
318
|
+
"LongTermDebtNoncurrent",
|
|
319
|
+
"ShortTermBorrowings",
|
|
320
|
+
"CommercialPaper",
|
|
321
|
+
)
|
|
322
|
+
# Each lease kind: the total tag, else its current + noncurrent parts.
|
|
323
|
+
LEASE_CONCEPTS = {
|
|
324
|
+
"OperatingLeaseLiability": ("OperatingLeaseLiabilityCurrent", "OperatingLeaseLiabilityNoncurrent"),
|
|
325
|
+
"FinanceLeaseLiability": ("FinanceLeaseLiabilityCurrent", "FinanceLeaseLiabilityNoncurrent"),
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def annual_fact(row):
|
|
330
|
+
if row.get("fp") != "FY" or row.get("form") not in {"10-K", "10-K/A", "20-F", "20-F/A", "40-F", "40-F/A"}:
|
|
331
|
+
return False
|
|
332
|
+
if "start" not in row:
|
|
333
|
+
return True
|
|
334
|
+
days = (date.fromisoformat(row["end"]) - date.fromisoformat(row["start"])).days
|
|
335
|
+
return 300 <= days <= 400
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def latest_facts(facts, names, unit):
|
|
339
|
+
values = {}
|
|
340
|
+
for name in names:
|
|
341
|
+
concept = {}
|
|
342
|
+
for row in facts.get(name, {}).get("units", {}).get(unit, []):
|
|
343
|
+
if annual_fact(row) and (row["end"] not in concept or row.get("filed", "") > concept[row["end"]]["filed"]):
|
|
344
|
+
concept[row["end"]] = row
|
|
345
|
+
values.update({end: row for end, row in concept.items() if end not in values})
|
|
346
|
+
return values
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def company_facts(symbol):
|
|
350
|
+
cik = resolve_cik(symbol)
|
|
351
|
+
return cached(
|
|
352
|
+
f"sec-companyfacts:{cik}", DAY, lambda: sec_get(f"https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json")
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def dcf_inputs(symbol, periods):
|
|
357
|
+
data = company_facts(symbol)
|
|
358
|
+
gaap = data.get("facts", {}).get("us-gaap", {})
|
|
359
|
+
rows = {
|
|
360
|
+
key: latest_facts(gaap, names, "shares" if key == "diluted_shares" else "USD")
|
|
361
|
+
for key, names in {**DCF_CONCEPTS, **DCF_INSTANTS}.items()
|
|
362
|
+
}
|
|
363
|
+
lease_names = [name for total, parts in LEASE_CONCEPTS.items() for name in (total, *parts)]
|
|
364
|
+
debt = {name: latest_facts(gaap, (name,), "USD") for name in (*DEBT_CONCEPTS, *lease_names)}
|
|
365
|
+
# Values keep the latest (restated) filing; labels and cover shares come from each period's original report.
|
|
366
|
+
originals = {}
|
|
367
|
+
for name in DCF_CONCEPTS["revenue"] + DCF_CONCEPTS["operating_income"]:
|
|
368
|
+
for row in gaap.get(name, {}).get("units", {}).get("USD", []):
|
|
369
|
+
if annual_fact(row) and (row["end"] not in originals or row["filed"] < originals[row["end"]]["filed"]):
|
|
370
|
+
originals[row["end"]] = row
|
|
371
|
+
ends = sorted(originals, reverse=True)[:periods]
|
|
372
|
+
outstanding = (
|
|
373
|
+
data.get("facts", {})
|
|
374
|
+
.get("dei", {})
|
|
375
|
+
.get("EntityCommonStockSharesOutstanding", {})
|
|
376
|
+
.get("units", {})
|
|
377
|
+
.get("shares", [])
|
|
378
|
+
)
|
|
379
|
+
result = []
|
|
380
|
+
for end in ends:
|
|
381
|
+
entry = {key: rows[key].get(end, {}).get("val") for key in rows}
|
|
382
|
+
source = originals[end]
|
|
383
|
+
if (date.fromisoformat(source["filed"]) - date.fromisoformat(end)).days > 365:
|
|
384
|
+
# Only a later year's comparative exists (e.g. pre-XBRL years); its labels would be wrong.
|
|
385
|
+
source = {}
|
|
386
|
+
parts = [debt["LongTermDebt"].get(end, {}).get("val")]
|
|
387
|
+
if parts[0] is None:
|
|
388
|
+
parts = [debt[name].get(end, {}).get("val") for name in ("LongTermDebtCurrent", "LongTermDebtNoncurrent")]
|
|
389
|
+
parts += [debt[name].get(end, {}).get("val") for name in ("ShortTermBorrowings", "CommercialPaper")]
|
|
390
|
+
leases = []
|
|
391
|
+
for total, split in LEASE_CONCEPTS.items():
|
|
392
|
+
names = (total,) if end in debt[total] else split
|
|
393
|
+
if all(end in debt[name] for name in names):
|
|
394
|
+
leases += [debt[name][end]["val"] for name in names]
|
|
395
|
+
# Multi-class issuers report one cover row per class in the same filing; sum them.
|
|
396
|
+
cover = [
|
|
397
|
+
row
|
|
398
|
+
for row in outstanding
|
|
399
|
+
if source and (row.get("accn"), row.get("filed")) == (source.get("accn"), source.get("filed"))
|
|
400
|
+
]
|
|
401
|
+
entry.update(
|
|
402
|
+
{
|
|
403
|
+
"period_end": end,
|
|
404
|
+
"currency": "USD",
|
|
405
|
+
"total_debt": sum(value for value in parts if value is not None)
|
|
406
|
+
if any(value is not None for value in parts)
|
|
407
|
+
else None,
|
|
408
|
+
"lease_liabilities": sum(leases) if leases else None,
|
|
409
|
+
"shares_outstanding": sum(row["val"] for row in cover) if cover else None,
|
|
410
|
+
"shares_outstanding_date": max(row["end"] for row in cover) if cover else None,
|
|
411
|
+
"form": source.get("form"),
|
|
412
|
+
"filed": source.get("filed"),
|
|
413
|
+
"fiscal_year": source.get("fy"),
|
|
414
|
+
}
|
|
415
|
+
)
|
|
416
|
+
result.append(entry)
|
|
417
|
+
if not result:
|
|
418
|
+
raise ValueError("SEC annual DCF facts unavailable")
|
|
419
|
+
return {
|
|
420
|
+
"source": "sec_companyfacts",
|
|
421
|
+
"name": data.get("entityName"),
|
|
422
|
+
"periods": result,
|
|
423
|
+
"warnings": [
|
|
424
|
+
"SEC XBRL tags vary by issuer; null fields are filled from Yahoo for the same period when available. "
|
|
425
|
+
"total_debt sums reported debt/borrowing tags and excludes leases; lease_liabilities is operating + finance "
|
|
426
|
+
"leases. Amounts use the latest filed (possibly restated) value; form/filed/shares_outstanding come from "
|
|
427
|
+
"the period's original annual report."
|
|
428
|
+
],
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def first_filed(rows, forms=("10-Q", "10-Q/A", "10-K", "10-K/A")):
|
|
433
|
+
"""Earliest filing per (start, end): the value the market could see then, not a later restatement."""
|
|
434
|
+
kept = {}
|
|
435
|
+
for row in rows:
|
|
436
|
+
key = (row.get("start"), row["end"])
|
|
437
|
+
if row.get("form") in forms and row.get("filed") and (key not in kept or row["filed"] < kept[key]["filed"]):
|
|
438
|
+
kept[key] = row
|
|
439
|
+
return list(kept.values())
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def valuation_facts(symbol):
|
|
443
|
+
"""Point-in-time TTM net income, equity and share count events, each dated by its SEC filing date."""
|
|
444
|
+
data = company_facts(symbol)
|
|
445
|
+
gaap = data.get("facts", {}).get("us-gaap", {})
|
|
446
|
+
income = first_filed(gaap.get("NetIncomeLoss", {}).get("units", {}).get("USD", []))
|
|
447
|
+
|
|
448
|
+
def days(row):
|
|
449
|
+
return (date.fromisoformat(row["end"]) - date.fromisoformat(row["start"])).days
|
|
450
|
+
|
|
451
|
+
quarters = {row["end"]: row for row in income if "start" in row and 80 <= days(row) <= 100}
|
|
452
|
+
for year in (row for row in income if "start" in row and 350 <= days(row) <= 380):
|
|
453
|
+
inside = [q for q in quarters.values() if year["start"] <= q["start"] and q["end"] <= year["end"]]
|
|
454
|
+
if year["end"] not in quarters and len(inside) == 3:
|
|
455
|
+
quarters[year["end"]] = {
|
|
456
|
+
"start": max(q["end"] for q in inside),
|
|
457
|
+
"end": year["end"],
|
|
458
|
+
"val": year["val"] - sum(q["val"] for q in inside),
|
|
459
|
+
"filed": year["filed"],
|
|
460
|
+
}
|
|
461
|
+
ordered = sorted(quarters.values(), key=lambda row: row["end"])
|
|
462
|
+
ttm = []
|
|
463
|
+
for index in range(3, len(ordered)):
|
|
464
|
+
window = ordered[index - 3 : index + 1]
|
|
465
|
+
span = (date.fromisoformat(window[-1]["end"]) - date.fromisoformat(window[0]["start"])).days
|
|
466
|
+
if 350 <= span <= 380:
|
|
467
|
+
ttm.append(
|
|
468
|
+
{
|
|
469
|
+
"filed": max(q["filed"] for q in window),
|
|
470
|
+
"end": window[-1]["end"],
|
|
471
|
+
"val": sum(q["val"] for q in window),
|
|
472
|
+
}
|
|
473
|
+
)
|
|
474
|
+
equity = [
|
|
475
|
+
{"filed": row["filed"], "end": row["end"], "val": row["val"]}
|
|
476
|
+
for row in first_filed(gaap.get("StockholdersEquity", {}).get("units", {}).get("USD", []))
|
|
477
|
+
]
|
|
478
|
+
shares = {}
|
|
479
|
+
for row in (
|
|
480
|
+
data.get("facts", {})
|
|
481
|
+
.get("dei", {})
|
|
482
|
+
.get("EntityCommonStockSharesOutstanding", {})
|
|
483
|
+
.get("units", {})
|
|
484
|
+
.get("shares", [])
|
|
485
|
+
):
|
|
486
|
+
if row.get("form") in ("10-Q", "10-Q/A", "10-K", "10-K/A") and row.get("filed"):
|
|
487
|
+
# Multi-class issuers report one row per class under the same filing; sum them.
|
|
488
|
+
entry = shares.setdefault(
|
|
489
|
+
(row.get("accn"), row["end"]), {"filed": row["filed"], "end": row["end"], "val": 0}
|
|
490
|
+
)
|
|
491
|
+
entry["val"] += row["val"]
|
|
492
|
+
basis = "cover_shares_outstanding"
|
|
493
|
+
if not shares:
|
|
494
|
+
# Some multi-class filers (e.g. Alphabet) omit dei cover shares; weighted diluted shares are the fallback.
|
|
495
|
+
basis = "weighted_diluted_shares"
|
|
496
|
+
diluted = gaap.get("WeightedAverageNumberOfDilutedSharesOutstanding", {}).get("units", {}).get("shares", [])
|
|
497
|
+
shares = {row["end"]: row for row in first_filed(diluted) if "start" in row and 80 <= days(row) <= 100}
|
|
498
|
+
if not ttm or not equity or not shares:
|
|
499
|
+
raise ValueError("SEC net income, equity or share count facts unavailable")
|
|
500
|
+
return {
|
|
501
|
+
"name": data.get("entityName"),
|
|
502
|
+
"ttm_net_income": ttm,
|
|
503
|
+
"equity": equity,
|
|
504
|
+
"shares": list(shares.values()),
|
|
505
|
+
"share_basis": basis,
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def filings(symbol, category, start, end, top):
|
|
510
|
+
forms = FILING_FORMS.get(category)
|
|
511
|
+
if forms is None:
|
|
512
|
+
raise ValueError(
|
|
513
|
+
f"category {category} has no SEC form equivalent; use all/annual/quarterly/issuance/reduction/inquiry"
|
|
514
|
+
)
|
|
515
|
+
identity()
|
|
516
|
+
cik = resolve_cik(symbol)
|
|
517
|
+
_, rows, incomplete = submissions(cik, forms, start.isoformat())
|
|
518
|
+
rows = [r for r in rows if r.get("filingDate", "") <= end.isoformat()]
|
|
519
|
+
items = []
|
|
520
|
+
for row in rows[:top]:
|
|
521
|
+
base = archive_base(cik, row)
|
|
522
|
+
document = row.get("primaryDocument") or ""
|
|
523
|
+
form = row["form"]
|
|
524
|
+
items.append(
|
|
525
|
+
{
|
|
526
|
+
"title": f"{form} {row.get('primaryDocDescription') or ''}".strip(),
|
|
527
|
+
"date": row.get("filingDate"),
|
|
528
|
+
"report_date": row.get("reportDate") or None,
|
|
529
|
+
"form": form,
|
|
530
|
+
"category": next((k for k, v in FILING_FORMS.items() if k != "all" and form in v), "other"),
|
|
531
|
+
"accession": row["accessionNumber"],
|
|
532
|
+
"document_url": f"{base}/{document}" if re.fullmatch(r"[\w.-]+", document) else None,
|
|
533
|
+
"filing_url": f"{base}/{row['accessionNumber']}-index.html",
|
|
534
|
+
"pdf_url": None,
|
|
535
|
+
}
|
|
536
|
+
)
|
|
537
|
+
return {
|
|
538
|
+
"symbol": symbol,
|
|
539
|
+
"cik": cik,
|
|
540
|
+
"market": "US",
|
|
541
|
+
"source": "sec_edgar",
|
|
542
|
+
"start_date": start.isoformat(),
|
|
543
|
+
"end_date": end.isoformat(),
|
|
544
|
+
"total": len(rows),
|
|
545
|
+
"announcements": items,
|
|
546
|
+
"truncated": incomplete or len(rows) > top,
|
|
547
|
+
"body_extracted": False,
|
|
548
|
+
"requested_category": category,
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
|
|
285
552
|
def insider_trades(args):
|
|
286
553
|
identity()
|
|
287
554
|
if not 1 <= args.days <= 365 or not 1 <= args.top <= 20:
|
package/tools/sec_holders.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Exact issuer CUSIPs joined to the latest published SEC 13F bulk window."""
|
|
2
2
|
|
|
3
|
+
import contextlib
|
|
3
4
|
import csv
|
|
4
5
|
import hashlib
|
|
5
6
|
import io
|
|
@@ -129,6 +130,11 @@ def bulk_file(window):
|
|
|
129
130
|
raise ValueError("SEC bulk download is not a valid ZIP archive")
|
|
130
131
|
finally:
|
|
131
132
|
response.close()
|
|
133
|
+
# Each quarter is a ~100 MB archive; keep only the current window.
|
|
134
|
+
for old in path.parent.glob("sec-13f-*.zip"):
|
|
135
|
+
if old != path:
|
|
136
|
+
with contextlib.suppress(OSError):
|
|
137
|
+
old.unlink()
|
|
132
138
|
return path
|
|
133
139
|
except OSError as exc:
|
|
134
140
|
raise ValueError(f"SEC bulk archive unavailable ({type(exc).__name__})") from None
|
package/tools/signal_tracker.py
CHANGED
|
@@ -24,7 +24,7 @@ from zoneinfo import ZoneInfo
|
|
|
24
24
|
|
|
25
25
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
26
26
|
from _cache import atomic_write, file_lock
|
|
27
|
-
from _subproc import command_timeout, run_tool, utf8_stdio # noqa: E402
|
|
27
|
+
from _subproc import command_timeout, error_message, run_tool, utf8_stdio # noqa: E402
|
|
28
28
|
from stock_data import detect_market # noqa: E402
|
|
29
29
|
|
|
30
30
|
_MARKET_TIMEZONES = {
|
|
@@ -183,7 +183,7 @@ def cmd_record(args):
|
|
|
183
183
|
_load_records(store, strict=True)
|
|
184
184
|
_append_record(store, record)
|
|
185
185
|
except (OSError, ValueError) as e:
|
|
186
|
-
return {"error":
|
|
186
|
+
return {"error": error_message(e)}
|
|
187
187
|
return record
|
|
188
188
|
|
|
189
189
|
|
|
@@ -310,7 +310,7 @@ def cmd_evaluate(args):
|
|
|
310
310
|
with _store_lock(store):
|
|
311
311
|
records = _load_records(store, strict=True)
|
|
312
312
|
except (OSError, ValueError) as e:
|
|
313
|
-
return {"error":
|
|
313
|
+
return {"error": error_message(e)}
|
|
314
314
|
results = []
|
|
315
315
|
evaluated = closed = 0
|
|
316
316
|
changed = False
|
|
@@ -400,7 +400,7 @@ def cmd_evaluate(args):
|
|
|
400
400
|
entry.update({key: rec.get(key) for key in ("outcome", "return_pct", "exit_date")})
|
|
401
401
|
closed += 1
|
|
402
402
|
except (OSError, ValueError) as e:
|
|
403
|
-
return {"error":
|
|
403
|
+
return {"error": error_message(e)}
|
|
404
404
|
return {
|
|
405
405
|
"evaluated": evaluated,
|
|
406
406
|
"closed": closed,
|
|
@@ -418,7 +418,7 @@ def cmd_summary(args):
|
|
|
418
418
|
with _store_lock(store):
|
|
419
419
|
records = _load_records(store, strict=True)
|
|
420
420
|
except (OSError, ValueError) as e:
|
|
421
|
-
return {"error":
|
|
421
|
+
return {"error": error_message(e)}
|
|
422
422
|
filtered = records
|
|
423
423
|
if args.source:
|
|
424
424
|
filtered = [r for r in filtered if r.get("source") == args.source]
|
|
@@ -196,6 +196,120 @@ def text(value, name):
|
|
|
196
196
|
return value.strip()
|
|
197
197
|
|
|
198
198
|
|
|
199
|
+
def dcf(p):
|
|
200
|
+
growth = p["revenue_growth"]
|
|
201
|
+
years = len(growth) if isinstance(growth, list) else 0
|
|
202
|
+
if not 1 <= years <= 10:
|
|
203
|
+
raise ValueError("revenue_growth must contain 1..10 years")
|
|
204
|
+
|
|
205
|
+
def series(name, minimum=None, maximum=None):
|
|
206
|
+
values = p[name]
|
|
207
|
+
if not isinstance(values, list) or len(values) != years:
|
|
208
|
+
raise ValueError(f"{name} must match revenue_growth length")
|
|
209
|
+
return [number(value, name, minimum, maximum) for value in values]
|
|
210
|
+
|
|
211
|
+
growth = series("revenue_growth", -0.99, 10)
|
|
212
|
+
margins = series("operating_margin", -10, 1)
|
|
213
|
+
taxes = series("tax_rate", 0, 1)
|
|
214
|
+
waccs = series("wacc", 0, 1)
|
|
215
|
+
revenue = positive(p["base_revenue"], "base_revenue")
|
|
216
|
+
sales_to_capital = positive(p["sales_to_capital"], "sales_to_capital")
|
|
217
|
+
terminal_growth = number(p["terminal_growth"], "terminal_growth", -0.99, 1)
|
|
218
|
+
terminal_wacc = number(p["terminal_wacc"], "terminal_wacc", 0, 1)
|
|
219
|
+
terminal_roic = positive(p["terminal_roic"], "terminal_roic")
|
|
220
|
+
shares = positive(p["diluted_shares"], "diluted_shares")
|
|
221
|
+
if terminal_wacc <= terminal_growth or terminal_growth > terminal_roic:
|
|
222
|
+
raise ValueError("terminal_wacc must exceed terminal_growth and terminal_growth must not exceed terminal_roic")
|
|
223
|
+
claims = {key: number(p.get(key, 0), key, 0) for key in ("cash", "debt", "minority_interests", "other_claims")}
|
|
224
|
+
nonoperating = number(p.get("nonoperating_assets", 0), "nonoperating_assets", 0)
|
|
225
|
+
projections, discount, pv_fcff = [], 1, 0
|
|
226
|
+
for year, (rate, margin, tax, wacc) in enumerate(zip(growth, margins, taxes, waccs), 1):
|
|
227
|
+
previous, revenue = revenue, revenue * (1 + rate)
|
|
228
|
+
ebit = revenue * margin
|
|
229
|
+
nopat = ebit * (1 - tax)
|
|
230
|
+
reinvestment = (revenue - previous) / sales_to_capital
|
|
231
|
+
fcff = nopat - reinvestment
|
|
232
|
+
discount *= 1 + wacc
|
|
233
|
+
present_value = fcff / discount
|
|
234
|
+
pv_fcff += present_value
|
|
235
|
+
projections.append(
|
|
236
|
+
{
|
|
237
|
+
"year": year,
|
|
238
|
+
"revenue": revenue,
|
|
239
|
+
"ebit": ebit,
|
|
240
|
+
"nopat": nopat,
|
|
241
|
+
"reinvestment": reinvestment,
|
|
242
|
+
"fcff": fcff,
|
|
243
|
+
"discount_factor": 1 / discount,
|
|
244
|
+
"present_value": present_value,
|
|
245
|
+
}
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def value(terminal_wacc_value, terminal_growth_value):
|
|
249
|
+
terminal_nopat = revenue * (1 + terminal_growth_value) * margins[-1] * (1 - taxes[-1])
|
|
250
|
+
reinvestment_rate = terminal_growth_value / terminal_roic
|
|
251
|
+
terminal_fcff = terminal_nopat * (1 - reinvestment_rate)
|
|
252
|
+
terminal_value = terminal_fcff / (terminal_wacc_value - terminal_growth_value)
|
|
253
|
+
enterprise = pv_fcff + terminal_value / discount
|
|
254
|
+
equity = enterprise + claims["cash"] + nonoperating - claims["debt"] - claims["minority_interests"]
|
|
255
|
+
equity -= claims["other_claims"]
|
|
256
|
+
return terminal_nopat, reinvestment_rate, terminal_fcff, terminal_value, enterprise, equity
|
|
257
|
+
|
|
258
|
+
terminal_nopat, reinvestment_rate, terminal_fcff, terminal_value, enterprise, equity = value(
|
|
259
|
+
terminal_wacc, terminal_growth
|
|
260
|
+
)
|
|
261
|
+
per_share = equity / shares
|
|
262
|
+
price = p.get("current_price")
|
|
263
|
+
if price is not None:
|
|
264
|
+
price = positive(price, "current_price")
|
|
265
|
+
sensitivity = []
|
|
266
|
+
for wacc_shift in (-0.01, 0, 0.01):
|
|
267
|
+
for growth_shift in (-0.005, 0, 0.005):
|
|
268
|
+
wacc_value, growth_value = terminal_wacc + wacc_shift, terminal_growth + growth_shift
|
|
269
|
+
valid = 0 <= wacc_value <= 1 and wacc_value > growth_value and growth_value <= terminal_roic
|
|
270
|
+
sensitivity.append(
|
|
271
|
+
{
|
|
272
|
+
"terminal_wacc": wacc_value,
|
|
273
|
+
"terminal_growth": growth_value,
|
|
274
|
+
"value_per_share": value(wacc_value, growth_value)[5] / shares if valid else None,
|
|
275
|
+
}
|
|
276
|
+
)
|
|
277
|
+
return {
|
|
278
|
+
"currency": text(p["currency"], "currency"),
|
|
279
|
+
"units": text(p["units"], "units"),
|
|
280
|
+
"valuation": {
|
|
281
|
+
"enterprise_value": enterprise,
|
|
282
|
+
"equity_value": equity,
|
|
283
|
+
"value_per_share": per_share,
|
|
284
|
+
"upside_pct": (per_share / price - 1) * 100 if price is not None else None,
|
|
285
|
+
"pv_fcff": pv_fcff,
|
|
286
|
+
"pv_terminal_value": terminal_value / discount,
|
|
287
|
+
"terminal_value_pct": terminal_value / discount / enterprise * 100 if enterprise > 0 else None,
|
|
288
|
+
},
|
|
289
|
+
"projections": projections,
|
|
290
|
+
"terminal": {
|
|
291
|
+
"nopat": terminal_nopat,
|
|
292
|
+
"reinvestment_rate": reinvestment_rate,
|
|
293
|
+
"fcff": terminal_fcff,
|
|
294
|
+
"value": terminal_value,
|
|
295
|
+
},
|
|
296
|
+
"sensitivity": sensitivity,
|
|
297
|
+
"assumptions": {
|
|
298
|
+
"model": "FCFF",
|
|
299
|
+
"sales_to_capital": sales_to_capital,
|
|
300
|
+
"terminal_growth": terminal_growth,
|
|
301
|
+
"terminal_wacc": terminal_wacc,
|
|
302
|
+
"terminal_roic": terminal_roic,
|
|
303
|
+
"diluted_shares": shares,
|
|
304
|
+
**claims,
|
|
305
|
+
"nonoperating_assets": nonoperating,
|
|
306
|
+
},
|
|
307
|
+
"warnings": [
|
|
308
|
+
"Input-driven valuation, not a forecast or trade signal. Amounts and shares must use one consistent currency and unit."
|
|
309
|
+
],
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
|
|
199
313
|
def rows(value, name, minimum=1, maximum=100):
|
|
200
314
|
if not isinstance(value, list) or not minimum <= len(value) <= maximum:
|
|
201
315
|
raise ValueError(f"{name} has invalid row count")
|
|
@@ -386,7 +500,7 @@ def portfolio(p):
|
|
|
386
500
|
centered = raw_vector - raw_vector.mean()
|
|
387
501
|
history_data[id(history)] = {
|
|
388
502
|
"days": days,
|
|
389
|
-
"
|
|
503
|
+
"ordinals": np.array(days, dtype="datetime64[D]").astype(np.int64),
|
|
390
504
|
"center": center,
|
|
391
505
|
"scale": scale,
|
|
392
506
|
"raw": raw_vector,
|
|
@@ -394,13 +508,14 @@ def portfolio(p):
|
|
|
394
508
|
"norm": np.linalg.norm(centered),
|
|
395
509
|
}
|
|
396
510
|
|
|
397
|
-
def scaled_vector(history,
|
|
511
|
+
def scaled_vector(history, indices):
|
|
398
512
|
data = history_data[id(history)]
|
|
399
|
-
|
|
513
|
+
days = data["days"]
|
|
514
|
+
if len(indices) == len(days):
|
|
400
515
|
return data["centered"], data["norm"]
|
|
401
516
|
|
|
402
517
|
def exact_common_vector():
|
|
403
|
-
values = history_returns(history,
|
|
518
|
+
values = history_returns(history, [days[index] for index in indices], returns_cache)
|
|
404
519
|
center = values[0]
|
|
405
520
|
deviations = [value - center for value in values]
|
|
406
521
|
scale = max((abs(value) for value in deviations), default=0)
|
|
@@ -411,10 +526,9 @@ def portfolio(p):
|
|
|
411
526
|
center, scale = data["center"], data["scale"]
|
|
412
527
|
if scale == 0 or scale > 1000000 or scale < Fraction(1, 1000000):
|
|
413
528
|
return exact_common_vector()
|
|
414
|
-
indices = np.searchsorted(data["days_array"], common)
|
|
415
529
|
subset = data["raw"][indices[1:] - 1].copy()
|
|
416
530
|
for index in np.flatnonzero(np.diff(indices) != 1):
|
|
417
|
-
gap = history_returns(history, [
|
|
531
|
+
gap = history_returns(history, [days[indices[index]], days[indices[index + 1]]], returns_cache)[0]
|
|
418
532
|
try:
|
|
419
533
|
gap_value = float((gap - center) / scale)
|
|
420
534
|
except OverflowError:
|
|
@@ -436,25 +550,23 @@ def portfolio(p):
|
|
|
436
550
|
|
|
437
551
|
def correlation_row(pair):
|
|
438
552
|
a, b = pair
|
|
439
|
-
|
|
553
|
+
_, a_indices, b_indices = np.intersect1d(
|
|
554
|
+
history_data[id(histories[a])]["ordinals"],
|
|
555
|
+
history_data[id(histories[b])]["ordinals"],
|
|
556
|
+
assume_unique=True,
|
|
557
|
+
return_indices=True,
|
|
558
|
+
)
|
|
440
559
|
corr = None
|
|
441
|
-
if len(
|
|
442
|
-
x, x_norm = scaled_vector(histories[a],
|
|
443
|
-
y, y_norm = scaled_vector(histories[b],
|
|
560
|
+
if len(a_indices) >= 4:
|
|
561
|
+
x, x_norm = scaled_vector(histories[a], a_indices)
|
|
562
|
+
y, y_norm = scaled_vector(histories[b], b_indices)
|
|
444
563
|
if x_norm and y_norm:
|
|
445
564
|
correlation = float(np.dot(x, y) / (x_norm * y_norm))
|
|
446
565
|
corr = max(-1.0, min(1.0, correlation))
|
|
447
|
-
return {"symbols": [a, b], "correlation": corr, "return_samples": max(len(
|
|
566
|
+
return {"symbols": [a, b], "correlation": corr, "return_samples": max(len(a_indices) - 1, 0)}
|
|
448
567
|
|
|
449
568
|
pairs = [(a, b) for i, a in enumerate(symbols) for b in symbols[i + 1 :]]
|
|
450
|
-
|
|
451
|
-
import os
|
|
452
|
-
from concurrent.futures import ThreadPoolExecutor
|
|
453
|
-
|
|
454
|
-
with ThreadPoolExecutor(max_workers=min(2, os.cpu_count() or 1)) as pool:
|
|
455
|
-
correlations = list(pool.map(correlation_row, pairs))
|
|
456
|
-
else:
|
|
457
|
-
correlations = [correlation_row(pair) for pair in pairs]
|
|
569
|
+
correlations = [correlation_row(pair) for pair in pairs]
|
|
458
570
|
warnings = [
|
|
459
571
|
"Price P&L uses current FX, excludes historical FX P&L, fees and distributions; stop risk is a scenario, not a guaranteed loss limit.",
|
|
460
572
|
"Correlations use local-price returns on common dates, exclude FX, and do not forecast future dependence.",
|
|
@@ -1136,6 +1248,7 @@ def robustness(p):
|
|
|
1136
1248
|
|
|
1137
1249
|
COMMANDS = {
|
|
1138
1250
|
"position_size": position_size,
|
|
1251
|
+
"dcf": dcf,
|
|
1139
1252
|
"portfolio": portfolio,
|
|
1140
1253
|
"rebalance": rebalance,
|
|
1141
1254
|
"peers": peers,
|