thetabook 2.2.1__tar.gz → 2.2.2__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.2.1 → thetabook-2.2.2}/CHANGELOG.md +31 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/CLAUDE.md +1 -1
- {thetabook-2.2.1 → thetabook-2.2.2}/PKG-INFO +1 -1
- {thetabook-2.2.1 → thetabook-2.2.2}/pyproject.toml +1 -1
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/_schwab.py +6 -5
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/get_positions.py +27 -7
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/import_csv_snapshot.py +10 -0
- thetabook-2.2.2/src/thetabook/preflight.py +169 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/pricing/greeks.py +85 -11
- {thetabook-2.2.1 → thetabook-2.2.2}/uv.lock +1 -1
- {thetabook-2.2.1 → thetabook-2.2.2}/.env.example +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/.github/workflows/ci.yml +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/.github/workflows/publish.yml +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/.gitignore +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/.python-version +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/CONTRIBUTING.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/LICENSE +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/README.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/ROADMAP.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/SECURITY.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/analysis/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/analysis/em.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/analysis/hv.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/analysis/scenarios.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/analysis/ta.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/analysis/vrp.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cache.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/_shared.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/accounts.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/adjust.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/bars.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/bs.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/chain.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/diff.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/dividends.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/earnings.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/em.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/evaluate.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/greeks.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/hv.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/ideas.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/import_csv.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/init.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/leg_mark.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/migrate_home.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/positions.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/price.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/refresh.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/roll.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/scenarios.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/skills.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/snapshot.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/ta.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/tickers.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/vrp.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/cli/wiki.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/config.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/ideas/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/ideas/adjust.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/ideas/core.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/ideas/evaluate_idea.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/ideas/manage_ideas.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/ideas/roll_scenarios.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/leg_parse.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/log.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/bars.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/chains.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/dividends.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/earnings.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/leg_marks.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/prices.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/market/vol_lookup.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/models.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/paths.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/accounts.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/csv_parsers/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/csv_parsers/_base.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/csv_parsers/empower.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/csv_parsers/fidelity.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/csv_parsers/schwab.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/diff_snapshots.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/options_book.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/portfolio/scaffold.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/pricing/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/pricing/bs.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/install.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/lint.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/models.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/parse.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/policy.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/registry.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/skills/render.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/README.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/accounts.toml.example +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/config.toml.example +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/idea.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/journal.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/learnings.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/skill.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/skills/setup-thetabook.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/wiki/index.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/wiki/log.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/wiki/overview.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/wiki/strategy.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/templates/wiki/underlying.md +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/tickers.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/wiki/__init__.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/wiki/lint.py +0 -0
- {thetabook-2.2.1 → thetabook-2.2.2}/src/thetabook/wiki/render.py +0 -0
|
@@ -3,6 +3,37 @@
|
|
|
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
|
+
## [2.2.2] — 2026-06-11
|
|
7
|
+
|
|
8
|
+
A risk-correctness fix for `thetabook greeks`: option underlyings are now
|
|
9
|
+
always re-priced live, so a fresh-but-aging snapshot can no longer value a
|
|
10
|
+
near-ATM option on a stale price. Per-underlying price provenance is now
|
|
11
|
+
visible in the output. **1723 tests pass, ruff + mypy clean.**
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- **`thetabook greeks` valued option underlyings on stale snapshot prices**
|
|
16
|
+
([#73](https://github.com/subsriram/thetabook/pull/73), closes #72). The
|
|
17
|
+
auto-fetch only refreshed prices when the snapshot was deemed *stale*; on a
|
|
18
|
+
*fresh* snapshot, option underlyings already present were used as-is — even
|
|
19
|
+
if hours old. Because option Greeks are far more price-sensitive than equity
|
|
20
|
+
delta (a ~$2 move on a near-ATM strike flips the ITM flag and swings
|
|
21
|
+
delta/theta), this risked materially wrong delta/theta/assignment readouts
|
|
22
|
+
mid-session. Option underlyings now always live-fetch when `fetch_missing`
|
|
23
|
+
is set, regardless of snapshot freshness; equity-only tickers keep the
|
|
24
|
+
gap-fill-only path (no slow 70+ ticker sweep). `--prices` overrides are now
|
|
25
|
+
preserved in *both* the fresh and stale paths — the stale path previously
|
|
26
|
+
clobbered them with the refetched price.
|
|
27
|
+
|
|
28
|
+
### Added
|
|
29
|
+
|
|
30
|
+
- **Per-underlying price provenance in `thetabook greeks`**
|
|
31
|
+
([#73](https://github.com/subsriram/thetabook/pull/73)). Each result entry
|
|
32
|
+
now carries `price` + `source`, the result gains `snapshot_fetched_at`, and
|
|
33
|
+
the rendered table gains `Price` / `Src` columns with a freshness label
|
|
34
|
+
(`live` / `prev-close` / `delayed` / `manual` / `snapshot <date>`) so a
|
|
35
|
+
Massive or snapshot fallback can no longer masquerade as a live quote.
|
|
36
|
+
|
|
6
37
|
## [2.2.1] — 2026-06-05
|
|
7
38
|
|
|
8
39
|
Two pending medium-priority roadmap items (M24 expected-move / VRP, M20
|
|
@@ -42,7 +42,7 @@ thetabook/
|
|
|
42
42
|
│ ├── wiki/ # personal/wiki/ lint + auto-rendered ideas roll-up
|
|
43
43
|
│ ├── skills/ # author-time tooling + registry installer for skill files
|
|
44
44
|
│ ├── cli/ # typer subcommands — one file per command
|
|
45
|
-
│ └── *.py # shared building blocks: models, leg_parse, paths, log, config, cache, tickers
|
|
45
|
+
│ └── *.py # shared building blocks: models, leg_parse, paths, log, config, cache, tickers, preflight
|
|
46
46
|
├── templates/ # canonical templates (idea.md, journal.md, skill.md, accounts.toml.example, wiki/*)
|
|
47
47
|
├── personal/ # PII data, gitignored
|
|
48
48
|
│ ├── snapshots/ # dated JSON snapshots of positions
|
|
@@ -24,10 +24,9 @@ _reset_warn_state() -> None
|
|
|
24
24
|
|
|
25
25
|
from __future__ import annotations
|
|
26
26
|
|
|
27
|
-
import os
|
|
28
|
-
|
|
29
27
|
from thetabook import log
|
|
30
28
|
from thetabook.paths import schwab_token_path
|
|
29
|
+
from thetabook.preflight import resolve_schwab_credentials
|
|
31
30
|
|
|
32
31
|
_warned_missing_tokens: set[str] = set()
|
|
33
32
|
|
|
@@ -49,8 +48,10 @@ def get_schwab_client():
|
|
|
49
48
|
- ``client_from_token_file`` raises → warn (every time; auth errors
|
|
50
49
|
are usually transient and worth surfacing per occurrence).
|
|
51
50
|
"""
|
|
52
|
-
|
|
51
|
+
creds = resolve_schwab_credentials()
|
|
52
|
+
if creds is None:
|
|
53
53
|
return None
|
|
54
|
+
api_key, app_secret, _callback_url = creds
|
|
54
55
|
|
|
55
56
|
token_path = schwab_token_path()
|
|
56
57
|
if not token_path.exists():
|
|
@@ -69,8 +70,8 @@ def get_schwab_client():
|
|
|
69
70
|
|
|
70
71
|
return client_from_token_file(
|
|
71
72
|
str(token_path),
|
|
72
|
-
|
|
73
|
-
|
|
73
|
+
api_key,
|
|
74
|
+
app_secret,
|
|
74
75
|
)
|
|
75
76
|
except Exception as exc:
|
|
76
77
|
log.warn(f"Schwab auth failed: {exc}")
|
|
@@ -11,7 +11,6 @@ SCHWAB_TOKEN_PATH and refreshed automatically on subsequent runs.
|
|
|
11
11
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
|
-
import os
|
|
15
14
|
import re
|
|
16
15
|
from datetime import date, datetime
|
|
17
16
|
|
|
@@ -21,6 +20,12 @@ from thetabook import PERSONAL_DIR, SNAPSHOTS_DIR, log
|
|
|
21
20
|
from thetabook.leg_parse import parse_occ_symbol
|
|
22
21
|
from thetabook.models import Snapshot
|
|
23
22
|
from thetabook.paths import load_env, schwab_token_path
|
|
23
|
+
from thetabook.preflight import (
|
|
24
|
+
PreflightError,
|
|
25
|
+
fail,
|
|
26
|
+
require_schwab_credentials,
|
|
27
|
+
validate_thetabook_home,
|
|
28
|
+
)
|
|
24
29
|
|
|
25
30
|
# Schwab refresh tokens expire after 7 days. easy_client deletes and re-auths
|
|
26
31
|
# any token older than this threshold, so the weekly expiry triggers a clean
|
|
@@ -96,9 +101,7 @@ def get_client(*, force_reauth: bool = False):
|
|
|
96
101
|
the user wants a fresh OAuth round before the proactive threshold.
|
|
97
102
|
"""
|
|
98
103
|
load_env()
|
|
99
|
-
api_key =
|
|
100
|
-
app_secret = os.environ["SCHWAB_APP_SECRET"]
|
|
101
|
-
callback_url = os.environ.get("SCHWAB_CALLBACK_URL", "https://127.0.0.1:8182")
|
|
104
|
+
api_key, app_secret, callback_url = require_schwab_credentials()
|
|
102
105
|
token_path = schwab_token_path()
|
|
103
106
|
|
|
104
107
|
if force_reauth and token_path.exists():
|
|
@@ -200,7 +203,14 @@ def print_positions(accounts):
|
|
|
200
203
|
|
|
201
204
|
|
|
202
205
|
def main(*, force_reauth: bool = False):
|
|
203
|
-
|
|
206
|
+
try:
|
|
207
|
+
validate_thetabook_home()
|
|
208
|
+
client = get_client(force_reauth=force_reauth)
|
|
209
|
+
except PreflightError as exc:
|
|
210
|
+
# Missing/empty credentials or an unwritable THETABOOK_HOME — there's
|
|
211
|
+
# nothing to fall back to. Surface one Error: line, no traceback.
|
|
212
|
+
fail(str(exc))
|
|
213
|
+
|
|
204
214
|
try:
|
|
205
215
|
accounts = fetch_positions(client)
|
|
206
216
|
except Exception as exc:
|
|
@@ -220,8 +230,18 @@ def main(*, force_reauth: bool = False):
|
|
|
220
230
|
f"complete the login."
|
|
221
231
|
)
|
|
222
232
|
token_path.unlink()
|
|
223
|
-
|
|
224
|
-
|
|
233
|
+
try:
|
|
234
|
+
client = get_client()
|
|
235
|
+
accounts = fetch_positions(client)
|
|
236
|
+
except Exception as retry_exc:
|
|
237
|
+
# The fresh login flow itself failed (user closed the OAuth
|
|
238
|
+
# browser, second auth error, network). Don't re-raise a raw
|
|
239
|
+
# exception — give a clean, actionable message and exit.
|
|
240
|
+
fail(
|
|
241
|
+
f"Schwab re-authentication failed: {retry_exc}\n"
|
|
242
|
+
f"Run `thetabook refresh --reauth` and complete the login "
|
|
243
|
+
f"flow in the browser when it opens."
|
|
244
|
+
)
|
|
225
245
|
log.note("Schwab token re-issued; subsequent runs will reuse it.")
|
|
226
246
|
|
|
227
247
|
print_positions(accounts)
|
|
@@ -56,6 +56,16 @@ def _warn_on_account_number_drift(
|
|
|
56
56
|
def run(csvs: list[Path], date_override: str | None = None) -> None:
|
|
57
57
|
"""Parse CSV files and write a snapshot. Used by the typer ``import-csv`` command."""
|
|
58
58
|
from thetabook import PERSONAL_DIR, SNAPSHOTS_DIR
|
|
59
|
+
from thetabook.preflight import PreflightError, fail, validate_thetabook_home
|
|
60
|
+
|
|
61
|
+
# The CSV path needs no Schwab credentials, but it does write under
|
|
62
|
+
# thetabook_home() — validate it up front so a misconfigured
|
|
63
|
+
# $THETABOOK_HOME (a file, an uncreatable nested path, an unwritable dir)
|
|
64
|
+
# surfaces as one Error: line instead of a raw mkdir/write_text traceback.
|
|
65
|
+
try:
|
|
66
|
+
validate_thetabook_home()
|
|
67
|
+
except PreflightError as exc:
|
|
68
|
+
fail(str(exc))
|
|
59
69
|
|
|
60
70
|
account_cfg = load_accounts()
|
|
61
71
|
all_accounts = []
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Credential & settings preflight — graceful, actionable errors.
|
|
2
|
+
|
|
3
|
+
Credential and settings handling used to be inconsistent: some paths failed
|
|
4
|
+
with a raw ``KeyError`` traceback (``thetabook refresh`` with no ``.env``),
|
|
5
|
+
others degraded silently, and settings were read but never validated. This
|
|
6
|
+
module centralizes the resolution so every entry point produces a single,
|
|
7
|
+
named, actionable ``Error:`` line instead of a stack trace.
|
|
8
|
+
|
|
9
|
+
Two flavours, by call-site intent:
|
|
10
|
+
|
|
11
|
+
- **Hard / required** (:func:`require_schwab_credentials`,
|
|
12
|
+
:func:`validate_thetabook_home`) raise :class:`PreflightError` with an
|
|
13
|
+
already-formatted, user-facing message. The entry point catches it and
|
|
14
|
+
routes it through :func:`fail` (``log.error`` + ``SystemExit(1)``) so the
|
|
15
|
+
user sees one line, no traceback. This is the ``refresh`` / ``get_positions``
|
|
16
|
+
path — without Schwab credentials there is nothing to fall back to.
|
|
17
|
+
|
|
18
|
+
- **Soft / optional** (:func:`resolve_schwab_credentials`) returns ``None``
|
|
19
|
+
when credentials are absent so the data cascade (Schwab → Massive →
|
|
20
|
+
yfinance) can fall through to the next source. This is the read path used
|
|
21
|
+
by ``prices`` / ``chains`` / ``dividends`` via ``market/_schwab.py``.
|
|
22
|
+
|
|
23
|
+
Both share :func:`_missing_schwab_creds` so "which keys are missing" is
|
|
24
|
+
computed in exactly one place.
|
|
25
|
+
|
|
26
|
+
All functions assume :func:`thetabook.paths.load_env` has already run — they
|
|
27
|
+
read from ``os.environ`` and do not load ``.env`` themselves.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
from typing import TYPE_CHECKING, NoReturn
|
|
34
|
+
|
|
35
|
+
from thetabook import log
|
|
36
|
+
from thetabook.paths import thetabook_home
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
|
|
41
|
+
# Default OAuth callback. schwab-py spins a local server on this URL during
|
|
42
|
+
# the login flow; it must match the callback registered on the Schwab app.
|
|
43
|
+
DEFAULT_SCHWAB_CALLBACK_URL = "https://127.0.0.1:8182"
|
|
44
|
+
|
|
45
|
+
# Required Schwab API credentials, in the order we name them in errors.
|
|
46
|
+
_REQUIRED_SCHWAB_KEYS = ("SCHWAB_API_KEY", "SCHWAB_APP_SECRET")
|
|
47
|
+
|
|
48
|
+
# Appended to every missing-credential message: the three ways to fix it.
|
|
49
|
+
SCHWAB_SETUP_HINT = (
|
|
50
|
+
"Add them to your .env, or run the /setup-thetabook wizard "
|
|
51
|
+
"(or `thetabook init`) to register a Schwab app and write the .env for you."
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PreflightError(Exception):
|
|
56
|
+
"""A required credential or setting is missing or invalid.
|
|
57
|
+
|
|
58
|
+
Carries an already-formatted, user-facing message (``str(exc)``). Entry
|
|
59
|
+
points catch this and route it through :func:`fail` so the user sees a
|
|
60
|
+
single ``Error: ...`` line and a non-zero exit, never a traceback.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def fail(message: str) -> NoReturn:
|
|
65
|
+
"""Emit a clean ``Error:`` line and exit non-zero — no traceback.
|
|
66
|
+
|
|
67
|
+
The standard terminal handler for a :class:`PreflightError`. Kept
|
|
68
|
+
separate so callers that build a message inline (rather than raising)
|
|
69
|
+
can reuse the same exit convention.
|
|
70
|
+
"""
|
|
71
|
+
log.error(message)
|
|
72
|
+
raise SystemExit(1)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _missing_schwab_creds() -> list[str]:
|
|
76
|
+
"""Return the required Schwab env vars that are unset or blank.
|
|
77
|
+
|
|
78
|
+
Treats an empty / whitespace-only value the same as unset — a ``.env``
|
|
79
|
+
with ``SCHWAB_API_KEY=`` is just as broken as one without the line, and
|
|
80
|
+
both should produce the same named error rather than a downstream auth
|
|
81
|
+
failure with an opaque message.
|
|
82
|
+
"""
|
|
83
|
+
return [name for name in _REQUIRED_SCHWAB_KEYS if not (os.environ.get(name) or "").strip()]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def resolve_schwab_credentials() -> tuple[str, str, str] | None:
|
|
87
|
+
"""Soft resolver: ``(api_key, app_secret, callback_url)`` or ``None``.
|
|
88
|
+
|
|
89
|
+
Returns ``None`` when either required credential is missing or blank, so
|
|
90
|
+
the read cascade can fall through to the next source without nagging a
|
|
91
|
+
clean install that never configured Schwab. Use this on optional paths;
|
|
92
|
+
use :func:`require_schwab_credentials` where Schwab is mandatory.
|
|
93
|
+
"""
|
|
94
|
+
if _missing_schwab_creds():
|
|
95
|
+
return None
|
|
96
|
+
return (
|
|
97
|
+
os.environ["SCHWAB_API_KEY"].strip(),
|
|
98
|
+
os.environ["SCHWAB_APP_SECRET"].strip(),
|
|
99
|
+
_resolve_callback_url(),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def require_schwab_credentials() -> tuple[str, str, str]:
|
|
104
|
+
"""Hard resolver: ``(api_key, app_secret, callback_url)`` or raise.
|
|
105
|
+
|
|
106
|
+
Raises :class:`PreflightError` naming exactly which of
|
|
107
|
+
``SCHWAB_API_KEY`` / ``SCHWAB_APP_SECRET`` are missing or empty, plus the
|
|
108
|
+
fix-it hint. Use on the ``refresh`` / ``get_positions`` path where there
|
|
109
|
+
is no fallback source — a missing credential is fatal, not a degrade.
|
|
110
|
+
"""
|
|
111
|
+
missing = _missing_schwab_creds()
|
|
112
|
+
if missing:
|
|
113
|
+
names = " and ".join(missing)
|
|
114
|
+
verb = "is" if len(missing) == 1 else "are"
|
|
115
|
+
raise PreflightError(f"Schwab credentials missing: {names} {verb} not set (or empty).\n{SCHWAB_SETUP_HINT}")
|
|
116
|
+
return (
|
|
117
|
+
os.environ["SCHWAB_API_KEY"].strip(),
|
|
118
|
+
os.environ["SCHWAB_APP_SECRET"].strip(),
|
|
119
|
+
_resolve_callback_url(),
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _resolve_callback_url() -> str:
|
|
124
|
+
"""Return ``SCHWAB_CALLBACK_URL`` or the default, never blank.
|
|
125
|
+
|
|
126
|
+
A present-but-empty ``SCHWAB_CALLBACK_URL=`` in ``.env`` falls back to
|
|
127
|
+
the default rather than handing schwab-py an empty string.
|
|
128
|
+
"""
|
|
129
|
+
return (os.environ.get("SCHWAB_CALLBACK_URL") or "").strip() or DEFAULT_SCHWAB_CALLBACK_URL
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def validate_thetabook_home() -> Path:
|
|
133
|
+
"""Validate that ``thetabook_home()`` exists (or is creatable) and is writable.
|
|
134
|
+
|
|
135
|
+
Returns the resolved, existing :class:`Path`. Raises
|
|
136
|
+
:class:`PreflightError` with a friendly message when:
|
|
137
|
+
|
|
138
|
+
- the configured path exists but is a file, not a directory;
|
|
139
|
+
- the directory can't be created (bad parent, permissions);
|
|
140
|
+
- the directory exists but isn't writable.
|
|
141
|
+
|
|
142
|
+
Call this before any command that writes under ``thetabook_home()``
|
|
143
|
+
(snapshots, journal, wiki) so a misconfigured ``$THETABOOK_HOME`` surfaces
|
|
144
|
+
as one ``Error:`` line instead of a deep ``PermissionError`` / ``OSError``
|
|
145
|
+
traceback from a ``mkdir`` or ``write_text`` further in.
|
|
146
|
+
"""
|
|
147
|
+
home = thetabook_home()
|
|
148
|
+
configured = os.environ.get("THETABOOK_HOME")
|
|
149
|
+
hint = (
|
|
150
|
+
f" (from $THETABOOK_HOME={configured!r})"
|
|
151
|
+
if configured
|
|
152
|
+
else " (set $THETABOOK_HOME to override the default location)"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
if home.exists() and not home.is_dir():
|
|
156
|
+
raise PreflightError(f"THETABOOK_HOME {home} exists but is not a directory{hint}.")
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
160
|
+
except OSError as exc:
|
|
161
|
+
raise PreflightError(f"Could not create THETABOOK_HOME {home}{hint}: {exc}") from exc
|
|
162
|
+
|
|
163
|
+
# os.access uses the real uid/gid and can false-positive (root, some
|
|
164
|
+
# ACLs, read-only mounts report writable). It's a friendliness check, not
|
|
165
|
+
# a guarantee — the actual snapshot write downstream remains the arbiter.
|
|
166
|
+
if not os.access(home, os.W_OK):
|
|
167
|
+
raise PreflightError(f"THETABOOK_HOME {home} is not writable{hint}.")
|
|
168
|
+
|
|
169
|
+
return home
|
|
@@ -47,6 +47,17 @@ DEFAULT_DIV_YIELD = 0.0
|
|
|
47
47
|
CONTRACT_MULTIPLIER = 100
|
|
48
48
|
|
|
49
49
|
|
|
50
|
+
def _snapshot_fetched_at(snapshot) -> str | None:
|
|
51
|
+
"""Return the snapshot's ``fetched_at`` timestamp, accepting dict or model.
|
|
52
|
+
|
|
53
|
+
Used to qualify ``snapshot``-sourced prices in the rendered output so a
|
|
54
|
+
snapshot-aged price doesn't read as a live quote.
|
|
55
|
+
"""
|
|
56
|
+
if isinstance(snapshot, dict):
|
|
57
|
+
return snapshot.get("fetched_at") or None
|
|
58
|
+
return getattr(snapshot, "fetched_at", None) or None
|
|
59
|
+
|
|
60
|
+
|
|
50
61
|
# ---------------------------------------------------------------------------
|
|
51
62
|
# Snapshot loading
|
|
52
63
|
# ---------------------------------------------------------------------------
|
|
@@ -235,12 +246,21 @@ def aggregate_greeks(
|
|
|
235
246
|
"gamma": ...,
|
|
236
247
|
"theta": ...,
|
|
237
248
|
"vega": ...,
|
|
249
|
+
"price": ..., # underlying price used (None if skipped)
|
|
250
|
+
"source": ..., # where the price came from (schwab/massive/snapshot/...)
|
|
238
251
|
},
|
|
239
252
|
...
|
|
240
253
|
},
|
|
241
|
-
"total": {same structure},
|
|
254
|
+
"total": {same structure, minus price/source},
|
|
242
255
|
"warnings": ["..."],
|
|
256
|
+
"vol_sources": {"chain": N, "flat": M},
|
|
257
|
+
"price_sources": {"AAPL": "schwab", ...},
|
|
258
|
+
"snapshot_fetched_at": "YYYY-MM-DDT...", # snapshot timestamp (None if absent)
|
|
243
259
|
}
|
|
260
|
+
|
|
261
|
+
Option underlyings are always re-priced live when ``fetch_missing`` is set,
|
|
262
|
+
regardless of snapshot freshness; equity-only tickers fall back to snapshot
|
|
263
|
+
prices unless missing. ``price_overrides`` always win over a fetched price.
|
|
244
264
|
"""
|
|
245
265
|
option_positions = extract_option_positions(snapshot)
|
|
246
266
|
equity_positions = extract_equity_positions(snapshot)
|
|
@@ -254,18 +274,34 @@ def aggregate_greeks(
|
|
|
254
274
|
for ticker in price_overrides:
|
|
255
275
|
price_sources[ticker] = "override"
|
|
256
276
|
|
|
257
|
-
# Auto-fetch prices when snapshot is stale or underlyings are missing
|
|
277
|
+
# Auto-fetch prices when snapshot is stale or underlyings are missing.
|
|
278
|
+
# Option underlyings are always re-priced live (option Greeks are far more
|
|
279
|
+
# price-sensitive than equity delta — a $2 move on a near-ATM strike can flip
|
|
280
|
+
# the ITM flag and swing delta/theta), while equity-only tickers fall back to
|
|
281
|
+
# snapshot prices unless they're outright missing. A --prices override always
|
|
282
|
+
# wins, so its tickers are excluded from the fetch in both paths.
|
|
258
283
|
if fetch_missing:
|
|
259
284
|
all_underlyings = {p["underlying"] for p in option_positions} | set(equity_positions)
|
|
285
|
+
option_underlyings = {p["underlying"] for p in option_positions}
|
|
286
|
+
overridden = set(price_overrides or {})
|
|
260
287
|
stale = snapshot_is_stale(snapshot)
|
|
261
288
|
if stale:
|
|
262
|
-
# Snapshot is outdated — refresh
|
|
263
|
-
to_fetch = sorted(all_underlyings)
|
|
289
|
+
# Snapshot is outdated — refresh every underlying we don't have an override for
|
|
290
|
+
to_fetch = [t for t in sorted(all_underlyings) if t not in overridden]
|
|
264
291
|
else:
|
|
265
|
-
# Snapshot is fresh —
|
|
266
|
-
|
|
292
|
+
# Snapshot is fresh — live-fetch option underlyings regardless, but only
|
|
293
|
+
# gap-fill equity-only tickers (avoids a slow 70+ ticker sweep every call).
|
|
294
|
+
equity_only = all_underlyings - option_underlyings
|
|
295
|
+
to_fetch = [t for t in sorted(option_underlyings) if t not in overridden] + [
|
|
296
|
+
t for t in sorted(equity_only) if t not in stock_prices and t not in overridden
|
|
297
|
+
]
|
|
267
298
|
if to_fetch:
|
|
268
|
-
|
|
299
|
+
if stale:
|
|
300
|
+
label = "Snapshot is stale; fetching"
|
|
301
|
+
elif option_underlyings & set(to_fetch):
|
|
302
|
+
label = "Fetching live prices for option underlyings"
|
|
303
|
+
else:
|
|
304
|
+
label = "Fetching prices for"
|
|
269
305
|
log.info(f"{label}: {', '.join(to_fetch)}")
|
|
270
306
|
fetched_with_sources = fetch_prices_with_sources(to_fetch)
|
|
271
307
|
for ticker, info in fetched_with_sources.items():
|
|
@@ -367,12 +403,21 @@ def aggregate_greeks(
|
|
|
367
403
|
f"Net {direction} {abs(total['delta']):,.0f} delta — equivalent to ~{abs(spy_equiv):.0f} shares of SPY"
|
|
368
404
|
)
|
|
369
405
|
|
|
406
|
+
# Annotate each underlying with the price used and where it came from, so the
|
|
407
|
+
# renderer can show provenance per row. A blended output (some option underlyings
|
|
408
|
+
# live, some equity-only tickers snapshot-aged) is then honest at a glance rather
|
|
409
|
+
# than relying on the warning lines alone.
|
|
410
|
+
for ticker, entry in by_underlying.items():
|
|
411
|
+
entry["price"] = stock_prices.get(ticker)
|
|
412
|
+
entry["source"] = price_sources.get(ticker)
|
|
413
|
+
|
|
370
414
|
return {
|
|
371
415
|
"by_underlying": dict(by_underlying),
|
|
372
416
|
"total": total,
|
|
373
417
|
"warnings": warnings,
|
|
374
418
|
"vol_sources": dict(vol_source_counts),
|
|
375
419
|
"price_sources": dict(price_sources),
|
|
420
|
+
"snapshot_fetched_at": _snapshot_fetched_at(snapshot),
|
|
376
421
|
}
|
|
377
422
|
|
|
378
423
|
|
|
@@ -381,21 +426,50 @@ def aggregate_greeks(
|
|
|
381
426
|
# ---------------------------------------------------------------------------
|
|
382
427
|
|
|
383
428
|
|
|
429
|
+
# Maps a price source to a short freshness label shown in the Src column.
|
|
430
|
+
_SOURCE_LABELS = {
|
|
431
|
+
"schwab": "live",
|
|
432
|
+
"massive": "prev-close",
|
|
433
|
+
"yfinance": "delayed",
|
|
434
|
+
"override": "manual",
|
|
435
|
+
"snapshot": "snapshot",
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _source_label(source: str | None, snapshot_fetched_at: str | None) -> str:
|
|
440
|
+
"""Render a price source as a short freshness label.
|
|
441
|
+
|
|
442
|
+
``snapshot``-sourced prices are dated with the snapshot's ``fetched_at`` so a
|
|
443
|
+
snapshot-aged price (e.g. under --no-fetch or a Schwab auth outage) doesn't
|
|
444
|
+
read as live.
|
|
445
|
+
"""
|
|
446
|
+
if source is None:
|
|
447
|
+
return "—"
|
|
448
|
+
label = _SOURCE_LABELS.get(source, source)
|
|
449
|
+
if source == "snapshot" and snapshot_fetched_at:
|
|
450
|
+
return f"{label} {snapshot_fetched_at[:10]}"
|
|
451
|
+
return label
|
|
452
|
+
|
|
453
|
+
|
|
384
454
|
def format_greeks_markdown(result: dict) -> str:
|
|
385
455
|
"""Format the aggregated Greeks result as a markdown table."""
|
|
456
|
+
snap_ts = result.get("snapshot_fetched_at")
|
|
386
457
|
lines = [
|
|
387
458
|
f"## Greeks Summary ({date.today().isoformat()})",
|
|
388
459
|
"",
|
|
389
|
-
"| Underlying | Shares | Opt Pos | Delta($) | Gamma($) | Theta($/day) | Vega($/%vol) |",
|
|
390
|
-
"
|
|
460
|
+
"| Underlying | Price | Src | Shares | Opt Pos | Delta($) | Gamma($) | Theta($/day) | Vega($/%vol) |",
|
|
461
|
+
"|---|---:|---|---:|---:|---:|---:|---:|---:|",
|
|
391
462
|
]
|
|
392
463
|
|
|
393
464
|
for ticker in sorted(result["by_underlying"].keys()):
|
|
394
465
|
entry = result["by_underlying"][ticker]
|
|
395
466
|
shares = entry.get("equity_shares", 0)
|
|
396
467
|
shares_str = f"{shares:+,}" if shares != 0 else "—"
|
|
468
|
+
price = entry.get("price")
|
|
469
|
+
price_str = f"${price:,.2f}" if price is not None else "—"
|
|
470
|
+
src_str = _source_label(entry.get("source"), snap_ts)
|
|
397
471
|
lines.append(
|
|
398
|
-
f"| {ticker} | {shares_str} | {entry['positions']} "
|
|
472
|
+
f"| {ticker} | {price_str} | {src_str} | {shares_str} | {entry['positions']} "
|
|
399
473
|
f"| {entry['delta']:+,.0f} "
|
|
400
474
|
f"| {entry['gamma']:+,.2f} "
|
|
401
475
|
f"| {entry['theta']:+,.2f} "
|
|
@@ -406,7 +480,7 @@ def format_greeks_markdown(result: dict) -> str:
|
|
|
406
480
|
total_shares = total.get("equity_shares", 0)
|
|
407
481
|
total_shares_str = f"{total_shares:+,}" if total_shares != 0 else "—"
|
|
408
482
|
lines.append(
|
|
409
|
-
f"| **TOTAL** | **{total_shares_str}** | **{total['positions']}** "
|
|
483
|
+
f"| **TOTAL** | | | **{total_shares_str}** | **{total['positions']}** "
|
|
410
484
|
f"| **{total['delta']:+,.0f}** "
|
|
411
485
|
f"| **{total['gamma']:+,.2f}** "
|
|
412
486
|
f"| **{total['theta']:+,.2f}** "
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|