thetabook 2.2.0__tar.gz → 2.2.1__tar.gz

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 (113) hide show
  1. {thetabook-2.2.0 → thetabook-2.2.1}/CHANGELOG.md +69 -1
  2. {thetabook-2.2.0 → thetabook-2.2.1}/CLAUDE.md +3 -1
  3. {thetabook-2.2.0 → thetabook-2.2.1}/PKG-INFO +1 -1
  4. {thetabook-2.2.0 → thetabook-2.2.1}/README.md +5 -0
  5. {thetabook-2.2.0 → thetabook-2.2.1}/ROADMAP.md +44 -14
  6. {thetabook-2.2.0 → thetabook-2.2.1}/pyproject.toml +1 -1
  7. thetabook-2.2.1/src/thetabook/analysis/em.py +118 -0
  8. thetabook-2.2.1/src/thetabook/analysis/vrp.py +145 -0
  9. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/__init__.py +9 -0
  10. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/_shared.py +21 -2
  11. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/bars.py +24 -17
  12. thetabook-2.2.1/src/thetabook/cli/em.py +149 -0
  13. thetabook-2.2.1/src/thetabook/cli/positions.py +79 -0
  14. thetabook-2.2.1/src/thetabook/cli/vrp.py +80 -0
  15. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/bars.py +242 -47
  16. thetabook-2.2.1/src/thetabook/portfolio/options_book.py +431 -0
  17. {thetabook-2.2.0 → thetabook-2.2.1}/uv.lock +1 -1
  18. {thetabook-2.2.0 → thetabook-2.2.1}/.env.example +0 -0
  19. {thetabook-2.2.0 → thetabook-2.2.1}/.github/workflows/ci.yml +0 -0
  20. {thetabook-2.2.0 → thetabook-2.2.1}/.github/workflows/publish.yml +0 -0
  21. {thetabook-2.2.0 → thetabook-2.2.1}/.gitignore +0 -0
  22. {thetabook-2.2.0 → thetabook-2.2.1}/.python-version +0 -0
  23. {thetabook-2.2.0 → thetabook-2.2.1}/CONTRIBUTING.md +0 -0
  24. {thetabook-2.2.0 → thetabook-2.2.1}/LICENSE +0 -0
  25. {thetabook-2.2.0 → thetabook-2.2.1}/SECURITY.md +0 -0
  26. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/__init__.py +0 -0
  27. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/analysis/__init__.py +0 -0
  28. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/analysis/hv.py +0 -0
  29. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/analysis/scenarios.py +0 -0
  30. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/analysis/ta.py +0 -0
  31. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cache.py +0 -0
  32. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/accounts.py +0 -0
  33. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/adjust.py +0 -0
  34. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/bs.py +0 -0
  35. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/chain.py +0 -0
  36. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/diff.py +0 -0
  37. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/dividends.py +0 -0
  38. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/earnings.py +0 -0
  39. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/evaluate.py +0 -0
  40. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/greeks.py +0 -0
  41. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/hv.py +0 -0
  42. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/ideas.py +0 -0
  43. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/import_csv.py +0 -0
  44. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/init.py +0 -0
  45. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/leg_mark.py +0 -0
  46. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/migrate_home.py +0 -0
  47. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/price.py +0 -0
  48. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/refresh.py +0 -0
  49. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/roll.py +0 -0
  50. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/scenarios.py +0 -0
  51. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/skills.py +0 -0
  52. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/snapshot.py +0 -0
  53. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/ta.py +0 -0
  54. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/tickers.py +0 -0
  55. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/cli/wiki.py +0 -0
  56. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/config.py +0 -0
  57. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/ideas/__init__.py +0 -0
  58. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/ideas/adjust.py +0 -0
  59. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/ideas/core.py +0 -0
  60. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/ideas/evaluate_idea.py +0 -0
  61. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/ideas/manage_ideas.py +0 -0
  62. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/ideas/roll_scenarios.py +0 -0
  63. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/leg_parse.py +0 -0
  64. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/log.py +0 -0
  65. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/__init__.py +0 -0
  66. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/_schwab.py +0 -0
  67. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/chains.py +0 -0
  68. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/dividends.py +0 -0
  69. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/earnings.py +0 -0
  70. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/leg_marks.py +0 -0
  71. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/prices.py +0 -0
  72. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/market/vol_lookup.py +0 -0
  73. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/models.py +0 -0
  74. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/paths.py +0 -0
  75. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/__init__.py +0 -0
  76. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/accounts.py +0 -0
  77. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/csv_parsers/__init__.py +0 -0
  78. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/csv_parsers/_base.py +0 -0
  79. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/csv_parsers/empower.py +0 -0
  80. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/csv_parsers/fidelity.py +0 -0
  81. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/csv_parsers/schwab.py +0 -0
  82. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/diff_snapshots.py +0 -0
  83. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/get_positions.py +0 -0
  84. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/import_csv_snapshot.py +0 -0
  85. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/portfolio/scaffold.py +0 -0
  86. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/pricing/__init__.py +0 -0
  87. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/pricing/bs.py +0 -0
  88. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/pricing/greeks.py +0 -0
  89. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/__init__.py +0 -0
  90. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/install.py +0 -0
  91. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/lint.py +0 -0
  92. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/models.py +0 -0
  93. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/parse.py +0 -0
  94. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/policy.py +0 -0
  95. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/registry.py +0 -0
  96. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/skills/render.py +0 -0
  97. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/README.md +0 -0
  98. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/accounts.toml.example +0 -0
  99. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/config.toml.example +0 -0
  100. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/idea.md +0 -0
  101. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/journal.md +0 -0
  102. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/learnings.md +0 -0
  103. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/skill.md +0 -0
  104. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/skills/setup-thetabook.md +0 -0
  105. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/wiki/index.md +0 -0
  106. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/wiki/log.md +0 -0
  107. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/wiki/overview.md +0 -0
  108. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/wiki/strategy.md +0 -0
  109. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/templates/wiki/underlying.md +0 -0
  110. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/tickers.py +0 -0
  111. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/wiki/__init__.py +0 -0
  112. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/wiki/lint.py +0 -0
  113. {thetabook-2.2.0 → thetabook-2.2.1}/src/thetabook/wiki/render.py +0 -0
@@ -3,7 +3,75 @@
3
3
  All notable changes to this project are recorded here. Format loosely follows
4
4
  [Keep a Changelog](https://keepachangelog.com). Dates are ISO 8601.
5
5
 
6
- ## [Unreleased]
6
+ ## [2.2.1] — 2026-06-05
7
+
8
+ Two pending medium-priority roadmap items (M24 expected-move / VRP, M20
9
+ effective options book) close out, and the historical-bars backbone's rolling
10
+ tail is re-routed through the live price cascade so `hv` / `ta` / `scenarios`
11
+ stay numerically consistent with `price` / `chain` / `greeks`.
12
+ **1696 tests pass, ruff + mypy clean.**
13
+
14
+ ### Added
15
+
16
+ - **`thetabook positions` — effective options book** (M20). Renders the
17
+ options-only table /portfolio reviews previously reconstructed by hand —
18
+ per-leg live mark (chain cascade), underlying spot, **cushion**, and
19
+ calendar DTE, grouped by account. Cushion is the short-seller OTM buffer,
20
+ signed so positive = out-of-the-money (safe) and negative = in-the-money
21
+ (danger) for both legs (`call: (K−S)/S`, `put: (S−K)/S`). Defaults to the
22
+ options view; `--equity` lists share-like holdings, `--all` shows both.
23
+ `--no-fetch` uses snapshot marks only; `--prices TICKER=X` overrides spot;
24
+ `--mark-mode` picks conservative vs mid. Spot resolution reuses the live
25
+ price cascade — Schwab (real-time) → Massive (previous-day close) →
26
+ yfinance (~15-min delayed) — under the same stale-snapshot policy as
27
+ `greeks`: a stale snapshot refreshes every underlying, a fresh one only
28
+ fills the gaps (option-only underlyings, which carry no snapshot share
29
+ price, always fetch). Per-leg marks come from the chain cascade and fall
30
+ back to the snapshot's stored mark when a strike has no live quote. Non-live
31
+ spot provenance (Massive previous-close, yfinance delayed) is flagged in a
32
+ footnote, the same convention `greeks` uses. New
33
+ `portfolio/options_book.py` stitches the snapshot loader + spot fetch from
34
+ `pricing.greeks`, the per-leg re-mark from `market.leg_marks`, and account
35
+ labels from `portfolio.accounts`; pure extract/cushion/render functions
36
+ keep the math hermetically testable.
37
+
38
+ - **`thetabook em` — expected move** ([#64](https://github.com/subsriram/thetabook/pull/64)).
39
+ Translates a vol figure into the ±1σ / ±2σ dollar range an option is pricing
40
+ by expiry: `spot · σ · sqrt(DTE/365)` (calendar-day horizon, the straddle
41
+ convention — deliberately *not* `hv`'s `sqrt(252)` annualization). Sigma
42
+ defaults to HV20, with `--iv` to override or `--source iv` to pull
43
+ front-month ATM IV off the chain (expiry auto-picked nearest the target DTE).
44
+ Pure math lives in `analysis/em.py`.
45
+ - **`thetabook vrp` — vol-risk-premium** ([#64](https://github.com/subsriram/thetabook/pull/64)).
46
+ Ratios front-month ATM implied vol against realized HV to answer "is implied
47
+ richer than realized right now?" — a *point-in-time* IV-vs-HV read, **not** a
48
+ historical IV-rank (no source ships historical option IV). Needs a
49
+ Greeks-bearing source (Schwab/Massive) for IV; exits non-zero on a
50
+ yfinance-only fallback rather than printing a bogus ratio. The ATM picker
51
+ (`analysis/vrp.atm_iv`) skips strikes with no usable IV and averages the
52
+ call+put IV at the nearest populated strike, and is shared with `em --source iv`.
53
+
54
+ ### Changed
55
+
56
+ - **Bars tail-fill now rides the live price cascade** ([#66](https://github.com/subsriram/thetabook/pull/66), closes #65).
57
+ The historical-bars backbone (`market/bars.py`) stitched defeatbeta deep
58
+ history with a **yfinance-only** rolling tail. yfinance is ~15-min delayed
59
+ and created a source-disagreement seam between `price` (Schwab → Massive →
60
+ yfinance) and `hv` / `ta` / `scenarios` (yfinance-only tail). The tail now
61
+ flows through the **same cascade as the live price pipeline — Schwab →
62
+ Massive → yfinance** (first source with tail data wins); defeatbeta stays the
63
+ deep-history source, only the tail changed. New `_fetch_schwab`
64
+ (`get_price_history_every_day`), `_fetch_massive` (Polygon `get_aggs`
65
+ date-range daily aggregates — not the single-bar `get_previous_close_agg`),
66
+ a shared `_normalize_epoch_ohlcv` (volume kept int64 so the stitched frame
67
+ doesn't promote to float on concat), and `_fetch_tail` returning
68
+ `(frame, source)`. `bars compare TICKER` now diffs defeatbeta vs the live
69
+ cascade and surfaces which source served the tail (`_yf` columns renamed
70
+ `_live`, plus a `source` column). Validated live: AAPL (non-payer) and O
71
+ (dividend payer) both served by Schwab with 0 rows flagged, and again with
72
+ Schwab disabled so Massive serves the tail — 0.000% close drift across O's
73
+ ex-dividend days, confirming the split-only (`adjusted=True`) close matches
74
+ defeatbeta with no off-by-one in the epoch-ms normalization.
7
75
 
8
76
  ## [2.2.0] — 2026-06-04
9
77
 
@@ -23,7 +23,8 @@ The name nods to **theta**, the daily decay that quietly drives most options P&L
23
23
  - **Use the `thetabook` CLI as much as possible** to fetch data, answer questions, and run analysis. The CLI loads `.env`, applies the source cascade (Schwab → Massive → yfinance), and uses consistent IV/rate/yield conventions. Examples: `thetabook chain ... --greeks`, `thetabook evaluate <id>`, `thetabook greeks`, `thetabook price`, `thetabook dividends -v`. Don't reach for `uv run python -c "from thetabook... import"` when a CLI command exists for the same job.
24
24
  - **When the CLI doesn't expose what you need, drop into Python** — but always call `thetabook.paths.load_env()` first. Without it, the Schwab client returns `None` and the data cascade silently falls through to a worse source (yfinance), producing answers that disagree with the CLI's. If the gap is reusable, file an issue to surface it via a flag or new subcommand rather than letting the Python escape hatch normalize.
25
25
  - **For technical analysis, use `thetabook hv` / `ta` / `scenarios` / `bars`.** `thetabook ta TICKER` gives RSI/MACD/Bollinger with interpretive labels; `thetabook hv TICKER` gives realized vol + HV-rank/percentile (the IV-rank substitute — there's no historical option IV); `thetabook scenarios match TICKER` answers "has this regime happened before?" with forward-return outcomes (run both `--mode trajectory` and `--mode state`; when they disagree, present both rather than averaging). These read daily *closes* from a historical-bars backbone, not the live price cascade — see [docs/cli.md](docs/cli.md) for the full flag set and [docs/behaviors.md](docs/behaviors.md) for the stitch.
26
- - **Know how fresh each source is before quoting a number.** The historical bars under `hv`/`ta`/`scenarios` are a stitch: defeatbeta (weekly HuggingFace dataset) covers history up to the **most recent Friday's close**, and yfinance fills the rolling tail through today — so the latest *complete* indicator bar is usually last Friday, and intraday moves aren't reflected until the day closes. In the live price cascade, **Massive returns the previous business day's close, not an intraday quote** (Polygon `get_previous_close_agg`); only Schwab is real-time and yfinance is ~15-min delayed. When a figure comes from Massive or from the defeatbeta history, say so — don't present it as the current price.
26
+ - **For vol-to-decision questions, use `thetabook em` / `vrp`.** `thetabook em TICKER --dte N` translates a vol figure into the ±1σ / ±2σ dollar range an option is pricing by expiry (`spot · σ · sqrt(DTE/365)`, calendar-day horizon — deliberately *not* `hv`'s `sqrt(252)`); sigma defaults to HV20, with `--iv` to override or `--source iv` to pull front-month ATM IV from the chain. `thetabook vrp TICKER` ratios that ATM IV against HV to answer "is implied richer than realized right now?" — a *point-in-time* IV-vs-HV read, **not** a historical IV-rank. Unlike the bars commands, both blend the live price/chain cascade (spot, IV) with bars-derived HV, so the IV paths need a Greeks-bearing source (Schwab or Massive) and exit non-zero on a yfinance-only fallback rather than printing a bogus number.
27
+ - **Know how fresh each source is before quoting a number.** The historical bars under `hv`/`ta`/`scenarios` are a stitch: defeatbeta (weekly HuggingFace dataset) covers history up to the **most recent Friday's close**, and the rolling tail through today is filled by the **same live cascade as the price pipeline — Schwab → Massive → yfinance** — so the latest *complete* indicator bar is usually last Friday, and intraday moves aren't reflected until the day closes. In the live price cascade, **Massive returns the previous business day's close, not an intraday quote** (Polygon `get_previous_close_agg`; the bars tail instead uses Massive's date-range daily aggregates); only Schwab is real-time and yfinance is ~15-min delayed. When a figure comes from Massive or from the defeatbeta history, say so — don't present it as the current price.
27
28
 
28
29
  ## Repo layout
29
30
 
@@ -62,6 +63,7 @@ After `uv sync`, every CLI lives under a single `thetabook` umbrella. The full s
62
63
  thetabook refresh # pull positions from Schwab → personal/snapshots/YYYY-MM-DD.json
63
64
  thetabook snapshot # show latest snapshot freshness
64
65
  thetabook greeks # portfolio Greeks from latest snapshot
66
+ thetabook positions # effective options book (live mark, spot, cushion, DTE) by account
65
67
  thetabook evaluate <id> # P&L, PoP, Greeks for an idea (live re-marks)
66
68
  thetabook chain AAPL 2026-06-20 --type put # browse a chain
67
69
  thetabook ideas record-fill <id> --price 2.95 --qty -1 # status transitions go through the CLI
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: thetabook
3
- Version: 2.2.0
3
+ Version: 2.2.1
4
4
  Summary: A journal for options traders who think in Greeks — Schwab portfolio review and strategy log with an AI copilot.
5
5
  License-File: LICENSE
6
6
  Requires-Python: >=3.12
@@ -227,6 +227,11 @@ thetabook greeks --vol 0.30 --rate 0.05 # flat --vol override
227
227
  thetabook greeks --prices AAPL=185 NVDA=800 # manual price overrides
228
228
  thetabook greeks --no-fetch # skip auto price fetch
229
229
 
230
+ # Effective options book (live mark, spot, cushion, DTE, by account)
231
+ thetabook positions # options book (default view)
232
+ thetabook positions --equity # share-like holdings
233
+ thetabook positions --all # both tables
234
+
230
235
  # Stock prices (Schwab → Massive → yfinance cascade)
231
236
  thetabook price AAPL SPY
232
237
 
@@ -4,7 +4,7 @@ Single source of truth for enhancement work. Supersedes the separate `IMPROVEMEN
4
4
 
5
5
  > "Ideas" in this file means *project enhancements*. Trade ideas live in `personal/ideas/`.
6
6
 
7
- Last updated: 2026-05-26 | Current: v2.1.0 | Release notes: [CHANGELOG.md](CHANGELOG.md)
7
+ Last updated: 2026-06-05 | Current: v2.2.1 | Release notes: [CHANGELOG.md](CHANGELOG.md)
8
8
 
9
9
  ---
10
10
 
@@ -12,6 +12,37 @@ Last updated: 2026-05-26 | Current: v2.1.0 | Release notes: [CHANGELOG.md](CHANG
12
12
 
13
13
  Items shipped with their originating commit. Listed newest first.
14
14
 
15
+ ### v2.2.1 — vol-to-decision pair (M24) + effective options book (M20) + bars live-cascade tail-fill
16
+ Two pending medium-priority items closed out plus a bars-backbone consistency fix. The vol-to-decision pair (`em` / `vrp`) shipped first ([PR #64](https://github.com/subsriram/thetabook/pull/64), [9c58ba1](https://github.com/subsriram/thetabook/commit/9c58ba1)); the effective options-book table (`positions`) followed ([#67](https://github.com/subsriram/thetabook/pull/67)); and the historical-bars rolling tail was re-routed through the live price cascade ([#66](https://github.com/subsriram/thetabook/pull/66)). **1696 tests pass, ruff + mypy clean.**
17
+
18
+ - **M24 — expected move + vol-risk-premium.** `thetabook em TICKER --dte N` translates a vol figure into the ±1σ / ±2σ dollar range an option is pricing by expiry (`spot · σ · sqrt(DTE/365)`, calendar-day horizon); sigma defaults to HV20 with `--iv` / `--source iv` overrides. `thetabook vrp TICKER` ratios front-month ATM IV against realized HV — a point-in-time IV-vs-HV read (not a historical IV-rank), exiting non-zero on a yfinance-only fallback rather than printing a bogus ratio. Pure math in `analysis/em.py`; the ATM picker (`analysis/vrp.atm_iv`, shared with `em --source iv`) skips IV-less strikes and averages call+put at the nearest populated strike.
19
+
20
+ - **M20 — effective options book.** `thetabook positions --options` (the default view; `--equity` / `--all` for the others) renders the options-only table /portfolio reviews previously reconstructed by hand: per-leg live mark (chain cascade), underlying spot, **cushion** (the short-seller OTM buffer — positive = OTM/safe, negative = ITM/danger, computed `call:(K−S)/S` / `put:(S−K)/S` so the danger sign reads correctly for both legs), and calendar DTE, grouped by account. New `portfolio/options_book.py` stitches the snapshot loader + spot fetch from `pricing.greeks`, the per-leg live re-mark from `market.leg_marks`, and account labels from `portfolio.accounts`; pure extract/cushion/render functions keep the math testable and the fetch helpers (`resolve_spots` / `resolve_marks`) are the monkeypatch surface. Non-live spot provenance (Massive previous-close, yfinance delayed) is flagged in a footnote the same way `greeks` does. `--no-fetch` / `--prices` honored. The cushion sign deliberately follows the ROADMAP's stated "negative = ITM, danger" intent rather than its loosely-computed worked example. A review-found bug — the per-leg mark dedup keyed on the option series without the long/short side, so the same series held long in one account and short in another collapsed to one conservative-mode pick — was fixed by keying the picked mark on `(series, qty ≥ 0)`.
21
+
22
+ - **Bars live-cascade tail-fill ([#66](https://github.com/subsriram/thetabook/pull/66), closes #65).** The historical-bars rolling tail moved from a yfinance-only fill to the **same cascade as the live price pipeline — Schwab → Massive → yfinance** (first source with tail data wins); defeatbeta stays the deep-history source. Removes the source-disagreement seam between `price` and `hv`/`ta`/`scenarios`. `bars compare` now surfaces which live source served the tail. Validated live (AAPL + O) with both Schwab and Massive serving the tail: 0 rows flagged, 0.000% close drift across ex-dividend days.
23
+
24
+ ### v2.2.0 — multi-broker CSV import: Empower + format-agnostic parser registry
25
+ The Schwab/Fidelity CSV importer rebuilt as a format-agnostic parser registry, with **Empower** (employer 401(k) / EquatePlus) joining the supported brokers. Adding the next broker is now a subclass + one-line registration. No changes to the trading/analysis CLIs. Shipped as [PR #56](https://github.com/subsriram/thetabook/pull/56) ([fd9664a](https://github.com/subsriram/thetabook/commit/fd9664a)), closing #54. **1604 tests pass, ruff + mypy clean.**
26
+
27
+ - **Extensible broker CSV parser registry.** The monolithic `import_csv_snapshot.py` is split into a `portfolio/csv_parsers/` package: a `BrokerCsvParser` ABC (`detect()` / `parse()`), one module per broker (`schwab.py`, `fidelity.py`, `empower.py`), and a `REGISTRY` walked by `detect_and_parse()` (first match wins, most-specific first). A new broker is a subclass + a line in `REGISTRY` — no edits to the importer or CLI. Format is auto-detected per file, so a single `import-csv` invocation can mix exports from different brokers. `import_csv_snapshot.py` is reduced to a thin entry point; the legacy `parse_schwab_csv` / `parse_fidelity_csv` shim functions were removed (callers use the `csv_parsers` package directly).
28
+
29
+ - **Empower Holdings CSV import.** `import-csv` recognizes Empower's multi-account holdings export (equities, ETFs, mutual funds, options) alongside Schwab and Fidelity. Because Empower exports carry the account subtype, `accounts totals` surfaces a `roth-401k` / `traditional-401k` suggestion for unconfigured accounts instead of a bare `?` (unlike Schwab, which can't distinguish IRA from taxable). Malformed files (missing a required column) warn and skip rather than raising `KeyError` mid-parse.
30
+
31
+ - **`instrument_symbol` per-account override.** For single-stock employer plans (e.g. EquatePlus) whose Fidelity rows carry no ticker, `accounts.toml` can map the account to a symbol so the shares import with the right underlying. Documented in `accounts.toml.example`.
32
+
33
+ - **Account numbers stored as the broker exposes them.** Fidelity and Empower numbers are stored verbatim; Schwab stays masked to `****<last4>` because the export only carries the last four (a broker limitation, not a masking decision). `import-csv` warns when a now-verbatim number no longer matches a masked `****<last4>` key left in `accounts.toml`, so per-account rules don't silently stop matching — re-key or re-run `/accounts-init`.
34
+
35
+ - **`parse_money` handles the `$-114.50` ordering.** A negative sign after the currency symbol now parses as negative (previously only `-$114.50` and `($114.50)` worked).
36
+
37
+ - **Packaging + docs.** sdist now excludes `personal/`, `.claude/`, `tests/`, `docs/` ([#62](https://github.com/subsriram/thetabook/pull/62)) — smaller distribution that no longer risks shipping local PII fixtures. Empower support, the `csv_parsers/` package, and the `import-csv` command are documented across README, `docs/cli.md`, `docs/architecture.md` ([#56](https://github.com/subsriram/thetabook/pull/56)); the v2.1.x technical-analysis stack is documented across the reference docs ([#63](https://github.com/subsriram/thetabook/pull/63)).
38
+
39
+ ### v2.1.2 — ship v2.1.x to PyPI + first-run setup fixes
40
+ First-time-setup bug fixes plus a CI hardening so releases stop being hostage to the GitHub Actions artifact-storage quota. No changes to the trading/analysis CLIs. **1564 tests pass, ruff + mypy clean.** v2.1.1's tag push had failed to publish on the pre-#59 artifact-handoff layout (storage quota); 2.1.2 supersedes it and is the first PyPI release after 2.0.0 to carry the v2.1.x feature set.
41
+
42
+ - **`thetabook init` / `/setup-thetabook` setup flow** ([#58](https://github.com/subsriram/thetabook/pull/58)). Three bugs broke first-time setup end to end: (1) the skill installer mirrored the source's flat form into `.claude/skills/<slug>.md`, but Claude Code only discovers folder form (`<slug>/SKILL.md`) — the installer now always normalizes to folder form at the destination and treats a pre-existing flat file as a prior install of the same slug; (2) `init --non-interactive` hit EOF on schwab-py's "Press ENTER" prompt because `--app-secret-stdin` consumes stdin — `_run_oauth` now passes `interactive=False`; (3) `init` wrote `SCHWAB_APP_KEY` while the rest of the app reads `SCHWAB_API_KEY` — the `.env` writer now emits the canonical key.
43
+
44
+ - **`publish.yml` — build + publish merged into one job** ([#59](https://github.com/subsriram/thetabook/pull/59)). The two-job layout handed `dist/` between jobs via `upload-artifact` → `download-artifact`, making every release hostage to the account-level artifact-storage quota (exactly what blocked the v2.1.1 publish). Build and publish now share one runner; `dist/` stays on disk and goes straight to PyPI. OIDC trusted publishing unchanged.
45
+
15
46
  ### v2.1.1 — test-coverage backfill for v2.1.0 + defeatbeta stdout-noise polish
16
47
  Two threads. (1) Test-coverage audit on the v2.1.0 release surfaced that the four new CLI modules (`hv`, `ta`, `bars`, `scenarios`) had zero integration coverage and that several internal paths (non-daily intervals, the `indicators()` wrapper integration, the 4-feature state-vector boundary clipping) were under-tested; this release fills those gaps. (2) The defeatbeta fetcher printed banner + nltk + DuckDB chatter on first per-ticker import that polluted CLI streams; new `_quiet_defeatbeta()` context manager scopes the suppressions to the wrapper boundary. **1561 tests pass (+74 net since v2.1.0), ruff + mypy clean.**
17
48
 
@@ -97,22 +128,21 @@ Useful but not urgent.
97
128
  ### ~~M23. PyPI distribution + `thetabook init` wizard + `$THETABOOK_HOME`~~ — **shipped in v2.0.0**
98
129
  Headline summary in [CHANGELOG.md](CHANGELOG.md#200--2026-05-13). As-shipped audit (what matched the design, what diverged, what's still open) lives at [docs/m23-audit.md](docs/m23-audit.md). Two follow-up items (`--with-accounts` flag, Homebrew tap) tracked under Deferred → "M23 follow-ups".
99
130
 
100
- ### M20. Effective options book table — `thetabook positions --options` (Medium effort) — wait-and-see
101
- During /portfolio reviews the user has to reconstruct an options-only table by hand: read average premium and market value out of `refresh` stdout, divide for current mark, then re-pull live marks via `evaluate <id>` per idea. The data already exists across three callers — `greeks` (snapshot loader + grouping by underlying), `evaluate_idea` (per-leg live-mark loop with cascade fallback), and `leg-mark` (single-leg current bid/ask) — so the table itself is mostly stitching. Target shape:
102
-
103
- ```
104
- $ thetabook positions --options
105
- contract qty entry mark spot cushion DTE account
106
- QQQ 2026-06-20 670 P -2 $4.50 $2.30 $666 -0.6% 54 main-margin
107
- AAPL 2026-05-16 180 C +1 $3.50 $5.20 $185 2.7% 19 main-margin
108
- …
109
- ```
131
+ ### ~~M20. Effective options book table — `thetabook positions --options`~~ — **shipped in v2.2.1**
132
+ Built as a new `cli/positions.py` + `portfolio/options_book.py` after one wait-and-see /portfolio cycle confirmed the friction (reconstructing an options-only table by hand from `refresh` + per-idea `evaluate`) didn't resolve itself. Default `--options` view (plus `--equity` / `--all`); per-leg live mark, spot, cushion, calendar DTE, grouped by account. The cushion sign follows the stated "negative = ITM, danger" intent — `call:(K−S)/S` / `put:(S−K)/S` — correcting the original sketch's worked example, which computed the short-call sign backwards. See the v2.2.1 entry under Done above and [CHANGELOG.md](CHANGELOG.md).
110
133
 
111
- Cushion is moneyness for the short side: `(S − K)/S` for short calls, `(K − S)/S` for short puts (negative = ITM, danger). DTE is calendar days. Group by account.
134
+ ### ~~M24. Expected move + vol-risk-premium — the two TA additions that extend the vol→dollars / theta-edge core~~ — **shipped in v2.2.1 ([#64](https://github.com/subsriram/thetabook/pull/64))**
135
+ Headline summary in [CHANGELOG.md](CHANGELOG.md) (`[2.2.1]`); as-shipped detail in the v2.2.1 entry under Done above.
112
136
 
113
- **Wait-and-see rationale:** Net plan items 1, 2, 3 + the `--show-all` flag landed in v1.7.x and meaningfully changed what /portfolio asks Claude to do. The previous workflow had Claude reconstructing this table because the commands one layer down (snapshot freshness, account totals, concentration ranking) were missing — now that those exist, Claude may be able to produce a serviceable options-book table by reading the snapshot + a single `evaluate` pass without a dedicated command. Hold one /portfolio cycle, see whether the friction resurfaces, then build.
137
+ ### M25. Remaining TA candidates from the 2026-06-04 review (Low–medium effort each) — build on demand
138
+ The same TA-capabilities review that produced M24 surfaced a second tier — useful but lower-leverage than expected-move / VRP, logged here so they're not re-derived from scratch. Roughly ordered by options-relevance:
114
139
 
115
- **Implementation sketch (when triggered):** new `cli/positions.py` typer command with `--options` / `--equity` / `--all` flags (default `--options` since that's the friction). Reuses `thetabook.ideas.evaluate_idea.resolve_market_data`-style live-mark logic factored out so it accepts a list of legs rather than an idea file. Or — likely simpler — add `--legs` to the existing `greeks` command since `greeks` already loads the snapshot and walks per-leg; the per-leg mark fetch + cushion/DTE columns become incremental.
140
+ - **ATR (Average True Range) + range-based sizing.** The one true gap in the vol layer: all current realized-vol is close-to-close, so there's no read on intraday range. `get_bars` already returns full OHLC, so `atr(ticker, window=14)` in `analysis/ta.py` is a few lines (`max(H−L, |H−Cprev|, |L−Cprev|)` then Wilder-smoothed). Useful for stop placement, comparing a strike's distance to "a normal day's move", and gut-checking the M24 expected move. Lowest effort, true gap.
141
+ - **Volatility cone.** Realized vol across multiple windows (10/20/30/60/90d) with historical percentile bands per window — the classic options-desk "is vol high or low *for the horizon I'm trading*" tool, and a natural aggregation over `hv_series` called at several windows. Directly informs DTE selection. Everything needed is already in `analysis/hv.py`; this is a presentation/aggregation layer (`thetabook hv --cone` or `thetabook vol-cone TICKER`).
142
+ - **Earnings-aware / event vol.** The package already resolves earnings dates (`cli/earnings.py`). De-earnings the HV (strip the known event-day jump) so the baseline vol quoted during a review isn't inflated by a scheduled catalyst — helps decide whether elevated IV (per M24's VRP) is event premium or a genuine regime shift.
143
+ - **Beta / correlation to SPY.** Portfolio-level, not single-ticker: helps `greeks`/`/portfolio` answer "how much of my delta is really one SPY bet" — concentration in disguise. Complements the existing delta aggregation; needs a two-ticker return regression over `get_bars` closes.
144
+ - **Support/resistance (pivot points, recent swing highs/lows).** Concrete price anchors for strike selection. Modest lift, modest payoff — build when a real review session reaches for it.
145
+ - **Generic directional indicators (ADX/trend strength, SMA/EMA crossovers, Stochastics, Ichimoku, Keltner/Donchian).** Standard but weak options tie-in — completeness rather than edge for a Greeks-first journal. Add only if a specific review actually calls for one; not worth a speculative build.
116
146
 
117
147
  ### M8. Windows symlink handling for `latest.json` (Low-medium effort) — defer
118
148
  `personal/snapshots/latest.json` is a POSIX symlink written by `get_positions.py`. On Windows, symlink creation requires Developer Mode or admin rights; without them the symlink write fails silently. **Deferred until first Windows contributor:** the user is solo on macOS; no symptom observed. When revisited, implement option 3 (read-resolver preferring newest dated file, treating `latest.json` as optional cache) — most robust across symlink states.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "thetabook"
3
- version = "2.2.0"
3
+ version = "2.2.1"
4
4
  description = "A journal for options traders who think in Greeks — Schwab portfolio review and strategy log with an AI copilot."
5
5
  requires-python = ">=3.12"
6
6
  dependencies = [
@@ -0,0 +1,118 @@
1
+ """Expected move — translate a vol figure into the dollar range an option
2
+ is pricing in by a given expiry.
3
+
4
+ This is the bridge between the realized-vol layer (:mod:`thetabook.analysis.hv`)
5
+ / live option IV and a strike-selection decision: "how far OTM should my
6
+ short strike sit?" is the same question as "how big is the ±1σ move the
7
+ market is pricing by expiry?".
8
+
9
+ Convention
10
+ ----------
11
+ - **Formula**: ``move_1σ = S · σ · sqrt(t)``, the standard one-standard-
12
+ deviation expected move (the same approximation behind the ATM-straddle
13
+ rule of thumb).
14
+ - **Horizon**: ``t = dte_days / 365`` — *calendar* days to expiry over 365.
15
+ This is the practitioner / straddle convention and is a **deliberate
16
+ mismatch** with :mod:`thetabook.analysis.hv`'s ``sqrt(252)`` (trading-day)
17
+ annualization. The two layers answer different questions: ``hv`` annualizes
18
+ a per-trading-day realized vol to a comparable yearly number; ``em`` prices
19
+ a move over a fixed calendar span to a known expiry date, and option DTE is
20
+ quoted in calendar days. Mixing the two conventions (calendar DTE with a
21
+ trading-day annualization, or vice versa) is the common footgun; keeping
22
+ ``em`` purely calendar-based matches how the move is quoted on a desk.
23
+ - **Sigma units**: annualized vol as a decimal (``0.24`` == 24%) — the same
24
+ units ``hv()`` and the chain's ``implied_vol`` field already emit, so a
25
+ caller can feed either straight in.
26
+
27
+ This module is pure math: no I/O, no data fetch. The CLI decides where
28
+ ``sigma`` comes from (HV, a manual ``--iv``, or ATM IV pulled from the chain
29
+ via :func:`thetabook.analysis.vrp.atm_iv`).
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import math
35
+ from dataclasses import dataclass
36
+
37
+ # Calendar days per year — the expected-move horizon denominator. See the
38
+ # module docstring for why this is 365 (calendar) and not 252 (trading).
39
+ CALENDAR_DAYS_PER_YEAR = 365.0
40
+
41
+
42
+ # NOTE: plain frozen dataclasses, not pydantic models, on purpose. These are
43
+ # within-feature, CLI-only display shapes that never cross a load/save boundary
44
+ # — consistent with the rest of analysis/ (hv/scenarios return floats/Series/
45
+ # DataFrames). CLAUDE.md's "cross-module shapes live in models.py as pydantic"
46
+ # rule is about serialized / boundary-crossing data. If a future caller needs to
47
+ # persist or validate one of these (e.g. writing an EM reading into idea
48
+ # frontmatter), promote it to a pydantic model in models.py at that point.
49
+ @dataclass(frozen=True)
50
+ class MoveBand:
51
+ """One ±Nσ band of an expected move."""
52
+
53
+ n: float
54
+ """Number of standard deviations (1.0, 2.0, ...)."""
55
+ move: float
56
+ """The ±dollar move at this band (always non-negative)."""
57
+ pct: float
58
+ """``move / spot`` — the move as a fraction of spot."""
59
+ low: float
60
+ """``spot - move`` — bottom of the band."""
61
+ high: float
62
+ """``spot + move`` — top of the band."""
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class ExpectedMove:
67
+ """Result of :func:`expected_move`: the spot/sigma/horizon inputs plus
68
+ one :class:`MoveBand` per requested sigma multiple."""
69
+
70
+ spot: float
71
+ sigma: float
72
+ dte_days: int
73
+ t_years: float
74
+ bands: tuple[MoveBand, ...]
75
+
76
+
77
+ def expected_move(
78
+ spot: float,
79
+ sigma: float,
80
+ dte_days: int,
81
+ *,
82
+ sigmas: tuple[float, ...] = (1.0, 2.0),
83
+ ) -> ExpectedMove:
84
+ """±Nσ expected move of ``spot`` over ``dte_days`` calendar days.
85
+
86
+ ``sigma`` is annualized vol as a decimal (``0.24`` == 24%). The 1σ move
87
+ is ``spot · sigma · sqrt(dte_days / 365)``; higher bands scale linearly
88
+ (the ``n``-σ move is ``n`` times the 1σ move), so the ~68% / ~95% /
89
+ ~99.7% normal-distribution coverage of 1σ / 2σ / 3σ applies.
90
+
91
+ Raises ``ValueError`` on negative inputs (a negative DTE means the
92
+ expiry is in the past; the caller should handle that before reaching
93
+ here). ``dte_days == 0`` and ``sigma == 0`` are valid degenerate inputs
94
+ and produce zero-width bands.
95
+ """
96
+ if spot <= 0:
97
+ raise ValueError(f"spot must be positive (got {spot})")
98
+ if sigma < 0:
99
+ raise ValueError(f"sigma must be non-negative (got {sigma})")
100
+ if dte_days < 0:
101
+ raise ValueError(f"dte_days must be non-negative (got {dte_days})")
102
+ if not sigmas:
103
+ raise ValueError("sigmas must contain at least one multiple")
104
+
105
+ t_years = dte_days / CALENDAR_DAYS_PER_YEAR
106
+ one_sigma = spot * sigma * math.sqrt(t_years)
107
+
108
+ bands = tuple(
109
+ MoveBand(
110
+ n=n,
111
+ move=n * one_sigma,
112
+ pct=n * one_sigma / spot,
113
+ low=spot - n * one_sigma,
114
+ high=spot + n * one_sigma,
115
+ )
116
+ for n in sigmas
117
+ )
118
+ return ExpectedMove(spot=spot, sigma=sigma, dte_days=dte_days, t_years=t_years, bands=bands)
@@ -0,0 +1,145 @@
1
+ """Vol-risk-premium — is implied vol richer than realized right now?
2
+
3
+ The core question a premium seller asks before opening a theta trade. The
4
+ package already has both halves: realized vol from
5
+ :mod:`thetabook.analysis.hv`, and live option *implied* vol on every chain
6
+ contract (``implied_vol`` from :func:`thetabook.market.chains.fetch_chain`,
7
+ populated by Schwab / Massive). This module cross-wires them: pull the
8
+ front-month ATM IV and ratio it against HV.
9
+
10
+ What this is **not**
11
+ --------------------
12
+ This is a *point-in-time* IV-vs-HV read, **not** a historical IV-rank.
13
+ Neither defeatbeta nor yfinance ships historical option IV, so there's no
14
+ "where does today's IV sit in its own 1-year range?" — that limitation is
15
+ unchanged (see :mod:`thetabook.analysis.hv` for the HV-rank substitute the
16
+ package uses for *that* question). VRP answers the orthogonal, equally
17
+ decision-relevant question: at this moment, is the option market pricing
18
+ more vol than the stock has recently realized?
19
+
20
+ Reading the number
21
+ -------------------
22
+ ``ratio = atm_iv / hv``; ``premium = atm_iv - hv`` (in vol points). A ratio
23
+ meaningfully above 1 means implied is richer than realized — the structural
24
+ edge premium sellers harvest. Below 1 means the stock has been moving more
25
+ than options are pricing, so selling premium is paying you less than the
26
+ realized risk; that's the caution flag.
27
+
28
+ Data-source caveat
29
+ ------------------
30
+ IV requires a Greeks-bearing source (Schwab or Massive). yfinance carries an
31
+ ``impliedVolatility`` field but it's unreliable and frequently absent; when
32
+ only yfinance is available :func:`atm_iv` may return ``None`` and
33
+ :func:`vrp` returns ``None`` rather than a bogus ratio. Spot freshness
34
+ follows the price cascade — if it came from Massive it's the prior-day
35
+ close, which ``fetch_prices`` already notes to stderr.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ from collections import defaultdict
41
+ from dataclasses import dataclass
42
+ from datetime import date
43
+
44
+ from thetabook.analysis.hv import hv
45
+ from thetabook.market.chains import fetch_chain, list_expirations
46
+ from thetabook.market.prices import fetch_prices
47
+
48
+ # ATM is found within ±this fraction of spot, to bound the chain fetch. Wide
49
+ # enough that a coarse strike grid still brackets spot; narrow enough to keep
50
+ # the contract list small.
51
+ _ATM_STRIKE_WINDOW = 0.10
52
+ # Dollar floor on that window so low-priced names (where ±10% can be narrower
53
+ # than one strike increment) still bracket at least a couple of strikes.
54
+ _ATM_STRIKE_FLOOR = 5.0
55
+
56
+
57
+ # Plain frozen dataclass (not pydantic) on purpose — a within-feature, CLI-only
58
+ # display shape, consistent with analysis/ precedent. See the matching note in
59
+ # analysis/em.py: promote to a pydantic model in models.py if a future caller
60
+ # ever needs to serialize or validate it across a boundary.
61
+ @dataclass(frozen=True)
62
+ class VrpResult:
63
+ """Result of :func:`vrp`: the ATM IV vs HV comparison at a point in time."""
64
+
65
+ spot: float
66
+ expiry: str
67
+ dte_days: int
68
+ atm_strike: float
69
+ atm_iv: float
70
+ hv: float
71
+ hv_window: int
72
+ ratio: float
73
+ """``atm_iv / hv`` — >1 means implied richer than realized."""
74
+ premium: float
75
+ """``atm_iv - hv`` — the premium in vol points (decimal)."""
76
+
77
+
78
+ def atm_iv(ticker: str, expiry: str, spot: float) -> tuple[float, float] | None:
79
+ """ATM implied vol for ``ticker`` at ``expiry``: ``(strike, iv)`` or ``None``.
80
+
81
+ Picks the strike nearest ``spot`` *that actually carries a usable IV* and
82
+ averages the call and put ``implied_vol`` there (both legs carry an IV;
83
+ averaging smooths the put/call skew at the money). Strikes with no usable
84
+ IV are skipped rather than disqualifying the lookup — so a sparse chain
85
+ whose single closest strike lacks IV still resolves via the next-nearest
86
+ populated strike. Returns ``None`` only when the chain has no contracts or
87
+ none with a usable IV at all — e.g. a yfinance-only fallback. Shared with
88
+ the ``thetabook em --source iv`` path.
89
+ """
90
+ window = max(spot * _ATM_STRIKE_WINDOW, _ATM_STRIKE_FLOOR)
91
+ contracts = fetch_chain(ticker, expiry, None, spot - window, spot + window)
92
+ if not contracts:
93
+ return None
94
+ # Group usable IVs by strike, then pick the populated strike nearest spot.
95
+ ivs_by_strike: dict[float, list[float]] = defaultdict(list)
96
+ for c in contracts:
97
+ iv = c.get("implied_vol")
98
+ if iv:
99
+ ivs_by_strike[c["strike"]].append(iv)
100
+ if not ivs_by_strike:
101
+ return None
102
+ atm_strike = min(ivs_by_strike, key=lambda k: abs(k - spot))
103
+ ivs = ivs_by_strike[atm_strike]
104
+ return atm_strike, sum(ivs) / len(ivs)
105
+
106
+
107
+ def vrp(ticker: str, *, hv_window: int = 20, expiry: str | None = None) -> VrpResult | None:
108
+ """Front-month ATM IV vs HV for ``ticker``, or ``None`` if data is missing.
109
+
110
+ ``expiry`` defaults to the nearest (front-month) expiration. Returns
111
+ ``None`` when spot, the chain IV, or HV can't be resolved — the CLI
112
+ turns that into a ``log.warn`` + non-zero exit rather than printing a
113
+ misleading ratio.
114
+ """
115
+ spot = fetch_prices([ticker]).get(ticker)
116
+ if spot is None or spot <= 0:
117
+ return None
118
+
119
+ if expiry is None:
120
+ exps = list_expirations(ticker)
121
+ if not exps:
122
+ return None
123
+ expiry = sorted(exps)[0]
124
+
125
+ picked = atm_iv(ticker, expiry, spot)
126
+ if picked is None:
127
+ return None
128
+ atm_strike, iv = picked
129
+
130
+ realized = hv(ticker, window=hv_window)
131
+ if realized is None or realized <= 0:
132
+ return None
133
+
134
+ dte_days = (date.fromisoformat(expiry) - date.today()).days
135
+ return VrpResult(
136
+ spot=spot,
137
+ expiry=expiry,
138
+ dte_days=dte_days,
139
+ atm_strike=atm_strike,
140
+ atm_iv=iv,
141
+ hv=realized,
142
+ hv_window=hv_window,
143
+ ratio=iv / realized,
144
+ premium=iv - realized,
145
+ )
@@ -12,8 +12,11 @@ Tools (each maps to a thin typer wrapper that delegates to the underlying
12
12
  evaluate — evaluate a trade idea (P&L, PoP, Greeks, live re-mark)
13
13
  adjust — what-if adjustment modeling (roll, add, close, assign)
14
14
  greeks — portfolio Greeks aggregated by underlying
15
+ positions — effective options/equity book (live marks, cushion, DTE)
15
16
  hv — historical (realized) vol + HV-rank / percentile
16
17
  ta — technical indicators (RSI, MACD, Bollinger Bands)
18
+ em — expected move (±σ dollar range) from HV or chain IV
19
+ vrp — vol-risk-premium: ATM IV vs realized HV
17
20
  roll — roll-decision scenario grid
18
21
  diff — compare two snapshots
19
22
  price — fetch current stock price(s)
@@ -47,6 +50,7 @@ from thetabook.cli import chain as _chain
47
50
  from thetabook.cli import diff as _diff
48
51
  from thetabook.cli import dividends as _dividends
49
52
  from thetabook.cli import earnings as _earnings
53
+ from thetabook.cli import em as _em
50
54
  from thetabook.cli import evaluate as _evaluate
51
55
  from thetabook.cli import greeks as _greeks
52
56
  from thetabook.cli import hv as _hv
@@ -55,6 +59,7 @@ from thetabook.cli import import_csv as _import_csv
55
59
  from thetabook.cli import init as _init
56
60
  from thetabook.cli import leg_mark as _leg_mark
57
61
  from thetabook.cli import migrate_home as _migrate_home
62
+ from thetabook.cli import positions as _positions
58
63
  from thetabook.cli import price as _price
59
64
  from thetabook.cli import refresh as _refresh
60
65
  from thetabook.cli import roll as _roll
@@ -63,6 +68,7 @@ from thetabook.cli import skills as _skills
63
68
  from thetabook.cli import snapshot as _snapshot
64
69
  from thetabook.cli import ta as _ta
65
70
  from thetabook.cli import tickers as _tickers
71
+ from thetabook.cli import vrp as _vrp
66
72
  from thetabook.cli import wiki as _wiki
67
73
 
68
74
  app = typer.Typer(
@@ -78,8 +84,11 @@ app.command("snapshot")(_snapshot.snapshot)
78
84
  app.command("evaluate")(_evaluate.evaluate)
79
85
  app.command("adjust")(_adjust.adjust)
80
86
  app.command("greeks")(_greeks.greeks)
87
+ app.command("positions")(_positions.positions)
81
88
  app.command("hv")(_hv.hv)
82
89
  app.command("ta")(_ta.ta)
90
+ app.command("em")(_em.em)
91
+ app.command("vrp")(_vrp.vrp)
83
92
  app.command("roll")(_roll.roll)
84
93
  app.command("diff")(_diff.diff)
85
94
  app.command("price")(_price.price)
@@ -21,10 +21,30 @@ Usage in a subcommand:
21
21
 
22
22
  from __future__ import annotations
23
23
 
24
+ from datetime import date
24
25
  from typing import Annotated
25
26
 
26
27
  import typer
27
28
 
29
+
30
+ # --- validators (use as typer Option/Argument callbacks) ---------------------
31
+ def validate_iso_date(value: str | None) -> str | None:
32
+ """Reject a non-ISO date string at parse time with a clean message.
33
+
34
+ Used as a ``callback=`` on date-shaped ``--expiry`` options so a typo
35
+ surfaces as ``Invalid value for '--expiry': ...`` instead of a raw
36
+ ``ValueError`` traceback from a downstream ``date.fromisoformat``.
37
+ Passes ``None`` through unchanged (the flag is optional).
38
+ """
39
+ if value is None:
40
+ return None
41
+ try:
42
+ date.fromisoformat(value)
43
+ except ValueError:
44
+ raise typer.BadParameter(f"must be an ISO date (YYYY-MM-DD); got {value!r}") from None
45
+ return value
46
+
47
+
28
48
  # --- price overrides ---------------------------------------------------------
29
49
  PricesOpt = Annotated[
30
50
  list[str] | None,
@@ -64,8 +84,7 @@ MarkModeOpt = Annotated[
64
84
  str | None,
65
85
  typer.Option(
66
86
  "--mark-mode",
67
- help="How to pick a current mark from bid/ask/mid. "
68
- "conservative = long→ask, short→bid. mid = (bid+ask)/2.",
87
+ help="How to pick a current mark from bid/ask/mid. conservative = long→ask, short→bid. mid = (bid+ask)/2.",
69
88
  ),
70
89
  ]
71
90
  GreeksSourceOpt = Annotated[