stock-analysis-plugin 0.2.10 → 0.2.12

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 (47) hide show
  1. package/README.md +237 -381
  2. package/docs/mcp.md +60 -0
  3. package/hermes/__init__.py +35 -0
  4. package/hermes/plugin.yaml +131 -0
  5. package/hermes/schemas.py +6 -0
  6. package/hermes/tools.py +630 -0
  7. package/mcp_host/__init__.py +1 -0
  8. package/mcp_host/__main__.py +3 -0
  9. package/mcp_host/server.py +222 -0
  10. package/package.json +17 -10
  11. package/pi/index.ts +53 -2887
  12. package/scripts/cli-json.mjs +23 -0
  13. package/scripts/exec-process.mjs +89 -0
  14. package/scripts/setup-python.mjs +37 -4
  15. package/scripts/tool-calls.mjs +489 -0
  16. package/skills/event-driven/SKILL.md +2 -2
  17. package/skills/growth-quality/SKILL.md +1 -1
  18. package/skills/stock-analysis/SKILL.md +12 -7
  19. package/skills/stock-analysis/references/stateless-analysis.md +9 -1
  20. package/tools/_cache.py +13 -0
  21. package/tools/_subproc.py +46 -0
  22. package/tools/alert_rules.py +65 -16
  23. package/tools/backtest.py +3 -3
  24. package/tools/capabilities.py +32 -9
  25. package/tools/cli_budgets.json +2 -0
  26. package/tools/diagnostics.py +3 -4
  27. package/tools/gather.py +2 -6
  28. package/tools/import_parser.py +3 -4
  29. package/tools/lixinger.py +119 -27
  30. package/tools/market_regime.py +5 -2
  31. package/tools/market_review.py +5 -6
  32. package/tools/name_resolver.py +82 -21
  33. package/tools/report_renderer.py +3 -3
  34. package/tools/requirements.txt +6 -5
  35. package/tools/risk_screening.py +3 -2
  36. package/tools/screener.py +6 -4
  37. package/tools/search_intel.py +81 -12
  38. package/tools/sec_edgar.py +266 -0
  39. package/tools/sec_holders.py +6 -0
  40. package/tools/signal_tracker.py +11 -10
  41. package/tools/stateless_analysis.py +115 -0
  42. package/tools/stock_data.py +707 -222
  43. package/tools/tiaa_disclosures.py +267 -0
  44. package/tools/tool_schemas.json +2704 -0
  45. package/tools/trading_calendar.py +65 -30
  46. package/tools/value_data.py +366 -134
  47. package/tools/watchlist.py +43 -5
@@ -9,9 +9,10 @@ import re
9
9
  import sys
10
10
  import time as _time
11
11
  from contextvars import ContextVar
12
+ from urllib.parse import urlparse
12
13
 
13
14
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
- from _subproc import scrub_secrets, utf8_stdio
15
+ from _subproc import error_message, scrub_secrets, utf8_stdio
15
16
 
16
17
  _SEARCH_STATE = ContextVar("search_budget", default=None)
17
18
 
@@ -228,13 +229,13 @@ def _searxng_search(query: str, max_results: int = 5) -> list[dict]:
228
229
  return []
229
230
 
230
231
 
231
- def search_news(query: str, max_results: int = 10) -> dict:
232
+ def search_news(query: str, max_results: int = 10, budget_seconds: int = 45) -> dict:
232
233
  results = []
233
234
  engines_tried = []
234
235
  engines_available = []
235
236
  engines_errors = {}
236
237
 
237
- with _search_budget(45) as state:
238
+ with _search_budget(budget_seconds) as state:
238
239
  for name, fn in [
239
240
  ("tavily", _tavily_search),
240
241
  ("brave", _brave_search),
@@ -474,25 +475,90 @@ def get_trending_sentiment() -> dict:
474
475
  # --------------- Article Extraction ---------------
475
476
 
476
477
 
477
- def extract_article(url: str) -> dict:
478
+ def _extract_pdf(url: str, max_chars: int, response) -> dict:
479
+ import io
480
+
481
+ content = bytearray()
482
+ try:
483
+ from pypdf import PdfReader
484
+
485
+ for chunk in response.iter_content(65536):
486
+ content.extend(chunk)
487
+ if len(content) > 25 * 1024 * 1024:
488
+ raise ValueError("PDF exceeds the 25 MiB download limit")
489
+ finally:
490
+ response.close()
491
+ if not content.startswith(b"%PDF-"):
492
+ raise ValueError("URL did not return a PDF document")
493
+
494
+ reader = PdfReader(io.BytesIO(content))
495
+ parts = []
496
+ for page in reader.pages:
497
+ parts.append(page.extract_text() or "")
498
+ if sum(map(len, parts)) > max_chars:
499
+ break
500
+ text = "\n".join(parts)
501
+ metadata = reader.metadata or {}
502
+ return {
503
+ "url": url,
504
+ "title": str(metadata.get("/Title") or ""),
505
+ "text": text[:max_chars],
506
+ "authors": [str(metadata["/Author"])] if metadata.get("/Author") else [],
507
+ "publish_date": str(metadata["/CreationDate"]) if metadata.get("/CreationDate") else None,
508
+ "top_image": None,
509
+ "format": "pdf",
510
+ "page_count": len(reader.pages),
511
+ "truncated": len(text) > max_chars,
512
+ }
513
+
514
+
515
+ def extract_article(url: str, max_chars: int = 3000) -> dict:
516
+ if isinstance(max_chars, bool) or not isinstance(max_chars, int) or not 1 <= max_chars <= 200000:
517
+ return {"url": url, "error": "max_chars must be an integer between 1 and 200000"}
518
+ is_pdf = url.lower().split("?", 1)[0].endswith(".pdf")
478
519
  try:
479
- from newspaper import Article
520
+ from newspaper import Article, network
521
+
522
+ config = network.Configuration()
523
+ config.allow_binary_content = True
524
+ config.requests_params.update(timeout=30, stream=True)
525
+ host = (urlparse(url).hostname or "").lower()
526
+ if host == "sec.gov" or host.endswith(".sec.gov"):
527
+ from sec_edgar import identity
528
+
529
+ config.browser_user_agent = identity() # SEC answers 403 to requests without a declared contact
530
+ response = network.do_request(url, config)
531
+ response.raise_for_status()
532
+ content_type = response.headers.get("content-type", "").lower()
533
+ is_pdf = is_pdf or "application/pdf" in content_type
534
+ if is_pdf:
535
+ return _extract_pdf(url, max_chars, response)
536
+ # allow_binary_content is on for PDFs only; refuse other binaries before reading the whole body.
537
+ if content_type.startswith(("image/", "video/", "audio/", "font/")) or (
538
+ content_type.startswith("application/") and "json" not in content_type and "xml" not in content_type
539
+ ):
540
+ response.close()
541
+ return {"url": url, "error": f"Unsupported binary content-type: {content_type}"}
480
542
 
481
543
  a = Article(url, language="zh")
482
- a.download()
544
+ a.download(input_html=network.get_html(url, config, response=response))
483
545
  a.parse()
546
+ text = a.text or ""
484
547
  return {
485
548
  "url": url,
486
549
  "title": a.title or "",
487
- "text": (a.text or "")[:3000],
550
+ "text": text[:max_chars],
488
551
  "authors": a.authors or [],
489
552
  "publish_date": str(a.publish_date) if a.publish_date else None,
490
553
  "top_image": a.top_image or None,
554
+ "format": "html",
555
+ "truncated": len(text) > max_chars,
491
556
  }
492
- except ImportError:
493
- return {"url": url, "error": "newspaper4k not installed. pip install newspaper4k"}
557
+ except ImportError as exc:
558
+ dependency = "pypdf" if exc.name == "pypdf" else "newspaper4k"
559
+ return {"url": url, "error": f"{dependency} not installed. pip install {dependency}"}
494
560
  except Exception as e:
495
- return {"url": url, "error": str(e)}
561
+ return {"url": url, "error": error_message(e)}
496
562
 
497
563
 
498
564
  # --------------- CLI Commands ---------------
@@ -515,7 +581,7 @@ def cmd_trending(args):
515
581
 
516
582
 
517
583
  def cmd_extract(args):
518
- return extract_article(args.url)
584
+ return extract_article(args.url, max_chars=args.max_chars)
519
585
 
520
586
 
521
587
  def main():
@@ -536,7 +602,8 @@ def main():
536
602
  sub.add_parser("trending")
537
603
 
538
604
  p_ext = sub.add_parser("extract")
539
- p_ext.add_argument("url", help="Article URL to extract")
605
+ p_ext.add_argument("url", help="Article or PDF URL to extract")
606
+ p_ext.add_argument("--max-chars", type=int, default=3000, help="Maximum extracted characters (1-200000)")
540
607
 
541
608
  args = parser.parse_args()
542
609
  if not args.command:
@@ -552,6 +619,8 @@ def main():
552
619
  }
553
620
  result = dispatch[args.command](args)
554
621
  print(json.dumps(result, ensure_ascii=False, default=str))
622
+ if isinstance(result, dict) and "error" in result:
623
+ sys.exit(1)
555
624
 
556
625
 
557
626
  if __name__ == "__main__":
@@ -282,6 +282,272 @@ def form4(cik, filing):
282
282
  return rows
283
283
 
284
284
 
285
+ # Announcement categories mapped to SEC form types; categories without an SEC equivalent are rejected.
286
+ FILING_FORMS = {
287
+ "annual": {"10-K", "10-K/A", "20-F", "20-F/A", "40-F", "40-F/A"},
288
+ "quarterly": {"10-Q", "10-Q/A"},
289
+ "current": {"8-K", "8-K/A", "6-K", "6-K/A"},
290
+ "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"},
291
+ "reduction": {"144"},
292
+ "inquiry": {"UPLOAD", "CORRESP"},
293
+ }
294
+ FILING_FORMS["all"] = set().union(*FILING_FORMS.values()) | {"DEF 14A", "DEFA14A"}
295
+
296
+
297
+ DCF_CONCEPTS = {
298
+ "revenue": ("Revenues", "RevenueFromContractWithCustomerExcludingAssessedTax", "SalesRevenueNet"),
299
+ "operating_income": ("OperatingIncomeLoss",),
300
+ "pretax_income": (
301
+ "IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest",
302
+ "IncomeLossFromContinuingOperationsBeforeIncomeTaxesMinorityInterestAndIncomeLossFromEquityMethodInvestments",
303
+ ),
304
+ "income_tax": ("IncomeTaxExpenseBenefit",),
305
+ "operating_cash_flow": ("NetCashProvidedByUsedInOperatingActivities",),
306
+ "capital_expenditure": ("PaymentsToAcquirePropertyPlantAndEquipment",),
307
+ "depreciation_amortization": ("DepreciationDepletionAndAmortization", "DepreciationAndAmortization"),
308
+ "diluted_shares": ("WeightedAverageNumberOfDilutedSharesOutstanding",),
309
+ }
310
+ DCF_INSTANTS = {
311
+ "cash": ("CashAndCashEquivalentsAtCarryingValue",),
312
+ "minority_interest": ("MinorityInterest",),
313
+ }
314
+ DEBT_CONCEPTS = (
315
+ "LongTermDebt",
316
+ "LongTermDebtCurrent",
317
+ "LongTermDebtNoncurrent",
318
+ "ShortTermBorrowings",
319
+ "CommercialPaper",
320
+ )
321
+ # Each lease kind: the total tag, else its current + noncurrent parts.
322
+ LEASE_CONCEPTS = {
323
+ "OperatingLeaseLiability": ("OperatingLeaseLiabilityCurrent", "OperatingLeaseLiabilityNoncurrent"),
324
+ "FinanceLeaseLiability": ("FinanceLeaseLiabilityCurrent", "FinanceLeaseLiabilityNoncurrent"),
325
+ }
326
+
327
+
328
+ def annual_fact(row):
329
+ 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"}:
330
+ return False
331
+ if "start" not in row:
332
+ return True
333
+ days = (date.fromisoformat(row["end"]) - date.fromisoformat(row["start"])).days
334
+ return 300 <= days <= 400
335
+
336
+
337
+ def latest_facts(facts, names, unit):
338
+ values = {}
339
+ for name in names:
340
+ concept = {}
341
+ for row in facts.get(name, {}).get("units", {}).get(unit, []):
342
+ if annual_fact(row) and (row["end"] not in concept or row.get("filed", "") > concept[row["end"]]["filed"]):
343
+ concept[row["end"]] = row
344
+ values.update({end: row for end, row in concept.items() if end not in values})
345
+ return values
346
+
347
+
348
+ def company_facts(symbol):
349
+ cik = resolve_cik(symbol)
350
+ return cached(
351
+ f"sec-companyfacts:{cik}", DAY, lambda: sec_get(f"https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json")
352
+ )
353
+
354
+
355
+ def dcf_inputs(symbol, periods):
356
+ data = company_facts(symbol)
357
+ gaap = data.get("facts", {}).get("us-gaap", {})
358
+ rows = {
359
+ key: latest_facts(gaap, names, "shares" if key == "diluted_shares" else "USD")
360
+ for key, names in {**DCF_CONCEPTS, **DCF_INSTANTS}.items()
361
+ }
362
+ lease_names = [name for total, parts in LEASE_CONCEPTS.items() for name in (total, *parts)]
363
+ debt = {name: latest_facts(gaap, (name,), "USD") for name in (*DEBT_CONCEPTS, *lease_names)}
364
+ # Values keep the latest (restated) filing; labels and cover shares come from each period's original report.
365
+ originals = {}
366
+ for name in DCF_CONCEPTS["revenue"] + DCF_CONCEPTS["operating_income"]:
367
+ for row in gaap.get(name, {}).get("units", {}).get("USD", []):
368
+ if annual_fact(row) and (row["end"] not in originals or row["filed"] < originals[row["end"]]["filed"]):
369
+ originals[row["end"]] = row
370
+ ends = sorted(originals, reverse=True)[:periods]
371
+ outstanding = (
372
+ data.get("facts", {})
373
+ .get("dei", {})
374
+ .get("EntityCommonStockSharesOutstanding", {})
375
+ .get("units", {})
376
+ .get("shares", [])
377
+ )
378
+ result = []
379
+ for end in ends:
380
+ entry = {key: rows[key].get(end, {}).get("val") for key in rows}
381
+ source = originals[end]
382
+ if (date.fromisoformat(source["filed"]) - date.fromisoformat(end)).days > 365:
383
+ # Only a later year's comparative exists (e.g. pre-XBRL years); its labels would be wrong.
384
+ source = {}
385
+ parts = [debt["LongTermDebt"].get(end, {}).get("val")]
386
+ if parts[0] is None:
387
+ parts = [debt[name].get(end, {}).get("val") for name in ("LongTermDebtCurrent", "LongTermDebtNoncurrent")]
388
+ parts += [debt[name].get(end, {}).get("val") for name in ("ShortTermBorrowings", "CommercialPaper")]
389
+ leases = []
390
+ for total, split in LEASE_CONCEPTS.items():
391
+ names = (total,) if end in debt[total] else split
392
+ if all(end in debt[name] for name in names):
393
+ leases += [debt[name][end]["val"] for name in names]
394
+ # Multi-class issuers report one cover row per class in the same filing; sum them.
395
+ cover = [
396
+ row
397
+ for row in outstanding
398
+ if source and (row.get("accn"), row.get("filed")) == (source.get("accn"), source.get("filed"))
399
+ ]
400
+ entry.update(
401
+ {
402
+ "period_end": end,
403
+ "currency": "USD",
404
+ "total_debt": sum(value for value in parts if value is not None)
405
+ if any(value is not None for value in parts)
406
+ else None,
407
+ "lease_liabilities": sum(leases) if leases else None,
408
+ "shares_outstanding": sum(row["val"] for row in cover) if cover else None,
409
+ "shares_outstanding_date": max(row["end"] for row in cover) if cover else None,
410
+ "form": source.get("form"),
411
+ "filed": source.get("filed"),
412
+ "fiscal_year": source.get("fy"),
413
+ }
414
+ )
415
+ result.append(entry)
416
+ if not result:
417
+ raise ValueError("SEC annual DCF facts unavailable")
418
+ return {
419
+ "source": "sec_companyfacts",
420
+ "name": data.get("entityName"),
421
+ "periods": result,
422
+ "warnings": [
423
+ "SEC XBRL tags vary by issuer; null fields are filled from Yahoo for the same period when available. "
424
+ "total_debt sums reported debt/borrowing tags and excludes leases; lease_liabilities is operating + finance "
425
+ "leases. Amounts use the latest filed (possibly restated) value; form/filed/shares_outstanding come from "
426
+ "the period's original annual report."
427
+ ],
428
+ }
429
+
430
+
431
+ def first_filed(rows, forms=("10-Q", "10-Q/A", "10-K", "10-K/A")):
432
+ """Earliest filing per (start, end): the value the market could see then, not a later restatement."""
433
+ kept = {}
434
+ for row in rows:
435
+ key = (row.get("start"), row["end"])
436
+ if row.get("form") in forms and row.get("filed") and (key not in kept or row["filed"] < kept[key]["filed"]):
437
+ kept[key] = row
438
+ return list(kept.values())
439
+
440
+
441
+ def valuation_facts(symbol):
442
+ """Point-in-time TTM net income, equity and share count events, each dated by its SEC filing date."""
443
+ data = company_facts(symbol)
444
+ gaap = data.get("facts", {}).get("us-gaap", {})
445
+ income = first_filed(gaap.get("NetIncomeLoss", {}).get("units", {}).get("USD", []))
446
+
447
+ def days(row):
448
+ return (date.fromisoformat(row["end"]) - date.fromisoformat(row["start"])).days
449
+
450
+ quarters = {row["end"]: row for row in income if "start" in row and 80 <= days(row) <= 100}
451
+ for year in (row for row in income if "start" in row and 350 <= days(row) <= 380):
452
+ inside = [q for q in quarters.values() if year["start"] <= q["start"] and q["end"] <= year["end"]]
453
+ if year["end"] not in quarters and len(inside) == 3:
454
+ quarters[year["end"]] = {
455
+ "start": max(q["end"] for q in inside),
456
+ "end": year["end"],
457
+ "val": year["val"] - sum(q["val"] for q in inside),
458
+ "filed": year["filed"],
459
+ }
460
+ ordered = sorted(quarters.values(), key=lambda row: row["end"])
461
+ ttm = []
462
+ for index in range(3, len(ordered)):
463
+ window = ordered[index - 3 : index + 1]
464
+ span = (date.fromisoformat(window[-1]["end"]) - date.fromisoformat(window[0]["start"])).days
465
+ if 350 <= span <= 380:
466
+ ttm.append(
467
+ {
468
+ "filed": max(q["filed"] for q in window),
469
+ "end": window[-1]["end"],
470
+ "val": sum(q["val"] for q in window),
471
+ }
472
+ )
473
+ equity = [
474
+ {"filed": row["filed"], "end": row["end"], "val": row["val"]}
475
+ for row in first_filed(gaap.get("StockholdersEquity", {}).get("units", {}).get("USD", []))
476
+ ]
477
+ shares = {}
478
+ for row in (
479
+ data.get("facts", {})
480
+ .get("dei", {})
481
+ .get("EntityCommonStockSharesOutstanding", {})
482
+ .get("units", {})
483
+ .get("shares", [])
484
+ ):
485
+ if row.get("form") in ("10-Q", "10-Q/A", "10-K", "10-K/A") and row.get("filed"):
486
+ # Multi-class issuers report one row per class under the same filing; sum them.
487
+ entry = shares.setdefault(
488
+ (row.get("accn"), row["end"]), {"filed": row["filed"], "end": row["end"], "val": 0}
489
+ )
490
+ entry["val"] += row["val"]
491
+ basis = "cover_shares_outstanding"
492
+ if not shares:
493
+ # Some multi-class filers (e.g. Alphabet) omit dei cover shares; weighted diluted shares are the fallback.
494
+ basis = "weighted_diluted_shares"
495
+ diluted = gaap.get("WeightedAverageNumberOfDilutedSharesOutstanding", {}).get("units", {}).get("shares", [])
496
+ shares = {row["end"]: row for row in first_filed(diluted) if "start" in row and 80 <= days(row) <= 100}
497
+ if not ttm or not equity or not shares:
498
+ raise ValueError("SEC net income, equity or share count facts unavailable")
499
+ return {
500
+ "name": data.get("entityName"),
501
+ "ttm_net_income": ttm,
502
+ "equity": equity,
503
+ "shares": list(shares.values()),
504
+ "share_basis": basis,
505
+ }
506
+
507
+
508
+ def filings(symbol, category, start, end, top):
509
+ forms = FILING_FORMS.get(category)
510
+ if forms is None:
511
+ raise ValueError(
512
+ f"category {category} has no SEC form equivalent; use all/annual/quarterly/issuance/reduction/inquiry"
513
+ )
514
+ identity()
515
+ cik = resolve_cik(symbol)
516
+ _, rows, incomplete = submissions(cik, forms, start.isoformat())
517
+ rows = [r for r in rows if r.get("filingDate", "") <= end.isoformat()]
518
+ items = []
519
+ for row in rows[:top]:
520
+ base = archive_base(cik, row)
521
+ document = row.get("primaryDocument") or ""
522
+ form = row["form"]
523
+ items.append(
524
+ {
525
+ "title": f"{form} {row.get('primaryDocDescription') or ''}".strip(),
526
+ "date": row.get("filingDate"),
527
+ "report_date": row.get("reportDate") or None,
528
+ "form": form,
529
+ "category": next((k for k, v in FILING_FORMS.items() if k != "all" and form in v), "other"),
530
+ "accession": row["accessionNumber"],
531
+ "document_url": f"{base}/{document}" if re.fullmatch(r"[\w.-]+", document) else None,
532
+ "filing_url": f"{base}/{row['accessionNumber']}-index.html",
533
+ "pdf_url": None,
534
+ }
535
+ )
536
+ return {
537
+ "symbol": symbol,
538
+ "cik": cik,
539
+ "market": "US",
540
+ "source": "sec_edgar",
541
+ "start_date": start.isoformat(),
542
+ "end_date": end.isoformat(),
543
+ "total": len(rows),
544
+ "announcements": items,
545
+ "truncated": incomplete or len(rows) > top,
546
+ "body_extracted": False,
547
+ "requested_category": category,
548
+ }
549
+
550
+
285
551
  def insider_trades(args):
286
552
  identity()
287
553
  if not 1 <= args.days <= 365 or not 1 <= args.top <= 20:
@@ -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
@@ -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 = {
@@ -136,11 +136,12 @@ def _save_records(store: Path, records: list):
136
136
  def _append_record(store: Path, record: dict):
137
137
  """Append one complete JSON line; caller holds the store lock."""
138
138
  payload = (json.dumps(record, ensure_ascii=False, default=str, allow_nan=False) + "\n").encode("utf-8")
139
- with store.open("a+b") as stream:
140
- if stream.seek(0, os.SEEK_END):
141
- stream.seek(-1, os.SEEK_END)
142
- if stream.read(1) != b"\n":
143
- stream.write(b"\n")
139
+ previous = store.read_bytes() if store.exists() else b""
140
+ # Publish only complete records; a failed append must not leave a corrupt tail.
141
+ with atomic_write(store, binary=True) as stream:
142
+ stream.write(previous)
143
+ if previous and not previous.endswith(b"\n"):
144
+ stream.write(b"\n")
144
145
  stream.write(payload)
145
146
 
146
147
 
@@ -182,7 +183,7 @@ def cmd_record(args):
182
183
  _load_records(store, strict=True)
183
184
  _append_record(store, record)
184
185
  except (OSError, ValueError) as e:
185
- return {"error": str(e)}
186
+ return {"error": error_message(e)}
186
187
  return record
187
188
 
188
189
 
@@ -309,7 +310,7 @@ def cmd_evaluate(args):
309
310
  with _store_lock(store):
310
311
  records = _load_records(store, strict=True)
311
312
  except (OSError, ValueError) as e:
312
- return {"error": str(e)}
313
+ return {"error": error_message(e)}
313
314
  results = []
314
315
  evaluated = closed = 0
315
316
  changed = False
@@ -399,7 +400,7 @@ def cmd_evaluate(args):
399
400
  entry.update({key: rec.get(key) for key in ("outcome", "return_pct", "exit_date")})
400
401
  closed += 1
401
402
  except (OSError, ValueError) as e:
402
- return {"error": str(e)}
403
+ return {"error": error_message(e)}
403
404
  return {
404
405
  "evaluated": evaluated,
405
406
  "closed": closed,
@@ -417,7 +418,7 @@ def cmd_summary(args):
417
418
  with _store_lock(store):
418
419
  records = _load_records(store, strict=True)
419
420
  except (OSError, ValueError) as e:
420
- return {"error": str(e)}
421
+ return {"error": error_message(e)}
421
422
  filtered = records
422
423
  if args.source:
423
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")
@@ -1136,6 +1250,7 @@ def robustness(p):
1136
1250
 
1137
1251
  COMMANDS = {
1138
1252
  "position_size": position_size,
1253
+ "dcf": dcf,
1139
1254
  "portfolio": portfolio,
1140
1255
  "rebalance": rebalance,
1141
1256
  "peers": peers,