thetabook 2.0.0__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 (83) hide show
  1. thetabook/__init__.py +50 -0
  2. thetabook/cache.py +136 -0
  3. thetabook/cli/__init__.py +99 -0
  4. thetabook/cli/_shared.py +93 -0
  5. thetabook/cli/accounts.py +86 -0
  6. thetabook/cli/adjust.py +88 -0
  7. thetabook/cli/bs.py +80 -0
  8. thetabook/cli/chain.py +70 -0
  9. thetabook/cli/diff.py +57 -0
  10. thetabook/cli/dividends.py +64 -0
  11. thetabook/cli/earnings.py +37 -0
  12. thetabook/cli/evaluate.py +64 -0
  13. thetabook/cli/greeks.py +46 -0
  14. thetabook/cli/ideas.py +137 -0
  15. thetabook/cli/import_csv.py +21 -0
  16. thetabook/cli/init.py +382 -0
  17. thetabook/cli/leg_mark.py +65 -0
  18. thetabook/cli/migrate_home.py +116 -0
  19. thetabook/cli/price.py +39 -0
  20. thetabook/cli/refresh.py +25 -0
  21. thetabook/cli/roll.py +60 -0
  22. thetabook/cli/skills.py +461 -0
  23. thetabook/cli/snapshot.py +87 -0
  24. thetabook/cli/tickers.py +126 -0
  25. thetabook/cli/wiki.py +178 -0
  26. thetabook/config.py +42 -0
  27. thetabook/ideas/__init__.py +0 -0
  28. thetabook/ideas/adjust.py +1219 -0
  29. thetabook/ideas/core.py +487 -0
  30. thetabook/ideas/evaluate_idea.py +996 -0
  31. thetabook/ideas/manage_ideas.py +550 -0
  32. thetabook/ideas/roll_scenarios.py +558 -0
  33. thetabook/leg_parse.py +201 -0
  34. thetabook/log.py +52 -0
  35. thetabook/market/__init__.py +0 -0
  36. thetabook/market/_schwab.py +77 -0
  37. thetabook/market/chains.py +514 -0
  38. thetabook/market/dividends.py +620 -0
  39. thetabook/market/earnings.py +205 -0
  40. thetabook/market/leg_marks.py +205 -0
  41. thetabook/market/prices.py +461 -0
  42. thetabook/market/vol_lookup.py +223 -0
  43. thetabook/models.py +280 -0
  44. thetabook/paths.py +383 -0
  45. thetabook/portfolio/__init__.py +0 -0
  46. thetabook/portfolio/accounts.py +1044 -0
  47. thetabook/portfolio/diff_snapshots.py +374 -0
  48. thetabook/portfolio/get_positions.py +252 -0
  49. thetabook/portfolio/import_csv_snapshot.py +397 -0
  50. thetabook/portfolio/scaffold.py +120 -0
  51. thetabook/pricing/__init__.py +0 -0
  52. thetabook/pricing/bs.py +185 -0
  53. thetabook/pricing/greeks.py +498 -0
  54. thetabook/skills/__init__.py +54 -0
  55. thetabook/skills/install.py +604 -0
  56. thetabook/skills/lint.py +475 -0
  57. thetabook/skills/models.py +170 -0
  58. thetabook/skills/parse.py +73 -0
  59. thetabook/skills/policy.py +80 -0
  60. thetabook/skills/registry.py +343 -0
  61. thetabook/skills/render.py +106 -0
  62. thetabook/templates/README.md +39 -0
  63. thetabook/templates/accounts.toml.example +98 -0
  64. thetabook/templates/config.toml.example +18 -0
  65. thetabook/templates/idea.md +40 -0
  66. thetabook/templates/journal.md +53 -0
  67. thetabook/templates/learnings.md +18 -0
  68. thetabook/templates/skill.md +52 -0
  69. thetabook/templates/skills/setup-thetabook.md +182 -0
  70. thetabook/templates/wiki/index.md +16 -0
  71. thetabook/templates/wiki/log.md +18 -0
  72. thetabook/templates/wiki/overview.md +32 -0
  73. thetabook/templates/wiki/strategy.md +41 -0
  74. thetabook/templates/wiki/underlying.md +34 -0
  75. thetabook/tickers.py +219 -0
  76. thetabook/wiki/__init__.py +15 -0
  77. thetabook/wiki/lint.py +813 -0
  78. thetabook/wiki/render.py +423 -0
  79. thetabook-2.0.0.dist-info/METADATA +15 -0
  80. thetabook-2.0.0.dist-info/RECORD +83 -0
  81. thetabook-2.0.0.dist-info/WHEEL +4 -0
  82. thetabook-2.0.0.dist-info/entry_points.txt +2 -0
  83. thetabook-2.0.0.dist-info/licenses/LICENSE +21 -0
thetabook/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """thetabook — a journal for options traders who think in Greeks.
2
+
3
+ A personal portfolio review and strategy log built around Schwab positions:
4
+ refresh a snapshot, talk through trades with an AI copilot, capture ideas as
5
+ they form, and let the wiki compound what you learn across sessions. No
6
+ orders, no automation — just a sharper loop between
7
+ *position → analysis → decision → reflection*.
8
+
9
+ Public utility constants:
10
+
11
+ REPO_ROOT absolute path to the repo root (where templates/, src/,
12
+ etc. live)
13
+ PERSONAL_DIR user-data root resolved by :func:`paths.thetabook_home`:
14
+ ``$THETABOOK_HOME`` → ``REPO_ROOT/personal`` (dev
15
+ checkout) → main-repo personal/ (worktree) →
16
+ ``~/thetabook`` (pipx/uvx install default).
17
+ TEMPLATES_DIR ``src/thetabook/templates`` — ships inside the wheel
18
+ via importlib.resources semantics.
19
+ SNAPSHOTS_DIR ``PERSONAL_DIR/snapshots``
20
+ IDEAS_DIR ``PERSONAL_DIR/ideas``
21
+
22
+ Modules that read or write user data should pull these from here so the
23
+ src/thetabook/ package layout doesn't push every caller to recompute the
24
+ correct number of ``.parents[]`` levels.
25
+ """
26
+
27
+ from pathlib import Path
28
+
29
+ # This file is at .../src/thetabook/__init__.py — repo root is two parents up.
30
+ REPO_ROOT = Path(__file__).resolve().parent.parent.parent
31
+
32
+ # Resolve PERSONAL_DIR via paths.thetabook_home() so the same code path
33
+ # governs dev checkouts, worktrees, and pipx installs. Late import to
34
+ # avoid a circular dependency (paths.py imports REPO_ROOT + log from
35
+ # this module).
36
+ from thetabook.paths import thetabook_home as _thetabook_home # noqa: E402
37
+
38
+ # Contract: PERSONAL_DIR is resolved ONCE at package import and cached
39
+ # as a real module attribute. Tests that need a different value use
40
+ # ``monkeypatch.setattr(thetabook, "PERSONAL_DIR", ...)``. If ``$THETABOOK_HOME``
41
+ # is flipped mid-process the cached value won't follow — callers that
42
+ # need live resolution should call ``paths.thetabook_home()`` directly.
43
+ # This is deliberate: lazy via PEP-562 ``__getattr__`` would break the
44
+ # existing ``monkeypatch.setattr`` pattern used across the test suite.
45
+ PERSONAL_DIR = _thetabook_home()
46
+ TEMPLATES_DIR = Path(__file__).resolve().parent / "templates"
47
+ SNAPSHOTS_DIR = PERSONAL_DIR / "snapshots"
48
+ IDEAS_DIR = PERSONAL_DIR / "ideas"
49
+
50
+ __all__ = ["IDEAS_DIR", "PERSONAL_DIR", "REPO_ROOT", "SNAPSHOTS_DIR", "TEMPLATES_DIR"]
thetabook/cache.py ADDED
@@ -0,0 +1,136 @@
1
+ """Generic on-disk JSON cache with TTL.
2
+
3
+ Lifted out of ``thetabook.market.earnings`` once a second consumer
4
+ (``thetabook.market.dividends``, M18) materialized. Both backing files live
5
+ under ``personal/snapshots/`` and share the same shape:
6
+
7
+ {
8
+ "<key>": {
9
+ "value": <json-serializable result, including null>,
10
+ "fetched_at": "<ISO-8601 UTC timestamp>",
11
+ },
12
+ ...
13
+ }
14
+
15
+ Public API
16
+ ----------
17
+ cached_fetch(key, fetcher, *, ttl, path) -> Any
18
+ Read the cache at *path*; if *key* is present and within *ttl*, return
19
+ its value. Otherwise call ``fetcher()``, persist the result, and return
20
+ it. Negative results (``None``) are cached too — yfinance lookups for
21
+ ETFs/indices legitimately have no answer, and we don't want to retry
22
+ them every invocation.
23
+
24
+ read_cache(path) -> dict
25
+ write_cache(path, data) -> None
26
+ entry_fresh(entry, ttl) -> bool
27
+ Lower-level primitives for callers that need finer control (e.g. when
28
+ the on-disk shape stores extra metadata alongside ``value`` /
29
+ ``fetched_at``).
30
+
31
+ clear_cache(path) -> None
32
+ Remove the cache file. Mostly for tests.
33
+
34
+ Errors
35
+ ------
36
+ ``read_cache`` warns on JSONDecodeError (corrupt cache) and OSError
37
+ (permission / I/O), returning ``{}`` so the caller can proceed with a
38
+ fresh fetch. ``write_cache`` warns on OSError. We never raise — a broken
39
+ cache should degrade to "no cache", not crash the analyzer.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import contextlib
45
+ import json
46
+ from datetime import UTC, datetime, timedelta
47
+ from typing import TYPE_CHECKING, Any
48
+
49
+ from thetabook import log
50
+
51
+ if TYPE_CHECKING:
52
+ from collections.abc import Callable
53
+ from pathlib import Path
54
+
55
+
56
+ def read_cache(path: Path) -> dict:
57
+ """Load *path* as JSON, returning ``{}`` on missing/corrupt/unreadable."""
58
+ if not path.exists():
59
+ return {}
60
+ try:
61
+ return json.loads(path.read_text())
62
+ except json.JSONDecodeError as exc:
63
+ log.warn(f"cache at {path} is corrupt ({exc}); ignoring")
64
+ return {}
65
+ except OSError as exc:
66
+ log.warn(f"could not read cache {path}: {exc}")
67
+ return {}
68
+
69
+
70
+ def write_cache(path: Path, data: dict) -> None:
71
+ """Persist *data* to *path*. Warns on OSError; never raises.
72
+
73
+ Callers are responsible for stringifying non-JSON-native values (dates,
74
+ Decimals, etc.) before passing them in. We deliberately don't pass
75
+ ``default=str`` to ``json.dumps`` — silent stringification masks the
76
+ case where a caller forgot to convert a ``date`` object, which then
77
+ round-trips back as a string the caller may not expect.
78
+ """
79
+ try:
80
+ path.parent.mkdir(parents=True, exist_ok=True)
81
+ path.write_text(json.dumps(data, indent=2, sort_keys=True))
82
+ except OSError as exc:
83
+ log.warn(f"could not write cache to {path}: {exc}")
84
+
85
+
86
+ def entry_fresh(entry: dict, ttl: timedelta) -> bool:
87
+ """True iff *entry*'s ``fetched_at`` is within *ttl* of now."""
88
+ fetched = entry.get("fetched_at")
89
+ if not fetched:
90
+ return False
91
+ try:
92
+ fetched_dt = datetime.fromisoformat(fetched)
93
+ except ValueError:
94
+ return False
95
+ if fetched_dt.tzinfo is None:
96
+ fetched_dt = fetched_dt.replace(tzinfo=UTC)
97
+ return datetime.now(UTC) - fetched_dt < ttl
98
+
99
+
100
+ def cached_fetch(
101
+ key: str,
102
+ fetcher: Callable[[], Any],
103
+ *,
104
+ ttl: timedelta,
105
+ path: Path,
106
+ force_refresh: bool = False,
107
+ ) -> Any:
108
+ """Read-through cache around *fetcher*.
109
+
110
+ Cache hit (key present and fresh) returns the stored ``value`` without
111
+ invoking *fetcher*. Cache miss or stale entry calls *fetcher*, stores
112
+ the result (including ``None``), and returns it.
113
+
114
+ Pass ``force_refresh=True`` to skip the freshness check — *fetcher*
115
+ is always called and the result re-persisted. Useful for ``--no-cache``
116
+ CLI paths that still want to update the cache rather than bypass it.
117
+ """
118
+ cache = read_cache(path)
119
+ entry = cache.get(key)
120
+ if not force_refresh and entry is not None and entry_fresh(entry, ttl):
121
+ return entry.get("value")
122
+
123
+ value = fetcher()
124
+ cache[key] = {
125
+ "value": value,
126
+ "fetched_at": datetime.now(UTC).isoformat(),
127
+ }
128
+ write_cache(path, cache)
129
+ return value
130
+
131
+
132
+ def clear_cache(path: Path) -> None:
133
+ """Remove *path* if it exists. For tests."""
134
+ if path.exists():
135
+ with contextlib.suppress(OSError):
136
+ path.unlink()
@@ -0,0 +1,99 @@
1
+ """thetabook command-line interface.
2
+
3
+ Single typer-based CLI replacing the previous one-script-per-tool layout.
4
+ All subcommands live under ``thetabook <subcommand>`` so .claude/commands/
5
+ slash-command shims become one-line pass-throughs.
6
+
7
+ Tools (each maps to a thin typer wrapper that delegates to the underlying
8
+ ``thetabook.<subpkg>.<module>`` logic):
9
+
10
+ refresh — pull positions from Schwab → personal/snapshots/
11
+ snapshot — print latest snapshot path + freshness summary
12
+ evaluate — evaluate a trade idea (P&L, PoP, Greeks, live re-mark)
13
+ adjust — what-if adjustment modeling (roll, add, close, assign)
14
+ greeks — portfolio Greeks aggregated by underlying
15
+ roll — roll-decision scenario grid
16
+ diff — compare two snapshots
17
+ price — fetch current stock price(s)
18
+ chain — fetch option chain
19
+ earnings — next earnings date(s) via yfinance cache
20
+ dividends — yield + next ex-div date(s) via yfinance cache
21
+ leg-mark — current bid/ask/mid/last for a leg
22
+ import-csv — convert Schwab/Fidelity CSV exports to snapshot JSON
23
+ init — install setup skill; --non-interactive does the install
24
+ migrate-home — one-time move of repo-root .env + token under personal/
25
+
26
+ accounts — sub-app: show, totals, check-idea, check-portfolio, init
27
+ ideas — sub-app: new, list, show, set-status
28
+ wiki — sub-app: lint (more in later slices)
29
+
30
+ Entry point declared in pyproject.toml ([project.scripts]); after
31
+ ``uv sync``, the CLI runs as ``thetabook ...``.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import typer
37
+
38
+ from thetabook.cli import accounts as _accounts
39
+ from thetabook.cli import adjust as _adjust
40
+ from thetabook.cli import bs as _bs
41
+ from thetabook.cli import chain as _chain
42
+ from thetabook.cli import diff as _diff
43
+ from thetabook.cli import dividends as _dividends
44
+ from thetabook.cli import earnings as _earnings
45
+ from thetabook.cli import evaluate as _evaluate
46
+ from thetabook.cli import greeks as _greeks
47
+ from thetabook.cli import ideas as _ideas
48
+ from thetabook.cli import import_csv as _import_csv
49
+ from thetabook.cli import init as _init
50
+ from thetabook.cli import leg_mark as _leg_mark
51
+ from thetabook.cli import migrate_home as _migrate_home
52
+ from thetabook.cli import price as _price
53
+ from thetabook.cli import refresh as _refresh
54
+ from thetabook.cli import roll as _roll
55
+ from thetabook.cli import skills as _skills
56
+ from thetabook.cli import snapshot as _snapshot
57
+ from thetabook.cli import tickers as _tickers
58
+ from thetabook.cli import wiki as _wiki
59
+
60
+ app = typer.Typer(
61
+ name="thetabook",
62
+ help="A journal for options traders who think in Greeks.",
63
+ no_args_is_help=True,
64
+ rich_markup_mode="rich",
65
+ )
66
+
67
+ # Top-level commands
68
+ app.command("refresh")(_refresh.refresh)
69
+ app.command("snapshot")(_snapshot.snapshot)
70
+ app.command("evaluate")(_evaluate.evaluate)
71
+ app.command("adjust")(_adjust.adjust)
72
+ app.command("greeks")(_greeks.greeks)
73
+ app.command("roll")(_roll.roll)
74
+ app.command("diff")(_diff.diff)
75
+ app.command("price")(_price.price)
76
+ app.command("chain")(_chain.chain)
77
+ app.command("earnings")(_earnings.earnings)
78
+ app.command("dividends")(_dividends.dividends)
79
+ app.command("leg-mark")(_leg_mark.leg_mark)
80
+ app.command("bs")(_bs.bs)
81
+ app.command("import-csv")(_import_csv.import_csv)
82
+ app.command("init")(_init.init)
83
+ app.command("migrate-home")(_migrate_home.migrate_home)
84
+
85
+ # Sub-apps
86
+ app.add_typer(_accounts.app, name="accounts", help="Per-account risk rules and tax notes.")
87
+ app.add_typer(_ideas.app, name="ideas", help="Trade-idea lifecycle (new / list / show / set-status).")
88
+ app.add_typer(_skills.app, name="skills", help="Author + maintainer tools for skill files.")
89
+ app.add_typer(_tickers.app, name="tickers", help="Manage the ticker alias dictionary.")
90
+ app.add_typer(_wiki.app, name="wiki", help="Wiki health checks and renderers.")
91
+
92
+
93
+ def main() -> None:
94
+ """Console-script entry point declared in pyproject.toml."""
95
+ app()
96
+
97
+
98
+ if __name__ == "__main__":
99
+ main()
@@ -0,0 +1,93 @@
1
+ """Shared typer Option types for the thetabook CLI.
2
+
3
+ A handful of flags appear across many commands (--prices, --marks,
4
+ --mark-mode, --no-fetch). Centralizing the typer.Option(...) declarations
5
+ here keeps the help text consistent and avoids drift between subcommands.
6
+
7
+ Usage in a subcommand:
8
+
9
+ from typing import Annotated
10
+ from thetabook.cli._shared import PricesOpt, VolOpt, MarksOpt
11
+
12
+ @app.command()
13
+ def evaluate(
14
+ id: int,
15
+ prices: PricesOpt = None,
16
+ vol: VolOpt = None,
17
+ marks: MarksOpt = None,
18
+ ):
19
+ ...
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Annotated
25
+
26
+ import typer
27
+
28
+ # --- price overrides ---------------------------------------------------------
29
+ PricesOpt = Annotated[
30
+ list[str] | None,
31
+ typer.Option(
32
+ "--prices",
33
+ help="Manual stock price overrides, e.g. --prices CRWV=102 SPY=520",
34
+ ),
35
+ ]
36
+
37
+ # --- vol / rate / div_yield --------------------------------------------------
38
+ VolOpt = Annotated[
39
+ float | None,
40
+ typer.Option(
41
+ "--vol",
42
+ help="Flat volatility override; otherwise per-leg IV from chain, flat 0.25 fallback",
43
+ ),
44
+ ]
45
+ RateOpt = Annotated[
46
+ float | None,
47
+ typer.Option("--rate", help="Risk-free rate (default: 0.045)"),
48
+ ]
49
+ DivYieldOpt = Annotated[
50
+ float | None,
51
+ typer.Option("--div-yield", help="Dividend yield (default: 0.0)"),
52
+ ]
53
+
54
+ # --- marks (live vs frozen) --------------------------------------------------
55
+ MarksOpt = Annotated[
56
+ str | None,
57
+ typer.Option(
58
+ "--marks",
59
+ help="Re-mark legs from the live chain ('live') or use file premiums "
60
+ "('frozen'). Default: live for open ideas, frozen for closed.",
61
+ ),
62
+ ]
63
+ MarkModeOpt = Annotated[
64
+ str | None,
65
+ typer.Option(
66
+ "--mark-mode",
67
+ help="How to pick a current mark from bid/ask/mid. "
68
+ "conservative = long→ask, short→bid. mid = (bid+ask)/2.",
69
+ ),
70
+ ]
71
+ GreeksSourceOpt = Annotated[
72
+ str | None,
73
+ typer.Option(
74
+ "--greeks-source",
75
+ help="Where to source per-leg Greeks. 'chain' (default) prefers "
76
+ "broker-supplied Greeks (Schwab) and falls back to BS recompute. "
77
+ "'bs' always recomputes via Black-Scholes — useful for what-if "
78
+ "vol-shock analysis with --vol.",
79
+ ),
80
+ ]
81
+
82
+ # --- behavior toggles --------------------------------------------------------
83
+ NoFetchOpt = Annotated[
84
+ bool,
85
+ typer.Option(
86
+ "--no-fetch",
87
+ help="Skip auto-fetching missing prices (use snapshot only).",
88
+ ),
89
+ ]
90
+ StockPriceOpt = Annotated[
91
+ float | None,
92
+ typer.Option("--stock-price", help="Current stock price (overrides snapshot)"),
93
+ ]
@@ -0,0 +1,86 @@
1
+ """thetabook accounts — per-account risk rules and tax notes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from typing import Annotated
7
+
8
+ import typer
9
+
10
+ app = typer.Typer(help="Per-account risk rules and tax notes.", no_args_is_help=True)
11
+
12
+
13
+ @app.command("show")
14
+ def show() -> None:
15
+ """Print configured accounts and their rules."""
16
+ from thetabook.portfolio.accounts import cmd_show
17
+
18
+ cmd_show(argparse.Namespace())
19
+
20
+
21
+ @app.command("totals")
22
+ def totals(
23
+ date: Annotated[
24
+ str | None,
25
+ typer.Argument(help="Snapshot date (YYYY-MM-DD); default: latest."),
26
+ ] = None,
27
+ ) -> None:
28
+ """Print per-account NLV / cash table from the latest snapshot."""
29
+ from thetabook.portfolio.accounts import cmd_totals
30
+
31
+ cmd_totals(argparse.Namespace(date=date))
32
+
33
+
34
+ @app.command("check-idea")
35
+ def check_idea(
36
+ idea_id: Annotated[int, typer.Argument(help="Idea number to check.")],
37
+ ) -> None:
38
+ """Check a trade idea against its account's rules + tax notes."""
39
+ from thetabook.portfolio.accounts import cmd_check_idea
40
+
41
+ cmd_check_idea(argparse.Namespace(id=idea_id))
42
+
43
+
44
+ @app.command("check-portfolio")
45
+ def check_portfolio(
46
+ date: Annotated[
47
+ str | None,
48
+ typer.Argument(help="Snapshot date (YYYY-MM-DD); default: latest."),
49
+ ] = None,
50
+ show_all: Annotated[
51
+ bool,
52
+ typer.Option(
53
+ "--show-all",
54
+ help=(
55
+ "Print the full per-account underlying ranking by % of NLV, "
56
+ "not just rule violations. Rows over max_position_pct are "
57
+ "tagged ⚠ inline so the ranking subsumes the violation listing."
58
+ ),
59
+ ),
60
+ ] = False,
61
+ top: Annotated[
62
+ int | None,
63
+ typer.Option(
64
+ "--top",
65
+ help="With --show-all, limit each account to the top N underlyings.",
66
+ ),
67
+ ] = None,
68
+ ) -> None:
69
+ """Check every account in a snapshot against its rules."""
70
+ from thetabook.portfolio.accounts import cmd_check_portfolio
71
+
72
+ cmd_check_portfolio(argparse.Namespace(date=date, show_all=show_all, top=top))
73
+
74
+
75
+ @app.command("init")
76
+ def init() -> None:
77
+ """Print guidance for setting up personal/accounts.toml."""
78
+ from thetabook.portfolio.accounts import cmd_init
79
+
80
+ cmd_init(argparse.Namespace())
81
+
82
+
83
+ @app.command("list")
84
+ def list_() -> None:
85
+ """Alias for ``show``."""
86
+ show()
@@ -0,0 +1,88 @@
1
+ """thetabook adjust — what-if adjustment modeling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from typing import Annotated
7
+
8
+ import typer
9
+
10
+ from thetabook.cli._shared import (
11
+ DivYieldOpt,
12
+ GreeksSourceOpt,
13
+ MarkModeOpt,
14
+ RateOpt,
15
+ StockPriceOpt,
16
+ VolOpt,
17
+ )
18
+
19
+
20
+ def adjust(
21
+ underlying: Annotated[str, typer.Argument(help="Ticker symbol (e.g. AAPL).")],
22
+ close: Annotated[
23
+ str | None,
24
+ typer.Option("--close", help='Close a leg: "YYYY-MM-DD STRIKE C/P"'),
25
+ ] = None,
26
+ open_leg: Annotated[
27
+ str | None,
28
+ typer.Option(
29
+ "--open",
30
+ help='Open a new leg: "YYYY-MM-DD STRIKE C/P [qty=N] [premium=X.XX]"',
31
+ ),
32
+ ] = None,
33
+ add: Annotated[
34
+ str | None,
35
+ typer.Option(
36
+ "--add",
37
+ help='Add a leg (no existing leg required): "YYYY-MM-DD STRIKE C/P qty=N [premium=X.XX]"',
38
+ ),
39
+ ] = None,
40
+ assign: Annotated[
41
+ str | None,
42
+ typer.Option(
43
+ "--assign",
44
+ help='Model assignment of a short put: "YYYY-MM-DD STRIKE P"',
45
+ ),
46
+ ] = None,
47
+ stock_price: StockPriceOpt = None,
48
+ vol: VolOpt = None,
49
+ rate: RateOpt = None,
50
+ div_yield: DivYieldOpt = None,
51
+ marks: Annotated[
52
+ str,
53
+ typer.Option(
54
+ "--marks",
55
+ help="Re-mark closing legs and new-leg premiums from the live chain "
56
+ "('live', default) or use snapshot market_price + BS fallback ('frozen'). "
57
+ "User-provided premium= and --stock-price still win.",
58
+ ),
59
+ ] = "live",
60
+ mark_mode: MarkModeOpt = None,
61
+ greeks_source: GreeksSourceOpt = None,
62
+ save: Annotated[
63
+ bool,
64
+ typer.Option("--save", help="Save the after-scenario as a new idea file."),
65
+ ] = False,
66
+ ) -> None:
67
+ """Model an adjustment to existing positions: roll, add, close, or assign."""
68
+ from thetabook.ideas.adjust import run
69
+
70
+ if greeks_source is not None and greeks_source not in ("chain", "bs"):
71
+ raise typer.BadParameter("--greeks-source must be 'chain' or 'bs'.")
72
+
73
+ args = argparse.Namespace(
74
+ underlying=underlying,
75
+ close=close,
76
+ open_leg=open_leg,
77
+ add=add,
78
+ assign=assign,
79
+ stock_price=stock_price,
80
+ vol=vol,
81
+ rate=rate,
82
+ div_yield=div_yield,
83
+ marks=marks,
84
+ mark_mode=mark_mode,
85
+ greeks_source=greeks_source,
86
+ save=save,
87
+ )
88
+ run(args)
thetabook/cli/bs.py ADDED
@@ -0,0 +1,80 @@
1
+ """thetabook bs — ad-hoc Black-Scholes pricing and Greeks for a single leg."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated
6
+
7
+ import typer
8
+
9
+ from thetabook.ideas.core import fmt_dollar, fmt_pct
10
+ from thetabook.pricing import bs as _bs
11
+
12
+
13
+ def bs(
14
+ spot: Annotated[float, typer.Argument(help="Underlying spot price (S).")],
15
+ strike: Annotated[float, typer.Argument(help="Strike price (K).")],
16
+ days: Annotated[
17
+ float,
18
+ typer.Argument(help="Calendar days to expiration."),
19
+ ],
20
+ iv: Annotated[
21
+ float,
22
+ typer.Argument(help="Implied volatility (e.g. 0.25 for 25%)."),
23
+ ],
24
+ option_type: Annotated[
25
+ str,
26
+ typer.Argument(
27
+ help="Option type: C/CALL or P/PUT (case-insensitive).",
28
+ metavar="C|P",
29
+ ),
30
+ ],
31
+ rate: Annotated[
32
+ float,
33
+ typer.Option("--rate", help="Risk-free rate (default 0.045)."),
34
+ ] = 0.045,
35
+ div_yield: Annotated[
36
+ float,
37
+ typer.Option("--yield", "--div-yield", help="Continuous dividend yield (default 0.0)."),
38
+ ] = 0.0,
39
+ ) -> None:
40
+ """Print BS price + per-share Greeks for a hypothetical leg.
41
+
42
+ Closes the gap that today forces dropping into ``uv run python -c
43
+ "from thetabook.pricing.bs import delta..."`` for quick "what's the
44
+ delta on a 5-strike-deeper call?" questions.
45
+ """
46
+ ot_in = option_type.strip().lower()
47
+ if ot_in in ("c", "call"):
48
+ ot = "call"
49
+ elif ot_in in ("p", "put"):
50
+ ot = "put"
51
+ else:
52
+ raise typer.BadParameter("option_type must be C, CALL, P, or PUT")
53
+
54
+ if days <= 0:
55
+ raise typer.BadParameter("days must be positive (use a non-expired contract).")
56
+ if iv <= 0:
57
+ raise typer.BadParameter("iv must be positive.")
58
+ if spot <= 0 or strike <= 0:
59
+ raise typer.BadParameter("spot and strike must be positive.")
60
+
61
+ T = days / 365.0
62
+ price = _bs.option_price(spot, strike, T, rate, iv, div_yield, ot)
63
+ delta_v = _bs.delta(spot, strike, T, rate, iv, div_yield, ot)
64
+ gamma_v = _bs.gamma(spot, strike, T, rate, iv, div_yield, ot)
65
+ theta_v = _bs.theta(spot, strike, T, rate, iv, div_yield, ot) / 365.0
66
+ vega_v = _bs.vega(spot, strike, T, rate, iv, div_yield, ot) / 100.0
67
+ rho_v = _bs.rho(spot, strike, T, rate, iv, div_yield, ot) / 100.0
68
+
69
+ cp = "C" if ot == "call" else "P"
70
+ print(
71
+ f"{cp} leg: S={fmt_dollar(spot)} K={fmt_dollar(strike)} "
72
+ f"T={days:g}d ({T:.4f}y) σ={fmt_pct(iv)} r={fmt_pct(rate)} "
73
+ f"q={fmt_pct(div_yield)}"
74
+ )
75
+ print(f" Price: {fmt_dollar(price)}")
76
+ print(f" Delta: {delta_v:+.4f}")
77
+ print(f" Gamma: {gamma_v:+.4f}")
78
+ print(f" Theta: {fmt_dollar(theta_v)}/day")
79
+ print(f" Vega: {fmt_dollar(vega_v)}/1%vol")
80
+ print(f" Rho: {fmt_dollar(rho_v)}/1%rate")