thetabook 2.3.0__tar.gz → 2.4.0__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.
- {thetabook-2.3.0 → thetabook-2.4.0}/CHANGELOG.md +124 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/CLAUDE.md +3 -3
- {thetabook-2.3.0 → thetabook-2.4.0}/PKG-INFO +1 -1
- {thetabook-2.3.0 → thetabook-2.4.0}/README.md +15 -11
- {thetabook-2.3.0 → thetabook-2.4.0}/ROADMAP.md +25 -2
- {thetabook-2.3.0 → thetabook-2.4.0}/pyproject.toml +2 -2
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/CLAUDE.md +4 -4
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/analysis/vrp.py +43 -42
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/_shared.py +40 -3
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/adjust.py +2 -9
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/bs.py +16 -6
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/chain.py +3 -3
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/em.py +5 -4
- thetabook-2.4.0/src/thetabook/cli/greeks.py +59 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/leg_mark.py +2 -1
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/positions.py +10 -3
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/roll.py +4 -2
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/skills.py +3 -3
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/vrp.py +7 -1
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/config.py +72 -1
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/ideas/adjust.py +705 -323
- thetabook-2.4.0/src/thetabook/ideas/core.py +1413 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/ideas/evaluate_idea.py +449 -292
- thetabook-2.4.0/src/thetabook/ideas/roll_scenarios.py +896 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/leg_parse.py +213 -47
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/bars.py +98 -10
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/chains.py +14 -3
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/dividends.py +39 -1
- thetabook-2.4.0/src/thetabook/market/leg_inputs.py +168 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/leg_marks.py +5 -2
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/prices.py +172 -6
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/vol_lookup.py +218 -31
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/models.py +148 -10
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/paths.py +82 -1
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/accounts.py +131 -135
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/diff_snapshots.py +12 -8
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/get_positions.py +0 -32
- thetabook-2.3.0/src/thetabook/pricing/greeks.py → thetabook-2.4.0/src/thetabook/portfolio/greeks_book.py +161 -312
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/options_book.py +74 -120
- thetabook-2.4.0/src/thetabook/pricing/leg_greeks.py +76 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/lint.py +6 -4
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/parse.py +14 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/render.py +3 -3
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/config.toml.example +15 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/journal.md +1 -1
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/tickers.py +66 -31
- {thetabook-2.3.0 → thetabook-2.4.0}/uv.lock +1 -1
- thetabook-2.3.0/src/thetabook/cli/greeks.py +0 -46
- thetabook-2.3.0/src/thetabook/ideas/core.py +0 -710
- thetabook-2.3.0/src/thetabook/ideas/roll_scenarios.py +0 -572
- {thetabook-2.3.0 → thetabook-2.4.0}/.env.example +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/.git-blame-ignore-revs +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/.github/workflows/ci.yml +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/.github/workflows/publish.yml +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/.gitignore +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/.python-version +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/AGENTS.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/CONTRIBUTING.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/LICENSE +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/SECURITY.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/scripts/demo.sh +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/analysis/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/analysis/em.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/analysis/hv.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/analysis/scenarios.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/analysis/ta.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/data.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/engine.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/grid.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/manifest.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/metrics.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/report.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/signals.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/strategies/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/strategies/dual_momentum.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/backtest/strategies/sector_rotation.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cache.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/CLAUDE.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/accounts.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/backtest.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/bars.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/diff.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/dividends.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/earnings.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/evaluate.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/hv.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/ideas.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/import_csv.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/init.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/migrate_home.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/price.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/refresh.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/scenarios.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/snapshot.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/ta.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/tickers.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/cli/wiki.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/ideas/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/ideas/manage_ideas.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/log.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/_schwab.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/market/earnings.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/csv_parsers/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/csv_parsers/_base.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/csv_parsers/empower.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/csv_parsers/fidelity.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/csv_parsers/schwab.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/import_csv_snapshot.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/portfolio/scaffold.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/preflight.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/pricing/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/pricing/bs.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/install.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/models.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/policy.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/skills/registry.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/README.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/accounts.toml.example +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/idea.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/learnings.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/skill.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/skills/setup-thetabook.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/wiki/index.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/wiki/log.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/wiki/overview.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/wiki/strategy.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/templates/wiki/underlying.md +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/wiki/__init__.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/wiki/lint.py +0 -0
- {thetabook-2.3.0 → thetabook-2.4.0}/src/thetabook/wiki/render.py +0 -0
|
@@ -5,6 +5,130 @@ All notable changes to this project are recorded here. Format loosely follows
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [2.4.0] — 2026-11-21
|
|
9
|
+
|
|
10
|
+
**M26: duplicated rules consolidated.** Rules that two or more commands each computed with their own code now have one owner each, in #126–#139. **Some numbers change.** `thetabook greeks` uses broker Greeks and a dividend yield per ticker. `evaluate` and `adjust` value option underlyings at a live spot even when the snapshot is fresh. `adjust --save` no longer puts a roll's realized P&L into the risk budget. That covers spot, per-leg Greeks, the horizon expiry, ATM IV, forward/Black-76 inputs, dividend yield, pricing defaults, expired-leg settlement, risk budgets, leg parsing, snapshot rows, event windows and share counting. The entries below marked "(M26)" are the user-visible results. The rule → owner table is in [docs/duplicated-rules-audit.md](docs/duplicated-rules-audit.md#outcome).
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **`[market] rate`, `fallback_vol` and `fallback_div_yield` in `personal/config.toml`** set the risk-free rate, flat fallback vol and dividend yield for every pricing command, with built-in defaults of 0.045, 0.25 and 0.0. `config.py` owns them as `config.DEFAULT_RATE`, `DEFAULT_VOL` and `DEFAULT_DIV_YIELD`, replacing copies in `evaluate`, `adjust`, `greeks`, `roll`, `bs` and the shared CLI help (M26, audit item 11b). `--help` shows the resolved default instead of a hard-coded number. A value out of range, such as a percent written as `rate = 4.5`, warns and falls back. See [behaviors.md](docs/behaviors.md) "Pricing defaults: rate, fallback vol, dividend yield".
|
|
15
|
+
- **`thetabook positions --rate`** sets the rate used to discount a VIX-family forward.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- **`thetabook greeks` now uses broker Greeks by default and prices each underlying with its own dividend yield, so its numbers change** (M26, audit item 3). It used to recompute every leg with Black-Scholes at one `q` for the whole book (`--div-yield`, else 0), while `evaluate` and `adjust` passed Schwab's Greeks through and priced at each ticker's fetched yield. One short XYZ 105C at S = 100, 60 DTE, chain IV 30%, read −38.99 delta / +4.33 theta in `greeks` and −38.00 / +5.00 in `evaluate`. With no broker Greeks and a 3% yield, `greeks` read −38.99 and `evaluate` −37.26. Both now read −38.00 / +5.00 and −37.26. `greeks` gains `--greeks-source chain|bs` (default `chain`), as on `evaluate` and `adjust`. `--div-yield` still sets one yield for every underlying; without it each one is auto-fetched through `market.dividends.resolve_div_yield`. The footer now lists the Greeks sources (`*Greeks sources: 3 schwab, 1 chain-iv-bs*`) and each option underlying's yield. **A VIX leg is now always recomputed with Black-76 on its expiry's forward, in all three commands**, even under `--greeks-source chain`: Schwab's VIX deltas exceed 1.0 on deep ITM calls, and `evaluate` and `adjust` used to pass them through (a short 2× VIX 10C read −224 delta, beyond the −200 a 2-lot can carry; it now reads −198.85, as `greeks` did). One owner, split by layer: `market.leg_inputs.resolve_leg_inputs` decides the inputs and `pricing.leg_greeks.leg_greeks` does the arithmetic. `core.compute_greeks` and `aggregate_greeks` both call the pair, and `pricing.greeks.compute_position_greeks` is gone. Broker Greeks are now validated before any of the three commands uses them. A Schwab `-999` sentinel row used to read +99,900 delta on one short contract in `evaluate` and `adjust`, and a row with zero gamma / theta / vega read 0 / 0 / 0. A row is refused if:
|
|
20
|
+
- delta is outside [−1, 1];
|
|
21
|
+
- gamma or vega is negative;
|
|
22
|
+
- any value is a `-999` sentinel;
|
|
23
|
+
- gamma, theta and vega are all zero on a live contract.
|
|
24
|
+
|
|
25
|
+
A refused row is priced with Black-Scholes, tagged `bs (broker greeks rejected)`, with one warning per run naming the contracts. `compute_greeks` no longer rounds per leg. Rounding is display-only, and `evaluate`'s Net row and `greeks`' TOTAL row are the sum of the rounded rows shown above them. `greeks --no-fetch` help now says option chains and dividend yields are still fetched. See [behaviors.md](docs/behaviors.md) "One leg's Greeks: one owner".
|
|
26
|
+
- **`evaluate` and `adjust` ask one function which dividend yield to price an underlying with** (M26, audit item 11a). Each held an identical copy of the sequence: `--div-yield`, else the fetched yield, else `[market] fallback_div_yield`. `market.dividends.resolve_div_yield` now owns it, with the same `override` / `auto` / `default` labels and the same warning on a failed fetch, so output is unchanged. A refinement such as `q = r` for forward-settled underlyings now lands in both commands at once. `roll` now uses it too (see Fixed). `greeks` moved onto it later in M26 (see the `thetabook greeks` entry above). See [behaviors.md](docs/behaviors.md) "Which yield an underlying is priced with: one owner".
|
|
27
|
+
- **Three duplicated rules whose copies agreed now have one owner each; output is unchanged** (M26, audit 12a and the leftovers of 12b). `ideas.core.classify_event` owns the `none` / `in_window` / `after_expiry` / `failed` taxonomy for earnings and ex-dividend dates, which `evaluate` and `adjust` each inlined twice. `core.check_event` wraps it with the fetch and the `lookup failed` warning. The window stays `[today, max_expiry]`, closed at both ends: an event today or on the expiry date is in window, the day after expiry is `after_expiry`, and anything before today is `none`. `market.vol_lookup.prices_off_forward` owns "does this leg get a forward" (forward-settled and `days_to_expiry > 0`). `VolResolver.bs_inputs` reads it, as do `positions`' three copies: forward resolution, the `fwd` column and the `--no-fetch` warning. `analysis.vrp.select_expiry` counts DTE with `models.days_to_expiry` instead of an inline copy. See [behaviors.md](docs/behaviors.md) "Earnings and ex-div windows: one owner" and "Black-Scholes inputs: one owner".
|
|
28
|
+
- **`/diff` slash command renamed to `/snapshot-diff`** (`.claude/commands/snapshot-diff.md`). The bare `/diff` name collided with Claude Code's diff-panel plugin, which refused to register and disabled its panel for the session. The `thetabook diff` CLI subcommand is unchanged.
|
|
29
|
+
- **`.claude/commands/` now passes `thetabook skills lint` with no errors.** Every command declares `name`, and the wording of `/accounts-init` and `/close` avoids ticker-shaped words beside `personal/` paths.
|
|
30
|
+
- **`skill-personal-pii-in-body` ignores the `YYYY`, `MM`, `DD` and `NNN` path placeholders.** A real ticker on the same line still fires.
|
|
31
|
+
- **`pricing/` is pure, and `greeks` aggregation moved to `portfolio/greeks_book.py`** (M26, audit item 10). `pricing/greeks.py` loaded snapshots and fetched spot, chains and dividend yields, so `pricing/` imported `market/`, `portfolio/` and `paths`, against the one-way layer rule. `aggregate_greeks`, `format_greeks_markdown`, `load_snapshot` and the equity extractors now live in `thetabook.portfolio.greeks_book`; `pricing/` keeps `bs` and `leg_greeks`, and strict mypy covers `thetabook.pricing.*`. The unused argparse `main()` is gone (`thetabook greeks` is the entry point). `validate_option_symbol` moved from `portfolio/get_positions.py` to `leg_parse.py`, beside the regex it wraps. `tests/pricing/test_layer_rule.py` fails if a `pricing` module imports a higher layer or a network library, directly (`ast`) or transitively (a fresh interpreter's `sys.modules`).
|
|
32
|
+
- **Share counts in `greeks` and `positions --equity` floor, as `adjust`'s always did** (M26, audit item 12d). They used `int()`, which truncates, so −10.5 shares showed −10 there and −11 in `adjust`. Every displayed count is now `leg_parse.whole_shares` of the exact quantity: −11 in all three, and `greeks`' TOTAL shares is the sum of the floored rows. Delta still uses the exact −10.5, and so does the check that decides whether `greeks` prints its concentration and SPY-equivalent warnings. See [behaviors.md](docs/behaviors.md) "Share legs in idea files".
|
|
33
|
+
|
|
34
|
+
### Fixed
|
|
35
|
+
|
|
36
|
+
- **`greeks` no longer crashes on an option row with no OCC symbol and no expiration date, and `adjust BRKB` finds the `BRK/B` positions** (M26, audit item 10). `greeks`, `positions` and `adjust` each read the snapshot's option rows with their own copy of the rule. A row with neither a parsable symbol nor `optionExpirationDate` was skipped by `positions` and `adjust` but kept by `greeks`, which raised `TypeError: fromisoformat: argument must be str` and printed nothing. `adjust` matched the underlying by exact string, so `adjust BRKB --close …` exited `No BRKB … position found in snapshot` on a book `greeks` showed holding `BRK/B`. One owner now: `leg_parse.snapshot_option_rows` for option rows and `models.snapshot_share_rows` for share rows, typed and `tickers.canonicalize`'d. A row missing an underlying, expiration, call/put or strike is skipped with a warning naming the command and what was missing, in all three. `adjust` canonicalizes its argument, so `adjust BRKB` reports `BRK/B`. Other visible changes from the same rule:
|
|
37
|
+
- `roll BRKB` finds the `BRK/B` short legs (it exited `No short C positions on BRKB in snapshot`).
|
|
38
|
+
- A snapshot that spells one ticker two ways, such as shares as `BRKB` and options on `BRK/B`, now shows one `BRK/B` underlying in `greeks` and `positions`. Its shares and options sit on one row, so Opt Pos and delta change and the `No price for BRK/B` warning goes away. The snapshot spot fallback (`resolve_spot`, `core.stock_price_from_snapshot`) looks a ticker up by its canonical form too, so `evaluate` / `adjust` on a `BRKB` idea find shares held under either spelling.
|
|
39
|
+
- A flat option row (long = short) is skipped before its symbol is read, so an unparseable symbol on it no longer warns.
|
|
40
|
+
|
|
41
|
+
On a book with none of these, `greeks`, `positions` and `adjust` print the same output as before. See [behaviors.md](docs/behaviors.md) "Which positions a snapshot holds: one owner".
|
|
42
|
+
- **`accounts check-idea` reads an idea's legs with the parser `evaluate` uses** (M26, audit item 9). It scanned the whole body for any line shaped like a contract with a `qty=`, while `evaluate` reads only `## Structure`. A single short XYZ 90 P plus an exit-plan line `XYZ 2027-01-15 90 P qty=+1 buy back at 50%` was one leg to `evaluate` and two to `check-idea`, which deferred a "multi-leg" structure, so an account forbidding `naked-put` raised nothing. `accounts.read_structure` now calls `leg_parse.parse_structure_body`, and the naked-leg label, the declared cover, the constructive-sale note and the cover hint all read that one parse. Share legs come through as `StockLeg`s, and long shares on the short call's underlying cover it inside `is_naked_short`. `accounts.structure_shares`, `accounts.extract_legs_from_body`, the `accounts.Leg` dataclass and `leg_parse.find_legs_in_text` are gone. **Legs written outside `## Structure` no longer count**, so an idea whose legs are only in a bullet list elsewhere now gets a new `structure` finding instead of a leg check. That finding appears when the section can't be read: on every account when the parser refuses it (say, a share line without `cost_basis=`), and on an account with a `naked-*` ban when the section is missing or lists no legs. See [behaviors.md](docs/behaviors.md) "Which legs an idea holds: one owner".
|
|
43
|
+
- **`vrp`, `em --source iv`, `evaluate` and `adjust` read one ATM implied vol** (M26, audit item 6). There were two estimators. `vrp` and `em` took the strike nearest spot with any truthy IV, which let Schwab's `-999` sentinel (`-9.99` after the chain's `/100`) through: with it on the ATM call, `vrp` read an ATM IV of −484.5% and a negative IV/HV ratio, and `em --source iv` crashed with `sigma must be non-negative (got -4.845)`. `evaluate` and `adjust` paired the nearest call and the nearest put independently, so with no IV on the ATM put they averaged the 100 call with the 105 put. `market.vol_lookup.atm_iv_from_chain` now owns the estimator for all four: among strikes within `spot ± max(10%, $5)`, the call+put straddle at the strike nearest spot where both sides carry a finite, positive IV; failing that, the nearest single usable side; ties to the lower strike. The window is in the owner so `evaluate`'s full chain and `vrp`'s windowed fetch see the same strikes. A chain with usable IV only outside it is a miss: `vrp`/`em` exit 1, and `evaluate`/`adjust` show `(flat)`. `vrp.atm_iv` is a thin wrapper over it and returns an `AtmIv` (`iv`, `strike`, `basis`) instead of a `(strike, iv)` tuple. On the 100-put-missing chain `vrp`/`em` move from 0.30 to 0.33; on the sentinel chain from −4.845 to 0.33, and `evaluate`/`adjust` from 0.30 to 0.33. **`evaluate`/`adjust` PoP and `vrp`/`em` figures can shift slightly** on any chain where the two estimators used to differ. A chain with no usable IV still exits 1 from `vrp` and `em` with the same message, now including an all-sentinel chain, which used to crash. A chain served by yfinance alone is now refused by `vrp` and `em --source iv` with a `chain came from yfinance only` warning. Before, any positive yfinance `impliedVolatility` was used, despite the documented Greeks-bearing-source contract. `fetch_chain` rows (and `thetabook chain --json`) now carry a `source` field naming the source that served them. `vrp` names the basis (`call+put avg`, `call only`, `put only`) and `em` labels a single-side IV. See [behaviors.md](docs/behaviors.md) "ATM implied vol: one owner".
|
|
44
|
+
- **`evaluate` and `adjust` now use a live spot for an option underlying even when the snapshot is fresh** (M26, audit item 2). They used the snapshot's share price while `snapshot_is_stale` said it was fresh, which only means "taken after the last 4pm ET close", and fetched only when it was stale. `greeks` and `positions` have always fetched an option underlying live (#72), so a fresh snapshot at 100 against a live 104 gave `greeks` 104 and `evaluate` `Stock price $100.00` for the same short 105 C. All four now read 104. `market.prices.resolve_spot` owns the rule for `evaluate`, `adjust`, `greeks`, `positions` and `roll`. An override (`--stock-price`, `--prices`) wins. Otherwise an option underlying is fetched live, and the snapshot price is the fallback, with a new `no live quote for XYZ; using the snapshot price …` warning. Share-only tickers keep the old rule. An underlying held only as options, with no share row, no longer makes a fresh-snapshot `evaluate` or `adjust` exit 1 with "Could not determine stock price". It gets the live quote, as the stale path and `greeks` already did. With no snapshot at all, `evaluate` now fetches instead of exiting. `evaluate` and `adjust` print the source of a live spot (`XYZ $104.00 — source: Schwab (real-time)`). `greeks` and `positions` now treat a live quote of 0 as a miss, where `greeks` used to take it. A zero or negative override (`--prices XYZ=0`, `--stock-price 0`) now leaves the ticker unpriced, with a warning: `greeks` skips its option Greeks, and `evaluate` / `adjust` exit 1. Before, it reached Black-Scholes and crashed with `ValueError: math domain error` whenever the underlying had options. With XYZ held in two accounts whose snapshot rows imply different prices, the snapshot fallback in `greeks` and `positions` (`--no-fetch`, or a live miss) now takes the first account's row, as `evaluate`, `adjust` and `greeks`' own share extraction already did. Before, it took the last. `market.prices.parse_prices` is the one `--prices` parser, replacing copies in `evaluate` and `greeks`, with the same warnings. `em` and `vrp` are unchanged. See [behaviors.md](docs/behaviors.md) "Which spot an option position is valued at: one owner".
|
|
45
|
+
- **Every command reads the same "latest" snapshot** (M26, audit item 12c). There were four loaders with four error policies, and only `thetabook snapshot` and `accounts totals` / `check-portfolio` had the worktree fallback to the main repo's `personal/snapshots/latest.json`. From a worktree with no `latest.json` of its own, `evaluate`, `adjust`, `roll`, `greeks`, `positions` and the per-account checks saw no snapshot while `thetabook snapshot` reported one. `paths.load_snapshot` is now the one loader, and each caller picks its policy for a missing or corrupt file: `raise` (`evaluate`, `adjust`, `roll`, `diff`), `warn` (per-account checks) or `exit` (`greeks`, `positions`, `accounts totals`, `check-portfolio`). A corrupt snapshot under `greeks` or `positions` prints one `Error:` line instead of a traceback. An explicit `$THETABOOK_HOME` now switches the worktree fallback off. Before, a worktree run with `THETABOOK_HOME` pointing at an empty home read the main repo's real snapshot from `thetabook snapshot` and `accounts totals` while `--date` read the empty home. See [behaviors.md](docs/behaviors.md) "Loading a snapshot: one owner".
|
|
46
|
+
- **`roll` prices off the shared owners for marks, IV, dividend yield and Black-Scholes inputs** (M26, audit item 5). `roll` (`ideas/roll_scenarios.py`) had private copies of each, and they broke on rows the owners already handle. A `0.0` chain IV, common on yfinance, raised `ZeroDivisionError`. Schwab's `-999` no-IV sentinel printed `IV=-999.0%` and a `BS model net: +77.95/sh` on a $2.60 option. A missing bid became a fake mid, so bid 0 / ask 2.70 read as 1.35. Per leg, `roll` now uses:
|
|
47
|
+
- `core.chain_pick` for the mark (mid, else last trade);
|
|
48
|
+
- `VolResolver.resolve_leg_iv` for IV;
|
|
49
|
+
- `market.dividends.resolve_div_yield` for `q`, with `--div-yield` as the override;
|
|
50
|
+
- `VolResolver.bs_inputs` for the BS price and `q`.
|
|
51
|
+
|
|
52
|
+
The two bad-IV rows above now price at the flat `[market] fallback_vol`, read `IV=25.0% (flat default)`, give a BS net of −0.06/sh, and warn. What still errors and what now falls back:
|
|
53
|
+
- **Exits 1, as before:** a requested `--open` or `--close` strike with no chain row at all, which is usually a typo (unless it's a closing strike the snapshot holds, which takes the snapshot's mark); a live expiry whose chain is empty or whose fetch failed; `--open` at a past expiry. A `--also` strike with no row is still skipped with a warning, but the `Option A (...)` label no longer names it. With no `--also` strike on the chain, the comparison is skipped with a warning, where it used to print an empty grid.
|
|
54
|
+
- **Falls back, labelled and warned:** a row with zero or sentinel IV takes the flat IV. A row with no bid/ask takes the last trade, then the snapshot's mark for a closing leg, then a Black-Scholes estimate, or intrinsic for a leg expiring today.
|
|
55
|
+
- **Settles:** a closing leg past expiry settles through `core.Settler`, as in `adjust`: intrinsic at the expiry-date close, or spot with a warning. That fixed amount is its close cost across the grid, and neither the chain nor the snapshot is asked. A short 95 C that expired yesterday with spot at 100 and a stale 0.40 snapshot mark reads as a −3.90/sh debit. `main` exited 1 on it.
|
|
56
|
+
|
|
57
|
+
A dividend payer is priced with its fetched yield, shown as `Div yield: 3.1% (auto)`. It was `q = 0`. A VIX roll prices each leg off its expiry's parity forward with `q = r` and names the forward. It priced off spot. `load_positions_for_underlying` moves from `adjust` into `ideas/core.py`, and `adjust` re-exports it, so `roll_scenarios` no longer imports from `adjust` or `evaluate_idea`. Leg rows now read `mark=… (source) IV=… (source)`, and the cost line reads `Market roll cost (N leg(s) not at chain mid)` when a leg wasn't marked at mid. See [behaviors.md](docs/behaviors.md) "`roll` inputs: on the shared owners".
|
|
58
|
+
- **`evaluate --days` prices VIX legs off the forward** (M26). The mid-curve priced each leg off spot with the dividend yield, while the same run's Greeks and PoP used the parity forward with `q = r` (Black-76). On a long VIX 15C marked at its 3.98 mid against an 18.40 forward, T+0 at spot read −$187.18 instead of ≈ $0. Each row's spot `p` now prices off `p · F/S`. `VolResolver.bs_inputs` is the one owner of which price and `q` a leg's Black-Scholes takes. It replaces copies in `compute_greeks`, `adjust` (`leg_underlying_px` is now `leg_bs_inputs`, which also returns `q_eff`) and `aggregate_greeks`. `days_to_expiry` moves to `models.py`, replacing two definitions and eight inline copies (audit item 12b). See [behaviors.md](docs/behaviors.md) "Black-Scholes inputs: one owner".
|
|
59
|
+
- **`evaluate` settles option legs past expiry, as `adjust` does** (M26). `evaluate` kept an expired leg in its payoff, extremes, breakevens, Greeks, marks walk and price domain. An expired short 150 P beside a 30-day 160/170 call spread at S = 160 read max loss −$15,050, while `adjust` read −$50 for the same legs: the spread's −$250 debit plus the put's +$200, which expired worthless. `core.settle_position` now owns the split for both commands, built on `core.Settler` / `settle_into`. An in-the-money equity or ETF leg becomes its share delivery, and anything else becomes cash at intrinsic on the expiry-date close. The option itself drives nothing. Both commands now read −$50 / +$950 / PoP 48.9% / DTE 30 on that position. A new `Settled legs` row names each settled leg, what it was settled against and what it became. The spot fallback warns as it does in `adjust`. A live-marks run measures from today, so it leaves settled cash out. The expired leg is no longer walked for a quote, so it can't turn a run `live-with-misses`. A position whose every leg has expired evaluates as its realized cash and any delivered shares. The write-once `max_gain` / `max_loss` budget comes from the structure alone: the open legs plus any delivered shares, never settled cash. Every budget writer (first seed, `--reseed-budget`, the ±inf heal, the #99 migration) reads it. Before, a naked short AAPL 200 C that expired worthless healed its `-.inf` budget to `max_loss: 300.0`, the realized profit, which `check_idea` then sized as a $300 loss. An SPX position seeded −$10,000 frozen and −$2,000 live; both modes now seed −$2,000. Share legs net per underlying before the budget is measured (`core.open_structure`), so shares a delivery closed carry their locked-in P&L into neither extreme. A covered call called away beside an open 160/170 call spread seeded `max_loss: 0.0` and can now bind at −$250. With every leg settled and nothing open after netting, the budget is left as it is, `--reseed-budget` included, and the run says so. A budget `max_loss` is never written above $0. The #99 migration is skipped while a leg is settled. `evaluated_max_*` keep the settled cash. `check_idea` now reads a positive `evaluated_max_loss` as no loss, where its `abs()` used to make that a loss. The double-count hint for shares listed beside a delivery now tells a delivery that adds to them from a covered call called away. See [behaviors.md](docs/behaviors.md) "Expired legs in `evaluate` and `adjust`: one owner".
|
|
60
|
+
- **`evaluate` and `adjust` agree on which expiry sets a position's horizon** (M26). `evaluate` took the first-*listed* option leg for its DTE row, ATM IV, forward and PoP `T`, while `adjust` and `evaluate --days DTE` took the shortest-dated leg. A put diagonal (long 100 P at 120 DTE, short 95 P at 30 DTE) read DTE 120 / PoP 36.9% or DTE 30 / PoP 26.7% depending on which line was written first. `core.position_horizon` now owns the choice, the shortest-dated leg that hasn't expired, and all three callers use it. A leg past expiry no longer becomes `evaluate`'s horizon or pins `--days DTE` at 0. See [behaviors.md](docs/behaviors.md) "Position horizon: one owner".
|
|
61
|
+
|
|
62
|
+
- **`adjust --save` budgets no longer include the roll's realized P&L** (M26, audit item 8). `--save` wrote the after-scenario's max profit and max loss into the write-once `max_gain` / `max_loss` budget and into `evaluated_max_*`. Those figures include the closed leg's realized P&L and any cash from legs that settled at expiry, but the saved `## Structure` carries neither. The first `evaluate` of the file measured the Structure alone and disagreed. Write-once and the `analytic` stamp then kept the wrong budget for the life of the file. A roll that realized −$250 and opened a short 95 P at $2.00 saved `max_loss: -9550.0`, and `evaluate` measured −$9,300. It now saves −$9,300 / +$200, and the first `evaluate` leaves both pairs as written. The realized P&L now appears in the file's `## Context` as a `Realized:` line, with the leg each amount came from. `adjust`'s before/after table still includes it. A `--save` that leaves nothing open writes a blank budget, where it used to seed the realized P&L as both `max_gain` and `max_loss`. `core.structure_budget` is the one owner of the budget, shared by `evaluate` and `adjust --save`. `save_as_idea` no longer takes the `before` / `after` scenarios. See [behaviors.md](docs/behaviors.md) "The risk budget of a structure: one owner".
|
|
63
|
+
- **`adjust --save` no longer rounds half strikes** (M26). Strikes were written with `{strike:.0f}`, which rounds half to even, so a roll into a 52.5 put was saved as a 52 put (7.5 → 8, 22.5 → 22). The next `evaluate` priced a contract nobody holds, and that file seeded the write-once `max_gain` / `max_loss` budget. Labels disagreed the same way: `positions` showed 52.5 while `evaluate` and `adjust` showed 52, and `roll-scenarios` truncated with `int()`. `leg_parse.format_option_line` is now the one writer of an option Structure line, and `leg_parse.contract_label` / `format_strike` the one label and strike formatter, used by every command. See [behaviors.md](docs/behaviors.md) "Writing and labelling an option leg".
|
|
64
|
+
- **`positions` derives a VIX forward at the run's rate.** `options_book.resolve_forwards` called `VolResolver.resolve_forward` without a rate, so it took that method's own `0.045` default, while `evaluate --rate 0.05` discounted parity at 5%. The same leg could read two forwards, and so two cushions. `resolve_forward` no longer has a rate default, so every caller must pass one.
|
|
65
|
+
- **`adjust` values contracts at or past expiry correctly.** Three connected defects, all in `ideas/adjust.py`:
|
|
66
|
+
- A contract **past expiry** now settles at intrinsic on the **expiry-date close**, read from the historical-bars backbone (`market.bars.close_on`). An in-the-money contract on an equity or ETF is physically settled, so it becomes its **share delivery** at the strike, premium in the basis (`core.delivery_leg`). Only cash-settled index roots (`tickers.is_cash_settled`) and out-of-the-money contracts become cash. Before, a closing or assigned leg used the snapshot's pre-expiry mark and an opening leg was priced at $0. A short AAPL 150 P (avg $2.00, snapshot mark $0.40) that expired with AAPL at $160 realized $160 and a $40 debit. It now realizes $200 with no debit, in both `--marks` modes. With no expiry close it settles against today's spot and warns. This replaces #106's "past expiry, so not quoted" warning, which said the price was wrong without fixing it.
|
|
67
|
+
- A contract **expiring today** with no chain quote is priced at **intrinsic** (Black-Scholes at `T = 0`; premium source `intrinsic`, was `none`). It was $0, which understated a short 190 C with spot at $200 by $1,000 a contract.
|
|
68
|
+
- An **expired option no longer drives the scenario.** The shortest-expiry pick chose it, so a negative DTE floored the horizon at one day, ATM IV was looked up on a chain that no longer exists, and its payoff was integrated over an `S_T` it can't reach. A worthless expired short 150 P beside a 30-day call spread read PoP 100.0% (83.2% settled), max loss −$14,620 (−$620) and a phantom breakeven at $146.20. It is now replaced by what it became: delivered shares, or a cash constant in the realized offset. The option itself sets no horizon, IV, forward, extremes or Greeks.
|
|
69
|
+
|
|
70
|
+
Premium source `expired` is now `settlement`. `--save` writes a delivery as its share line and a cash settlement to `## Context`. `--close` of an in-the-money equity option past expiry warns that it was delivered, not closed, and `--assign` of one that expired worthless warns that it wasn't assigned. Tests stub the close via `args._close_fetcher`, `Settler(close_fetcher=...)` or the new autouse `bars.close_on` stub. See [behaviors.md](docs/behaviors.md) "Contracts at or past expiry in `adjust`".
|
|
71
|
+
|
|
72
|
+
- **`adjust --assign` no longer counts the put premium twice.** It added the put's close-at-mark P&L, `qty × 100 × (mark − premium)`, to the realized offset *and* folded the premium into the share basis. Assignment delivers shares at the strike and doesn't buy the put back, so in `effective` mode nothing else is realized, and in `strike` mode only the premium is. A short 520 P (avg $4.00, mark $2.50) showed a phantom +$150. Assigned past expiry at a $10.00 settlement, a short 150 P showed a phantom −$800, moving the breakeven from $144 to $148. The closing line now reads `**Assigned:**` and says what was booked. The put's mark is no longer asked for, since nothing uses it: a live run whose lookup for it missed used to read `frozen-fallback` and warn about a stale mark that appeared nowhere in the output.
|
|
73
|
+
- **`adjust --assign` refuses cash-settled index roots.** An expired in-the-money SPX 6000 P (close $5,900) was assigned into +100 "shares" of the index at $5,980, a −$598,000 max loss beside the before column's −$8,000 cash settlement. `tickers.CASH_SETTLED` also gains the roots a CSV import can carry as the underlying: NDXP, RUTW, VIXW and XND, beside SPXW. `market_symbol` now sends each to its index (`SPXW` → `$SPX`, `NDXP` → `$NDX`), so its expiry close, quote and chain are found rather than falling back to spot, and VIXW is forward-settled like VIX.
|
|
74
|
+
- **`bars.close_on` no longer stops at a tail source that lacks the date.** `get_bars` keeps the first tail source with any rows, so Schwab returning the days around an expiry but not the expiry itself ended the cascade, and the contract settled against today's spot. `_fetch_tail(require=day, after=source)` re-asks only the sources after the one that answered, and counts one only if it has a positive close for that date.
|
|
75
|
+
|
|
76
|
+
- **`thetabook skills lint`, `render-readme` and `show` no longer crash on a skill that fails schema validation.** A file missing `name` raised an uncaught pydantic `ValidationError` and stopped the run. It's now reported per file, naming the bad field.
|
|
77
|
+
- **One marks label, derived from the legs, instead of six places answering
|
|
78
|
+
"is this run live?"**
|
|
79
|
+
([#104](https://github.com/subsriram/thetabook/issues/104)). `evaluate`
|
|
80
|
+
decided whether a run was live in five places that could disagree, and
|
|
81
|
+
`adjust` added a sixth. Two opposite regressions inside one PR came from
|
|
82
|
+
exactly that: shares re-marking to spot under a label claiming entry
|
|
83
|
+
(−$17,272 on a covered call against −$17,000 live and −$14,772 frozen, in
|
|
84
|
+
the number `max_position_pct` is enforced against), and then the per-leg
|
|
85
|
+
marks table disappearing on a partial chain miss — the one case where its
|
|
86
|
+
`src` column is worth reading.
|
|
87
|
+
|
|
88
|
+
`core.apply_marks` now walks every leg once, stamps each leg's
|
|
89
|
+
`mark_source`, and `core.label_for` *derives* the run's label from what it
|
|
90
|
+
stamped. `frozen-fallback` became "no leg carries a live source" — a fact
|
|
91
|
+
about the legs rather than a branch computed beside the share gate, which
|
|
92
|
+
is the seam that produced the first regression. Shares are just another leg
|
|
93
|
+
the walk visits, and the walk commits **one baseline for the whole position
|
|
94
|
+
or none**.
|
|
95
|
+
|
|
96
|
+
Visible fix: the stdout banner printed the *requested* mode, so a run whose
|
|
97
|
+
chain lookups all failed said `Marks: live` above a table and a frontmatter
|
|
98
|
+
that both said `frozen-fallback`. Banner, metric row and frontmatter now
|
|
99
|
+
read one derived value, and `core.marks_cell` is the single owner of when
|
|
100
|
+
the bid/mid/ask pick gets named. `adjust` had the same defect and now
|
|
101
|
+
reports what resolved (`frozen-fallback` when every quote fell back to the
|
|
102
|
+
snapshot and Black-Scholes) rather than what was asked for.
|
|
103
|
+
|
|
104
|
+
One question deliberately survives separately: whether live was
|
|
105
|
+
*requested*, which still gates whether a per-leg marks table exists at all.
|
|
106
|
+
Collapsing it into the label is the second regression above.
|
|
107
|
+
|
|
108
|
+
`adjust`'s retained legs keep measuring from their cost basis — that frame
|
|
109
|
+
is what makes its before/after comparison apples to apples, and it is why
|
|
110
|
+
its max loss agrees with `evaluate --marks frozen`. Re-marking them to now
|
|
111
|
+
while `realized_offset` still measured from entry would rebuild the same
|
|
112
|
+
two-baseline blend on the other side; the snapshot-derived legs are now
|
|
113
|
+
stamped `frozen` to say so.
|
|
114
|
+
|
|
115
|
+
Follow-ups from review. `evaluate`'s assignment-risk check measured
|
|
116
|
+
extrinsic against `leg.premium`, which on a frozen or fallback run is the
|
|
117
|
+
entry premium. It now takes today's chain mid, as `adjust` already did,
|
|
118
|
+
through one shared `core.assignment_mark_for`. In `adjust`, a leg past
|
|
119
|
+
expiry, opened or closed, no longer asks the chain or counts as a miss, so
|
|
120
|
+
modelling an assignment the day after expiry doesn't read as an outage. It
|
|
121
|
+
warns instead that the price it used (the snapshot's pre-expiry mark for a
|
|
122
|
+
close, $0 for an open) is not the settlement value. One expiring today
|
|
123
|
+
still asks, and its miss still counts. A degraded label warns on stderr as
|
|
124
|
+
it does in `evaluate`, naming each leg that fell back. In the per-leg marks
|
|
125
|
+
table, a `stale` option leg shows no current mark and stays out of Net MTM
|
|
126
|
+
rather than counting as $0; shares keep their drift, which spot makes
|
|
127
|
+
exact. The "usable chain mark"
|
|
128
|
+
rule now lives once, in `core.chain_pick`, for `evaluate`'s walk and both
|
|
129
|
+
of `adjust`'s resolvers, and a marks mode other than `live` / `frozen` is
|
|
130
|
+
refused by the walk itself as well as by `--marks`.
|
|
131
|
+
|
|
8
132
|
## [2.3.0] — 2026-11-01
|
|
9
133
|
|
|
10
134
|
The first release since v2.2.3. It adds a backtester for systematic
|
|
@@ -35,10 +35,10 @@ thetabook/
|
|
|
35
35
|
├── docs/ # see docs/README.md — index + which file owns what
|
|
36
36
|
├── pyproject.toml # project metadata + [project.scripts] = thetabook
|
|
37
37
|
├── src/thetabook/ # the package (has its own CLAUDE.md — layer boundaries)
|
|
38
|
-
│ ├── pricing/ # pure math: Black-Scholes, Greeks
|
|
38
|
+
│ ├── pricing/ # pure math: Black-Scholes, one leg's Greeks
|
|
39
39
|
│ ├── market/ # data sources + caches (Schwab → Massive → defeatbeta → yfinance)
|
|
40
40
|
│ ├── analysis/ # derived signals: HV, TA, expected move, VRP, scenario lookup
|
|
41
|
-
│ ├── portfolio/ # snapshot I/O, CSV import, options
|
|
41
|
+
│ ├── portfolio/ # snapshot I/O, CSV import, Greeks + options books, per-account rules, scaffold
|
|
42
42
|
│ ├── ideas/ # trade-idea workflow (manage / evaluate / adjust / roll)
|
|
43
43
|
│ ├── backtest/ # hypothetical strategy backtests + live signal (one code path)
|
|
44
44
|
│ ├── wiki/ # personal/wiki/ lint + auto-rendered ideas roll-up
|
|
@@ -203,7 +203,7 @@ Configuration lives in `pyproject.toml`. Active rule packs: `E, W, F, I, B, UP,
|
|
|
203
203
|
|
|
204
204
|
## Mypy
|
|
205
205
|
|
|
206
|
-
Permissive baseline by default (no `disallow_untyped_defs`); strict in modules that are clean today (currently `
|
|
206
|
+
Permissive baseline by default (no `disallow_untyped_defs`); strict in modules that are clean today (currently `pricing/*`, `config.py` and `backtest/{engine,signals,metrics,manifest}.py` — list lives in `[[tool.mypy.overrides]]`). Tests are excluded from mypy. With pydantic models everywhere post-M17, fixture types are clear at the call site; ad-hoc test typing isn't worth the churn.
|
|
207
207
|
|
|
208
208
|
When mypy flags something, prefer fixing the underlying type over adding `# type: ignore`. If you do suppress, use a specific code (`# type: ignore[arg-type]`) and a one-line reason. Never invent fallback branches just to satisfy the type checker — if an upstream contract already excludes the unsafe case, prefer a walrus filter, an `assert` with rationale, or a typed ignore over a defensive code path that's dead at runtime.
|
|
209
209
|
|
|
@@ -170,8 +170,8 @@ Quick lookups anytime — no review session needed:
|
|
|
170
170
|
- **`/price AAPL SPY`** — fetch current stock prices (Schwab → Massive → yfinance cascade)
|
|
171
171
|
- **`/chain AAPL`** — list available option expirations with DTE
|
|
172
172
|
- **`/chain AAPL 2026-06-20 puts 240-260`** — filtered option chain with bid/ask, IV, volume, OI (and Greeks when available from Schwab/Massive)
|
|
173
|
-
- **`/diff`** — compare latest snapshot vs. previous: positions added/removed, price moves, account value change
|
|
174
|
-
- **`/diff 2026-04-10`** — compare a specific date against latest
|
|
173
|
+
- **`/snapshot-diff`** — compare latest snapshot vs. previous: positions added/removed, price moves, account value change
|
|
174
|
+
- **`/snapshot-diff 2026-04-10`** — compare a specific date against latest
|
|
175
175
|
|
|
176
176
|
In between reviews, use **`/ideas`** to browse:
|
|
177
177
|
|
|
@@ -197,12 +197,14 @@ In between reviews, use **`/ideas`** to browse:
|
|
|
197
197
|
| `/greeks` | Portfolio-level Greeks (delta, gamma, theta, vega) outside a review |
|
|
198
198
|
| `/price <tickers>` | Fetch current stock prices (Schwab → Massive → yfinance) |
|
|
199
199
|
| `/chain <ticker>` | Fetch option chain: expirations, strikes, bid/ask, IV, Greeks |
|
|
200
|
-
| `/diff [dates]`
|
|
200
|
+
| `/snapshot-diff [dates]` | Compare two snapshots: positions added/removed/changed, balance moves |
|
|
201
201
|
| `/accounts-init` | Scaffold `personal/accounts.toml` from latest snapshot (label each type)|
|
|
202
202
|
| `/wiki-lint` | Health check on the wiki (orphan ideas, stale stats, drift, missing) |
|
|
203
203
|
| `/backtest` | Hypothetical strategy backtest, parameter grid, or this period's signal |
|
|
204
204
|
|
|
205
205
|
> **Note on `/review`:** that name is taken by a Claude Code built-in (GitHub PR reviewer). Use `/portfolio` for portfolio review.
|
|
206
|
+
>
|
|
207
|
+
> **Note on `/diff`:** snapshot comparison moved to `/snapshot-diff`, so `/diff` no longer compares snapshots in this project.
|
|
206
208
|
|
|
207
209
|
## CLI reference
|
|
208
210
|
|
|
@@ -333,11 +335,11 @@ On transient failures (timeout / connection reset / 5xx), `fetch_prices_massive`
|
|
|
333
335
|
|
|
334
336
|
### Snapshot freshness
|
|
335
337
|
|
|
336
|
-
`snapshot_is_stale` compares a snapshot's `fetched_at` timestamp against the **most recent 4pm ET close on a Mon–Fri**, not the calendar date. A snapshot taken Friday after close stays fresh through the weekend and Monday pre-market; it only becomes stale once Monday's 4pm close passes. This matches how prices actually move — markets don't move overnight or on weekends — so `/greeks
|
|
338
|
+
`snapshot_is_stale` compares a snapshot's `fetched_at` timestamp against the **most recent 4pm ET close on a Mon–Fri**, not the calendar date. A snapshot taken Friday after close stays fresh through the weekend and Monday pre-market; it only becomes stale once Monday's 4pm close passes. This matches how prices actually move — markets don't move overnight or on weekends — so `/greeks` doesn't over-eagerly refetch equity-only tickers on Saturday mornings. Freshness doesn't gate an option underlying's spot: every command fetches that live (see below). Caveat: NYSE holidays aren't tracked, so a Wednesday-evening snapshot may be flagged stale on Thanksgiving morning. Run `/refresh` manually if in doubt.
|
|
337
339
|
|
|
338
340
|
### Price provenance in `greeks` and `positions`
|
|
339
341
|
|
|
340
|
-
Option Greeks are far more price-sensitive than equity delta — a couple of dollars on a near-ATM strike flips the ITM flag and swings delta/theta — so `thetabook greeks` and `
|
|
342
|
+
Option Greeks are far more price-sensitive than equity delta — a couple of dollars on a near-ATM strike flips the ITM flag and swings delta/theta — so `thetabook greeks`, `positions`, `evaluate` and `adjust` **always re-price option underlyings live**, even when the snapshot is fresh (`market.prices.resolve_spot` owns the rule; the snapshot price is only the fallback). Equity-only tickers keep the cheaper gap-fill-only path. Both commands render a `Src` column and a freshness label (`live` / `prev-close` / `delayed` / `manual` / `snapshot <date>`) so a Massive previous-close or a snapshot fallback can't masquerade as a live quote. Details in [docs/behaviors.md](docs/behaviors.md).
|
|
341
343
|
|
|
342
344
|
### Backtests
|
|
343
345
|
|
|
@@ -371,7 +373,7 @@ thetabook/
|
|
|
371
373
|
│ ├── __init__.py # exposes REPO_ROOT, PERSONAL_DIR, SNAPSHOTS_DIR, IDEAS_DIR, …
|
|
372
374
|
│ ├── CLAUDE.md # layer boundaries + import direction (loaded when editing here)
|
|
373
375
|
│ ├── models.py # pydantic v2 models: OptionLeg/StockLeg, Snapshot family, IdeaFrontmatter
|
|
374
|
-
│ ├── leg_parse.py #
|
|
376
|
+
│ ├── leg_parse.py # leg parsers + writers: OCC, ## Structure bodies, CLI specs, snapshot rows
|
|
375
377
|
│ ├── paths.py # $THETABOOK_HOME resolution + token/.env/snapshot lookup
|
|
376
378
|
│ ├── preflight.py # credential + settings checks (hard require_* / soft resolve_*)
|
|
377
379
|
│ ├── config.py # project-wide defaults from personal/config.toml
|
|
@@ -379,15 +381,16 @@ thetabook/
|
|
|
379
381
|
│ ├── tickers.py # ticker alias dictionary (BRKB → BRK/B) + user overrides
|
|
380
382
|
│ ├── log.py # stderr logging (warn / error / info / note)
|
|
381
383
|
│ │
|
|
382
|
-
│ ├── pricing/ # math
|
|
384
|
+
│ ├── pricing/ # pure math — no I/O, nothing from a higher layer
|
|
383
385
|
│ │ ├── bs.py # Black-Scholes (pricing, Greeks, implied vol w/ Brent fallback)
|
|
384
|
-
│ │ └──
|
|
386
|
+
│ │ └── leg_greeks.py # one leg's dollar Greeks (BS or broker, × qty × 100)
|
|
385
387
|
│ │
|
|
386
388
|
│ ├── market/ # market-data sources + caches
|
|
387
389
|
│ │ ├── _schwab.py # shared Schwab client factory (soft credential resolve)
|
|
388
|
-
│ │ ├── prices.py # stock prices (Schwab → Massive → yfinance)
|
|
390
|
+
│ │ ├── prices.py # stock prices (Schwab → Massive → yfinance), freshness, resolve_spot
|
|
389
391
|
│ │ ├── chains.py # option chains (same cascade)
|
|
390
|
-
│ │ ├── vol_lookup.py # per-leg IV, ATM IV, leg marks (shared cache)
|
|
392
|
+
│ │ ├── vol_lookup.py # per-leg IV, ATM IV, leg marks, Black-Scholes inputs (shared cache)
|
|
393
|
+
│ │ ├── leg_inputs.py # one leg's Greek inputs (IV, forward, q, validated broker Greeks)
|
|
391
394
|
│ │ ├── leg_marks.py # fetch_leg_mark + pick_mark (conservative/mid)
|
|
392
395
|
│ │ ├── earnings.py # upcoming-earnings lookup (7-day on-disk cache)
|
|
393
396
|
│ │ ├── dividends.py # yield + next ex-div lookup (7-day on-disk cache)
|
|
@@ -407,6 +410,7 @@ thetabook/
|
|
|
407
410
|
│ │ │ ├── __init__.py # REGISTRY + detect_and_parse() dispatch
|
|
408
411
|
│ │ │ ├── _base.py # BrokerCsvParser ABC + shared helpers
|
|
409
412
|
│ │ │ ├── schwab.py / fidelity.py / empower.py
|
|
413
|
+
│ │ ├── greeks_book.py # portfolio-level Greeks aggregation behind `thetabook greeks`
|
|
410
414
|
│ │ ├── options_book.py # effective options book behind `thetabook positions`
|
|
411
415
|
│ │ ├── diff_snapshots.py # compare two snapshots
|
|
412
416
|
│ │ ├── accounts.py # per-account risk rules + tax notes
|
|
@@ -503,7 +507,7 @@ thetabook/
|
|
|
503
507
|
├── setup.md / refresh.md / portfolio.md
|
|
504
508
|
├── idea.md / ideas.md / evaluate.md / adjust.md
|
|
505
509
|
├── open.md / close.md / roll.md / roll-scenarios.md
|
|
506
|
-
├── greeks.md / price.md / chain.md / diff.md
|
|
510
|
+
├── greeks.md / price.md / chain.md / snapshot-diff.md
|
|
507
511
|
├── accounts-init.md / wiki-lint.md
|
|
508
512
|
├── backtest.md
|
|
509
513
|
```
|
|
@@ -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-11-
|
|
7
|
+
Last updated: 2026-11-21 | Current: v2.4.0 | Release notes: [CHANGELOG.md](CHANGELOG.md)
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -12,6 +12,15 @@ Last updated: 2026-11-01 | Current: v2.3.0 | Release notes: [CHANGELOG.md](CHANG
|
|
|
12
12
|
|
|
13
13
|
Items shipped with their originating commit. Listed newest first.
|
|
14
14
|
|
|
15
|
+
### v2.4.0 — M26: one owner per duplicated rule
|
|
16
|
+
Fourteen PRs ([#126](https://github.com/subsriram/thetabook/pull/126)–[#139](https://github.com/subsriram/thetabook/pull/139)), each moving one rule that two or more commands computed separately to a single owner. Each PR added a test that the former callers agree. **2874 tests pass, ruff + mypy clean.**
|
|
17
|
+
|
|
18
|
+
- **Numbers that change.** `thetabook greeks` defaults to broker Greeks, with a dividend yield per ticker. Broker rows that fail sanity checks are recomputed with Black-Scholes, and VIX always uses Black-76. `evaluate` and `adjust` value option underlyings at a live spot. `adjust --save` budgets from the structure alone, and `evaluate` settles expired legs as `adjust` does. All four ATM-IV callers use one straddle estimator inside one strike window.
|
|
19
|
+
- **Crashes and silent errors fixed.** `roll` no longer crashes on zero or `-999` IV. `vrp` and `em` no longer quote a negative IV. `greeks` no longer crashes on a row with no expiry. `adjust --save` no longer rounds 52.5 strikes to 52. `check-idea` no longer lets an exit-plan line hide a naked put.
|
|
20
|
+
- **Structure.** `pricing/` is pure: `aggregate_greeks` moved to `portfolio/greeks_book.py`, and `tests/pricing/test_layer_rule.py` fails the build on any upward import. Pricing defaults live in `config.py` (`[market] rate`, `fallback_vol`, `fallback_div_yield`).
|
|
21
|
+
|
|
22
|
+
The rule → owner table is in [docs/duplicated-rules-audit.md](docs/duplicated-rules-audit.md#outcome).
|
|
23
|
+
|
|
15
24
|
### v2.3.0 — hypothetical strategy backtests + share legs + closed-form risk
|
|
16
25
|
A new workflow layer and a run of fixes that change what `evaluate` records. **2377 tests pass, ruff + mypy clean.**
|
|
17
26
|
|
|
@@ -130,6 +139,20 @@ Eleven releases from v1.2.0 (workflow + analytics polish) through v1.8.2 (Schwab
|
|
|
130
139
|
|
|
131
140
|
## Pending — high priority
|
|
132
141
|
|
|
142
|
+
### ~~M26. Consolidate duplicated rules — one owner per rule, one PR each~~ — **shipped in v2.4.0 ([#126](https://github.com/subsriram/thetabook/pull/126)–[#139](https://github.com/subsriram/thetabook/pull/139))**
|
|
143
|
+
Every rule below now has one owner, and `pricing/` imports nothing above itself; [tests/pricing/test_layer_rule.py](tests/pricing/test_layer_rule.py) enforces that. The outcome table (rule → PR → owner) and what was left open are in [docs/duplicated-rules-audit.md](docs/duplicated-rules-audit.md#outcome). The user-visible changes are in [CHANGELOG.md](CHANGELOG.md) under 2.4.0.
|
|
144
|
+
|
|
145
|
+
A 2026-11-14 scan had found a dozen rules that two commands answered with separate code, and that already disagreed:
|
|
146
|
+
- `adjust --save` rounds 52.5 strikes to 52
|
|
147
|
+
- `evaluate` uses the morning snapshot spot while `positions` uses live
|
|
148
|
+
- `greeks` and `evaluate` give different deltas for the same leg
|
|
149
|
+
- `evaluate`'s PoP depends on the order legs are listed
|
|
150
|
+
- `roll-scenarios` crashes on zero IV
|
|
151
|
+
- `vrp` / `em` can quote a negative ATM IV
|
|
152
|
+
- `greeks`, `positions` and `roll` price at a dividend yield of 0 while `evaluate` auto-fetches it, and the rate / vol defaults are copied into 7+ places
|
|
153
|
+
|
|
154
|
+
The original findings, evidence and phased PR order are kept in the audit as a historical record. Supersedes nothing: the deferred "Extract shared analytics into `analytics.py`" below is a module move, while M26 fixes individual rules.
|
|
155
|
+
|
|
133
156
|
### M7. Tax-lot awareness — **blocked on Schwab**, revisit when API improves
|
|
134
157
|
Natural follow-on to v1.2.5's per-account rules. Surface during `/portfolio` for any position being considered for close: wash-sale risk, ST vs. LT, lots near LT crossover. Critical in taxable accounts, irrelevant in IRA.
|
|
135
158
|
|
|
@@ -246,7 +269,7 @@ Proposed during the v1.6.2 /portfolio friction review as wrappers around "find t
|
|
|
246
269
|
The v1.7.x slash-command audit (PR #25) re-raised this: [portfolio.md](.claude/commands/portfolio.md) step 5 and [open.md](.claude/commands/open.md) step 6 both create `personal/journal/YYYY-MM-DD.md` from `templates/journal.md` with date substitution — same template-copy + sed pattern in two places. A `thetabook journal new` (or, lighter-weight, a `--touch` flag on `thetabook snapshot` that creates today's journal as a side effect of the snapshot freshness check) would collapse both. **Recommendation: still defer.** Two callers of a `cp` + `sed` is below the threshold for a CLI; the duplication is a one-line bash recipe in each slash command. Revisit only if a real templating need emerges (journal frontmatter, placeholder substitution like `manage_ideas.py` does for ideas) — at that point a CLI starts pulling its weight.
|
|
247
270
|
|
|
248
271
|
### `thetabook diff --last-week` / `--last-month` / `--vs N-days-ago`
|
|
249
|
-
[diff.md](.claude/commands/diff.md) accepts user input like "last week" or "previous" but the underlying CLI only takes ISO dates, so Claude has to do the calendar math + `ls personal/snapshots/` to resolve the relative form. Native `--last-week` / `--last-month` / `--vs N-days-ago` flags on `thetabook diff` would push the resolution down into Python (deterministic, testable, market-hours-aware via `last_market_close()`). Surfaced by the v1.7.x slash-command audit (PR #25). **Recommendation: defer.** The calendar math is one-line and Claude rarely gets it wrong. Revisit if the user starts running diff with relative ranges frequently and the date-resolution step shows up as friction in a real session.
|
|
272
|
+
[snapshot-diff.md](.claude/commands/snapshot-diff.md) accepts user input like "last week" or "previous" but the underlying CLI only takes ISO dates, so Claude has to do the calendar math + `ls personal/snapshots/` to resolve the relative form. Native `--last-week` / `--last-month` / `--vs N-days-ago` flags on `thetabook diff` would push the resolution down into Python (deterministic, testable, market-hours-aware via `last_market_close()`). Surfaced by the v1.7.x slash-command audit (PR #25). **Recommendation: defer.** The calendar math is one-line and Claude rarely gets it wrong. Revisit if the user starts running diff with relative ranges frequently and the date-resolution step shows up as friction in a real session.
|
|
250
273
|
|
|
251
274
|
### Slash-command drift risks (open.md / wiki-update blocks / portfolio.md / idea.md)
|
|
252
275
|
Four small drift / cosmetic findings from the v1.7.x slash-command audit (PR #25) deliberately not fixed in that PR; logged here to avoid re-auditing them.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "thetabook"
|
|
3
|
-
version = "2.
|
|
3
|
+
version = "2.4.0"
|
|
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 = [
|
|
@@ -81,7 +81,7 @@ exclude = [
|
|
|
81
81
|
# Modules already strict-clean — tighten one-by-one as M11/M12/M13 land.
|
|
82
82
|
[[tool.mypy.overrides]]
|
|
83
83
|
module = [
|
|
84
|
-
"thetabook.pricing
|
|
84
|
+
"thetabook.pricing.*",
|
|
85
85
|
"thetabook.config",
|
|
86
86
|
"thetabook.backtest.engine",
|
|
87
87
|
"thetabook.backtest.signals",
|
|
@@ -16,16 +16,16 @@ pricing/ ← pure math, no I/O
|
|
|
16
16
|
models.py leg_parse.py tickers.py log.py paths.py config.py cache.py preflight.py
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
**Never import upward.** A `pricing/` module that imports from `market/` is a bug, not a shortcut — `pricing/` runs under strict mypy and must stay network-free and testable without fixtures. When two same-layer modules need shared logic, extract it downward (that's why `ideas/core.py` exists: so `evaluate_idea`, `adjust`, and `roll_scenarios` don't cross-import each other).
|
|
19
|
+
**Never import upward.** A `pricing/` module that imports from `market/` is a bug, not a shortcut — `pricing/` runs under strict mypy and must stay network-free and testable without fixtures. `tests/pricing/test_layer_rule.py` enforces it: no `pricing` module may import a higher layer, `paths`, or a network library, directly or transitively. Portfolio-level Greeks aggregation was the last violator (`pricing/greeks.py` imported `market/`, `portfolio/` and `paths`); it now lives in `portfolio/greeks_book.py`. When two same-layer modules need shared logic, extract it downward (that's why `ideas/core.py` exists: so `evaluate_idea`, `adjust`, and `roll_scenarios` don't cross-import each other).
|
|
20
20
|
|
|
21
21
|
If a constant is needed by more than one layer, it goes in `models.py` — not in whichever layer happened to need it first. `SHARE_ASSET_TYPES` lived in `ideas/core.py` once; `pricing/greeks.py` couldn't import it without inverting the dependency, so the two copies drifted and QQQ silently dropped out of portfolio Greeks.
|
|
22
22
|
|
|
23
23
|
## Layer briefs
|
|
24
24
|
|
|
25
|
-
- **`pricing/`** — Black-Scholes
|
|
25
|
+
- **`pricing/`** — Black-Scholes (`bs.py`) and one leg's Greeks arithmetic (`leg_greeks.py`). No I/O, no network, nothing from a higher layer. **Strict mypy** (`thetabook.pricing.*`).
|
|
26
26
|
- **`market/`** — every network call lives here. Owns the Schwab → Massive → yfinance cascade and its retry semantics. Reads network, **never writes user files**. Schwab auth goes through `market/_schwab.py`; don't re-inline the token dance.
|
|
27
27
|
- **`analysis/`** — pure functions over a close `Series` where possible. `em.py` / `vrp.py` are the exceptions: they touch the live cascade, so their freshness model differs (see behaviors.md).
|
|
28
|
-
- **`portfolio/`** — snapshot lifecycle + per-account rules. Rule checks are **advisory, never blocking** — this repo is read-only with respect to the broker.
|
|
28
|
+
- **`portfolio/`** — snapshot lifecycle + per-account rules, plus the two book views: `greeks_book.py` (`thetabook greeks`) and `options_book.py` (`thetabook positions`). Which rows a snapshot holds is not decided here: `leg_parse.snapshot_option_rows` and `models.snapshot_share_rows` own that for every command. Rule checks are **advisory, never blocking** — this repo is read-only with respect to the broker.
|
|
29
29
|
- **`ideas/`** — the trade-idea workflow. Shared helpers in `core.py`.
|
|
30
30
|
- **`backtest/`** — hypothetical strategy backtests. `engine` / `signals` / `metrics` are pure and **strict mypy**; `report.simulate` is the single path `backtest run`, `signal` and `grid` all use (`grid` loads the panel once and passes it in). Stdout only, except `--save`, which goes through `backtest/manifest.py` (the third write boundary, below).
|
|
31
31
|
- **`wiki/` / `skills/`** — both follow a pure `compute_*_report()` → `render_*_text()` / `render_*_json()` split so JSON consumers and humans read the same data. Keep new checks in that shape and give each a stable check ID.
|
|
@@ -52,4 +52,4 @@ All non-stdout output goes through `log.py`: `warn` / `error` / `info` / `note`.
|
|
|
52
52
|
|
|
53
53
|
## Types
|
|
54
54
|
|
|
55
|
-
Permissive mypy baseline, strict on `
|
|
55
|
+
Permissive mypy baseline, strict on `pricing/*`, `config.py` and `backtest/{engine,signals,metrics,manifest}.py` (see `[[tool.mypy.overrides]]`). Prefer fixing the underlying type over `# type: ignore`; if you must suppress, use a specific code plus a one-line reason. **Never invent a fallback branch just to satisfy the checker** — if an upstream contract already excludes the unsafe case, use a walrus filter, an `assert` with rationale, or a typed ignore rather than a defensive path that's dead at runtime.
|
|
@@ -28,30 +28,24 @@ realized risk; that's the caution flag.
|
|
|
28
28
|
Data-source caveat
|
|
29
29
|
------------------
|
|
30
30
|
IV requires a Greeks-bearing source (Schwab or Massive). yfinance carries an
|
|
31
|
-
``impliedVolatility`` field but it's unreliable and frequently absent
|
|
32
|
-
|
|
33
|
-
|
|
31
|
+
``impliedVolatility`` field but it's unreliable and frequently absent, so
|
|
32
|
+
when the chain cascade fell all the way through to yfinance :func:`atm_iv`
|
|
33
|
+
refuses it (``fetch_chain`` tags each row with its source) and :func:`vrp`
|
|
34
|
+
returns ``None`` rather than a bogus ratio. Spot freshness
|
|
34
35
|
follows the price cascade — if it came from Massive it's the prior-day
|
|
35
36
|
close, which ``fetch_prices`` already notes to stderr.
|
|
36
37
|
"""
|
|
37
38
|
|
|
38
39
|
from __future__ import annotations
|
|
39
40
|
|
|
40
|
-
from collections import defaultdict
|
|
41
41
|
from dataclasses import dataclass
|
|
42
|
-
from datetime import date
|
|
43
42
|
|
|
43
|
+
from thetabook import log
|
|
44
44
|
from thetabook.analysis.hv import hv
|
|
45
45
|
from thetabook.market.chains import fetch_chain, list_expirations
|
|
46
46
|
from thetabook.market.prices import fetch_prices
|
|
47
|
-
|
|
48
|
-
|
|
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
|
|
47
|
+
from thetabook.market.vol_lookup import AtmBasis, AtmIv, atm_iv_from_chain, atm_strike_bounds
|
|
48
|
+
from thetabook.models import days_to_expiry
|
|
55
49
|
|
|
56
50
|
|
|
57
51
|
# Plain frozen dataclass (not pydantic) on purpose — a within-feature, CLI-only
|
|
@@ -67,6 +61,8 @@ class VrpResult:
|
|
|
67
61
|
dte_days: int
|
|
68
62
|
atm_strike: float
|
|
69
63
|
atm_iv: float
|
|
64
|
+
atm_basis: AtmBasis
|
|
65
|
+
"""``"straddle"`` (call+put averaged at ``atm_strike``) or the single side that stood in."""
|
|
70
66
|
hv: float
|
|
71
67
|
hv_window: int
|
|
72
68
|
ratio: float
|
|
@@ -75,33 +71,34 @@ class VrpResult:
|
|
|
75
71
|
"""``atm_iv - hv`` — the premium in vol points (decimal)."""
|
|
76
72
|
|
|
77
73
|
|
|
78
|
-
def atm_iv(ticker: str, expiry: str, spot: float) ->
|
|
79
|
-
"""ATM implied vol for ``ticker`` at ``expiry
|
|
74
|
+
def atm_iv(ticker: str, expiry: str, spot: float) -> AtmIv | None:
|
|
75
|
+
"""ATM implied vol for ``ticker`` at ``expiry``, or ``None`` if there is no trustworthy one.
|
|
76
|
+
|
|
77
|
+
A thin wrapper over the owner, :func:`thetabook.market.vol_lookup.atm_iv_from_chain`
|
|
78
|
+
(the same-strike straddle nearest spot, else the nearest single usable
|
|
79
|
+
side, within ``spot ± max(10%, $5)`` — the estimator ``evaluate`` and
|
|
80
|
+
``adjust`` use for PoP). It adds two things:
|
|
81
|
+
|
|
82
|
+
- The chain fetch is bounded to the owner's :func:`atm_strike_bounds`, so
|
|
83
|
+
it's small and sees exactly the strikes the owner would consider.
|
|
84
|
+
- A chain served by **yfinance alone** returns ``None`` with a warning.
|
|
85
|
+
``vrp`` and ``em --source iv`` need a Greeks-bearing source (Schwab or
|
|
86
|
+
Massive); yfinance's ``impliedVolatility`` is unreliable, and a positive
|
|
87
|
+
value would otherwise pass as usable.
|
|
80
88
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
+
``None`` also covers an empty chain and one with no usable IV near the
|
|
90
|
+
money. Callers exit non-zero on it rather than print a guess. Shared with
|
|
91
|
+
``thetabook em --source iv``.
|
|
89
92
|
"""
|
|
90
|
-
|
|
91
|
-
contracts = fetch_chain(ticker, expiry, None,
|
|
92
|
-
if
|
|
93
|
+
lo, hi = atm_strike_bounds(spot)
|
|
94
|
+
contracts = fetch_chain(ticker, expiry, None, lo, hi)
|
|
95
|
+
if contracts and all(c.get("source") == "yfinance" for c in contracts):
|
|
96
|
+
log.warn(
|
|
97
|
+
f"{ticker} {expiry} chain came from yfinance only; its IV isn't trusted for ATM IV "
|
|
98
|
+
f"(needs Schwab or Massive)."
|
|
99
|
+
)
|
|
93
100
|
return None
|
|
94
|
-
|
|
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)
|
|
101
|
+
return atm_iv_from_chain(contracts, spot)
|
|
105
102
|
|
|
106
103
|
|
|
107
104
|
def select_expiry(expirations: list[str], min_dte: int | None) -> str | None:
|
|
@@ -111,15 +108,18 @@ def select_expiry(expirations: list[str], min_dte: int | None) -> str | None:
|
|
|
111
108
|
rather than returning nothing — a horizon past the last listed expiry is a
|
|
112
109
|
reason to show the closest available and let the caller see the DTE, not a
|
|
113
110
|
reason to fail. Callers compare ``dte_days`` against what they asked for.
|
|
111
|
+
|
|
112
|
+
DTE is :func:`thetabook.models.days_to_expiry` — the same count ``vrp``
|
|
113
|
+
reports as ``dte_days`` — so the selection can't disagree with the number
|
|
114
|
+
printed beside it.
|
|
114
115
|
"""
|
|
115
116
|
if not expirations:
|
|
116
117
|
return None
|
|
117
118
|
ordered = sorted(expirations)
|
|
118
119
|
if min_dte is None:
|
|
119
120
|
return ordered[0]
|
|
120
|
-
today = date.today()
|
|
121
121
|
for exp in ordered:
|
|
122
|
-
if (
|
|
122
|
+
if days_to_expiry(exp) >= min_dte:
|
|
123
123
|
return exp
|
|
124
124
|
return ordered[-1]
|
|
125
125
|
|
|
@@ -160,19 +160,20 @@ def vrp(
|
|
|
160
160
|
picked = atm_iv(ticker, expiry, spot)
|
|
161
161
|
if picked is None:
|
|
162
162
|
return None
|
|
163
|
-
|
|
163
|
+
iv = picked.iv
|
|
164
164
|
|
|
165
165
|
realized = hv(ticker, window=hv_window)
|
|
166
166
|
if realized is None or realized <= 0:
|
|
167
167
|
return None
|
|
168
168
|
|
|
169
|
-
dte_days = (
|
|
169
|
+
dte_days = days_to_expiry(expiry)
|
|
170
170
|
return VrpResult(
|
|
171
171
|
spot=spot,
|
|
172
172
|
expiry=expiry,
|
|
173
173
|
dte_days=dte_days,
|
|
174
|
-
atm_strike=
|
|
174
|
+
atm_strike=picked.strike,
|
|
175
175
|
atm_iv=iv,
|
|
176
|
+
atm_basis=picked.basis,
|
|
176
177
|
hv=realized,
|
|
177
178
|
hv_window=hv_window,
|
|
178
179
|
ratio=iv / realized,
|